diff --git a/dmap.js b/dmap.js index 7975002..019eeaf 100644 --- a/dmap.js +++ b/dmap.js @@ -1,21 +1,14 @@ +const kek = require('js-sha3') const ebnf = require('ebnf') -const ethers = require('ethers') -const multiformats = require('multiformats') -const pack = require('./pack/premap.dpack.json') -const artifact = require('./pack/Dmap.json') +const pack = require('./pack/dmap.json') +const artifact = require('./pack/ipfs/Dmap.json') -const abi = artifact.abi -const dmap_i = new ethers.utils.Interface(abi) const dmap_address = pack.objects.dmap.address const fail =s=> { throw new Error(s) } const need =(b,s)=> b || fail(s) -const coder = ethers.utils.defaultAbiCoder -const keccak256 = ethers.utils.keccak256 -const prefLenIndex = 2 - module.exports = lib = {} lib.address = dmap_address @@ -43,8 +36,8 @@ lib.parse =s=> { } lib.get = async (dmap, slot) => { - const nextslot = ethers.utils.hexZeroPad( - ethers.BigNumber.from(slot).add(1).toHexString(), 32 + const nextslot = hexZeroPad( + hexlify(BigInt(slot) + BigInt(1)), 32 ) let meta, data await Promise.all( @@ -53,28 +46,24 @@ lib.get = async (dmap, slot) => { dmap.provider.getStorageAt(dmap.address, nextslot) ] ).then(res => [meta, data] = res) - const resdata = dmap_i.encodeFunctionResult("get", [meta, data]) - const res = dmap_i.decodeFunctionResult("get", resdata) - return res + return [meta, data] } lib.getByZoneAndName = async (dmap, zone, name) => { - const slot = keccak256(coder.encode(["address", "bytes32"], [zone, name])) + const slot = keccak256(encodeZoneAndName(zone, name)); return lib.get(dmap, slot) } lib.set = async (dmap, name, meta, data) => { - const calldata = dmap_i.encodeFunctionData("set", [name, meta, data]) + const calldata = encodeFunctionCallBytes32Args("set(bytes32,bytes32,bytes32)", [name, meta, data]) return dmap.signer.sendTransaction({to: dmap.address, data: calldata}) } -const slotabi = ["function slot(bytes32 s) external view returns (bytes32)"] -const slot_i = new ethers.utils.Interface(slotabi) +// const slotabi = ["function slot(bytes32 s) external view returns (bytes32)"] +// const slot_i = new ethers.utils.Interface(slotabi) lib.slot = async (dmap, slot) => { const val = await dmap.provider.getStorageAt(dmap.address, slot) - const resdata = slot_i.encodeFunctionResult("slot", [val]) - const res = slot_i.decodeFunctionResult("slot", resdata) - return res[0] + return val } @@ -87,11 +76,11 @@ lib.walk = async (dmap, path) => { if (zone === '0x' + '00'.repeat(20)) { fail(`zero register`) } - const fullname = '0x' + Buffer.from(step.name).toString('hex') + '00'.repeat(32-step.name.length); + const fullname = '0x' + lib._strToHex(step.name) + '00'.repeat(32-step.name.length); [meta, data] = await lib.getByZoneAndName(dmap, zone, fullname) if (step.locked) { need(ctx.locked, `Encountered ':' in unlocked subpath`) - need((Buffer.from(meta.slice(2), 'hex')[31] & lib.FLAG_LOCK) !== 0, `Entry is not locked`) + need((lib._hexToArrayBuffer(meta)[31] & lib.FLAG_LOCK) !== 0, `Entry is not locked`) ctx.locked = true } ctx.locked = step.locked @@ -99,35 +88,135 @@ lib.walk = async (dmap, path) => { return {meta, data} } -lib.prepareCID = (cidStr, lock) => { - const cid = multiformats.CID.parse(cidStr) - need(cid.multihash.size <= 32, `Hash exceeds 256 bits`) - const prefixLen = cid.byteLength - cid.multihash.size - const meta = new Uint8Array(32).fill(0) - const data = new Uint8Array(32).fill(0) - - data.set(cid.bytes.slice(-cid.multihash.size), 32 - cid.multihash.size) - meta.set(cid.bytes.slice(0, prefixLen), 32 - prefixLen) - if (lock) meta[0] |= lib.FLAG_LOCK - meta[prefLenIndex] = prefixLen - return [meta, data] +lib.walk2 = async (dmap, path) => { + if ( path.length > 0 && ![':', '.'].includes(path.charAt(0))) path = ':' + path + let [meta, data] = await lib.get(dmap, '0x' + '00'.repeat(32)) + let ctx = {locked: path.charAt(0) === ':'} + const trace = [[meta,data]] + for (const step of lib.parse(path)) { + zone = data.slice(0, 21 * 2) + if (zone === '0x' + '00'.repeat(20)) { + fail(`zero register`) + } + const fullname = '0x' + lib._strToHex(step.name) + '00'.repeat(32-step.name.length); + [meta, data] = await lib.getByZoneAndName(dmap, zone, fullname) + trace.push([meta,data]) + if (step.locked) { + need(ctx.locked, `Encountered ':' in unlocked subpath`) + need((lib._hexToArrayBuffer(meta)[31] & lib.FLAG_LOCK) !== 0, `Entry is not locked`) + ctx.locked = true + } + ctx.locked = step.locked + } + return trace } -lib.unpackCID = (metaStr, dataStr) => { - const meta = Buffer.from(metaStr.slice(2), 'hex') - const data = Buffer.from(dataStr.slice(2), 'hex') - const prefixLen = meta[prefLenIndex] - const specs = multiformats.CID.inspectBytes(meta.slice(-prefixLen)) - const hashLen = specs.digestSize - const cidBytes = new Uint8Array(prefixLen + hashLen) - - cidBytes.set(meta.slice(-prefixLen), 0) - cidBytes.set(data.slice(32 - hashLen), prefixLen) - const cid = multiformats.CID.decode(cidBytes) - return cid.toString() +lib._hexToArrayBuffer = hex => { + const bytes = [] + for (let c = 2; c < hex.length; c += 2) + bytes.push(parseInt(hex.slice(c, c + 2), 16)) + return new Uint8Array(bytes) } -lib.readCID = async (dmap, path) => { - const packed = await lib.walk(dmap, path) - return lib.unpackCID(packed.meta, packed.data) +lib._strToHex = str => { + let codes = str.split('').map(c => c.charCodeAt(0)) + return codes.map(c => c.toString(16)).join('') +} + +// GLOBAL TODO: !DMFXYZ! error and bounds checking for inputs +const HexCharacters = "0123456789abcdef"; + +function hexZeroPad(value, length) { + if (typeof(value) !== "string") { + value = hexlify(value); + } + + if (value.length > 2 * length + 2) { + throw "Value too big" + } + + while (value.length < 2 * length + 2) { + value = "0x0" + value.substring(2); + } + + return value; +} + +function hexlify(value) { + + if (typeof(value) === "number") { + let hex = ""; + while (value) { + hex = HexCharacters[value & 0xf] + hex; + value = Math.floor(value / 16); // can bitshift instead + } + + 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 (typeof(value) === 'string') { + return lib._strToHex(value); + } +} + +// Assumes value is a hex encoded string for now, or already a byte array +function keccak256(value) { + + if (typeof(value) == "string") { + return "0x" + kek.keccak256(new Uint8Array(_toBytes(value))); + } + // add back in prefix and return as unsigned 1byte int array + return "0x" + kek.keccak256(value); +} + +function encodeZoneAndName(zone, name) { + // zone should be an address, start by zero-padding 12 bytes + let params = '0x' + '00'.repeat(12); + if (zone.length == 0) { + params = params + '00'.repeat(20); + } else { + params = params + zone.slice(2); // assume has leading 0x, prob shouldn't do this + } + if (name.length == 0 || name == null) { + params = params + '00'.repeat(32); + } else if (typeof(name) == 'object') { + params = params + name.toString('hex'); + } else { + // if already a hex string, just drop the 0x + params = params + name.slice(2); + } + return params; +} + +function encodeFunctionCallBytes32Args(signature, args) { + // calculate function selector as first 4 bytes of hashed signature + // keccak256 returns a string, so we take the first 10 characters + let data = keccak256(signature).slice(0, 10) + for (arg of args) { + typeof arg == 'object' ? data += arg.toString('hex') : data += arg.slice(2) + } + return data; + +} + +function _toBytes(value) { + if (typeof(value) == 'string') { + return lib._hexToArrayBuffer(value) + } + return value } diff --git a/docs/CNAME b/docs/CNAME new file mode 100644 index 0000000..7b59bb5 --- /dev/null +++ b/docs/CNAME @@ -0,0 +1 @@ +dmap.sh \ No newline at end of file diff --git a/docs/dependencies.unmin.js b/docs/dependencies.unmin.js index 95d70ed..9f23425 100644 --- a/docs/dependencies.unmin.js +++ b/docs/dependencies.unmin.js @@ -1,43366 +1,2260 @@ (self["webpackChunk"] = self["webpackChunk"] || []).push([[697],{ -/***/ 4189: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "i": () => (/* binding */ version) -/* harmony export */ }); -const version = "abi/5.5.0"; -//# sourceMappingURL=_version.js.map - -/***/ }), - -/***/ 786: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ 173: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "R": () => (/* binding */ AbiCoder), - "$": () => (/* binding */ defaultAbiCoder) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/_version.js -var _version = __webpack_require__(4189); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js -var abstract_coder = __webpack_require__(4364); -// EXTERNAL MODULE: ../node_modules/@ethersproject/address/lib.esm/index.js + 1 modules -var address_lib_esm = __webpack_require__(9808); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/address.js - - - - -class AddressCoder extends abstract_coder/* Coder */.XI { - constructor(localName) { - super("address", "address", localName, false); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000"; +// https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* +syntax ::= RULE_EOL* rule+ +rule ::= " "* "<" rule-name ">" " "* "::=" firstExpression otherExpression* " "* RULE_EOL+ " "* +firstExpression ::= " "* list +otherExpression ::= " "* "|" " "* list +RULE_EOL ::= "\r" | "\n" +list ::= term " "* list | term +term ::= literal | "<" rule-name ">" +literal ::= '"' RULE_CHARACTER1* '"' | "'" RULE_CHARACTER2* "'" +RULE_CHARACTER ::= " " | RULE_LETTER | RULE_DIGIT | RULE_SYMBOL +RULE_LETTER ::= "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" +RULE_DIGIT ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" +RULE_SYMBOL ::= "-" | "_" | "!" | "#" | "$" | "%" | "&" | "(" | ")" | "*" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | "=" | ">" | "?" | "@" | "[" | "\" | "]" | "^" | "_" | "`" | "{" | "|" | "}" | "~" +RULE_CHARACTER1 ::= RULE_CHARACTER | "'" +RULE_CHARACTER2 ::= RULE_CHARACTER | '"' +rule-name ::= RULE_LETTER RULE_CHAR* +RULE_CHAR ::= RULE_LETTER | RULE_DIGIT | "_" | "-" +*/ +const SemanticHelpers_1 = __webpack_require__(241); +const Parser_1 = __webpack_require__(489); +var BNF; +(function (BNF) { + BNF.RULES = [ + { + name: 'syntax', + bnf: [['RULE_EOL*', 'rule+']] + }, + { + name: 'rule', + bnf: [ + [ + '" "*', + '"<"', + 'rule-name', + '">"', + '" "*', + '"::="', + 'firstExpression', + 'otherExpression*', + '" "*', + 'RULE_EOL+', + '" "*' + ] + ] + }, + { + name: 'firstExpression', + bnf: [['" "*', 'list']] + }, + { + name: 'otherExpression', + bnf: [['" "*', '"|"', '" "*', 'list']] + }, + { + name: 'RULE_EOL', + bnf: [['"\\r"'], ['"\\n"']] + }, + { + name: 'list', + bnf: [['term', '" "*', 'list'], ['term']] + }, + { + name: 'term', + bnf: [['literal'], ['"<"', 'rule-name', '">"']] + }, + { + name: 'literal', + bnf: [[`'"'`, 'RULE_CHARACTER1*', `'"'`], [`"'"`, 'RULE_CHARACTER2*', `"'"`]] + }, + { + name: 'RULE_CHARACTER', + bnf: [['" "'], ['RULE_LETTER'], ['RULE_DIGIT'], ['RULE_SYMBOL']] + }, + { + name: 'RULE_LETTER', + bnf: [ + ['"A"'], + ['"B"'], + ['"C"'], + ['"D"'], + ['"E"'], + ['"F"'], + ['"G"'], + ['"H"'], + ['"I"'], + ['"J"'], + ['"K"'], + ['"L"'], + ['"M"'], + ['"N"'], + ['"O"'], + ['"P"'], + ['"Q"'], + ['"R"'], + ['"S"'], + ['"T"'], + ['"U"'], + ['"V"'], + ['"W"'], + ['"X"'], + ['"Y"'], + ['"Z"'], + ['"a"'], + ['"b"'], + ['"c"'], + ['"d"'], + ['"e"'], + ['"f"'], + ['"g"'], + ['"h"'], + ['"i"'], + ['"j"'], + ['"k"'], + ['"l"'], + ['"m"'], + ['"n"'], + ['"o"'], + ['"p"'], + ['"q"'], + ['"r"'], + ['"s"'], + ['"t"'], + ['"u"'], + ['"v"'], + ['"w"'], + ['"x"'], + ['"y"'], + ['"z"'] + ] + }, + { + name: 'RULE_DIGIT', + bnf: [['"0"'], ['"1"'], ['"2"'], ['"3"'], ['"4"'], ['"5"'], ['"6"'], ['"7"'], ['"8"'], ['"9"']] + }, + { + name: 'RULE_SYMBOL', + bnf: [ + ['"-"'], + ['"_"'], + ['"!"'], + ['"#"'], + ['"$"'], + ['"%"'], + ['"&"'], + ['"("'], + ['")"'], + ['"*"'], + ['"+"'], + ['","'], + ['"-"'], + ['"."'], + ['"/"'], + ['":"'], + ['";"'], + ['"<"'], + ['"="'], + ['">"'], + ['"?"'], + ['"@"'], + ['"["'], + ['"\\"'], + ['"]"'], + ['"^"'], + ['"_"'], + ['"`"'], + ['"{"'], + ['"|"'], + ['"}"'], + ['"~"'] + ] + }, + { + name: 'RULE_CHARACTER1', + bnf: [['RULE_CHARACTER'], [`"'"`]] + }, + { + name: 'RULE_CHARACTER2', + bnf: [['RULE_CHARACTER'], [`'"'`]] + }, + { + name: 'rule-name', + bnf: [['RULE_LETTER', 'RULE_CHAR*']] + }, + { + name: 'RULE_CHAR', + bnf: [['RULE_LETTER'], ['RULE_DIGIT'], ['"_"'], ['"-"']] + } + ]; + BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); + function getAllTerms(expr) { + let terms = SemanticHelpers_1.findChildrenByType(expr, 'term').map(term => { + return SemanticHelpers_1.findChildrenByType(term, 'literal').concat(SemanticHelpers_1.findChildrenByType(term, 'rule-name'))[0].text; + }); + SemanticHelpers_1.findChildrenByType(expr, 'list').forEach(expr => { + terms = terms.concat(getAllTerms(expr)); + }); + return terms; } - encode(writer, value) { - try { - value = (0,address_lib_esm/* getAddress */.Kn)(value); + function getRules(source, parser = BNF.defaultParser) { + let ast = parser.getAST(source); + if (!ast) + throw new Error('Could not parse ' + source); + if (ast.errors && ast.errors.length) { + throw ast.errors[0]; } - catch (error) { - this._throwError(error.message, value); + let rules = SemanticHelpers_1.findChildrenByType(ast, 'rule'); + let ret = rules.map((rule) => { + let name = SemanticHelpers_1.findChildrenByType(rule, 'rule-name')[0].text; + let expressions = SemanticHelpers_1.findChildrenByType(rule, 'firstExpression').concat(SemanticHelpers_1.findChildrenByType(rule, 'otherExpression')); + let bnf = []; + expressions.forEach(expr => { + bnf.push(getAllTerms(expr)); + }); + return { + name: name, + bnf + }; + }); + if (!ret.some(x => x.name == 'EOL')) { + ret.push({ + name: 'EOL', + bnf: [['"\\r\\n"', '"\\r"', '"\\n"']] + }); } - return writer.writeValue(value); - } - decode(reader) { - return (0,address_lib_esm/* getAddress */.Kn)((0,lib_esm/* hexZeroPad */.$m)(reader.readValue().toHexString(), 20)); - } -} -//# sourceMappingURL=address.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/anonymous.js - - -// Clones the functionality of an existing Coder, but without a localName -class AnonymousCoder extends abstract_coder/* Coder */.XI { - constructor(coder) { - super(coder.name, coder.type, undefined, coder.dynamic); - this.coder = coder; - } - defaultValue() { - return this.coder.defaultValue(); - } - encode(writer, value) { - return this.coder.encode(writer, value); + return ret; } - decode(reader) { - return this.coder.decode(reader); + BNF.getRules = getRules; + function Transform(source, subParser = BNF.defaultParser) { + return getRules(source.join(''), subParser); } -} -//# sourceMappingURL=anonymous.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/array.js - - - -const logger = new logger_lib_esm/* Logger */.Yd(_version/* version */.i); - - -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.throwError("cannot encode object for signature with missing names", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "values", - coder: coder, - value: values - }); - } - if (unique[name]) { - logger.throwError("cannot encode object for signature with duplicate names", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "values", - coder: coder, - value: values - }); - } - unique[name] = true; - return values[name]; - }); - } - else { - logger.throwArgumentError("invalid tuple value", "tuple", values); - } - if (coders.length !== arrayValues.length) { - logger.throwArgumentError("types/value length mismatch", "tuple", values); - } - let staticWriter = new abstract_coder/* Writer */.QV(writer.wordSize); - let dynamicWriter = new abstract_coder/* Writer */.QV(writer.wordSize); - let updateFuncs = []; - coders.forEach((coder, index) => { - let value = arrayValues[index]; - if (coder.dynamic) { - // Get current dynamic offset (for the future pointer) - let dynamicOffset = dynamicWriter.length; - // Encode the dynamic value into the dynamicWriter - coder.encode(dynamicWriter, value); - // Prepare to populate the correct offset once we are done - let updateFunc = staticWriter.writeUpdatableValue(); - updateFuncs.push((baseOffset) => { - updateFunc(baseOffset + dynamicOffset); - }); - } - else { - coder.encode(staticWriter, value); - } - }); - // Backfill all the dynamic offsets, now that we know the static length - updateFuncs.forEach((func) => { func(staticWriter.length); }); - let length = writer.appendWriter(staticWriter); - length += writer.appendWriter(dynamicWriter); - return length; -} -function unpack(reader, coders) { - let values = []; - // A reader anchored to this base - 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) { - // Cannot recover from this - if (error.code === logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.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) { - // Cannot recover from this - if (error.code === logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - if (value != undefined) { - values.push(value); - } - }); - // We only output named properties for uniquely named coders - const uniqueNames = coders.reduce((accum, coder) => { - const name = coder.localName; - if (name) { - if (!accum[name]) { - accum[name] = 0; - } - accum[name]++; - } - return accum; - }, {}); - // Add any named parameters (i.e. tuples) - 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 Object.freeze(values); -} -class ArrayCoder extends abstract_coder/* Coder */.XI { - 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() { - // Verifies the child coder is valid (even if the array is dynamic or 0-length) - const defaultChild = this.coder.defaultValue(); - const result = []; - for (let i = 0; i < this.length; i++) { - result.push(defaultChild); - } - return result; - } - encode(writer, value) { - 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.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(); - // Check that there is *roughly* enough data to ensure - // stray random data is not being read as a length. Each - // slot requires at least 32 bytes for their value (or 32 - // bytes as a link to the data). This could use a much - // tighter bound, but we are erroring on the side of safety. - if (count * 32 > reader._data.length) { - logger.throwError("insufficient data length", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, { - length: reader._data.length, - count: count - }); - } - } - let coders = []; - for (let i = 0; i < count; i++) { - coders.push(new AnonymousCoder(this.coder)); - } - return reader.coerce(this.name, unpack(reader, coders)); - } -} -//# sourceMappingURL=array.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/boolean.js - - -class BooleanCoder extends abstract_coder/* Coder */.XI { - 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()); - } -} -//# sourceMappingURL=boolean.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/bytes.js - - - -class DynamicBytesCoder extends abstract_coder/* Coder */.XI { - constructor(type, localName) { - super(type, type, localName, true); - } - defaultValue() { - return "0x"; - } - encode(writer, value) { - value = (0,lib_esm/* arrayify */.lE)(value); - let length = writer.writeValue(value.length); - length += writer.writeBytes(value); - return length; - } - decode(reader) { - return reader.readBytes(reader.readValue().toNumber(), true); - } -} -class BytesCoder extends DynamicBytesCoder { - constructor(localName) { - super("bytes", localName); - } - decode(reader) { - return reader.coerce(this.name, (0,lib_esm/* hexlify */.Dv)(super.decode(reader))); - } -} -//# sourceMappingURL=bytes.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/fixed-bytes.js - - - -// @TODO: Merge this with bytes -class FixedBytesCoder extends abstract_coder/* Coder */.XI { - 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 = (0,lib_esm/* arrayify */.lE)(value); - if (data.length !== this.size) { - this._throwError("incorrect data length", value); - } - return writer.writeBytes(data); - } - decode(reader) { - return reader.coerce(this.name, (0,lib_esm/* hexlify */.Dv)(reader.readBytes(this.size))); - } -} -//# sourceMappingURL=fixed-bytes.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/null.js - - -class NullCoder extends abstract_coder/* Coder */.XI { - 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); - } -} -//# sourceMappingURL=null.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/constants/lib.esm/bignumbers.js -var bignumbers = __webpack_require__(5733); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/number.js - - - - -class NumberCoder extends abstract_coder/* Coder */.XI { - 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/* BigNumber.from */.O$.from(value); - // Check bounds are safe for encoding - let maxUintValue = bignumbers/* MaxUint256.mask */.Bz.mask(writer.wordSize * 8); - if (this.signed) { - let bounds = maxUintValue.mask(this.size * 8 - 1); - if (v.gt(bounds) || v.lt(bounds.add(bignumbers/* One */.fh).mul(bignumbers/* NegativeOne */.tL))) { - this._throwError("value out-of-bounds", value); - } - } - else if (v.lt(bignumbers/* Zero */._Y) || 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); - } -} -//# sourceMappingURL=number.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/strings/lib.esm/utf8.js + 1 modules -var utf8 = __webpack_require__(5804); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/string.js - - - -class StringCoder extends DynamicBytesCoder { - constructor(localName) { - super("string", localName); - } - defaultValue() { - return ""; - } - encode(writer, value) { - return super.encode(writer, (0,utf8/* toUtf8Bytes */.Y0)(value)); - } - decode(reader) { - return (0,utf8/* toUtf8String */.ZN)(super.decode(reader)); - } -} -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/tuple.js - - - -class TupleCoder extends abstract_coder/* Coder */.XI { - 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()); - }); - // We only output named properties for uniquely named coders - const uniqueNames = this.coders.reduce((accum, coder) => { - const name = coder.localName; - if (name) { - if (!accum[name]) { - accum[name] = 0; - } - accum[name]++; - } - return accum; - }, {}); - // Add named values - this.coders.forEach((coder, index) => { - let name = coder.localName; - if (!name || uniqueNames[name] !== 1) { - return; - } - if (name === "length") { - name = "_length"; - } - if (values[name] != null) { - return; - } - values[name] = values[index]; - }); - return Object.freeze(values); - } - encode(writer, value) { - return pack(writer, this.coders, value); - } - decode(reader) { - return reader.coerce(this.name, unpack(reader, this.coders)); - } -} -//# sourceMappingURL=tuple.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/fragments.js -var fragments = __webpack_require__(7755); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abi/lib.esm/abi-coder.js - -// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI - - - - -const abi_coder_logger = new logger_lib_esm/* Logger */.Yd(_version/* version */.i); - - - - - - - - - - - -const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); -const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); -class AbiCoder { - constructor(coerceFunc) { - abi_coder_logger.checkNew(new.target, AbiCoder); - (0,properties_lib_esm/* defineReadOnly */.zG)(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); - } - // u?int[0-9]* - let match = param.type.match(paramTypeNumber); - if (match) { - let size = parseInt(match[2] || "256"); - if (size === 0 || size > 256 || (size % 8) !== 0) { - abi_coder_logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param); - } - return new NumberCoder(size / 8, (match[1] === "int"), param.name); - } - // bytes[0-9]+ - match = param.type.match(paramTypeBytes); - if (match) { - let size = parseInt(match[1]); - if (size === 0 || size > 32) { - abi_coder_logger.throwArgumentError("invalid bytes length", "param", param); - } - return new FixedBytesCoder(size, param.name); - } - return abi_coder_logger.throwArgumentError("invalid type", "type", param.type); - } - _getWordSize() { return 32; } - _getReader(data, allowLoose) { - return new abstract_coder/* Reader */.Ej(data, this._getWordSize(), this.coerceFunc, allowLoose); - } - _getWriter() { - return new abstract_coder/* Writer */.QV(this._getWordSize()); - } - getDefaultValue(types) { - const coders = types.map((type) => this._getCoder(fragments/* ParamType.from */._R.from(type))); - const coder = new TupleCoder(coders, "_"); - return coder.defaultValue(); - } - encode(types, values) { - if (types.length !== values.length) { - abi_coder_logger.throwError("types/values length mismatch", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - count: { types: types.length, values: values.length }, - value: { types: types, values: values } - }); - } - const coders = types.map((type) => this._getCoder(fragments/* ParamType.from */._R.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(fragments/* ParamType.from */._R.from(type))); - const coder = new TupleCoder(coders, "_"); - return coder.decode(this._getReader((0,lib_esm/* arrayify */.lE)(data), loose)); - } -} -const defaultAbiCoder = new AbiCoder(); -//# sourceMappingURL=abi-coder.js.map - -/***/ }), - -/***/ 4364: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BR": () => (/* binding */ checkResultErrors), -/* harmony export */ "Ej": () => (/* binding */ Reader), -/* harmony export */ "QV": () => (/* binding */ Writer), -/* harmony export */ "XI": () => (/* binding */ Coder) -/* harmony export */ }); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4189); - - - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); -function checkResultErrors(result) { - // Find the first error (if any) - 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: error }); - } - } - }; - checkErrors([], result); - return errors; -} -class Coder { - constructor(name, type, localName, dynamic) { - // @TODO: defineReadOnly these - this.name = name; - this.type = type; - this.localName = localName; - this.dynamic = dynamic; - } - _throwError(message, value) { - logger.throwArgumentError(message, this.localName, value); - } -} -class Writer { - constructor(wordSize) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "wordSize", wordSize || 32); - this._data = []; - this._dataLength = 0; - this._padding = new Uint8Array(wordSize); - } - get data() { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)(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((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)(writer._data)); - } - // Arrayish items; padded on the right to wordSize - writeBytes(value) { - let bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(value); - const paddingOffset = bytes.length % this.wordSize; - if (paddingOffset) { - bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([bytes, this._padding.slice(paddingOffset)]); - } - return this._writeData(bytes); - } - _getValue(value) { - let bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(value)); - if (bytes.length > this.wordSize) { - logger.throwError("value out-of-bounds", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.BUFFER_OVERRUN */ .Yd.errors.BUFFER_OVERRUN, { - length: this.wordSize, - offset: bytes.length - }); - } - if (bytes.length % this.wordSize) { - bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([this._padding.slice(bytes.length % this.wordSize), bytes]); - } - return bytes; - } - // BigNumberish items; padded on the left to wordSize - 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) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "_data", (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(data)); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "wordSize", wordSize || 32); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "_coerceFunc", coerceFunc); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "allowLoose", allowLoose); - this._offset = 0; - } - get data() { return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(this._data); } - get consumed() { return this._offset; } - // The default Coerce function - 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); + BNF.Transform = Transform; + class Parser extends Parser_1.Parser { + constructor(source, options) { + const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; + super(getRules(source, subParser), options); + this.source = source; } - 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.throwError("data out-of-bounds", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.BUFFER_OVERRUN */ .Yd.errors.BUFFER_OVERRUN, { - length: this._data.length, - offset: this._offset + alignedLength - }); - } + emitSource() { + return this.source; } - 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 bytes = this._peekBytes(0, length, !!loose); - this._offset += bytes.length; - // @TODO: Make sure the length..end bytes are all 0? - return bytes.slice(0, length); - } - readValue() { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(this.readBytes(this.wordSize)); - } -} -//# sourceMappingURL=abstract-coder.js.map + BNF.Parser = Parser; +})(BNF || (BNF = {})); +exports["default"] = BNF; +//# sourceMappingURL=BNF.js.map /***/ }), -/***/ 7755: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ 657: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "HY": () => (/* binding */ Fragment), -/* harmony export */ "IC": () => (/* binding */ ErrorFragment), -/* harmony export */ "QV": () => (/* binding */ EventFragment), -/* harmony export */ "Xg": () => (/* binding */ ConstructorFragment), -/* harmony export */ "YW": () => (/* binding */ FunctionFragment), -/* harmony export */ "_R": () => (/* binding */ ParamType), -/* harmony export */ "pc": () => (/* binding */ FormatTypes) -/* harmony export */ }); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4189); - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); -; -const _constructorGuard = {}; -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 (ModifiersBytes[name] || name === "payable") { - logger.throwArgumentError("invalid modifier", "name", name); - } - return false; -} -// @TODO: Make sure that children of an indexed tuple are marked with a null indexed -function parseParamType(param, allowIndexed) { - let originalParam = param; - function throwError(i) { - logger.throwArgumentError(`unexpected character at position ${i}`, "param", param); - } - param = param.replace(/\s/g, " "); - function newNode(parent) { - let node = { type: "", name: "", parent: parent, state: { allowType: true } }; - if (allowIndexed) { - node.indexed = false; - } - return node; - } - 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); - //{ type: "", name: "", parent: node.parent, state: { allowType: true } }; - node.parent.components.push(sibling); - delete node.parent; - node = sibling; - break; - // Hit a space... - case " ": - // If reading type, the type is done and may read a param or name - 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 reading name, the name is done - 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); - } +// https://www.w3.org/TR/REC-xml/#NT-Name +// http://www.bottlecaps.de/rr/ui +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Grammar ::= Production* +// Production ::= NCName '::=' Choice +// NCName ::= [http://www.w3.org/TR/xml-names/#NT-NCName] +// Choice ::= SequenceOrDifference ( '|' SequenceOrDifference )* +// SequenceOrDifference ::= (Item ( '-' Item | Item* ))? +// Item ::= Primary ( '?' | '*' | '+' )? +// Primary ::= NCName | StringLiteral | CharCode | CharClass | '(' Choice ')' +// StringLiteral ::= '"' [^"]* '"' | "'" [^']* "'" +// CharCode ::= '#x' [0-9a-fA-F]+ +// CharClass ::= '[' '^'? ( RULE_Char | CharCode | CharRange | CharCodeRange )+ ']' +// RULE_Char ::= [http://www.w3.org/TR/xml#NT-RULE_Char] +// CharRange ::= RULE_Char '-' ( RULE_Char - ']' ) +// CharCodeRange ::= CharCode '-' CharCode +// RULE_WHITESPACE ::= RULE_S | Comment +// RULE_S ::= #x9 | #xA | #xD | #x20 +// Comment ::= '/*' ( [^*] | '*'+ [^*/] )* '*'* '*/' +const TokenError_1 = __webpack_require__(217); +const Parser_1 = __webpack_require__(489); +var BNF; +(function (BNF) { + BNF.RULES = [ + { + name: 'Grammar', + bnf: [['RULE_S*', 'Attributes?', 'RULE_S*', '%Atomic*', 'EOF']] + }, + { + name: '%Atomic', + bnf: [['Production', 'RULE_S*']], + fragment: true + }, + { + name: 'Production', + bnf: [ + [ + 'NCName', + 'RULE_S*', + '"::="', + 'RULE_WHITESPACE*', + '%Choice', + 'RULE_WHITESPACE*', + 'Attributes?', + 'RULE_EOL+', + 'RULE_S*' + ] + ] + }, + { + name: 'NCName', + bnf: [[/[a-zA-Z][a-zA-Z_0-9]*/]] + }, + { + name: 'Attributes', + bnf: [['"{"', 'Attribute', '%Attributes*', 'RULE_S*', '"}"']] + }, + { + name: '%Attributes', + bnf: [['RULE_S*', '","', 'Attribute']], + fragment: true + }, + { + name: 'Attribute', + bnf: [['RULE_S*', 'NCName', 'RULE_WHITESPACE*', '"="', 'RULE_WHITESPACE*', 'AttributeValue']] + }, + { + name: 'AttributeValue', + bnf: [['NCName'], [/[1-9][0-9]*/]] + }, + { + name: '%Choice', + bnf: [['SequenceOrDifference', '%_Choice_1*']], + fragment: true + }, + { + name: '%_Choice_1', + bnf: [['RULE_S*', '"|"', 'RULE_S*', 'SequenceOrDifference']], + fragment: true + }, + { + name: 'SequenceOrDifference', + bnf: [['%Item', 'RULE_WHITESPACE*', '%_Item_1?']] + }, + { + name: '%_Item_1', + bnf: [['Minus', '%Item'], ['%Item*']], + fragment: true + }, + { + name: 'Minus', + bnf: [['"-"']] + }, + { + name: '%Item', + bnf: [['RULE_WHITESPACE*', 'PrimaryPreDecoration?', '%Primary', 'PrimaryDecoration?']], + fragment: true + }, + { + name: 'PrimaryDecoration', + bnf: [['"?"'], ['"*"'], ['"+"']] + }, + { + name: 'PrimaryPreDecoration', + bnf: [['"&"'], ['"!"'], ['"~"']] + }, + { + name: '%Primary', + bnf: [['NCName'], ['StringLiteral'], ['CharCode'], ['CharClass'], ['SubItem']], + fragment: true + }, + { + name: 'SubItem', + bnf: [['"("', 'RULE_S*', '%Choice', 'RULE_S*', '")"']] + }, + { + name: 'StringLiteral', + bnf: [[`'"'`, /[^"]*/, `'"'`], [`"'"`, /[^']*/, `"'"`]] + }, + { + name: 'CharCode', + bnf: [['"#x"', /[0-9a-zA-Z]+/]] + }, + { + name: 'CharClass', + bnf: [["'['", "'^'?", '%RULE_CharClass_1+', '"]"']] + }, + { + name: '%RULE_CharClass_1', + bnf: [['CharCodeRange'], ['CharRange'], ['CharCode'], ['RULE_Char']], + fragment: true + }, + { + name: 'RULE_Char', + bnf: [[/\x09/], [/\x0A/], [/\x0D/], [/[\x20-\x5c]/], [/[\x5e-\uD7FF]/], [/[\uE000-\uFFFD]/]] + }, + { + name: 'CharRange', + bnf: [['RULE_Char', '"-"', 'RULE_Char']] + }, + { + name: 'CharCodeRange', + bnf: [['CharCode', '"-"', 'CharCode']] + }, + { + name: 'RULE_WHITESPACE', + bnf: [['%RULE_WHITESPACE_CHAR*'], ['Comment', 'RULE_WHITESPACE*']] + }, + { + name: 'RULE_S', + bnf: [['RULE_WHITESPACE', 'RULE_S*'], ['RULE_EOL', 'RULE_S*']] + }, + { + name: '%RULE_WHITESPACE_CHAR', + bnf: [[/\x09/], [/\x20/]], + fragment: true + }, + { + name: 'Comment', + bnf: [['"/*"', '%RULE_Comment_Body*', '"*/"']] + }, + { + name: '%RULE_Comment_Body', + bnf: [[/[^*]/], ['"*"+', /[^/]*/]], + fragment: true + }, + { + name: 'RULE_EOL', + bnf: [[/\x0D/, /\x0A/], [/\x0A/], [/\x0D/]] + }, + { + name: 'Link', + bnf: [["'['", 'Url', "']'"]] + }, + { + name: 'Url', + bnf: [[/[^\x5D:/?#]/, '"://"', /[^\x5D#]+/, '%Url1?']] + }, + { + name: '%Url1', + bnf: [['"#"', 'NCName']], + fragment: true } - } - if (node.parent) { - logger.throwArgumentError("unexpected eof", "param", param); - } - delete parent.state; - if (node.name === "indexed") { - if (!allowIndexed) { - throwError(originalParam.length - 7); + ]; + BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); + const preDecorationRE = /^(!|&)/; + const decorationRE = /(\?|\+|\*)$/; + const subExpressionRE = /^%/; + function getBNFRule(name, parser) { + if (typeof name == 'string') { + let decoration = decorationRE.exec(name); + let preDecoration = preDecorationRE.exec(name); + let preDecorationText = preDecoration ? preDecoration[0] : ''; + let decorationText = decoration ? decoration[0] + ' ' : ''; + let subexpression = subExpressionRE.test(name); + if (subexpression) { + let lonely = isLonelyRule(name, parser); + if (lonely) + return preDecorationText + getBNFBody(name, parser) + decorationText; + return preDecorationText + '(' + getBNFBody(name, parser) + ')' + decorationText; + } + return name.replace(preDecorationRE, preDecorationText); } - if (node.indexed) { - throwError(originalParam.length - 7); + else { + return name.source + .replace(/\\(?:x|u)([a-zA-Z0-9]+)/g, '#x$1') + .replace(/\[\\(?:x|u)([a-zA-Z0-9]+)-\\(?:x|u)([a-zA-Z0-9]+)\]/g, '[#x$1-#x$2]'); } - node.indexed = true; - node.name = ""; } - else if (checkModifier(node.type, node.name)) { - node.name = ""; + /// Returns true if the rule is a string literal or regular expression without a descendant tree + function isLonelyRule(name, parser) { + let rule = Parser_1.findRuleByName(name, parser); + return (rule && + rule.bnf.length == 1 && + rule.bnf[0].length == 1 && + (rule.bnf[0][0] instanceof RegExp || rule.bnf[0][0][0] == '"' || rule.bnf[0][0][0] == "'")); } - parent.type = verifyType(parent.type); - return parent; -} -function populate(object, params) { - for (let key in params) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(object, key, params[key]); + function getBNFChoice(rules, parser) { + return rules.map(x => getBNFRule(x, parser)).join(' '); } -} -const FormatTypes = Object.freeze({ - // Bare formatting, as is needed for computing a sighash of an event or function - sighash: "sighash", - // Human-Readable with Minimal spacing and without names (compact human-readable) - minimal: "minimal", - // Human-Readable with nice spacing, including all names - full: "full", - // JSON-format a la Solidity - json: "json" -}); -const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); -class ParamType { - constructor(constructorGuard, params) { - if (constructorGuard !== _constructorGuard) { - logger.throwError("use fromString", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.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); + function getBNFBody(name, parser) { + let rule = Parser_1.findRuleByName(name, parser); + if (rule) + return rule.bnf.map(x => getBNFChoice(x, parser)).join(' | '); + return 'RULE_NOT_FOUND {' + name + '}'; } - // Format the parameter fragment - // - sighash: "(uint256,address)" - // - minimal: "tuple(uint256,address) indexed" - // - full: "tuple(uint256 foo, address bar) indexed baz" - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - let result = { - type: ((this.baseType === "tuple") ? "tuple" : this.type), - name: (this.name || undefined) - }; - if (typeof (this.indexed) === "boolean") { - result.indexed = this.indexed; - } - if (this.components) { - result.components = this.components.map((comp) => JSON.parse(comp.format(format))); + function emit(parser) { + let acumulator = []; + parser.grammarRules.forEach(l => { + if (!/^%/.test(l.name)) { + let recover = l.recover ? ' { recoverUntil=' + l.recover + ' }' : ''; + acumulator.push(l.name + ' ::= ' + getBNFBody(l.name, parser) + recover); } - return JSON.stringify(result); - } - let result = ""; - // Array - 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(_constructorGuard, { - name: (value.name || null), - type: verifyType(value.type), - indexed: ((value.indexed == null) ? null : !!value.indexed), - components: (value.components ? value.components.map(ParamType.fromObject) : null) }); + return acumulator.join('\n'); } - 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 parseParams(value, allowIndex) { - return splitNesting(value).map((param) => ParamType.fromString(param, allowIndex)); -} -class Fragment { - constructor(constructorGuard, params) { - if (constructorGuard !== _constructorGuard) { - logger.throwError("use a static from method", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.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": - // @TODO: Something? Maybe return a FunctionFragment? A custom DefaultFunctionFragment? - return null; - } - return logger.throwArgumentError("invalid fragment object", "value", value); - } - static fromString(value) { - // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space - 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 logger.throwArgumentError("unsupported fragment", "value", value); + BNF.emit = emit; + let subitems = 0; + function restar(total, resta) { + console.log('reberia restar ' + resta + ' a ' + total); + throw new Error('Difference not supported yet'); } - static isFragment(value) { - return !!(value && value._isFragment); + function convertRegex(txt) { + return new RegExp(txt + .replace(/#x([a-zA-Z0-9]{4})/g, '\\u$1') + .replace(/#x([a-zA-Z0-9]{3})/g, '\\u0$1') + .replace(/#x([a-zA-Z0-9]{2})/g, '\\x$1') + .replace(/#x([a-zA-Z0-9]{1})/g, '\\x0$1')); } -} -class EventFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger.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 "; + function getSubItems(tmpRules, seq, parentName, parentAttributes) { + let anterior = null; + let bnfSeq = []; + seq.children.forEach((x, i) => { + if (x.type == 'Minus') { + restar(anterior, x); } - } - 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") { - logger.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(_constructorGuard, params); - } - static fromString(value) { - let match = value.match(regexParen); - if (!match) { - logger.throwArgumentError("invalid event string", "value", value); - } - let anonymous = false; - match[3].split(" ").forEach((modifier) => { - switch (modifier.trim()) { - case "anonymous": - anonymous = true; + else { + } + let decoration = seq.children[i + 1]; + decoration = (decoration && decoration.type == 'PrimaryDecoration' && decoration.text) || ''; + let preDecoration = ''; + if (anterior && anterior.type == 'PrimaryPreDecoration') { + preDecoration = anterior.text; + } + let pinned = preDecoration == '~' ? 1 : undefined; + if (pinned) { + preDecoration = ''; + } + switch (x.type) { + case 'SubItem': + let name = '%' + (parentName + subitems++); + createRule(tmpRules, x, name, parentAttributes); + bnfSeq.push(preDecoration + name + decoration); + break; + case 'NCName': + bnfSeq.push(preDecoration + x.text + decoration); + break; + case 'StringLiteral': + if (decoration || preDecoration || !/^['"/()a-zA-Z0-9&_.:=,+*\-\^\\]+$/.test(x.text)) { + bnfSeq.push(preDecoration + x.text + decoration); + } + else { + for (const c of x.text.slice(1, -1)) { + if (parentAttributes && parentAttributes["ignoreCase"] == "true" && /[a-zA-Z]/.test(c)) { + bnfSeq.push(new RegExp("[" + c.toUpperCase() + c.toLowerCase() + "]")); + } + else { + bnfSeq.push(new RegExp(Parser_1.escapeRegExp(c))); + } + } + } + break; + case 'CharCode': + case 'CharClass': + if (decoration || preDecoration) { + let newRule = { + name: '%' + (parentName + subitems++), + bnf: [[convertRegex(x.text)]], + pinned + }; + tmpRules.push(newRule); + bnfSeq.push(preDecoration + newRule.name + decoration); + } + else { + bnfSeq.push(convertRegex(x.text)); + } break; - case "": + case 'PrimaryPreDecoration': + case 'PrimaryDecoration': break; default: - logger.warn("unknown modifier: " + modifier); + throw new Error(' HOW SHOULD I PARSE THIS? ' + x.type + ' -> ' + JSON.stringify(x.text)); } + anterior = x; }); - return EventFragment.fromObject({ - name: match[1].trim(), - anonymous: anonymous, - inputs: parseParams(match[2], true), - type: "event" - }); - } - static isEventFragment(value) { - return (value && value._isFragment && value.type === "event"); - } -} -function parseGas(value, params) { - params.gas = null; - let comps = value.split("@"); - if (comps.length !== 1) { - if (comps.length > 2) { - logger.throwArgumentError("invalid human-readable ABI signature", "value", value); - } - if (!comps[1].match(/^[0-9]+$/)) { - logger.throwArgumentError("invalid human-readable ABI signature gas", "value", value); - } - params.gas = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_3__/* .BigNumber.from */ .O$.from(comps[1]); - return comps[0]; + return bnfSeq; } - 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 createRule(tmpRules, token, name, parentAttributes = undefined) { + let attrNode = token.children.filter(x => x.type == 'Attributes')[0]; + let attributes = {}; + if (attrNode) { + attrNode.children.forEach(x => { + let name = x.children.filter(x => x.type == 'NCName')[0].text; + if (name in attributes) { + throw new TokenError_1.TokenError('Duplicated attribute ' + name, x); + } + else { + attributes[name] = x.children.filter(x => x.type == 'AttributeValue')[0].text; + } + }); } - }); -} -function verifyState(value) { - let result = { - constant: false, - payable: true, - stateMutability: "payable" - }; - if (value.stateMutability != null) { - result.stateMutability = value.stateMutability; - // Set (and check things are consistent) the constant property - result.constant = (result.stateMutability === "view" || result.stateMutability === "pure"); - if (value.constant != null) { - if ((!!value.constant) !== result.constant) { - logger.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value); - } + let bnf = token.children.filter(x => x.type == 'SequenceOrDifference').map(s => getSubItems(tmpRules, s, name, parentAttributes ? parentAttributes : attributes)); + let rule = { + name, + bnf + }; + if (name.indexOf('%') == 0) + rule.fragment = true; + if (attributes['recoverUntil']) { + rule.recover = attributes['recoverUntil']; + if (rule.bnf.length > 1) + throw new TokenError_1.TokenError('only one-option productions are suitable for error recovering', token); } - // Set (and check things are consistent) the payable property - result.payable = (result.stateMutability === "payable"); - if (value.payable != null) { - if ((!!value.payable) !== result.payable) { - logger.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value); + if ('pin' in attributes) { + let num = parseInt(attributes['pin']); + if (!isNaN(num)) { + rule.pinned = num; } + if (rule.bnf.length > 1) + throw new TokenError_1.TokenError('only one-option productions are suitable for pinning', token); } - } - else if (value.payable != null) { - result.payable = !!value.payable; - // If payable we can assume non-constant; otherwise we can't assume - if (value.constant == null && !result.payable && value.type !== "constructor") { - logger.throwArgumentError("unable to determine stateMutability", "value", value); - } - result.constant = !!value.constant; - if (result.constant) { - result.stateMutability = "view"; + if ('ws' in attributes) { + rule.implicitWs = attributes['ws'] != 'explicit'; } else { - result.stateMutability = (result.payable ? "payable" : "nonpayable"); - } - if (result.payable && result.constant) { - logger.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") { - logger.throwArgumentError("unable to determine stateMutability", "value", value); - } - return result; -} -class ConstructorFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - return JSON.stringify({ - type: "constructor", - stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined), - payable: this.payable, - gas: (this.gas ? this.gas.toNumber() : undefined), - inputs: this.inputs.map((input) => JSON.parse(input.format(format))) - }); - } - if (format === FormatTypes.sighash) { - logger.throwError("cannot format a constructor for sighash", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.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); - } - static fromObject(value) { - if (ConstructorFragment.isConstructorFragment(value)) { - return value; - } - if (value.type !== "constructor") { - logger.throwArgumentError("invalid constructor object", "value", value); - } - let state = verifyState(value); - if (state.constant) { - logger.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 ? _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_3__/* .BigNumber.from */ .O$.from(value.gas) : null) - }; - return new ConstructorFragment(_constructorGuard, params); - } - static fromString(value) { - let params = { type: "constructor" }; - value = parseGas(value, params); - let parens = value.match(regexParen); - if (!parens || parens[1].trim() !== "constructor") { - logger.throwArgumentError("invalid constructor string", "value", value); + rule.implicitWs = null; } - 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"); + rule.fragment = rule.fragment || attributes['fragment'] == 'true'; + rule.simplifyWhenOneChildren = attributes['simplifyWhenOneChildren'] == 'true'; + tmpRules.push(rule); } -} -class FunctionFragment extends ConstructorFragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger.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 : undefined), - payable: this.payable, - gas: (this.gas ? this.gas.toNumber() : undefined), - 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 "; + function getRules(source, parser = BNF.defaultParser) { + let ast = parser.getAST(source); + if (!ast) + throw new Error('Could not parse ' + source); + if (ast.errors && ast.errors.length) { + throw ast.errors[0]; } - 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 + " "); + let implicitWs = null; + let attrNode = ast.children.filter(x => x.type == 'Attributes')[0]; + let attributes = {}; + if (attrNode) { + attrNode.children.forEach(x => { + let name = x.children.filter(x => x.type == 'NCName')[0].text; + if (name in attributes) { + throw new TokenError_1.TokenError('Duplicated attribute ' + name, x); } - } - 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 from(value) { - if (typeof (value) === "string") { - return FunctionFragment.fromString(value); + else { + attributes[name] = x.children.filter(x => x.type == 'AttributeValue')[0].text; + } + }); } - return FunctionFragment.fromObject(value); + implicitWs = attributes['ws'] == 'implicit'; + let tmpRules = []; + ast.children.filter(x => x.type == 'Production').map((x) => { + let name = x.children.filter(x => x.type == 'NCName')[0].text; + createRule(tmpRules, x, name); + }); + tmpRules.forEach(rule => { + if (rule.implicitWs === null) + rule.implicitWs = implicitWs; + }); + return tmpRules; } - static fromObject(value) { - if (FunctionFragment.isFunctionFragment(value)) { - return value; - } - if (value.type !== "function") { - logger.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 ? _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_3__/* .BigNumber.from */ .O$.from(value.gas) : null) - }; - return new FunctionFragment(_constructorGuard, params); + BNF.getRules = getRules; + function Transform(source, subParser = BNF.defaultParser) { + return getRules(source.join(''), subParser); } - static fromString(value) { - let params = { type: "function" }; - value = parseGas(value, params); - let comps = value.split(" returns "); - if (comps.length > 2) { - logger.throwArgumentError("invalid function string", "value", value); - } - let parens = comps[0].match(regexParen); - if (!parens) { - logger.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); - // We have outputs - if (comps.length > 1) { - let returns = comps[1].match(regexParen); - if (returns[1].trim() != "" || returns[3].trim() != "") { - logger.throwArgumentError("unexpected tokens", "value", value); - } - params.outputs = parseParams(returns[2], false); + BNF.Transform = Transform; + class Parser extends Parser_1.Parser { + constructor(source, options) { + const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; + super(getRules(source, subParser), options); } - else { - params.outputs = []; + emitSource() { + return emit(this); } - return FunctionFragment.fromObject(params); - } - static isFunctionFragment(value) { - return (value && value._isFragment && value.type === "function"); - } -} -//export class StructFragment extends Fragment { -//} -function checkForbidden(fragment) { - const sig = fragment.format(); - if (sig === "Error(string)" || sig === "Panic(uint256)") { - logger.throwArgumentError(`cannot specify user defined ${sig} error`, "fragment", fragment); } - return fragment; -} -class ErrorFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger.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 from(value) { - if (typeof (value) === "string") { - return ErrorFragment.fromString(value); - } - return ErrorFragment.fromObject(value); - } - static fromObject(value) { - if (ErrorFragment.isErrorFragment(value)) { - return value; - } - if (value.type !== "error") { - logger.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(_constructorGuard, params)); - } - static fromString(value) { - let params = { type: "error" }; - let parens = value.match(regexParen); - if (!parens) { - logger.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 isErrorFragment(value) { - return (value && value._isFragment && value.type === "error"); - } -} -function verifyType(type) { - // These need to be transformed to their full description - if (type.match(/^uint($|[^1-9])/)) { - type = "uint256" + type.substring(4); - } - else if (type.match(/^int($|[^1-9])/)) { - type = "int256" + type.substring(3); - } - // @TODO: more verification - return type; -} -// See: https://github.com/ethereum/solidity/blob/1f8f1a3db93a548d0555e3e14cfc55a10e25b60e/docs/grammar/SolidityLexer.g4#L234 -const regexIdentifier = new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$"); -function verifyIdentifier(value) { - if (!value || !value.match(regexIdentifier)) { - logger.throwArgumentError(`invalid identifier "${value}"`, "value", value); - } - 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) { - logger.throwArgumentError("unbalanced parenthesis", "value", value); - } - } - } - } - if (accum) { - result.push(accum); - } - return result; -} -//# sourceMappingURL=fragments.js.map + BNF.Parser = Parser; +})(BNF || (BNF = {})); +exports["default"] = BNF; +//# sourceMappingURL=Custom.js.map /***/ }), -/***/ 3017: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ 575: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CC": () => (/* binding */ LogDescription), -/* harmony export */ "Hk": () => (/* binding */ Indexed), -/* harmony export */ "vU": () => (/* binding */ Interface), -/* harmony export */ "vk": () => (/* binding */ TransactionDescription) -/* harmony export */ }); -/* unused harmony export ErrorDescription */ -/* harmony import */ var _ethersproject_address__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9808); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(14); -/* harmony import */ var _ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2677); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(300); -/* harmony import */ var _abi_coder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(786); -/* harmony import */ var _fragments__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7755); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4189); - - - - - - - - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); - -class LogDescription extends _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .Description */ .dk { -} -class TransactionDescription extends _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .Description */ .dk { -} -class ErrorDescription extends _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .Description */ .dk { -} -class Indexed extends _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .Description */ .dk { - static isIndexed(value) { - return !!(value && value._isIndexed); - } -} -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 checkNames(fragment: Fragment, type: "input" | "output", params: Array): void { - params.reduce((accum, param) => { - if (param.name) { - if (accum[param.name]) { - logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment); - } - accum[param.name] = true; +// https://www.w3.org/TR/REC-xml/#NT-Name +// http://www.bottlecaps.de/rr/ui +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Grammar ::= Production* +// Production ::= NCName '::=' Choice +// NCName ::= [http://www.w3.org/TR/xml-names/#NT-NCName] +// Choice ::= SequenceOrDifference ( '|' SequenceOrDifference )* +// SequenceOrDifference ::= (Item ( '-' Item | Item* ))? +// Item ::= Primary ( '?' | '*' | '+' )? +// Primary ::= NCName | StringLiteral | CharCode | CharClass | '(' Choice ')' +// StringLiteral ::= '"' [^"]* '"' | "'" [^']* "'" +// CharCode ::= '#x' [0-9a-fA-F]+ +// CharClass ::= '[' '^'? ( RULE_Char | CharCode | CharRange | CharCodeRange )+ ']' +// RULE_Char ::= [http://www.w3.org/TR/xml#NT-RULE_Char] +// CharRange ::= RULE_Char '-' ( RULE_Char - ']' ) +// CharCodeRange ::= CharCode '-' CharCode +// RULE_WHITESPACE ::= RULE_S | Comment +// RULE_S ::= #x9 | #xA | #xD | #x20 +// Comment ::= '/*' ( [^*] | '*'+ [^*/] )* '*'* '*/' +const Parser_1 = __webpack_require__(489); +var BNF; +(function (BNF) { + BNF.RULES = [ + { + name: 'Grammar', + bnf: [['RULE_S*', '%Atomic*', 'EOF']] + }, + { + name: '%Atomic', + bnf: [['Production', 'RULE_S*']], + fragment: true + }, + { + name: 'Production', + bnf: [['NCName', 'RULE_S*', '"::="', 'RULE_WHITESPACE*', 'Choice', 'RULE_WHITESPACE*', 'RULE_EOL+', 'RULE_S*']] + }, + { + name: 'NCName', + bnf: [[/[a-zA-Z][a-zA-Z_0-9]*/]] + }, + { + name: 'Choice', + bnf: [['SequenceOrDifference', '%_Choice_1*']], + fragment: true + }, + { + name: '%_Choice_1', + bnf: [['RULE_WHITESPACE*', '"|"', 'RULE_WHITESPACE*', 'SequenceOrDifference']], + fragment: true + }, + { + name: 'SequenceOrDifference', + bnf: [['Item', 'RULE_WHITESPACE*', '%_Item_1?']] + }, + { + name: '%_Item_1', + bnf: [['Minus', 'Item'], ['Item*']], + fragment: true + }, + { + name: 'Minus', + bnf: [['"-"']] + }, + { + name: 'Item', + bnf: [['RULE_WHITESPACE*', '%Primary', 'PrimaryDecoration?']], + fragment: true + }, + { + name: 'PrimaryDecoration', + bnf: [['"?"'], ['"*"'], ['"+"']] + }, + { + name: 'DecorationName', + bnf: [['"ebnf://"', /[^\x5D#]+/]] + }, + { + name: '%Primary', + bnf: [['NCName'], ['StringLiteral'], ['CharCode'], ['CharClass'], ['SubItem']], + fragment: true + }, + { + name: 'SubItem', + bnf: [['"("', 'RULE_WHITESPACE*', 'Choice', 'RULE_WHITESPACE*', '")"']] + }, + { + name: 'StringLiteral', + bnf: [[`'"'`, /[^"]*/, `'"'`], [`"'"`, /[^']*/, `"'"`]], + pinned: 1 + }, + { + name: 'CharCode', + bnf: [['"#x"', /[0-9a-zA-Z]+/]] + }, + { + name: 'CharClass', + bnf: [["'['", "'^'?", '%RULE_CharClass_1+', '"]"']] + }, + { + name: '%RULE_CharClass_1', + bnf: [['CharCodeRange'], ['CharRange'], ['CharCode'], ['RULE_Char']], + fragment: true + }, + { + name: 'RULE_Char', + bnf: [[/\x09/], [/\x0A/], [/\x0D/], [/[\x20-\x5c]/], [/[\x5e-\uD7FF]/], [/[\uE000-\uFFFD]/]] + }, + { + name: 'CharRange', + bnf: [['RULE_Char', '"-"', 'RULE_Char']] + }, + { + name: 'CharCodeRange', + bnf: [['CharCode', '"-"', 'CharCode']] + }, + { + name: 'RULE_WHITESPACE', + bnf: [['%RULE_WHITESPACE_CHAR*'], ['Comment', 'RULE_WHITESPACE*']] + }, + { + name: 'RULE_S', + bnf: [['RULE_WHITESPACE', 'RULE_S*'], ['RULE_EOL', 'RULE_S*']] + }, + { + name: '%RULE_WHITESPACE_CHAR', + bnf: [[/\x09/], [/\x20/]], + fragment: true + }, + { + name: 'Comment', + bnf: [['"/*"', '%RULE_Comment_Body*', '"*/"']] + }, + { + name: '%RULE_Comment_Body', + bnf: [['!"*/"', /[^*]/]], + fragment: true + }, + { + name: 'RULE_EOL', + bnf: [[/\x0D/, /\x0A/], [/\x0A/], [/\x0D/]] + }, + { + name: 'Link', + bnf: [["'['", 'Url', "']'"]] + }, + { + name: 'Url', + bnf: [[/[^\x5D:/?#]/, '"://"', /[^\x5D#]+/, '%Url1?']] + }, + { + name: '%Url1', + bnf: [['"#"', 'NCName']], + fragment: true } - return accum; - }, <{ [ name: string ]: boolean }>{ }); -} -*/ -class Interface { - constructor(fragments) { - logger.checkNew(new.target, Interface); - let abi = []; - if (typeof (fragments) === "string") { - abi = JSON.parse(fragments); + ]; + BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); + const preDecorationRE = /^(!|&)/; + const decorationRE = /(\?|\+|\*)$/; + const subExpressionRE = /^%/; + function getBNFRule(name, parser) { + if (typeof name == 'string') { + if (preDecorationRE.test(name)) + return ''; + let subexpression = subExpressionRE.test(name); + if (subexpression) { + let decoration = decorationRE.exec(name); + let decorationText = decoration ? decoration[0] + ' ' : ''; + let lonely = isLonelyRule(name, parser); + if (lonely) + return getBNFBody(name, parser) + decorationText; + return '(' + getBNFBody(name, parser) + ')' + decorationText; + } + return name; } else { - abi = fragments; - } - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "fragments", abi.map((fragment) => { - return _fragments__WEBPACK_IMPORTED_MODULE_3__/* .Fragment.from */ .HY.from(fragment); - }).filter((fragment) => (fragment != null))); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "_abiCoder", (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .getStatic */ .tu)(new.target, "getAbiCoder")()); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "functions", {}); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "errors", {}); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "events", {}); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "structs", {}); - // Add all fragments by their signature - this.fragments.forEach((fragment) => { - let bucket = null; - switch (fragment.type) { - case "constructor": - if (this.deploy) { - logger.warn("duplicate definition - constructor"); - return; - } - //checkNames(fragment, "input", fragment.inputs); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "deploy", fragment); - return; - case "function": - //checkNames(fragment, "input", fragment.inputs); - //checkNames(fragment, "output", (fragment).outputs); - bucket = this.functions; - break; - case "event": - //checkNames(fragment, "input", fragment.inputs); - bucket = this.events; - break; - case "error": - bucket = this.errors; - break; - default: - return; - } - let signature = fragment.format(); - if (bucket[signature]) { - logger.warn("duplicate definition - " + signature); - return; - } - bucket[signature] = fragment; - }); - // If we do not have a constructor add a default - if (!this.deploy) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "deploy", _fragments__WEBPACK_IMPORTED_MODULE_3__/* .ConstructorFragment.from */ .Xg.from({ - payable: false, - type: "constructor" - })); + return name.source + .replace(/\\(?:x|u)([a-zA-Z0-9]+)/g, '#x$1') + .replace(/\[\\(?:x|u)([a-zA-Z0-9]+)-\\(?:x|u)([a-zA-Z0-9]+)\]/g, '[#x$1-#x$2]'); } - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "_isInterface", true); } - format(format) { - if (!format) { - format = _fragments__WEBPACK_IMPORTED_MODULE_3__/* .FormatTypes.full */ .pc.full; - } - if (format === _fragments__WEBPACK_IMPORTED_MODULE_3__/* .FormatTypes.sighash */ .pc.sighash) { - logger.throwArgumentError("interface does not support formatting sighash", "format", format); - } - const abi = this.fragments.map((fragment) => fragment.format(format)); - // We need to re-bundle the JSON fragments a bit - if (format === _fragments__WEBPACK_IMPORTED_MODULE_3__/* .FormatTypes.json */ .pc.json) { - return JSON.stringify(abi.map((j) => JSON.parse(j))); - } - return abi; + /// Returns true if the rule is a string literal or regular expression without a descendant tree + function isLonelyRule(name, parser) { + let rule = Parser_1.findRuleByName(name, parser); + return (rule && + rule.bnf.length == 1 && + rule.bnf[0].length == 1 && + (rule.bnf[0][0] instanceof RegExp || rule.bnf[0][0][0] == '"' || rule.bnf[0][0][0] == "'")); } - // Sub-classes can override these to handle other blockchains - static getAbiCoder() { - return _abi_coder__WEBPACK_IMPORTED_MODULE_4__/* .defaultAbiCoder */ .$; + function getBNFChoice(rules, parser) { + return rules.map(x => getBNFRule(x, parser)).join(' '); } - static getAddress(address) { - return (0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_5__/* .getAddress */ .Kn)(address); - } - static getSighash(fragment) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexDataSlice */ .p3)((0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__.id)(fragment.format()), 0, 4); - } - static getEventTopic(eventFragment) { - return (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__.id)(eventFragment.format()); - } - // Find a function definition by any means necessary (unless it is ambiguous) - getFunction(nameOrSignatureOrSighash) { - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .isHexString */ .A7)(nameOrSignatureOrSighash)) { - for (const name in this.functions) { - if (nameOrSignatureOrSighash === this.getSighash(name)) { - return this.functions[name]; - } - } - logger.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash); - } - // It is a bare name, look up the function (will return null if ambiguous) - if (nameOrSignatureOrSighash.indexOf("(") === -1) { - const name = nameOrSignatureOrSighash.trim(); - const matching = Object.keys(this.functions).filter((f) => (f.split("(" /* fix:) */)[0] === name)); - if (matching.length === 0) { - logger.throwArgumentError("no matching function", "name", name); - } - else if (matching.length > 1) { - logger.throwArgumentError("multiple matching functions", "name", name); - } - return this.functions[matching[0]]; - } - // Normalize the signature and lookup the function - const result = this.functions[_fragments__WEBPACK_IMPORTED_MODULE_3__/* .FunctionFragment.fromString */ .YW.fromString(nameOrSignatureOrSighash).format()]; - if (!result) { - logger.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash); - } - return result; - } - // Find an event definition by any means necessary (unless it is ambiguous) - getEvent(nameOrSignatureOrTopic) { - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .isHexString */ .A7)(nameOrSignatureOrTopic)) { - const topichash = nameOrSignatureOrTopic.toLowerCase(); - for (const name in this.events) { - if (topichash === this.getEventTopic(name)) { - return this.events[name]; - } - } - logger.throwArgumentError("no matching event", "topichash", topichash); - } - // It is a bare name, look up the function (will return null if ambiguous) - if (nameOrSignatureOrTopic.indexOf("(") === -1) { - const name = nameOrSignatureOrTopic.trim(); - const matching = Object.keys(this.events).filter((f) => (f.split("(" /* fix:) */)[0] === name)); - if (matching.length === 0) { - logger.throwArgumentError("no matching event", "name", name); - } - else if (matching.length > 1) { - logger.throwArgumentError("multiple matching events", "name", name); - } - return this.events[matching[0]]; - } - // Normalize the signature and lookup the function - const result = this.events[_fragments__WEBPACK_IMPORTED_MODULE_3__/* .EventFragment.fromString */ .QV.fromString(nameOrSignatureOrTopic).format()]; - if (!result) { - logger.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic); - } - return result; - } - // Find a function definition by any means necessary (unless it is ambiguous) - getError(nameOrSignatureOrSighash) { - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .isHexString */ .A7)(nameOrSignatureOrSighash)) { - const getSighash = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .getStatic */ .tu)(this.constructor, "getSighash"); - for (const name in this.errors) { - const error = this.errors[name]; - if (nameOrSignatureOrSighash === getSighash(error)) { - return this.errors[name]; - } - } - logger.throwArgumentError("no matching error", "sighash", nameOrSignatureOrSighash); - } - // It is a bare name, look up the function (will return null if ambiguous) - if (nameOrSignatureOrSighash.indexOf("(") === -1) { - const name = nameOrSignatureOrSighash.trim(); - const matching = Object.keys(this.errors).filter((f) => (f.split("(" /* fix:) */)[0] === name)); - if (matching.length === 0) { - logger.throwArgumentError("no matching error", "name", name); - } - else if (matching.length > 1) { - logger.throwArgumentError("multiple matching errors", "name", name); - } - return this.errors[matching[0]]; - } - // Normalize the signature and lookup the function - const result = this.errors[_fragments__WEBPACK_IMPORTED_MODULE_3__/* .FunctionFragment.fromString */ .YW.fromString(nameOrSignatureOrSighash).format()]; - if (!result) { - logger.throwArgumentError("no matching error", "signature", nameOrSignatureOrSighash); - } - return result; - } - // Get the sighash (the bytes4 selector) used by Solidity to identify a function - getSighash(fragment) { - if (typeof (fragment) === "string") { - try { - fragment = this.getFunction(fragment); - } - catch (error) { - try { - fragment = this.getError(fragment); - } - catch (_) { - throw error; - } - } - } - return (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .getStatic */ .tu)(this.constructor, "getSighash")(fragment); - } - // Get the topic (the bytes32 hash) used by Solidity to identify an event - getEventTopic(eventFragment) { - if (typeof (eventFragment) === "string") { - eventFragment = this.getEvent(eventFragment); - } - return (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .getStatic */ .tu)(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 bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .arrayify */ .lE)(data); - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(bytes.slice(0, 4)) !== this.getSighash(fragment)) { - logger.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(bytes)); - } - return this._decodeParams(fragment.inputs, bytes.slice(4)); - } - encodeErrorResult(fragment, values) { - if (typeof (fragment) === "string") { - fragment = this.getError(fragment); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .concat */ .zo)([ - this.getSighash(fragment), - this._encodeParams(fragment.inputs, values || []) - ])); - } - // Decode the data for a function call (e.g. tx.data) - decodeFunctionData(functionFragment, data) { - if (typeof (functionFragment) === "string") { - functionFragment = this.getFunction(functionFragment); - } - const bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .arrayify */ .lE)(data); - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) { - logger.throwArgumentError(`data signature does not match function ${functionFragment.name}.`, "data", (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(bytes)); - } - return this._decodeParams(functionFragment.inputs, bytes.slice(4)); - } - // Encode the data for a function call (e.g. tx.data) - encodeFunctionData(functionFragment, values) { - if (typeof (functionFragment) === "string") { - functionFragment = this.getFunction(functionFragment); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .concat */ .zo)([ - this.getSighash(functionFragment), - this._encodeParams(functionFragment.inputs, values || []) - ])); + function getBNFBody(name, parser) { + let rule = Parser_1.findRuleByName(name, parser); + if (rule) + return rule.bnf.map(x => getBNFChoice(x, parser)).join(' | '); + return 'RULE_NOT_FOUND {' + name + '}'; } - // Decode the result from a function call (e.g. from eth_call) - decodeFunctionResult(functionFragment, data) { - if (typeof (functionFragment) === "string") { - functionFragment = this.getFunction(functionFragment); - } - let bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .arrayify */ .lE)(data); - let reason = null; - let errorArgs = null; - let errorName = null; - let errorSignature = null; - switch (bytes.length % this._abiCoder._getWordSize()) { - case 0: - try { - return this._abiCoder.decode(functionFragment.outputs, bytes); - } - catch (error) { } - break; - case 4: { - const selector = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(bytes.slice(0, 4)); - const builtin = BuiltinErrors[selector]; - if (builtin) { - errorArgs = this._abiCoder.decode(builtin.inputs, bytes.slice(4)); - errorName = builtin.name; - errorSignature = builtin.signature; - if (builtin.reason) { - reason = errorArgs[0]; - } - } - else { - try { - const error = this.getError(selector); - errorArgs = this._abiCoder.decode(error.inputs, bytes.slice(4)); - errorName = error.name; - errorSignature = error.format(); - } - catch (error) { - console.log(error); - } - } - break; + function emit(parser) { + let acumulator = []; + parser.grammarRules.forEach(l => { + if (!/^%/.test(l.name)) { + let recover = l.recover ? ' /* { recoverUntil=' + l.recover + ' } */' : ''; + acumulator.push(l.name + ' ::= ' + getBNFBody(l.name, parser) + recover); } - } - return logger.throwError("call revert exception", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION, { - method: functionFragment.format(), - errorArgs, errorName, errorSignature, reason }); + return acumulator.join('\n'); } - // Encode the result for a function call (e.g. for eth_call) - encodeFunctionResult(functionFragment, values) { - if (typeof (functionFragment) === "string") { - functionFragment = this.getFunction(functionFragment); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(this._abiCoder.encode(functionFragment.outputs, values || [])); - } - // Create the filter for the event with search criteria (e.g. for eth_filterLog) - encodeFilterTopics(eventFragment, values) { - if (typeof (eventFragment) === "string") { - eventFragment = this.getEvent(eventFragment); - } - if (values.length > eventFragment.inputs.length) { - logger.throwError("too many arguments for " + eventFragment.format(), _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNEXPECTED_ARGUMENT */ .Yd.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 (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__.id)(value); - } - else if (param.type === "bytes") { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_8__/* .keccak256 */ .w)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(value)); - } - // Check addresses are valid - if (param.type === "address") { - this._abiCoder.encode(["address"], [value]); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexZeroPad */ .$m)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(value), 32); - }; - values.forEach((value, index) => { - let param = eventFragment.inputs[index]; - if (!param.indexed) { - if (value != null) { - logger.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.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value); - } - else if (Array.isArray(value)) { - topics.push(value.map((value) => encodeTopic(param, value))); - } - else { - topics.push(encodeTopic(param, value)); - } - }); - // Trim off trailing nulls - while (topics.length && topics[topics.length - 1] === null) { - topics.pop(); - } - return topics; + BNF.emit = emit; + let subitems = 0; + function restar(total, resta) { + console.log('reberia restar ' + resta + ' a ' + total); + throw new Error('Difference not supported yet'); } - 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.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((0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__.id)(value)); - } - else if (param.type === "bytes") { - topics.push((0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_8__/* .keccak256 */ .w)(value)); - } - else if (param.baseType === "tuple" || param.baseType === "array") { - // @TODO - throw new Error("not implemented"); - } - else { - topics.push(this._abiCoder.encode([param.type], [value])); - } - } - else { - dataTypes.push(param); - dataValues.push(value); - } - }); - return { - data: this._abiCoder.encode(dataTypes, dataValues), - topics: topics - }; + function convertRegex(txt) { + return new RegExp(txt + .replace(/#x([a-zA-Z0-9]{4})/g, '\\u$1') + .replace(/#x([a-zA-Z0-9]{3})/g, '\\u0$1') + .replace(/#x([a-zA-Z0-9]{2})/g, '\\x$1') + .replace(/#x([a-zA-Z0-9]{1})/g, '\\x0$1')); } - // Decode a filter for the event and the search criteria - decodeEventLog(eventFragment, data, topics) { - if (typeof (eventFragment) === "string") { - eventFragment = this.getEvent(eventFragment); - } - if (topics != null && !eventFragment.anonymous) { - let topicHash = this.getEventTopic(eventFragment); - if (!(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .isHexString */ .A7)(topics[0], 32) || topics[0].toLowerCase() !== topicHash) { - logger.throwError("fragment/topic mismatch", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.INVALID_ARGUMENT */ .Yd.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(_fragments__WEBPACK_IMPORTED_MODULE_3__/* .ParamType.fromObject */ ._R.fromObject({ type: "bytes32", name: param.name })); - dynamic.push(true); - } - else { - indexed.push(param); - dynamic.push(false); - } + function getSubItems(tmpRules, seq, parentName) { + let anterior = null; + let bnfSeq = []; + seq.children.forEach((x, i) => { + if (x.type == 'Minus') { + restar(anterior, x); } else { - nonIndexed.push(param); - dynamic.push(false); } - }); - let resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .concat */ .zo)(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++]; + let decoration = seq.children[i + 1]; + decoration = (decoration && decoration.type == 'PrimaryDecoration' && decoration.text) || ''; + let preDecoration = ''; + switch (x.type) { + case 'SubItem': + let name = '%' + (parentName + subitems++); + createRule(tmpRules, x, name); + bnfSeq.push(preDecoration + name + decoration); + break; + case 'NCName': + case 'StringLiteral': + bnfSeq.push(preDecoration + x.text + decoration); + break; + case 'CharCode': + case 'CharClass': + if (decoration || preDecoration) { + let newRule = { + name: '%' + (parentName + subitems++), + bnf: [[convertRegex(x.text)]] + }; + tmpRules.push(newRule); + bnfSeq.push(preDecoration + newRule.name + decoration); } - catch (error) { - result[index] = error; + else { + bnfSeq.push(convertRegex(x.text)); } - } - } - else { - try { - result[index] = resultNonIndexed[nonIndexedIndex++]; - } - catch (error) { - result[index] = error; - } - } - // Add the keyword argument if named and safe - if (param.name && result[param.name] == null) { - const value = result[index]; - // Make error named values throw on access - 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; - } + break; + case 'PrimaryDecoration': + break; + default: + throw new Error(' HOW SHOULD I PARSE THIS? ' + x.type + ' -> ' + JSON.stringify(x.text)); } + anterior = x; }); - // Make all error indexed values throw on access - 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); + return bnfSeq; } - // Given a transaction, find the matching function fragment (if any) and - // determine all its properties and call parameters - 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: _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_9__/* .BigNumber.from */ .O$.from(tx.value || "0"), + function createRule(tmpRules, token, name) { + let bnf = token.children.filter(x => x.type == 'SequenceOrDifference').map(s => getSubItems(tmpRules, s, name)); + let rule = { + name, + bnf + }; + let recover = null; + bnf.forEach(x => { + recover = recover || x['recover']; + delete x['recover']; }); + if (name.indexOf('%') == 0) + rule.fragment = true; + if (recover) + rule.recover = recover; + tmpRules.push(rule); } - // @TODO - //parseCallResult(data: BytesLike): ?? - // Given an event log, find the matching event fragment (if any) and - // determine all its properties and values - parseLog(log) { - let fragment = this.getEvent(log.topics[0]); - if (!fragment || fragment.anonymous) { - return null; + function getRules(source, parser = BNF.defaultParser) { + let ast = parser.getAST(source); + if (!ast) + throw new Error('Could not parse ' + source); + if (ast.errors && ast.errors.length) { + throw ast.errors[0]; } - // @TODO: If anonymous, and the only method, and the input count matches, should we parse? - // Probably not, because just because it is the only event in the ABI does - // not mean we have the full ABI; maybe just a fragment? - return new LogDescription({ - eventFragment: fragment, - name: fragment.name, - signature: fragment.format(), - topic: this.getEventTopic(fragment), - args: this.decodeEventLog(fragment, log.data, log.topics) + let tmpRules = []; + ast.children.filter(x => x.type == 'Production').map((x) => { + let name = x.children.filter(x => x.type == 'NCName')[0].text; + createRule(tmpRules, x, name); }); + return tmpRules; } - parseError(data) { - const hexData = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_6__/* .hexlify */ .Dv)(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), - }); + BNF.getRules = getRules; + function Transform(source, subParser = BNF.defaultParser) { + return getRules(source.join(''), subParser); } - /* - static from(value: Array | string | Interface) { - if (Interface.isInterface(value)) { - return value; + BNF.Transform = Transform; + class Parser extends Parser_1.Parser { + constructor(source, options) { + const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; + super(getRules(source, subParser), options); } - if (typeof(value) === "string") { - return new Interface(JSON.parse(value)); + emitSource() { + return emit(this); } - return new Interface(value); } - */ - static isInterface(value) { - return !!(value && value._isInterface); - } -} -//# sourceMappingURL=interface.js.map + BNF.Parser = Parser; +})(BNF || (BNF = {})); +exports["default"] = BNF; +//# sourceMappingURL=W3CEBNF.js.map /***/ }), -/***/ 2639: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ 652: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Sg": () => (/* binding */ ForkEvent), - "zt": () => (/* binding */ Provider) -}); - -// UNUSED EXPORTS: BlockForkEvent, TransactionForkEvent, TransactionOrderForkEvent - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abstract-provider/lib.esm/_version.js -const version = "abstract-provider/5.5.1"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abstract-provider/lib.esm/index.js - -var __awaiter = (undefined && undefined.__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()); - }); -}; - +Object.defineProperty(exports, "__esModule", ({ value: true })); +var BNF_1 = __webpack_require__(173); +Object.defineProperty(exports, "BNF", ({ enumerable: true, get: function () { return BNF_1.default; } })); +var W3CEBNF_1 = __webpack_require__(575); +Object.defineProperty(exports, "W3C", ({ enumerable: true, get: function () { return W3CEBNF_1.default; } })); +var Custom_1 = __webpack_require__(657); +Object.defineProperty(exports, "Custom", ({ enumerable: true, get: function () { return Custom_1.default; } })); +//# sourceMappingURL=index.js.map +/***/ }), +/***/ 489: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +"use strict"; -const logger = new logger_lib_esm/* Logger */.Yd(version); -; -; -//export type CallTransactionable = { -// call(transaction: TransactionRequest): Promise; -//}; -class ForkEvent extends lib_esm/* Description */.dk { - static isForkEvent(value) { - return !!(value && value._isForkEvent); - } -} -class BlockForkEvent extends (/* unused pure expression or super */ null && (ForkEvent)) { - constructor(blockHash, expiry) { - if (!isHexString(blockHash, 32)) { - logger.throwArgumentError("invalid blockHash", "blockHash", blockHash); - } - super({ - _isForkEvent: true, - _isBlockForkEvent: true, - expiry: (expiry || 0), - blockHash: blockHash - }); - } -} -class TransactionForkEvent extends (/* unused pure expression or super */ null && (ForkEvent)) { - constructor(hash, expiry) { - if (!isHexString(hash, 32)) { - logger.throwArgumentError("invalid transaction hash", "hash", hash); - } - super({ - _isForkEvent: true, - _isTransactionForkEvent: true, - expiry: (expiry || 0), - hash: hash - }); - } -} -class TransactionOrderForkEvent extends (/* unused pure expression or super */ null && (ForkEvent)) { - constructor(beforeHash, afterHash, expiry) { - if (!isHexString(beforeHash, 32)) { - logger.throwArgumentError("invalid transaction hash", "beforeHash", beforeHash); - } - if (!isHexString(afterHash, 32)) { - logger.throwArgumentError("invalid transaction hash", "afterHash", afterHash); - } - super({ - _isForkEvent: true, - _isTransactionOrderForkEvent: true, - expiry: (expiry || 0), - beforeHash: beforeHash, - afterHash: afterHash - }); +// https://www.ics.uci.edu/~pattis/ICS-33/lectures/ebnf.pdf +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Parser = exports.findRuleByName = exports.parseRuleName = exports.escapeRegExp = exports.readToken = void 0; +const UPPER_SNAKE_RE = /^[A-Z0-9_]+$/; +const decorationRE = /(\?|\+|\*)$/; +const preDecorationRE = /^(@|&|!)/; +const WS_RULE = 'WS'; +const TokenError_1 = __webpack_require__(217); +function readToken(txt, expr) { + let result = expr.exec(txt); + if (result && result.index == 0) { + if (result[0].length == 0 && expr.source.length > 0) + return null; + return { + type: null, + text: result[0], + rest: txt.substr(result[0].length), + start: 0, + end: result[0].length - 1, + fullText: result[0], + errors: [], + children: [], + parent: null + }; } + return null; } -/////////////////////////////// -// Exported Abstracts -class Provider { - constructor() { - logger.checkAbstract(new.target, Provider); - (0,lib_esm/* defineReadOnly */.zG)(this, "_isProvider", true); - } - getFeeData() { - return __awaiter(this, void 0, void 0, function* () { - const { block, gasPrice } = yield (0,lib_esm/* resolveProperties */.mE)({ - block: this.getBlock("latest"), - gasPrice: this.getGasPrice().catch((error) => { - // @TODO: Why is this now failing on Calaveras? - //console.log(error); - return null; - }) - }); - let maxFeePerGas = null, maxPriorityFeePerGas = null; - if (block && block.baseFeePerGas) { - // We may want to compute this more accurately in the future, - // using the formula "check if the base fee is correct". - // See: https://eips.ethereum.org/EIPS/eip-1559 - maxPriorityFeePerGas = bignumber/* BigNumber.from */.O$.from("2500000000"); - maxFeePerGas = block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas); - } - return { maxFeePerGas, maxPriorityFeePerGas, gasPrice }; - }); - } - // Alias for "on" - addListener(eventName, listener) { - return this.on(eventName, listener); - } - // Alias for "off" - removeListener(eventName, listener) { - return this.off(eventName, listener); - } - static isProvider(value) { - return !!(value && value._isProvider); - } +exports.readToken = readToken; +function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 4502: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "E": () => (/* binding */ Signer), - "b": () => (/* binding */ VoidSigner) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abstract-signer/lib.esm/_version.js -const version = "abstract-signer/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/abstract-signer/lib.esm/index.js - -var __awaiter = (undefined && undefined.__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 logger = new logger_lib_esm/* Logger */.Yd(version); -const allowedTransactionKeys = [ - "accessList", "chainId", "customData", "data", "from", "gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "to", "type", "value" -]; -const forwardErrors = [ - logger_lib_esm/* Logger.errors.INSUFFICIENT_FUNDS */.Yd.errors.INSUFFICIENT_FUNDS, - logger_lib_esm/* Logger.errors.NONCE_EXPIRED */.Yd.errors.NONCE_EXPIRED, - logger_lib_esm/* Logger.errors.REPLACEMENT_UNDERPRICED */.Yd.errors.REPLACEMENT_UNDERPRICED, -]; -; -; -class Signer { - /////////////////// - // Sub-classes MUST call super - constructor() { - logger.checkAbstract(new.target, Signer); - (0,lib_esm/* defineReadOnly */.zG)(this, "_isSigner", true); - } - /////////////////// - // Sub-classes MAY override these - getBalance(blockTag) { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("getBalance"); - return yield this.provider.getBalance(this.getAddress(), blockTag); - }); - } - getTransactionCount(blockTag) { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("getTransactionCount"); - return yield this.provider.getTransactionCount(this.getAddress(), blockTag); - }); - } - // Populates "from" if unspecified, and estimates the gas for the transaction - estimateGas(transaction) { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("estimateGas"); - const tx = yield (0,lib_esm/* resolveProperties */.mE)(this.checkTransaction(transaction)); - return yield this.provider.estimateGas(tx); - }); - } - // Populates "from" if unspecified, and calls with the transaction - call(transaction, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("call"); - const tx = yield (0,lib_esm/* resolveProperties */.mE)(this.checkTransaction(transaction)); - return yield this.provider.call(tx, blockTag); - }); - } - // Populates all fields in a transaction, signs it and sends it to the network - sendTransaction(transaction) { - return __awaiter(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 __awaiter(this, void 0, void 0, function* () { - this._checkProvider("getChainId"); - const network = yield this.provider.getNetwork(); - return network.chainId; - }); - } - getGasPrice() { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("getGasPrice"); - return yield this.provider.getGasPrice(); - }); - } - getFeeData() { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("getFeeData"); - return yield this.provider.getFeeData(); - }); - } - resolveName(name) { - return __awaiter(this, void 0, void 0, function* () { - this._checkProvider("resolveName"); - return yield this.provider.resolveName(name); - }); - } - // Checks a transaction does not contain invalid keys and if - // no "from" is provided, populates it. - // - does NOT require a provider - // - adds "from" is not present - // - returns a COPY (safe to mutate the result) - // By default called from: (overriding these prevents it) - // - call - // - estimateGas - // - populateTransaction (and therefor sendTransaction) - checkTransaction(transaction) { - for (const key in transaction) { - if (allowedTransactionKeys.indexOf(key) === -1) { - logger.throwArgumentError("invalid transaction key: " + key, "transaction", transaction); +exports.escapeRegExp = escapeRegExp; +function fixRest(token) { + token.rest = ''; + token.children && token.children.forEach(c => fixRest(c)); +} +function fixPositions(token, start) { + token.start += start; + token.end += start; + token.children && token.children.forEach(c => fixPositions(c, token.start)); +} +function agregateErrors(errors, token) { + if (token.errors && token.errors.length) + token.errors.forEach(err => errors.push(err)); + token.children && token.children.forEach(tok => agregateErrors(errors, tok)); +} +function parseRuleName(name) { + let postDecoration = decorationRE.exec(name); + let preDecoration = preDecorationRE.exec(name); + let postDecorationText = (postDecoration && postDecoration[0]) || ''; + let preDecorationText = (preDecoration && preDecoration[0]) || ''; + let out = { + raw: name, + name: name.replace(decorationRE, '').replace(preDecorationRE, ''), + isOptional: postDecorationText == '?' || postDecorationText == '*', + allowRepetition: postDecorationText == '+' || postDecorationText == '*', + atLeastOne: postDecorationText == '+', + lookupPositive: preDecorationText == '&', + lookupNegative: preDecorationText == '!', + pinned: preDecorationText == '@', + lookup: false, + isLiteral: false + }; + out.isLiteral = out.name[0] == "'" || out.name[0] == '"'; + out.lookup = out.lookupNegative || out.lookupPositive; + return out; +} +exports.parseRuleName = parseRuleName; +function findRuleByName(name, parser) { + let parsed = parseRuleName(name); + return parser.cachedRules[parsed.name] || null; +} +exports.findRuleByName = findRuleByName; +/// Removes all the nodes starting with 'RULE_' +function stripRules(token, re) { + if (token.children) { + let localRules = token.children.filter(x => x.type && re.test(x.type)); + for (let i = 0; i < localRules.length; i++) { + let indexOnChildren = token.children.indexOf(localRules[i]); + if (indexOnChildren != -1) { + token.children.splice(indexOnChildren, 1); } } - const tx = (0,lib_esm/* shallowCopy */.DC)(transaction); - if (tx.from == null) { - tx.from = this.getAddress(); - } - else { - // Make sure any provided address matches this signer - tx.from = Promise.all([ - Promise.resolve(tx.from), - this.getAddress() - ]).then((result) => { - if (result[0].toLowerCase() !== result[1].toLowerCase()) { - logger.throwArgumentError("from address mismatch", "transaction", transaction); - } - return result[0]; - }); - } - return tx; + token.children.forEach(c => stripRules(c, re)); } - // Populates ALL keys for a transaction and checks that "from" matches - // this Signer. Should be used by sendTransaction but NOT by signTransaction. - // By default called from: (overriding these prevents it) - // - sendTransaction - // - // Notes: - // - We allow gasPrice for EIP-1559 as long as it matches maxFeePerGas - populateTransaction(transaction) { - return __awaiter(this, void 0, void 0, function* () { - const tx = yield (0,lib_esm/* resolveProperties */.mE)(this.checkTransaction(transaction)); - if (tx.to != null) { - tx.to = Promise.resolve(tx.to).then((to) => __awaiter(this, void 0, void 0, function* () { - if (to == null) { - return null; - } - const address = yield this.resolveName(to); - if (address == null) { - logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to); - } - return address; - })); - // Prevent this error from causing an UnhandledPromiseException - tx.to.catch((error) => { }); - } - // Do not allow mixing pre-eip-1559 and eip-1559 properties - const hasEip1559 = (tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null); - if (tx.gasPrice != null && (tx.type === 2 || hasEip1559)) { - logger.throwArgumentError("eip-1559 transaction do not support gasPrice", "transaction", transaction); - } - else if ((tx.type === 0 || tx.type === 1) && hasEip1559) { - logger.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "transaction", transaction); +} +const ignoreMissingRules = ['EOF']; +class Parser { + constructor(grammarRules, options) { + this.grammarRules = grammarRules; + this.options = options; + this.cachedRules = {}; + this.debug = options ? options.debug === true : false; + let errors = []; + let neededRules = []; + grammarRules.forEach(rule => { + let parsedName = parseRuleName(rule.name); + if (parsedName.name in this.cachedRules) { + errors.push('Duplicated rule ' + parsedName.name); + return; } - if ((tx.type === 2 || tx.type == null) && (tx.maxFeePerGas != null && tx.maxPriorityFeePerGas != null)) { - // Fully-formed EIP-1559 transaction (skip getFeeData) - tx.type = 2; + else { + this.cachedRules[parsedName.name] = rule; } - else if (tx.type === 0 || tx.type === 1) { - // Explicit Legacy or EIP-2930 transaction - // Populate missing gasPrice - if (tx.gasPrice == null) { - tx.gasPrice = this.getGasPrice(); - } + if (!rule.bnf || !rule.bnf.length) { + let error = 'Missing rule content, rule: ' + rule.name; + if (errors.indexOf(error) == -1) + errors.push(error); } else { - // We need to get fee data to determine things - const feeData = yield this.getFeeData(); - if (tx.type == null) { - // We need to auto-detect the intended type of this transaction... - if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { - // The network supports EIP-1559! - // Upgrade transaction from null to eip-1559 - tx.type = 2; - if (tx.gasPrice != null) { - // Using legacy gasPrice property on an eip-1559 network, - // so use gasPrice as both fee properties - const gasPrice = tx.gasPrice; - delete tx.gasPrice; - tx.maxFeePerGas = gasPrice; - tx.maxPriorityFeePerGas = gasPrice; - } - else { - // Populate missing fee data - if (tx.maxFeePerGas == null) { - tx.maxFeePerGas = feeData.maxFeePerGas; - } - if (tx.maxPriorityFeePerGas == null) { - tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - } + rule.bnf.forEach(options => { + if (typeof options[0] === 'string') { + let parsed = parseRuleName(options[0]); + if (parsed.name == rule.name) { + let error = 'Left recursion is not allowed, rule: ' + rule.name; + if (errors.indexOf(error) == -1) + errors.push(error); } } - else if (feeData.gasPrice != null) { - // Network doesn't support EIP-1559... - // ...but they are trying to use EIP-1559 properties - if (hasEip1559) { - logger.throwError("network does not support EIP-1559", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "populateTransaction" - }); - } - // Populate missing fee data - if (tx.gasPrice == null) { - tx.gasPrice = feeData.gasPrice; + options.forEach(option => { + if (typeof option == 'string') { + let name = parseRuleName(option); + if (!name.isLiteral && + neededRules.indexOf(name.name) == -1 && + ignoreMissingRules.indexOf(name.name) == -1) + neededRules.push(name.name); } - // Explicitly set untyped transaction to legacy - tx.type = 0; - } - else { - // getFeeData has failed us. - logger.throwError("failed to get consistent fee data", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "signer.getFeeData" - }); - } - } - else if (tx.type === 2) { - // Explicitly using EIP-1559 - // Populate missing fee data - 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 logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", logger_lib_esm/* Logger.errors.UNPREDICTABLE_GAS_LIMIT */.Yd.errors.UNPREDICTABLE_GAS_LIMIT, { - error: error, - tx: tx }); }); } - if (tx.chainId == null) { - tx.chainId = this.getChainId(); + if (WS_RULE == rule.name) + rule.implicitWs = false; + if (rule.implicitWs) { + if (neededRules.indexOf(WS_RULE) == -1) + neededRules.push(WS_RULE); } - else { - tx.chainId = Promise.all([ - Promise.resolve(tx.chainId), - this.getChainId() - ]).then((results) => { - if (results[1] !== 0 && results[0] !== results[1]) { - logger.throwArgumentError("chainId address mismatch", "transaction", transaction); - } - return results[0]; - }); + if (rule.recover) { + if (neededRules.indexOf(rule.recover) == -1) + neededRules.push(rule.recover); } - return yield (0,lib_esm/* resolveProperties */.mE)(tx); }); - } - /////////////////// - // Sub-classes SHOULD leave these alone - _checkProvider(operation) { - if (!this.provider) { - logger.throwError("missing provider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: (operation || "_checkProvider") - }); - } - } - static isSigner(value) { - return !!(value && value._isSigner); - } -} -class VoidSigner extends Signer { - constructor(address, provider) { - logger.checkNew(new.target, VoidSigner); - super(); - (0,lib_esm/* defineReadOnly */.zG)(this, "address", address); - (0,lib_esm/* defineReadOnly */.zG)(this, "provider", provider || null); - } - getAddress() { - return Promise.resolve(this.address); - } - _fail(message, operation) { - return Promise.resolve().then(() => { - logger.throwError(message, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: operation }); + neededRules.forEach(ruleName => { + if (!(ruleName in this.cachedRules)) { + errors.push('Missing rule ' + ruleName); + } }); + if (errors.length) + throw new Error(errors.join('\n')); } - signMessage(message) { - return this._fail("VoidSigner cannot sign messages", "signMessage"); - } - 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); - } -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9808: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Kn": () => (/* binding */ getAddress), - "CR": () => (/* binding */ getContractAddress), - "hB": () => (/* binding */ getCreate2Address), - "vU": () => (/* binding */ getIcapAddress), - "UJ": () => (/* binding */ isAddress) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/keccak256/lib.esm/index.js -var keccak256_lib_esm = __webpack_require__(2677); -// EXTERNAL MODULE: ../node_modules/@ethersproject/rlp/lib.esm/index.js + 1 modules -var rlp_lib_esm = __webpack_require__(6868); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/address/lib.esm/_version.js -const version = "address/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/address/lib.esm/index.js - - - - - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -function getChecksumAddress(address) { - if (!(0,lib_esm/* isHexString */.A7)(address, 20)) { - logger.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 = (0,lib_esm/* arrayify */.lE)((0,keccak256_lib_esm/* keccak256 */.w)(expanded)); - for (let i = 0; i < 40; i += 2) { - if ((hashed[i >> 1] >> 4) >= 8) { - chars[i] = chars[i].toUpperCase(); + getAST(txt, target) { + if (!target) { + target = this.grammarRules.filter(x => !x.fragment && x.name.indexOf('%') != 0)[0].name; } - if ((hashed[i >> 1] & 0x0f) >= 8) { - chars[i + 1] = chars[i + 1].toUpperCase(); + let result = this.parse(txt, target); + if (result) { + agregateErrors(result.errors, result); + fixPositions(result, 0); + // REMOVE ALL THE TAGS MATCHING /^%/ + stripRules(result, /^%/); + if (!this.options || !this.options.keepUpperRules) + stripRules(result, UPPER_SNAKE_RE); + let rest = result.rest; + if (rest) { + new TokenError_1.TokenError('Unexpected end of input: \n' + rest, result); + } + fixRest(result); + result.rest = rest; } + return result; } - return "0x" + chars.join(""); -} -// Shims for environments that are missing some required constants and functions -const MAX_SAFE_INTEGER = 0x1fffffffffffff; -function log10(x) { - if (Math.log10) { - return Math.log10(x); + emitSource() { + return 'CANNOT EMIT SOURCE FROM BASE Parser'; } - return Math.log(x) / Math.LN10; -} -// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number -// Create lookup table -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); -} -// How many decimal digits can we process? (for 64-bit float, this is 15) -const safeDigits = Math.floor(log10(MAX_SAFE_INTEGER)); -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(""); - // Javascript can handle integers safely up to 15 (decimal) digits - 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") { - logger.throwArgumentError("invalid address", "address", address); - } - if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - // Missing the 0x prefix - if (address.substring(0, 2) !== "0x") { - address = "0x" + address; - } - result = getChecksumAddress(address); - // It is a checksummed address with a bad checksum - if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { - logger.throwArgumentError("bad address checksum", "address", address); - } - // Maybe ICAP? (we only support direct mode) - } - else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - // It is an ICAP address with a bad checksum - if (address.substring(2, 4) !== ibanChecksum(address)) { - logger.throwArgumentError("bad icap checksum", "address", address); - } - result = (0,bignumber/* _base36To16 */.g$)(address.substring(4)); - while (result.length < 40) { - result = "0" + result; - } - result = getChecksumAddress("0x" + result); - } - else { - logger.throwArgumentError("invalid address", "address", address); - } - return result; -} -function isAddress(address) { - try { - getAddress(address); - return true; - } - catch (error) { } - return false; -} -function getIcapAddress(address) { - let base36 = (0,bignumber/* _base16To36 */.t2)(getAddress(address).substring(2)).toUpperCase(); - while (base36.length < 30) { - base36 = "0" + base36; - } - return "XE" + ibanChecksum("XE00" + base36) + base36; -} -// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed -function getContractAddress(transaction) { - let from = null; - try { - from = getAddress(transaction.from); - } - catch (error) { - logger.throwArgumentError("missing from address", "transaction", transaction); - } - const nonce = (0,lib_esm/* stripZeros */.G1)((0,lib_esm/* arrayify */.lE)(bignumber/* BigNumber.from */.O$.from(transaction.nonce).toHexString())); - return getAddress((0,lib_esm/* hexDataSlice */.p3)((0,keccak256_lib_esm/* keccak256 */.w)((0,rlp_lib_esm.encode)([from, nonce])), 12)); -} -function getCreate2Address(from, salt, initCodeHash) { - if ((0,lib_esm/* hexDataLength */.E1)(salt) !== 32) { - logger.throwArgumentError("salt must be 32 bytes", "salt", salt); - } - if ((0,lib_esm/* hexDataLength */.E1)(initCodeHash) !== 32) { - logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash); - } - return getAddress((0,lib_esm/* hexDataSlice */.p3)((0,keccak256_lib_esm/* keccak256 */.w)((0,lib_esm/* concat */.zo)(["0xff", getAddress(from), salt, initCodeHash])), 12)); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 6284: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "J": () => (/* binding */ decode), -/* harmony export */ "c": () => (/* binding */ encode) -/* harmony export */ }); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3756); - - -function decode(textData) { - textData = atob(textData); - const data = []; - for (let i = 0; i < textData.length; i++) { - data.push(textData.charCodeAt(i)); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_0__/* .arrayify */ .lE)(data); -} -function encode(data) { - data = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_0__/* .arrayify */ .lE)(data); - let textData = ""; - for (let i = 0; i < data.length; i++) { - textData += String.fromCharCode(data[i]); - } - return btoa(textData); -} -//# sourceMappingURL=base64.js.map - -/***/ }), - -/***/ 3581: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "eU": () => (/* binding */ Base58) -/* harmony export */ }); -/* unused harmony exports BaseX, Base32 */ -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(300); -/** - * var basex = require("base-x"); - * - * This implementation is heavily based on base-x. The main reason to - * deviate was to prevent the dependency of Buffer. - * - * Contributors: - * - * base-x encoding - * Forked from https://github.com/cryptocoinjs/bs58 - * Originally written by Mike Hearn for BitcoinJ - * Copyright (c) 2011 Google Inc - * Ported to JavaScript by Stefan Thomas - * Merged Buffer refactorings from base58-native by Stephen Pair - * Copyright (c) 2013 BitPay Inc - * - * The MIT License (MIT) - * - * Copyright base-x contributors (c) 2016 - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - */ - - -class BaseX { - constructor(alphabet) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_0__/* .defineReadOnly */ .zG)(this, "alphabet", alphabet); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_0__/* .defineReadOnly */ .zG)(this, "base", alphabet.length); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_0__/* .defineReadOnly */ .zG)(this, "_alphabetMap", {}); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_0__/* .defineReadOnly */ .zG)(this, "_leader", alphabet.charAt(0)); - // pre-compute lookup table - for (let i = 0; i < alphabet.length; i++) { - this._alphabetMap[alphabet.charAt(i)] = i; - } - } - encode(value) { - let source = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_1__/* .arrayify */ .lE)(value); - if (source.length === 0) { - 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; - } - } - let string = ""; - // deal with leading zeros - for (let k = 0; source[k] === 0 && k < source.length - 1; ++k) { - string += this._leader; - } - // convert digits to a string - 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 bytes = []; - if (value.length === 0) { - return new Uint8Array(bytes); - } - bytes.push(0); - for (let i = 0; i < value.length; i++) { - let byte = this._alphabetMap[value[i]]; - if (byte === undefined) { - throw new Error("Non-base" + this.base + " character"); - } - let carry = byte; - for (let j = 0; j < bytes.length; ++j) { - carry += bytes[j] * this.base; - bytes[j] = carry & 0xff; - carry >>= 8; + parse(txt, target, recursion = 0) { + let out = null; + let type = parseRuleName(target); + let expr; + let printable = this.debug && /*!isLiteral &*/ !UPPER_SNAKE_RE.test(type.name); + printable && + console.log(new Array(recursion).join('│ ') + 'Trying to get ' + target + ' from ' + JSON.stringify(txt.split('\n')[0])); + let realType = type.name; + let targetLex = findRuleByName(type.name, this); + if (type.name == 'EOF') { + if (txt.length) { + return null; } - while (carry > 0) { - bytes.push(carry & 0xff); - carry >>= 8; + else if (txt.length == 0) { + return { + type: 'EOF', + text: '', + rest: '', + start: 0, + end: 0, + fullText: '', + errors: [], + children: [], + parent: null + }; } } - // deal with leading zeros - for (let k = 0; value[k] === this._leader && k < value.length - 1; ++k) { - bytes.push(0); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_1__/* .arrayify */ .lE)(new Uint8Array(bytes.reverse())); - } -} -const Base32 = new BaseX("abcdefghijklmnopqrstuvwxyz234567"); -const Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - -//console.log(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj")) -//console.log(Base58.encode(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj"))) -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9251: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "i": () => (/* binding */ version) -/* harmony export */ }); -const version = "bignumber/5.5.0"; -//# sourceMappingURL=_version.js.map - -/***/ }), - -/***/ 3922: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "O$": () => (/* binding */ BigNumber), -/* harmony export */ "Zm": () => (/* binding */ isBigNumberish), -/* harmony export */ "g$": () => (/* binding */ _base36To16), -/* harmony export */ "t2": () => (/* binding */ _base16To36) -/* harmony export */ }); -/* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3785); -/* harmony import */ var bn_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bn_js__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9251); - -/** - * BigNumber - * - * A wrapper around the BN.js object. We use the BN.js library - * because it is used by elliptic, so it is required regardless. - * - */ - -var BN = (bn_js__WEBPACK_IMPORTED_MODULE_0___default().BN); - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_2__/* .version */ .i); -const _constructorGuard = {}; -const MAX_SAFE = 0x1fffffffffffff; -function isBigNumberish(value) { - return (value != null) && (BigNumber.isBigNumber(value) || - (typeof (value) === "number" && (value % 1) === 0) || - (typeof (value) === "string" && !!value.match(/^-?[0-9]+$/)) || - (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(value) || - (typeof (value) === "bigint") || - (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isBytes */ ._t)(value)); -} -// Only warn about passing 10 into radix once -let _warnedToStringRadix = false; -class BigNumber { - constructor(constructorGuard, hex) { - logger.checkNew(new.target, BigNumber); - if (constructorGuard !== _constructorGuard) { - logger.throwError("cannot call constructor directly; use BigNumber.from", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.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("cannot modulo negative values", "mod"); - } - return toBigNumber(toBN(this).umod(value)); - } - pow(other) { - const value = toBN(other); - if (value.isNeg()) { - throwFault("cannot raise to negative values", "pow"); - } - return toBigNumber(toBN(this).pow(value)); - } - and(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("cannot 'and' negative values", "and"); - } - return toBigNumber(toBN(this).and(value)); - } - or(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("cannot 'or' negative values", "or"); - } - return toBigNumber(toBN(this).or(value)); - } - xor(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("cannot 'xor' negative values", "xor"); - } - return toBigNumber(toBN(this).xor(value)); - } - mask(value) { - if (this.isNegative() || value < 0) { - throwFault("cannot mask negative values", "mask"); - } - return toBigNumber(toBN(this).maskn(value)); - } - shl(value) { - if (this.isNegative() || value < 0) { - throwFault("cannot shift negative values", "shl"); - } - return toBigNumber(toBN(this).shln(value)); - } - shr(value) { - if (this.isNegative() || value < 0) { - throwFault("cannot shift negative values", "shr"); - } - return toBigNumber(toBN(this).shrn(value)); - } - eq(other) { - return toBN(this).eq(toBN(other)); - } - lt(other) { - return toBN(this).lt(toBN(other)); - } - lte(other) { - return toBN(this).lte(toBN(other)); - } - gt(other) { - return toBN(this).gt(toBN(other)); - } - gte(other) { - return toBN(this).gte(toBN(other)); - } - isNegative() { - return (this._hex[0] === "-"); - } - isZero() { - return toBN(this).isZero(); - } - toNumber() { - try { - return toBN(this).toNumber(); - } - catch (error) { - throwFault("overflow", "toNumber", this.toString()); - } - return null; - } - toBigInt() { try { - return BigInt(this.toString()); - } - catch (e) { } - return logger.throwError("this platform does not support BigInt", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - value: this.toString() - }); - } - toString() { - // Lots of people expect this, which we do not support, so check (See: #889) - if (arguments.length > 0) { - if (arguments[0] === 10) { - if (!_warnedToStringRadix) { - _warnedToStringRadix = true; - logger.warn("BigNumber.toString does not accept any parameters; base-10 is assumed"); + if (!targetLex && type.isLiteral) { + // tslint:disable-next-line: no-eval + let src = eval(type.name); + if (src === '') { + return { + type: '%%EMPTY%%', + text: '', + rest: txt, + start: 0, + end: 0, + fullText: '', + errors: [], + children: [], + parent: null + }; } + expr = new RegExp(escapeRegExp(src)); + realType = null; } - else if (arguments[0] === 16) { - logger.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNEXPECTED_ARGUMENT */ .Yd.errors.UNEXPECTED_ARGUMENT, {}); - } - else { - logger.throwError("BigNumber.toString does not accept parameters", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNEXPECTED_ARGUMENT */ .Yd.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 logger.throwArgumentError("invalid BigNumber string", "value", value); } - if (typeof (value) === "number") { - if (value % 1) { - throwFault("underflow", "BigNumber.from", value); - } - if (value >= MAX_SAFE || value <= -MAX_SAFE) { - throwFault("overflow", "BigNumber.from", value); + catch (e) { + if (e instanceof ReferenceError) { + console.error(e); } - return BigNumber.from(String(value)); - } - const anyValue = value; - if (typeof (anyValue) === "bigint") { - return BigNumber.from(anyValue.toString()); - } - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isBytes */ ._t)(anyValue)) { - return BigNumber.from((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(anyValue)); + return null; } - if (anyValue) { - // Hexable interface (takes priority) - if (anyValue.toHexString) { - const hex = anyValue.toHexString(); - if (typeof (hex) === "string") { - return BigNumber.from(hex); - } - } - else { - // For now, handle legacy JSON-ified values (goes away in v6) - let hex = anyValue._hex; - // New-form JSON - if (hex == null && anyValue.type === "BigNumber") { - hex = anyValue.hex; - } - if (typeof (hex) === "string") { - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(hex) || (hex[0] === "-" && (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(hex.substring(1)))) { - return BigNumber.from(hex); - } - } + if (expr) { + let result = readToken(txt, expr); + if (result) { + result.type = realType; + return result; } } - return logger.throwArgumentError("invalid BigNumber value", "value", value); - } - static isBigNumber(value) { - return !!(value && value._isBigNumber); - } -} -// Normalize the hex string -function toHex(value) { - // For BN, call on the hex string - if (typeof (value) !== "string") { - return toHex(value.toString(16)); - } - // If negative, prepend the negative sign to the normalized positive value - if (value[0] === "-") { - // Strip off the negative sign - value = value.substring(1); - // Cannot have multiple negative signs (e.g. "--0x04") - if (value[0] === "-") { - logger.throwArgumentError("invalid hex", "value", value); - } - // Call toHex on the positive component - value = toHex(value); - // Do not allow "-0x00" - if (value === "0x00") { - return value; - } - // Negate the value - return "-" + value; - } - // Add a "0x" prefix if missing - if (value.substring(0, 2) !== "0x") { - value = "0x" + value; - } - // Normalize zero - if (value === "0x") { - return "0x00"; - } - // Make the string even length - if (value.length % 2) { - value = "0x0" + value.substring(2); - } - // Trim to smallest even-length string - 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: fault, operation: operation }; - if (value != null) { - params.value = value; - } - return logger.throwError(fault, _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.NUMERIC_FAULT */ .Yd.errors.NUMERIC_FAULT, params); -} -// value should have no prefix -function _base36To16(value) { - return (new BN(value, 36)).toString(16); -} -// value should have no prefix -function _base16To36(value) { - return (new BN(value, 16)).toString(36); -} -//# sourceMappingURL=bignumber.js.map - -/***/ }), - -/***/ 3756: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "lE": () => (/* binding */ arrayify), - "zo": () => (/* binding */ concat), - "xs": () => (/* binding */ hexConcat), - "E1": () => (/* binding */ hexDataLength), - "p3": () => (/* binding */ hexDataSlice), - "Ou": () => (/* binding */ hexStripZeros), - "$P": () => (/* binding */ hexValue), - "$m": () => (/* binding */ hexZeroPad), - "Dv": () => (/* binding */ hexlify), - "_t": () => (/* binding */ isBytes), - "Zq": () => (/* binding */ isBytesLike), - "A7": () => (/* binding */ isHexString), - "gV": () => (/* binding */ joinSignature), - "N": () => (/* binding */ splitSignature), - "G1": () => (/* binding */ stripZeros), - "Bu": () => (/* binding */ zeroPad) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/bytes/lib.esm/_version.js -const version = "bytes/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js - - - -const logger = new lib_esm/* Logger */.Yd(version); -/////////////////////////////// -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") { - logger.checkSafeUint53(value, "invalid arrayify value"); - const result = []; - while (value) { - result.unshift(value & 0xff); - 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 = "0x0" + hex.substring(2); - } - else if (options.hexPad === "right") { - hex += "0"; - } - else { - logger.throwArgumentError("hex data is odd-length", "value", value); + else { + let options = targetLex.bnf; + if (options instanceof Array) { + options.forEach(phases => { + if (out) + return; + let pinned = null; + let tmp = { + type: type.name, + text: '', + children: [], + end: 0, + errors: [], + fullText: '', + parent: null, + start: 0, + rest: txt + }; + if (targetLex.fragment) + tmp.fragment = true; + let tmpTxt = txt; + let position = 0; + let allOptional = phases.length > 0; + let foundSomething = false; + for (let i = 0; i < phases.length; i++) { + if (typeof phases[i] == 'string') { + let localTarget = parseRuleName(phases[i]); + allOptional = allOptional && localTarget.isOptional; + let got; + let foundAtLeastOne = false; + do { + got = null; + if (targetLex.implicitWs) { + got = this.parse(tmpTxt, localTarget.name, recursion + 1); + if (!got) { + let WS; + do { + WS = this.parse(tmpTxt, WS_RULE, recursion + 1); + if (WS) { + tmp.text = tmp.text + WS.text; + tmp.end = tmp.text.length; + WS.parent = tmp; + tmp.children.push(WS); + tmpTxt = tmpTxt.substr(WS.text.length); + position += WS.text.length; + } + else { + break; + } + } while (WS && WS.text.length); + } + } + got = got || this.parse(tmpTxt, localTarget.name, recursion + 1); + // rule ::= "true" ![a-zA-Z] + // negative lookup, if it does not match, we should continue + if (localTarget.lookupNegative) { + if (got) + return /* cancel this path */; + break; + } + if (localTarget.lookupPositive) { + if (!got) + return; + } + if (!got) { + if (localTarget.isOptional) + break; + if (localTarget.atLeastOne && foundAtLeastOne) + break; + } + if (got && targetLex.pinned == i + 1) { + pinned = got; + printable && console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' PINNED'); + } + if (!got) + got = this.parseRecovery(targetLex, tmpTxt, recursion + 1); + if (!got) { + if (pinned) { + out = tmp; + got = { + type: 'SyntaxError', + text: tmpTxt, + children: [], + end: tmpTxt.length, + errors: [], + fullText: '', + parent: null, + start: 0, + rest: '' + }; + if (tmpTxt.length) { + new TokenError_1.TokenError(`Unexpected end of input. Expecting ${localTarget.name} Got: ${tmpTxt}`, got); + } + else { + new TokenError_1.TokenError(`Unexpected end of input. Missing ${localTarget.name}`, got); + } + printable && + console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' ' + JSON.stringify(got.text)); + } + else { + return; + } + } + foundAtLeastOne = true; + foundSomething = true; + if (got.type == '%%EMPTY%%') { + break; + } + got.start += position; + got.end += position; + if (!localTarget.lookupPositive && got.type) { + if (got.fragment) { + got.children && + got.children.forEach(x => { + x.start += position; + x.end += position; + x.parent = tmp; + tmp.children.push(x); + }); + } + else { + got.parent = tmp; + tmp.children.push(got); + } + } + if (localTarget.lookup) + got.lookup = true; + printable && + console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' ' + JSON.stringify(got.text)); + // Eat it from the input stream, only if it is not a lookup + if (!localTarget.lookup && !got.lookup) { + tmp.text = tmp.text + got.text; + tmp.end = tmp.text.length; + tmpTxt = tmpTxt.substr(got.text.length); + position += got.text.length; + } + tmp.rest = tmpTxt; + } while (got && localTarget.allowRepetition && tmpTxt.length && !got.lookup); + } /* IS A REGEXP */ + else { + let got = readToken(tmpTxt, phases[i]); + if (!got) { + return; + } + printable && + console.log(new Array(recursion + 1).join('│ ') + '└> ' + JSON.stringify(got.text) + phases[i].source); + foundSomething = true; + got.start += position; + got.end += position; + tmp.text = tmp.text + got.text; + tmp.end = tmp.text.length; + tmpTxt = tmpTxt.substr(got.text.length); + position += got.text.length; + tmp.rest = tmpTxt; + } + } + if (foundSomething) { + out = tmp; + printable && + console.log(new Array(recursion).join('│ ') + '├<─┴< PUSHING ' + out.type + ' ' + JSON.stringify(out.text)); + } + }); } - } - 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 logger.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; - } - // Find the first non-zero entry - let start = 0; - while (start < result.length && result[start] === 0) { - start++; - } - // If we started with zeros, strip them - if (start) { - result = result.slice(start); - } - return result; -} -function zeroPad(value, length) { - value = arrayify(value); - if (value.length > length) { - logger.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") { - logger.checkSafeUint53(value, "invalid hexlify value"); - let hex = ""; - while (value) { - hex = HexCharacters[value & 0xf] + hex; - value = Math.floor(value / 16); - } - if (hex.length) { - if (hex.length % 2) { - hex = "0" + hex; + if (out && targetLex.simplifyWhenOneChildren && out.children.length == 1) { + out = out.children[0]; } - return "0x" + hex; } - return "0x00"; - } - if (typeof (value) === "bigint") { - value = value.toString(16); - if (value.length % 2) { - return ("0x0" + value); + if (!out) { + printable && console.log(target + ' NOT RESOLVED FROM ' + txt); } - return "0x" + value; - } - if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") { - value = "0x" + value; - } - if (isHexable(value)) { - return value.toHexString(); + return out; } - if (isHexString(value)) { - if (value.length % 2) { - if (options.hexPad === "left") { - value = "0x0" + value.substring(2); - } - else if (options.hexPad === "right") { - value += "0"; - } - else { - logger.throwArgumentError("hex data is odd-length", "value", value); + parseRecovery(recoverableToken, tmpTxt, recursion) { + if (recoverableToken.recover && tmpTxt.length) { + let printable = this.debug; + printable && + console.log(new Array(recursion + 1).join('│ ') + + 'Trying to recover until token ' + + recoverableToken.recover + + ' from ' + + JSON.stringify(tmpTxt.split('\n')[0] + tmpTxt.split('\n')[1])); + let tmp = { + type: 'SyntaxError', + text: '', + children: [], + end: 0, + errors: [], + fullText: '', + parent: null, + start: 0, + rest: '' + }; + let got; + do { + got = this.parse(tmpTxt, recoverableToken.recover, recursion + 1); + if (got) { + new TokenError_1.TokenError('Unexpected input: "' + tmp.text + `" Expecting: ${recoverableToken.name}`, tmp); + break; + } + else { + tmp.text = tmp.text + tmpTxt[0]; + tmp.end = tmp.text.length; + tmpTxt = tmpTxt.substr(1); + } + } while (!got && tmpTxt.length > 0); + if (tmp.text.length > 0 && got) { + printable && console.log(new Array(recursion + 1).join('│ ') + 'Recovered text: ' + JSON.stringify(tmp.text)); + return tmp; } } - return value.toLowerCase(); - } - if (isBytes(value)) { - let result = "0x"; - for (let i = 0; i < value.length; i++) { - let v = value[i]; - result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; - } - return result; - } - return logger.throwArgumentError("invalid hexlify value", "value", value); -} -/* -function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number { - if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") { - return "0x0" + value.substring(2); - } - return 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)) { - logger.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)) { - logger.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)) { - logger.throwArgumentError("invalid hex string", "value", value); - } - if (value.length > 2 * length + 2) { - logger.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 - }; - if (isBytesLike(signature)) { - const bytes = arrayify(signature); - if (bytes.length !== 65) { - logger.throwArgumentError("invalid signature string; must be 65 bytes", "signature", signature); - } - // Get the r, s and v - result.r = hexlify(bytes.slice(0, 32)); - result.s = hexlify(bytes.slice(32, 64)); - result.v = bytes[64]; - // Allow a recid to be used as the v - if (result.v < 27) { - if (result.v === 0 || result.v === 1) { - result.v += 27; - } - else { - logger.throwArgumentError("signature invalid v byte", "signature", signature); - } - } - // Compute recoveryParam from v - result.recoveryParam = 1 - (result.v % 2); - // Compute _vs from recoveryParam and s - if (result.recoveryParam) { - bytes[32] |= 0x80; - } - 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 the _vs is available, use it to populate missing s, v and recoveryParam - // and verify non-missing s, v and recoveryParam - if (result._vs != null) { - const vs = zeroPad(arrayify(result._vs), 32); - result._vs = hexlify(vs); - // Set or check the recid - const recoveryParam = ((vs[0] >= 128) ? 1 : 0); - if (result.recoveryParam == null) { - result.recoveryParam = recoveryParam; - } - else if (result.recoveryParam !== recoveryParam) { - logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature); - } - // Set or check the s - vs[0] &= 0x7f; - const s = hexlify(vs); - if (result.s == null) { - result.s = s; - } - else if (result.s !== s) { - logger.throwArgumentError("signature v mismatch _vs", "signature", signature); - } - } - // Use recid and v to populate each other - if (result.recoveryParam == null) { - if (result.v == null) { - logger.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) { - logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature); - } - } - } - if (result.r == null || !isHexString(result.r)) { - logger.throwArgumentError("signature missing or invalid r", "signature", signature); - } - else { - result.r = hexZeroPad(result.r, 32); - } - if (result.s == null || !isHexString(result.s)) { - logger.throwArgumentError("signature missing or invalid s", "signature", signature); - } - else { - result.s = hexZeroPad(result.s, 32); - } - const vs = arrayify(result.s); - if (vs[0] >= 128) { - logger.throwArgumentError("signature s out of range", "signature", signature); - } - if (result.recoveryParam) { - vs[0] |= 0x80; - } - const _vs = hexlify(vs); - if (result._vs) { - if (!isHexString(result._vs)) { - logger.throwArgumentError("signature invalid _vs", "signature", signature); - } - result._vs = hexZeroPad(result._vs, 32); - } - // Set or check the _vs - if (result._vs == null) { - result._vs = _vs; - } - else if (result._vs !== _vs) { - logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature); - } - } - return result; -} -function joinSignature(signature) { - signature = splitSignature(signature); - return hexlify(concat([ - signature.r, - signature.s, - (signature.recoveryParam ? "0x1c" : "0x1b") - ])); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 1210: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "d": () => (/* binding */ AddressZero) -/* harmony export */ }); -const AddressZero = "0x0000000000000000000000000000000000000000"; -//# sourceMappingURL=addresses.js.map - -/***/ }), - -/***/ 5733: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "$B": () => (/* binding */ MinInt256), -/* harmony export */ "Bz": () => (/* binding */ MaxUint256), -/* harmony export */ "Ce": () => (/* binding */ WeiPerEther), -/* harmony export */ "PS": () => (/* binding */ MaxInt256), -/* harmony export */ "Py": () => (/* binding */ Two), -/* harmony export */ "_Y": () => (/* binding */ Zero), -/* harmony export */ "fh": () => (/* binding */ One), -/* harmony export */ "tL": () => (/* binding */ NegativeOne) -/* harmony export */ }); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3922); - -const NegativeOne = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from(-1)); -const Zero = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from(0)); -const One = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from(1)); -const Two = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from(2)); -const WeiPerEther = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from("1000000000000000000")); -const MaxUint256 = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); -const MinInt256 = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from("-0x8000000000000000000000000000000000000000000000000000000000000000")); -const MaxInt256 = ( /*#__PURE__*/_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_0__/* .BigNumber.from */ .O$.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); - -//# sourceMappingURL=bignumbers.js.map - -/***/ }), - -/***/ 2728: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "R": () => (/* binding */ HashZero) -/* harmony export */ }); -const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000"; -//# sourceMappingURL=hashes.js.map - -/***/ }), - -/***/ 3726: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "VZ": () => (/* binding */ BaseContract), - "CH": () => (/* binding */ Contract), - "lV": () => (/* binding */ ContractFactory) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js -var abstract_coder = __webpack_require__(4364); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/interface.js -var lib_esm_interface = __webpack_require__(3017); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abstract-provider/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(2639); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abstract-signer/lib.esm/index.js + 1 modules -var abstract_signer_lib_esm = __webpack_require__(4502); -// EXTERNAL MODULE: ../node_modules/@ethersproject/address/lib.esm/index.js + 1 modules -var address_lib_esm = __webpack_require__(9808); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var bytes_lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/transactions/lib.esm/index.js + 1 modules -var transactions_lib_esm = __webpack_require__(9165); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/contracts/lib.esm/_version.js -const version = "contracts/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/contracts/lib.esm/index.js - -var __awaiter = (undefined && undefined.__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 logger = new logger_lib_esm/* Logger */.Yd(version); -; -; -/////////////////////////////// -const allowedTransactionKeys = { - 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 -}; -function resolveName(resolver, nameOrPromise) { - return __awaiter(this, void 0, void 0, function* () { - const name = yield nameOrPromise; - if (typeof (name) !== "string") { - logger.throwArgumentError("invalid address or ENS name", "name", name); - } - // If it is already an address, just use it (after adding checksum) - try { - return (0,address_lib_esm/* getAddress */.Kn)(name); - } - catch (error) { } - if (!resolver) { - logger.throwError("a provider or signer is needed to resolve ENS names", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "resolveName" - }); - } - const address = yield resolver.resolveName(name); - if (address == null) { - logger.throwArgumentError("resolver or addr is not configured for ENS name", "name", name); - } - return address; - }); -} -// Recursively replaces ENS names with promises to resolve the name and resolves all properties -function resolveAddresses(resolver, value, paramType) { - return __awaiter(this, void 0, void 0, function* () { - if (Array.isArray(paramType)) { - return yield Promise.all(paramType.map((paramType, index) => { - return resolveAddresses(resolver, ((Array.isArray(value)) ? value[index] : value[paramType.name]), paramType); - })); - } - 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(logger.makeError("invalid value for array", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "value", - value - })); - } - return yield Promise.all(value.map((v) => resolveAddresses(resolver, v, paramType.arrayChildren))); - } - return value; - }); -} -function populateTransaction(contract, fragment, args) { - return __awaiter(this, void 0, void 0, function* () { - // If an extra argument is given, it is overrides - let overrides = {}; - if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") { - overrides = (0,properties_lib_esm/* shallowCopy */.DC)(args.pop()); - } - // Make sure the parameter count matches - logger.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract"); - // Populate "from" override (allow promises) - if (contract.signer) { - if (overrides.from) { - // Contracts with a Signer are from the Signer's frame-of-reference; - // but we allow overriding "from" if it matches the signer - overrides.from = (0,properties_lib_esm/* resolveProperties */.mE)({ - override: resolveName(contract.signer, overrides.from), - signer: contract.signer.getAddress() - }).then((check) => __awaiter(this, void 0, void 0, function* () { - if ((0,address_lib_esm/* getAddress */.Kn)(check.signer) !== check.override) { - logger.throwError("Contract with a Signer cannot override from", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.from" - }); - } - return check.override; - })); - } - else { - overrides.from = contract.signer.getAddress(); - } - } - else if (overrides.from) { - overrides.from = resolveName(contract.provider, overrides.from); - //} else { - // Contracts without a signer can override "from", and if - // unspecified the zero address is used - //overrides.from = AddressZero; - } - // Wait for all dependencies to be resolved (prefer the signer over the provider) - const resolved = yield (0,properties_lib_esm/* resolveProperties */.mE)({ - args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs), - address: contract.resolvedAddress, - overrides: ((0,properties_lib_esm/* resolveProperties */.mE)(overrides) || {}) - }); - // The ABI coded transaction - const data = contract.interface.encodeFunctionData(fragment, resolved.args); - const tx = { - data: data, - to: resolved.address - }; - // Resolved Overrides - const ro = resolved.overrides; - // Populate simple overrides - if (ro.nonce != null) { - tx.nonce = bignumber/* BigNumber.from */.O$.from(ro.nonce).toNumber(); - } - if (ro.gasLimit != null) { - tx.gasLimit = bignumber/* BigNumber.from */.O$.from(ro.gasLimit); - } - if (ro.gasPrice != null) { - tx.gasPrice = bignumber/* BigNumber.from */.O$.from(ro.gasPrice); - } - if (ro.maxFeePerGas != null) { - tx.maxFeePerGas = bignumber/* BigNumber.from */.O$.from(ro.maxFeePerGas); - } - if (ro.maxPriorityFeePerGas != null) { - tx.maxPriorityFeePerGas = bignumber/* BigNumber.from */.O$.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 = (0,transactions_lib_esm/* accessListify */.z7)(ro.accessList); - } - // If there was no "gasLimit" override, but the ABI specifies a default, use it - if (tx.gasLimit == null && fragment.gas != null) { - // Compute the intrinsic gas cost for this transaction - // @TODO: This is based on the yellow paper as of Petersburg; this is something - // we may wish to parameterize in v6 as part of the Network object. Since this - // is always a non-nil to address, we can ignore G_create, but may wish to add - // similar logic to the ContractFactory. - let intrinsic = 21000; - const bytes = (0,bytes_lib_esm/* arrayify */.lE)(data); - for (let i = 0; i < bytes.length; i++) { - intrinsic += 4; - if (bytes[i]) { - intrinsic += 64; - } - } - tx.gasLimit = bignumber/* BigNumber.from */.O$.from(fragment.gas).add(intrinsic); - } - // Populate "value" override - if (ro.value) { - const roValue = bignumber/* BigNumber.from */.O$.from(ro.value); - if (!roValue.isZero() && !fragment.payable) { - logger.throwError("non-payable method cannot override value", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.value", - value: overrides.value - }); - } - tx.value = roValue; - } - if (ro.customData) { - tx.customData = (0,properties_lib_esm/* shallowCopy */.DC)(ro.customData); - } - // Remove the overrides - 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; - // Make sure there are no stray overrides, which may indicate a - // typo or using an unsupported key. - const leftovers = Object.keys(overrides).filter((key) => (overrides[key] != null)); - if (leftovers.length) { - logger.throwError(`cannot override ${leftovers.map((l) => JSON.stringify(l)).join(",")}`, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.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 __awaiter(this, void 0, void 0, function* () { - if (!signerOrProvider) { - logger.throwError("estimate require a provider or signer", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.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 = (0,properties_lib_esm/* deepCopy */.p$)(log); - let parsed = null; - try { - parsed = contract.interface.parseLog(log); - } - catch (e) { } - // Successfully parsed the event log; include it - 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; - } - // Useful operations - 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 __awaiter(this, void 0, void 0, function* () { - // Extract the "blockTag" override if present - let blockTag = undefined; - if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") { - const overrides = (0,properties_lib_esm/* shallowCopy */.DC)(args.pop()); - if (overrides.blockTag != null) { - blockTag = yield overrides.blockTag; - } - delete overrides.blockTag; - args.push(overrides); - } - // If the contract was just deployed, wait until it is mined - if (contract.deployTransaction != null) { - yield contract._deployed(blockTag); - } - // Call a node and get the result - 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_lib_esm/* Logger.errors.CALL_EXCEPTION */.Yd.errors.CALL_EXCEPTION) { - error.address = contract.address; - error.args = args; - error.transaction = tx; - } - throw error; - } - }); - }; -} -function buildSend(contract, fragment) { - return function (...args) { - return __awaiter(this, void 0, void 0, function* () { - if (!contract.signer) { - logger.throwError("sending a transaction requires a signer", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "sendTransaction" - }); - } - // If the contract was just deployed, wait until it is mined - if (contract.deployTransaction != null) { - yield contract._deployed(); - } - const txRequest = yield populateTransaction(contract, fragment, args); - const tx = yield contract.signer.sendTransaction(txRequest); - // Tweak the tx.wait so the receipt has extra properties - addContractWait(contract, tx); - return tx; - }); - }; -} -function buildDefault(contract, fragment, collapseSimple) { - if (fragment.constant) { - return buildCall(contract, fragment, collapseSimple); - } - return buildSend(contract, fragment); -} -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(":") : ""); -} -class RunningEvent { - constructor(tag, filter) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "tag", tag); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "filter", filter); - this._listeners = []; - } - addListener(listener, once) { - this._listeners.push({ listener: listener, once: 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; - } - run(args) { - const listenerCount = this.listenerCount(); - this._listeners = this._listeners.filter((item) => { - const argsCopy = args.slice(); - // Call the callback in the next event loop - setTimeout(() => { - item.listener.apply(this, argsCopy); - }, 0); - // Reschedule it if it not "once" - return !(item.once); - }); - return listenerCount; - } - prepareEvent(event) { - } - // Returns the array that will be applied to an emit - getEmit(event) { - return [event]; - } -} -class ErrorRunningEvent extends RunningEvent { - constructor() { - super("error", null); - } -} -// @TODO Fragment should inherit Wildcard? and just override getEmit? -// or have a common abstract super class, with enough constructor -// options to configure both. -// A Fragment Event will populate all the properties that Wildcard -// will, and additionally dereference the arguments when emitting -class FragmentRunningEvent extends RunningEvent { - constructor(address, contractInterface, fragment, topics) { - const filter = { - address: address - }; - let topic = contractInterface.getEventTopic(fragment); - if (topics) { - if (topic !== topics[0]) { - logger.throwArgumentError("topic mismatch", "topics", topics); - } - filter.topics = topics.slice(); - } - else { - filter.topics = [topic]; - } - super(getEventTag(filter), filter); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", address); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "interface", contractInterface); - (0,properties_lib_esm/* defineReadOnly */.zG)(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; - } - } - getEmit(event) { - const errors = (0,abstract_coder/* checkResultErrors */.BR)(event.args); - if (errors.length) { - throw errors[0].error; - } - const args = (event.args || []).slice(); - args.push(event); - return args; - } -} -// A Wildcard Event will attempt to populate: -// - event The name of the event name -// - eventSignature The full signature of the event -// - decode A function to decode data and topics -// - args The decoded data and topics -class WildcardRunningEvent extends RunningEvent { - constructor(address, contractInterface) { - super("*", { address: address }); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", address); - (0,properties_lib_esm/* defineReadOnly */.zG)(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) { - // No matching event - } - } -} -class BaseContract { - constructor(addressOrName, contractInterface, signerOrProvider) { - logger.checkNew(new.target, Contract); - // @TODO: Maybe still check the addressOrName looks like a valid address or name? - //address = getAddress(address); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "interface", (0,properties_lib_esm/* getStatic */.tu)(new.target, "getInterface")(contractInterface)); - if (signerOrProvider == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "provider", null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "signer", null); - } - else if (abstract_signer_lib_esm/* Signer.isSigner */.E.isSigner(signerOrProvider)) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "provider", signerOrProvider.provider || null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "signer", signerOrProvider); - } - else if (lib_esm/* Provider.isProvider */.zt.isProvider(signerOrProvider)) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "provider", signerOrProvider); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "signer", null); - } - else { - logger.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "callStatic", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "estimateGas", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "functions", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "populateTransaction", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "filters", {}); - { - const uniqueFilters = {}; - Object.keys(this.interface.events).forEach((eventSignature) => { - const event = this.interface.events[eventSignature]; - (0,properties_lib_esm/* defineReadOnly */.zG)(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) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.filters, name, this.filters[filters[0]]); - } - else { - logger.warn(`Duplicate definition of ${name} (${filters.join(", ")})`); - } - }); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_runningEvents", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_wrappedEmits", {}); - if (addressOrName == null) { - logger.throwArgumentError("invalid contract address or ENS name", "addressOrName", addressOrName); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", addressOrName); - if (this.provider) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "resolvedAddress", resolveName(this.provider, addressOrName)); - } - else { - try { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "resolvedAddress", Promise.resolve((0,address_lib_esm/* getAddress */.Kn)(addressOrName))); - } - catch (error) { - // Without a provider, we cannot use ENS names - logger.throwError("provider is required to use ENS name as contract address", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "new Contract" - }); - } - } - const uniqueNames = {}; - const uniqueSignatures = {}; - Object.keys(this.interface.functions).forEach((signature) => { - const fragment = this.interface.functions[signature]; - // Check that the signature is unique; if not the ABI generation has - // not been cleaned or may be incorrectly generated - if (uniqueSignatures[signature]) { - logger.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`); - return; - } - uniqueSignatures[signature] = true; - // Track unique names; we only expose bare named functions if they - // are ambiguous - { - const name = fragment.name; - if (!uniqueNames[`%${name}`]) { - uniqueNames[`%${name}`] = []; - } - uniqueNames[`%${name}`].push(signature); - } - if (this[signature] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, signature, buildDefault(this, fragment, true)); - } - // We do not collapse simple calls on this bucket, which allows - // frameworks to safely use this without introspection as well as - // allows decoding error recovery. - if (this.functions[signature] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.functions, signature, buildDefault(this, fragment, false)); - } - if (this.callStatic[signature] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.callStatic, signature, buildCall(this, fragment, true)); - } - if (this.populateTransaction[signature] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.populateTransaction, signature, buildPopulate(this, fragment)); - } - if (this.estimateGas[signature] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.estimateGas, signature, buildEstimate(this, fragment)); - } - }); - Object.keys(uniqueNames).forEach((name) => { - // Ambiguous names to not get attached as bare names - const signatures = uniqueNames[name]; - if (signatures.length > 1) { - return; - } - // Strip off the leading "%" used for prototype protection - name = name.substring(1); - const signature = signatures[0]; - // If overwriting a member property that is null, swallow the error - try { - if (this[name] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, name, this[signature]); - } - } - catch (e) { } - if (this.functions[name] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.functions, name, this.functions[signature]); - } - if (this.callStatic[name] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.callStatic, name, this.callStatic[signature]); - } - if (this.populateTransaction[name] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.populateTransaction, name, this.populateTransaction[signature]); - } - if (this.estimateGas[name] == null) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this.estimateGas, name, this.estimateGas[signature]); - } - }); - } - static getContractAddress(transaction) { - return (0,address_lib_esm/* getContractAddress */.CR)(transaction); - } - static getInterface(contractInterface) { - if (lib_esm_interface/* Interface.isInterface */.vU.isInterface(contractInterface)) { - return contractInterface; - } - return new lib_esm_interface/* Interface */.vU(contractInterface); - } - // @TODO: Allow timeout? - deployed() { - return this._deployed(); - } - _deployed(blockTag) { - if (!this._deployedPromise) { - // If we were just deployed, we know the transaction we should occur in - if (this.deployTransaction) { - this._deployedPromise = this.deployTransaction.wait().then(() => { - return this; - }); - } - else { - // @TODO: Once we allow a timeout to be passed in, we will wait - // up to that many blocks for getCode - // Otherwise, poll for our code to be deployed - this._deployedPromise = this.provider.getCode(this.address, blockTag).then((code) => { - if (code === "0x") { - logger.throwError("contract not deployed", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - contractAddress: this.address, - operation: "getDeployed" - }); - } - return this; - }); - } - } - return this._deployedPromise; - } - // @TODO: - // estimateFallback(overrides?: TransactionRequest): Promise - // @TODO: - // estimateDeploy(bytecode: string, ...args): Promise - fallback(overrides) { - if (!this.signer) { - logger.throwError("sending a transactions require a signer", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" }); - } - const tx = (0,properties_lib_esm/* shallowCopy */.DC)(overrides || {}); - ["from", "to"].forEach(function (key) { - if (tx[key] == null) { - return; - } - logger.throwError("cannot override " + key, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: key }); - }); - tx.to = this.resolvedAddress; - return this.deployed().then(() => { - return this.signer.sendTransaction(tx); - }); - } - // Reconnect to a different signer or provider - connect(signerOrProvider) { - if (typeof (signerOrProvider) === "string") { - signerOrProvider = new abstract_signer_lib_esm/* VoidSigner */.b(signerOrProvider, this.provider); - } - const contract = new (this.constructor)(this.address, this.interface, signerOrProvider); - if (this.deployTransaction) { - (0,properties_lib_esm/* defineReadOnly */.zG)(contract, "deployTransaction", this.deployTransaction); - } - return contract; - } - // Re-attach to a different on-chain instance of this contract - attach(addressOrName) { - return new (this.constructor)(addressOrName, this.interface, this.signer || this.provider); - } - static isIndexed(value) { - return lib_esm_interface/* Indexed.isIndexed */.Hk.isIndexed(value); - } - _normalizeRunningEvent(runningEvent) { - // Already have an instance of this event running; we can re-use it - if (this._runningEvents[runningEvent.tag]) { - return this._runningEvents[runningEvent.tag]; - } - return runningEvent; - } - _getRunningEvent(eventName) { - if (typeof (eventName) === "string") { - // Listen for "error" events (if your contract has an error event, include - // the full signature to bypass this special event keyword) - if (eventName === "error") { - return this._normalizeRunningEvent(new ErrorRunningEvent()); - } - // Listen for any event that is registered - if (eventName === "event") { - return this._normalizeRunningEvent(new RunningEvent("event", null)); - } - // Listen for any event - if (eventName === "*") { - return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface)); - } - // Get the event Fragment (throws if ambiguous/unknown event) - const fragment = this.interface.getEvent(eventName); - return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment)); - } - // We have topics to filter by... - if (eventName.topics && eventName.topics.length > 0) { - // Is it a known topichash? (throws if no matching topichash) - try { - const topic = eventName.topics[0]; - if (typeof (topic) !== "string") { - throw new Error("invalid topic"); // @TODO: May happen for anonymous events - } - const fragment = this.interface.getEvent(topic); - return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics)); - } - catch (error) { } - // Filter by the unknown topichash - 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]; - // If we have a poller for this, remove it - const emit = this._wrappedEmits[runningEvent.tag]; - if (emit && runningEvent.filter) { - this.provider.off(runningEvent.filter, emit); - delete this._wrappedEmits[runningEvent.tag]; - } - } - } - // Subclasses can override this to gracefully recover - // from parse errors if they wish - _wrapEvent(runningEvent, log, listener) { - const event = (0,properties_lib_esm/* deepCopy */.p$)(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); }; - // This may throw if the topics and data mismatch the signature - runningEvent.prepareEvent(event); - return event; - } - _addEventListener(runningEvent, listener, once) { - if (!this.provider) { - logger.throwError("events require a provider or a signer with a provider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: "once" }); - } - runningEvent.addListener(listener, once); - // Track this running event and its listeners (may already be there; but no hard in updating) - this._runningEvents[runningEvent.tag] = runningEvent; - // If we are not polling the provider, start polling - if (!this._wrappedEmits[runningEvent.tag]) { - const wrappedEmit = (log) => { - let event = this._wrapEvent(runningEvent, log, listener); - // Try to emit the result for the parameterized event... - if (event.decodeError == null) { - try { - const args = runningEvent.getEmit(event); - this.emit(runningEvent.filter, ...args); - } - catch (error) { - event.decodeError = error.error; - } - } - // Always emit "event" for fragment-base events - if (runningEvent.filter != null) { - this.emit("event", event); - } - // Emit "error" if there was an error - if (event.decodeError != null) { - this.emit("error", event.decodeError, event); - } - }; - this._wrappedEmits[runningEvent.tag] = wrappedEmit; - // Special events, like "error" do not have a filter - if (runningEvent.filter != null) { - this.provider.on(runningEvent.filter, wrappedEmit); - } - } - } - queryFilter(event, fromBlockOrBlockhash, toBlock) { - const runningEvent = this._getRunningEvent(event); - const filter = (0,properties_lib_esm/* shallowCopy */.DC)(runningEvent.filter); - if (typeof (fromBlockOrBlockhash) === "string" && (0,bytes_lib_esm/* isHexString */.A7)(fromBlockOrBlockhash, 32)) { - if (toBlock != null) { - logger.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)); - }); - } - 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); - // May have drained all the "once" events; check for living events - 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; - } - if (eventName == null) { - for (const tag in this._runningEvents) { - const runningEvent = this._runningEvents[tag]; - runningEvent.removeAllListeners(); - this._checkRunningEvents(runningEvent); - } - return this; - } - // Delete any listeners - const runningEvent = this._getRunningEvent(eventName); - runningEvent.removeAllListeners(); - this._checkRunningEvents(runningEvent); - return this; - } - off(eventName, listener) { - if (!this.provider) { - return this; - } - 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 ((0,bytes_lib_esm/* isBytes */._t)(bytecode)) { - bytecodeHex = (0,bytes_lib_esm/* hexlify */.Dv)(bytecode); - } - else if (bytecode && typeof (bytecode.object) === "string") { - // Allow the bytecode object from the Solidity compiler - bytecodeHex = bytecode.object; - } - else { - // Crash in the next verification step - bytecodeHex = "!"; - } - // Make sure it is 0x prefixed - if (bytecodeHex.substring(0, 2) !== "0x") { - bytecodeHex = "0x" + bytecodeHex; - } - // Make sure the final result is valid bytecode - if (!(0,bytes_lib_esm/* isHexString */.A7)(bytecodeHex) || (bytecodeHex.length % 2)) { - logger.throwArgumentError("invalid bytecode", "bytecode", bytecode); - } - // If we have a signer, make sure it is valid - if (signer && !abstract_signer_lib_esm/* Signer.isSigner */.E.isSigner(signer)) { - logger.throwArgumentError("invalid signer", "signer", signer); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "bytecode", bytecodeHex); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "interface", (0,properties_lib_esm/* getStatic */.tu)(new.target, "getInterface")(contractInterface)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "signer", signer || null); - } - // @TODO: Future; rename to populateTransaction? - getDeployTransaction(...args) { - let tx = {}; - // If we have 1 additional argument, we allow transaction overrides - if (args.length === this.interface.deploy.inputs.length + 1 && typeof (args[args.length - 1]) === "object") { - tx = (0,properties_lib_esm/* shallowCopy */.DC)(args.pop()); - for (const key in tx) { - if (!allowedTransactionKeys[key]) { - throw new Error("unknown transaction override " + key); - } - } - } - // Do not allow these to be overridden in a deployment transaction - ["data", "from", "to"].forEach((key) => { - if (tx[key] == null) { - return; - } - logger.throwError("cannot override " + key, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: key }); - }); - if (tx.value) { - const value = bignumber/* BigNumber.from */.O$.from(tx.value); - if (!value.isZero() && !this.interface.deploy.payable) { - logger.throwError("non-payable constructor cannot override value", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.value", - value: tx.value - }); - } - } - // Make sure the call matches the constructor signature - logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); - // Set the data to the bytecode + the encoded constructor arguments - tx.data = (0,bytes_lib_esm/* hexlify */.Dv)((0,bytes_lib_esm/* concat */.zo)([ - this.bytecode, - this.interface.encodeDeploy(args) - ])); - return tx; - } - deploy(...args) { - return __awaiter(this, void 0, void 0, function* () { - let overrides = {}; - // If 1 extra parameter was passed in, it contains overrides - if (args.length === this.interface.deploy.inputs.length + 1) { - overrides = args.pop(); - } - // Make sure the call matches the constructor signature - logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); - // Resolve ENS names and promises in the arguments - const params = yield resolveAddresses(this.signer, args, this.interface.deploy.inputs); - params.push(overrides); - // Get the deployment transaction (with optional overrides) - const unsignedTx = this.getDeployTransaction(...params); - // Send the deployment transaction - const tx = yield this.signer.sendTransaction(unsignedTx); - const address = (0,properties_lib_esm/* getStatic */.tu)(this.constructor, "getContractAddress")(tx); - const contract = (0,properties_lib_esm/* getStatic */.tu)(this.constructor, "getContract")(address, this.interface, this.signer); - // Add the modified wait that wraps events - addContractWait(contract, tx); - (0,properties_lib_esm/* defineReadOnly */.zG)(contract, "deployTransaction", tx); - return contract; - }); - } - attach(address) { - return (this.constructor).getContract(address, this.interface, this.signer); - } - connect(signer) { - return new (this.constructor)(this.interface, this.bytecode, signer); - } - static fromSolidity(compilerOutput, signer) { - if (compilerOutput == null) { - logger.throwError("missing compiler output", logger_lib_esm/* Logger.errors.MISSING_ARGUMENT */.Yd.errors.MISSING_ARGUMENT, { argument: "compilerOutput" }); - } - if (typeof (compilerOutput) === "string") { - compilerOutput = JSON.parse(compilerOutput); - } - const abi = 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(abi, bytecode, signer); - } - static getInterface(contractInterface) { - return Contract.getInterface(contractInterface); - } - static getContractAddress(tx) { - return (0,address_lib_esm/* getContractAddress */.CR)(tx); - } - static getContract(address, contractInterface, signer) { - return new Contract(address, contractInterface, signer); - } -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 1890: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "i": () => (/* binding */ version) -/* harmony export */ }); -const version = "hash/5.5.0"; -//# sourceMappingURL=_version.js.map - -/***/ }), - -/***/ 14: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "id": () => (/* binding */ id) -/* harmony export */ }); -/* harmony import */ var _ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2677); -/* harmony import */ var _ethersproject_strings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5804); - - -function id(text) { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_0__/* .keccak256 */ .w)((0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_1__/* .toUtf8Bytes */ .Y0)(text)); -} -//# sourceMappingURL=id.js.map - -/***/ }), - -/***/ 3314: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "V": () => (/* binding */ namehash), -/* harmony export */ "r": () => (/* binding */ isValidName) -/* harmony export */ }); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_strings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(592); -/* harmony import */ var _ethersproject_strings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5804); -/* harmony import */ var _ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2677); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1890); - - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); -const Zeros = new Uint8Array(32); -Zeros.fill(0); -const Partition = new RegExp("^((.*)\\.)?([^.]+)$"); -function isValidName(name) { - try { - const comps = name.split("."); - for (let i = 0; i < comps.length; i++) { - if ((0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_2__/* .nameprep */ .Ll)(comps[i]).length === 0) { - throw new Error("empty"); - } - } - return true; - } - catch (error) { } - return false; -} -function namehash(name) { - /* istanbul ignore if */ - if (typeof (name) !== "string") { - logger.throwArgumentError("invalid ENS name; not a string", "name", name); - } - let current = name; - let result = Zeros; - while (current.length) { - const partition = current.match(Partition); - if (partition == null || partition[2] === "") { - logger.throwArgumentError("invalid ENS address; missing component", "name", name); - } - const label = (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_3__/* .toUtf8Bytes */ .Y0)((0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_2__/* .nameprep */ .Ll)(partition[3])); - result = (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_4__/* .keccak256 */ .w)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .concat */ .zo)([result, (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_4__/* .keccak256 */ .w)(label)])); - current = partition[2] || ""; - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .hexlify */ .Dv)(result); -} -//# sourceMappingURL=namehash.js.map - -/***/ }), - -/***/ 506: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "E": () => (/* binding */ TypedDataEncoder) -/* harmony export */ }); -/* harmony import */ var _ethersproject_address__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9808); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2677); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1890); -/* harmony import */ var _id__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(14); -var __awaiter = (undefined && undefined.__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 logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); - -const padding = new Uint8Array(32); -padding.fill(0); -const NegativeOne = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(-1); -const Zero = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(0); -const One = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(1); -const MaxUint256 = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -function hexPadRight(value) { - const bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(value); - const padOffset = bytes.length % 32; - if (padOffset) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)([bytes, padding.slice(padOffset)]); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(bytes); -} -const hexTrue = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(One.toHexString(), 32); -const hexFalse = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(Zero.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.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 _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(value).toString(); - } - catch (error) { } - return logger.throwArgumentError(`invalid domain value for "chainId"`, "domain.chainId", value); - }, - verifyingContract: function (value) { - try { - return (0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_4__/* .getAddress */ .Kn)(value).toLowerCase(); - } - catch (error) { } - return logger.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); - }, - salt: function (value) { - try { - const bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(value); - if (bytes.length !== 32) { - throw new Error("bad length"); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(bytes); - } - catch (error) { } - return logger.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); - } -}; -function getBaseEncoder(type) { - // intXX and uintXX - { - const match = type.match(/^(u?)int(\d*)$/); - if (match) { - const signed = (match[1] === ""); - const width = parseInt(match[2] || "256"); - if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) { - logger.throwArgumentError("invalid numeric width", "type", type); - } - const boundsUpper = MaxUint256.mask(signed ? (width - 1) : width); - const boundsLower = signed ? boundsUpper.add(One).mul(NegativeOne) : Zero; - return function (value) { - const v = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(value); - if (v.lt(boundsLower) || v.gt(boundsUpper)) { - logger.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(v.toTwos(256).toHexString(), 32); - }; - } - } - // bytesXX - { - const match = type.match(/^bytes(\d+)$/); - if (match) { - const width = parseInt(match[1]); - if (width === 0 || width > 32 || match[1] !== String(width)) { - logger.throwArgumentError("invalid bytes width", "type", type); - } - return function (value) { - const bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(value); - if (bytes.length !== width) { - logger.throwArgumentError(`invalid length for ${type}`, "value", value); - } - return hexPadRight(value); - }; - } - } - switch (type) { - case "address": return function (value) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)((0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_4__/* .getAddress */ .Kn)(value), 32); - }; - case "bool": return function (value) { - return ((!value) ? hexFalse : hexTrue); - }; - case "bytes": return function (value) { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w)(value); - }; - case "string": return function (value) { - return (0,_id__WEBPACK_IMPORTED_MODULE_6__.id)(value); - }; - } - return null; -} -function encodeType(name, fields) { - return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`; -} -class TypedDataEncoder { - constructor(types) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .defineReadOnly */ .zG)(this, "types", Object.freeze((0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .deepCopy */ .p$)(types))); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .defineReadOnly */ .zG)(this, "_encoderCache", {}); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .defineReadOnly */ .zG)(this, "_types", {}); - // Link struct types to their direct child structs - const links = {}; - // Link structs to structs which contain them as a child - const parents = {}; - // Link all subtypes within a given struct - const subtypes = {}; - Object.keys(types).forEach((type) => { - links[type] = {}; - parents[type] = []; - subtypes[type] = {}; - }); - for (const name in types) { - const uniqueNames = {}; - types[name].forEach((field) => { - // Check each field has a unique name - if (uniqueNames[field.name]) { - logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); - } - uniqueNames[field.name] = true; - // Get the base type (drop any array specifiers) - const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]; - if (baseType === name) { - logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); - } - // Is this a base encoding type? - const encoder = getBaseEncoder(baseType); - if (encoder) { - return; - } - if (!parents[baseType]) { - logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); - } - // Add linkage - parents[baseType].push(name); - links[name][baseType] = true; - }); - } - // Deduce the primary type - const primaryTypes = Object.keys(parents).filter((n) => (parents[n].length === 0)); - if (primaryTypes.length === 0) { - logger.throwArgumentError("missing primary type", "types", types); - } - else if (primaryTypes.length > 1) { - logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", types); - } - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .defineReadOnly */ .zG)(this, "primaryType", primaryTypes[0]); - // Check for circular type references - function checkCircular(type, found) { - if (found[type]) { - logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); - } - found[type] = true; - Object.keys(links[type]).forEach((child) => { - if (!parents[child]) { - return; - } - // Recursively check children - checkCircular(child, found); - // Mark all ancestors as having this decendant - Object.keys(found).forEach((subtype) => { - subtypes[subtype][child] = true; - }); - }); - delete found[type]; - } - checkCircular(this.primaryType, {}); - // Compute each fully describe type - 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) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return encoder; - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const subEncoder = this.getEncoder(subtype); - const length = parseInt(match[3]); - return (value) => { - if (length >= 0 && value.length !== length) { - logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); - } - let result = value.map(subEncoder); - if (this._types[subtype]) { - result = result.map(_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w); - } - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)(result)); - }; - } - // Struct - const fields = this.types[type]; - if (fields) { - const encodedType = (0,_id__WEBPACK_IMPORTED_MODULE_6__.id)(this._types[type]); - return (value) => { - const values = fields.map(({ name, type }) => { - const result = this.getEncoder(type)(value[name]); - if (this._types[type]) { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w)(result); - } - return result; - }); - values.unshift(encodedType); - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)(values); - }; - } - return logger.throwArgumentError(`unknown type: ${type}`, "type", type); - } - encodeType(name) { - const result = this._types[name]; - if (!result) { - logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); - } - return result; - } - encodeData(type, value) { - return this.getEncoder(type)(value); - } - hashStruct(name, value) { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w)(this.encodeData(name, value)); - } - encode(value) { - return this.encodeData(this.primaryType, value); - } - hash(value) { - return this.hashStruct(this.primaryType, value); - } - _visit(type, value, callback) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return callback(type, value); - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const length = parseInt(match[3]); - if (length >= 0 && value.length !== length) { - logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); - } - return value.map((v) => this._visit(subtype, v, callback)); - } - // Struct - const fields = this.types[type]; - if (fields) { - return fields.reduce((accum, { name, type }) => { - accum[name] = this._visit(type, value[name], callback); - return accum; - }, {}); - } - return logger.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.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 (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)([ - "0x1901", - TypedDataEncoder.hashDomain(domain), - TypedDataEncoder.from(types).hash(value) - ]); - } - static hash(domain, types, value) { - return (0,_ethersproject_keccak256__WEBPACK_IMPORTED_MODULE_5__/* .keccak256 */ .w)(TypedDataEncoder.encode(domain, types, value)); - } - // Replaces all address types with ENS names with their looked up address - static resolveNames(domain, types, value, resolveName) { - return __awaiter(this, void 0, void 0, function* () { - // Make a copy to isolate it from the object passed in - domain = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .shallowCopy */ .DC)(domain); - // Look up all ENS names - const ensCache = {}; - // Do we need to look up the domain's verifyingContract? - if (domain.verifyingContract && !(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(domain.verifyingContract, 20)) { - ensCache[domain.verifyingContract] = "0x"; - } - // We are going to use the encoder to visit all the base values - const encoder = TypedDataEncoder.from(types); - // Get a list of all the addresses - encoder.visit(value, (type, value) => { - if (type === "address" && !(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(value, 20)) { - ensCache[value] = "0x"; - } - return value; - }); - // Lookup each name - for (const name in ensCache) { - ensCache[name] = yield resolveName(name); - } - // Replace the domain verifyingContract if needed - if (domain.verifyingContract && ensCache[domain.verifyingContract]) { - domain.verifyingContract = ensCache[domain.verifyingContract]; - } - // Replace all ENS names with their address - value = encoder.visit(value, (type, value) => { - if (type === "address" && ensCache[value]) { - return ensCache[value]; - } - return value; - }); - return { domain, value }; - }); - } - static getPayload(domain, types, value) { - // Validate the domain fields - TypedDataEncoder.hashDomain(domain); - // Derive the EIP712Domain Struct reference type - const domainValues = {}; - const domainTypes = []; - domainFieldNames.forEach((name) => { - const value = domain[name]; - if (value == null) { - return; - } - domainValues[name] = domainChecks[name](value); - domainTypes.push({ name, type: domainFieldTypes[name] }); - }); - const encoder = TypedDataEncoder.from(types); - const typesWithDomain = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_7__/* .shallowCopy */ .DC)(types); - if (typesWithDomain.EIP712Domain) { - logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); - } - else { - typesWithDomain.EIP712Domain = domainTypes; - } - // Validate the data structures and types - encoder.encode(value); - return { - types: typesWithDomain, - domain: domainValues, - primaryType: encoder.primaryType, - message: encoder.visit(value, (type, value) => { - // bytes - if (type.match(/^bytes(\d*)/)) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(value)); - } - // uint or int - if (type.match(/^u?int/)) { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_2__/* .BigNumber.from */ .O$.from(value).toString(); - } - switch (type) { - case "address": - return value.toLowerCase(); - case "bool": - return !!value; - case "string": - if (typeof (value) !== "string") { - logger.throwArgumentError(`invalid string`, "value", value); - } - return value; - } - return logger.throwArgumentError("unsupported type", "type", type); - }) - }; - } -} -//# sourceMappingURL=typed-data.js.map - -/***/ }), - -/***/ 2677: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "w": () => (/* binding */ keccak256) -/* harmony export */ }); -/* harmony import */ var js_sha3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(338); -/* harmony import */ var js_sha3__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(js_sha3__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3756); - - - -function keccak256(data) { - return '0x' + js_sha3__WEBPACK_IMPORTED_MODULE_0___default().keccak_256((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_1__/* .arrayify */ .lE)(data)); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 1424: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "jK": () => (/* binding */ ErrorCode), - "Yd": () => (/* binding */ Logger) -}); - -// UNUSED EXPORTS: LogLevel - -;// CONCATENATED MODULE: ../node_modules/@ethersproject/logger/lib.esm/_version.js -const version = "logger/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js - -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 = []; - // Make sure all forms of normalization are supported - ["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(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) { - throw new Error("broken implementation"); - } - } - catch (error) { - return error.message; - } - return null; -} -const _normalizeError = _checkNormalize(); -var LogLevel; -(function (LogLevel) { - LogLevel["DEBUG"] = "DEBUG"; - LogLevel["INFO"] = "INFO"; - LogLevel["WARNING"] = "WARNING"; - LogLevel["ERROR"] = "ERROR"; - LogLevel["OFF"] = "OFF"; -})(LogLevel || (LogLevel = {})); -var ErrorCode; -(function (ErrorCode) { - /////////////////// - // Generic Errors - // Unknown Error - ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; - // Not Implemented - ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; - // Unsupported Operation - // - operation - ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; - // Network Error (i.e. Ethereum Network, such as an invalid chain ID) - // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown) - ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR"; - // Some sort of bad response from the server - ErrorCode["SERVER_ERROR"] = "SERVER_ERROR"; - // Timeout - ErrorCode["TIMEOUT"] = "TIMEOUT"; - /////////////////// - // Operational Errors - // Buffer Overrun - ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; - // Numeric Fault - // - operation: the operation being executed - // - fault: the reason this faulted - ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT"; - /////////////////// - // Argument Errors - // Missing new operator to an object - // - name: The name of the class - ErrorCode["MISSING_NEW"] = "MISSING_NEW"; - // Invalid argument (e.g. value is incompatible with type) to a function: - // - argument: The argument name that was invalid - // - value: The value of the argument - ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; - // Missing argument to a function: - // - count: The number of arguments received - // - expectedCount: The number of arguments expected - ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; - // Too many arguments - // - count: The number of arguments received - // - expectedCount: The number of arguments expected - ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; - /////////////////// - // Blockchain Errors - // Call exception - // - transaction: the transaction - // - address?: the contract address - // - args?: The arguments passed into the function - // - method?: The Solidity method signature - // - errorSignature?: The EIP848 error signature - // - errorArgs?: The EIP848 error parameters - // - reason: The reason (only for EIP848 "Error(string)") - ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION"; - // Insufficient funds (< value + gasLimit * gasPrice) - // - transaction: the transaction attempted - ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; - // Nonce has already been used - // - transaction: the transaction attempted - ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED"; - // The replacement fee for the transaction is too low - // - transaction: the transaction attempted - ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; - // The gas limit could not be estimated - // - transaction: the transaction passed to estimateGas - ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; - // The transaction was replaced by one with a higher gas price - // - reason: "cancelled", "replaced" or "repriced" - // - cancelled: true if reason == "cancelled" or reason == "replaced") - // - hash: original transaction hash - // - replacement: the full TransactionsResponse for the replacement - // - receipt: the receipt of the replacement - ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; -})(ErrorCode || (ErrorCode = {})); -; -const HEX = "0123456789abcdef"; -class Logger { - constructor(version) { - Object.defineProperty(this, "version", { - enumerable: true, - value: version, - 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) { - // Errors are being censored - 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] & 0x0f]; - } - messageDetails.push(key + "=Uint8Array(0x" + hex + ")"); - } - else { - messageDetails.push(key + "=" + JSON.stringify(value)); - } - } - catch (error) { - messageDetails.push(key + "=" + JSON.stringify(params[key].toString())); - } - }); - messageDetails.push(`code=${code}`); - messageDetails.push(`version=${this.version}`); - const reason = message; - if (messageDetails.length) { - message += " (" + messageDetails.join(", ") + ")"; - } - // @TODO: Any?? - 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: value - }); - } - assert(condition, message, code, params) { - if (!!condition) { - return; - } - this.throwError(message, code, params); - } - assertArgument(condition, message, name, value) { - if (!!condition) { - return; - } - this.throwArgumentError(message, name, value); - } - checkNormalize(message) { - if (message == null) { - message = "platform missing String.prototype.normalize"; - } - if (_normalizeError) { - this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "String.prototype.normalize", form: _normalizeError - }); - } - } - checkSafeUint53(value, message) { - if (typeof (value) !== "number") { - return; - } - if (message == null) { - message = "value not safe"; - } - if (value < 0 || value >= 0x1fffffffffffff) { - this.throwError(message, Logger.errors.NUMERIC_FAULT, { - operation: "checkSafeInteger", - fault: "out-of-safe-range", - value: value - }); - } - if (value % 1) { - this.throwError(message, Logger.errors.NUMERIC_FAULT, { - operation: "checkSafeInteger", - fault: "non-integer", - value: value - }); - } - } - checkArgumentCount(count, expectedCount, message) { - if (message) { - message = ": " + message; - } - else { - message = ""; - } - if (count < expectedCount) { - this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, { - count: count, - expectedCount: expectedCount - }); - } - if (count > expectedCount) { - this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, { - count: count, - expectedCount: 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(version) { - return new Logger(version); - } -} -Logger.errors = ErrorCode; -Logger.levels = LogLevel; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 7357: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "H": () => (/* binding */ getNetwork) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/networks/lib.esm/_version.js -const version = "networks/5.5.2"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/networks/lib.esm/index.js - - - -const logger = new lib_esm/* Logger */.Yd(version); -; -function isRenetworkable(value) { - return (value && typeof (value.renetwork) === "function"); -} -function ethDefaultProvider(network) { - const func = function (providers, options) { - if (options == null) { - options = {}; - } - const providerList = []; - if (providers.InfuraProvider) { - try { - providerList.push(new providers.InfuraProvider(network, options.infura)); - } - catch (error) { } - } - if (providers.EtherscanProvider) { - try { - providerList.push(new providers.EtherscanProvider(network, options.etherscan)); - } - catch (error) { } - } - if (providers.AlchemyProvider) { - try { - providerList.push(new providers.AlchemyProvider(network, options.alchemy)); - } - catch (error) { } - } - if (providers.PocketProvider) { - // These networks are currently faulty on Pocket as their - // network does not handle the Berlin hardfork, which is - // live on these ones. - // @TODO: This goes away once Pocket has upgraded their nodes - const skip = ["goerli", "ropsten", "rinkeby"]; - try { - const provider = new providers.PocketProvider(network); - if (provider.network && skip.indexOf(provider.network.name) === -1) { - providerList.push(provider); - } - } - catch (error) { } - } - if (providers.CloudflareProvider) { - try { - providerList.push(new providers.CloudflareProvider(network)); - } - 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; - } - return new providers.FallbackProvider(providerList, quorum); - } - return providerList[0]; - }; - func.renetwork = function (network) { - return ethDefaultProvider(network); - }; - return func; -} -function etcDefaultProvider(url, network) { - const func = function (providers, options) { - if (providers.JsonRpcProvider) { - return new providers.JsonRpcProvider(url, network); - } - return null; - }; - func.renetwork = function (network) { - return etcDefaultProvider(url, network); - }; - 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") -}; -// See: https://chainlist.org -const networks = { - unspecified: { chainId: 0, name: "unspecified" }, - homestead: homestead, - mainnet: homestead, - morden: { chainId: 2, name: "morden" }, - ropsten: 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" }, - // ETC (See: #351) - classic: { - chainId: 61, - name: "classic", - _defaultProvider: etcDefaultProvider("https:/\/www.ethercluster.com/etc", "classic") - }, - classicMorden: { chainId: 62, name: "classicMorden" }, - classicMordor: 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" }, - maticmum: { chainId: 80001, name: "maticmum" }, - optimism: { chainId: 10, name: "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" }, - bnb: { chainId: 56, name: "bnb" }, - bnbt: { chainId: 97, name: "bnbt" }, -}; -/** - * getNetwork - * - * Converts a named common networks or chain ID (network ID) to a Network - * and verifies a network is a valid Network.. - */ -function getNetwork(network) { - // No network (null) - if (network == null) { - return null; - } - if (typeof (network) === "number") { - for (const name in networks) { - const standard = networks[name]; - if (standard.chainId === network) { - return { - name: standard.name, - chainId: standard.chainId, - ensAddress: (standard.ensAddress || null), - _defaultProvider: (standard._defaultProvider || null) - }; - } - } - return { - chainId: network, - name: "unknown" - }; - } - if (typeof (network) === "string") { - const standard = networks[network]; - if (standard == null) { - return null; - } - return { - name: standard.name, - chainId: standard.chainId, - ensAddress: standard.ensAddress, - _defaultProvider: (standard._defaultProvider || null) - }; - } - const standard = networks[network.name]; - // Not a standard network; check that it is a valid network in general - if (!standard) { - if (typeof (network.chainId) !== "number") { - logger.throwArgumentError("invalid network chainId", "network", network); - } - return network; - } - // Make sure the chainId matches the expected network chainId (or is 0; disable EIP-155) - if (network.chainId !== 0 && network.chainId !== standard.chainId) { - logger.throwArgumentError("network chainId mismatch", "network", network); - } - // @TODO: In the next major version add an attach function to a defaultProvider - // class and move the _defaultProvider internal to this file (extend Network) - let defaultProvider = network._defaultProvider || null; - if (defaultProvider == null && standard._defaultProvider) { - if (isRenetworkable(standard._defaultProvider)) { - defaultProvider = standard._defaultProvider.renetwork(network); - } - else { - defaultProvider = standard._defaultProvider; - } - } - // Standard Network (allow overriding the ENS address) - return { - name: network.name, - chainId: standard.chainId, - ensAddress: (network.ensAddress || standard.ensAddress || null), - _defaultProvider: defaultProvider - }; -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 300: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "dk": () => (/* binding */ Description), - "uj": () => (/* binding */ checkProperties), - "p$": () => (/* binding */ deepCopy), - "zG": () => (/* binding */ defineReadOnly), - "tu": () => (/* binding */ getStatic), - "mE": () => (/* binding */ resolveProperties), - "DC": () => (/* binding */ shallowCopy) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/properties/lib.esm/_version.js -const version = "properties/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js - -var __awaiter = (undefined && undefined.__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 logger = new lib_esm/* Logger */.Yd(version); -function defineReadOnly(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - value: value, - writable: false, - }); -} -// Crawl up the constructor chain to find a static method -function getStatic(ctor, key) { - for (let i = 0; i < 32; i++) { - if (ctor[key]) { - return ctor[key]; - } - if (!ctor.prototype || typeof (ctor.prototype) !== "object") { - break; - } - ctor = Object.getPrototypeOf(ctor.prototype).constructor; - } - return null; -} -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: 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") { - logger.throwArgumentError("invalid object", "object", object); - } - Object.keys(object).forEach((key) => { - if (!properties[key]) { - logger.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) { - // Opaque objects are not mutable, so safe to copy by assignment - if (object === undefined || 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) { - // If accessing a value triggers an error, it is a getter - // designed to do so (e.g. Result) and is therefore "frozen" - continue; - } - if (!_isFrozen(value)) { - return false; - } - } - return true; - } - return logger.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, "object", object); -} -// Returns a new copy of object, such that no properties may be replaced. -// New properties may be added only to objects. -function _deepCopy(object) { - if (_isFrozen(object)) { - return object; - } - // Arrays are mutable, so we need to create a copy - 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 === undefined) { - continue; - } - defineReadOnly(result, key, deepCopy(value)); - } - return result; - } - return logger.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]); - } - } -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 2405: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "i": () => (/* binding */ version) -/* harmony export */ }); -const version = "providers/5.5.3"; -//# sourceMappingURL=_version.js.map - -/***/ }), - -/***/ 2001: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "H2": () => (/* binding */ Resolver), -/* harmony export */ "Zk": () => (/* binding */ BaseProvider) -/* harmony export */ }); -/* unused harmony export Event */ -/* harmony import */ var _ethersproject_abstract_provider__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2639); -/* harmony import */ var _ethersproject_basex__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(3581); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(2728); -/* harmony import */ var _ethersproject_hash__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3314); -/* harmony import */ var _ethersproject_networks__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(7357); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_sha2__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(9088); -/* harmony import */ var _ethersproject_strings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(5804); -/* harmony import */ var _ethersproject_web__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(2585); -/* harmony import */ var bech32__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8194); -/* harmony import */ var bech32__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bech32__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2405); -/* harmony import */ var _formatter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(8523); - -var __awaiter = (undefined && undefined.__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 logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_2__/* .version */ .i); - -////////////////////////////// -// Event Serializeing -function checkTopic(topic) { - if (topic == null) { - return "null"; - } - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataLength */ .E1)(topic) !== 32) { - logger.throwArgumentError("invalid topic", "topic", topic); - } - return topic.toLowerCase(); -} -function serializeTopics(topics) { - // Remove trailing null AND-topics; they are redundant - topics = topics.slice(); - while (topics.length > 0 && topics[topics.length - 1] == null) { - topics.pop(); - } - return topics.map((topic) => { - if (Array.isArray(topic)) { - // Only track unique OR-topics - const unique = {}; - topic.forEach((topic) => { - unique[checkTopic(topic)] = true; - }); - // The order of OR-topics does not matter - const sorted = Object.keys(unique); - sorted.sort(); - return sorted.join("|"); - } - else { - return checkTopic(topic); - } - }).join("&"); -} -function deserializeTopics(data) { - if (data === "") { - return []; - } - return data.split(/&/g).map((topic) => { - if (topic === "") { - return []; - } - const comps = topic.split("|").map((topic) => { - return ((topic === "null") ? null : topic); - }); - return ((comps.length === 1) ? comps[0] : comps); - }); -} -function getEventTag(eventName) { - if (typeof (eventName) === "string") { - eventName = eventName.toLowerCase(); - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataLength */ .E1)(eventName) === 32) { - return "tx:" + eventName; - } - if (eventName.indexOf(":") === -1) { - return eventName; - } - } - else if (Array.isArray(eventName)) { - return "filter:*:" + serializeTopics(eventName); - } - else if (_ethersproject_abstract_provider__WEBPACK_IMPORTED_MODULE_4__/* .ForkEvent.isForkEvent */ .Sg.isForkEvent(eventName)) { - logger.warn("not implemented"); - throw new Error("not implemented"); - } - else if (eventName && typeof (eventName) === "object") { - return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []); - } - throw new Error("invalid event - " + eventName); -} -////////////////////////////// -// Helper Object -function getTime() { - return (new Date()).getTime(); -} -function stall(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); -} -////////////////////////////// -// Provider Object -/** - * EventType - * - "block" - * - "poll" - * - "didPoll" - * - "pending" - * - "error" - * - "network" - * - filter - * - topics array - * - transaction hash - */ -const PollableEvents = ["block", "network", "pending", "poll"]; -class Event { - constructor(tag, listener, once) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "tag", tag); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "listener", listener); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "once", once); - } - 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 comps[1]; - } - get filter() { - const comps = this.tag.split(":"); - if (comps[0] !== "filter") { - return null; - } - const address = comps[1]; - const topics = deserializeTopics(comps[2]); - const filter = {}; - if (topics.length > 0) { - filter.topics = topics; - } - if (address && address !== "*") { - filter.address = address; - } - return filter; - } - pollable() { - return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0); - } -} -; -// https://github.com/satoshilabs/slips/blob/master/slip-0044.md -const coinInfos = { - "0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" }, - "2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" }, - "3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 }, - "60": { symbol: "eth", ilk: "eth" }, - "61": { symbol: "etc", ilk: "eth" }, - "700": { symbol: "xdai", ilk: "eth" }, -}; -function bytes32ify(value) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(value).toHexString(), 32); -} -// Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d) -function base58Encode(data) { - return _ethersproject_basex__WEBPACK_IMPORTED_MODULE_7__/* .Base58.encode */ .eU.encode((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([data, (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataSlice */ .p3)((0,_ethersproject_sha2__WEBPACK_IMPORTED_MODULE_8__/* .sha256 */ .JQ)((0,_ethersproject_sha2__WEBPACK_IMPORTED_MODULE_8__/* .sha256 */ .JQ)(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) { - try { - return (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_9__/* .toUtf8String */ .ZN)(_parseBytes(result)); - } - catch (error) { } - return null; -} -function _parseBytes(result) { - if (result === "0x") { - return null; - } - const offset = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataSlice */ .p3)(result, 0, 32)).toNumber(); - const length = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataSlice */ .p3)(result, offset, offset + 32)).toNumber(); - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataSlice */ .p3)(result, offset + 32, offset + 32 + length); -} -// Trim off the ipfs:// prefix and return the default gateway URL -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.throwArgumentError("unsupported IPFS format", "link", link); - } - return `https:/\/gateway.ipfs.io/ipfs/${link}`; -} -class Resolver { - // The resolvedAddress is only for creating a ReverseLookup resolver - constructor(provider, address, name, resolvedAddress) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "provider", provider); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "name", name); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "address", provider.formatter.address(address)); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "_resolvedAddress", resolvedAddress); - } - _fetchBytes(selector, parameters) { - return __awaiter(this, void 0, void 0, function* () { - // e.g. keccak256("addr(bytes32,uint256)") - const tx = { - to: this.address, - data: (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)([selector, (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_10__/* .namehash */ .V)(this.name), (parameters || "0x")]) - }; - try { - return _parseBytes(yield this.provider.call(tx)); - } - catch (error) { - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION) { - return null; - } - return null; - } - }); - } - _getAddress(coinType, hexBytes) { - const coinInfo = coinInfos[String(coinType)]; - if (coinInfo == null) { - logger.throwError(`unsupported coin type: ${coinType}`, _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: `getAddress(${coinType})` - }); - } - if (coinInfo.ilk === "eth") { - return this.provider.formatter.address(hexBytes); - } - const bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(hexBytes); - // P2PKH: OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG - 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((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([[coinInfo.p2pkh], ("0x" + p2pkh[2])])); - } - } - } - // P2SH: OP_HASH160 OP_EQUAL - 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((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([[coinInfo.p2sh], ("0x" + p2sh[2])])); - } - } - } - // Bech32 - if (coinInfo.prefix != null) { - const length = bytes[1]; - // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program - let version = bytes[0]; - if (version === 0x00) { - if (length !== 20 && length !== 32) { - version = -1; - } - } - else { - version = -1; - } - if (version >= 0 && bytes.length === 2 + length && length >= 1 && length <= 75) { - const words = bech32__WEBPACK_IMPORTED_MODULE_0___default().toWords(bytes.slice(2)); - words.unshift(version); - return bech32__WEBPACK_IMPORTED_MODULE_0___default().encode(coinInfo.prefix, words); - } - } - return null; - } - getAddress(coinType) { - return __awaiter(this, void 0, void 0, function* () { - if (coinType == null) { - coinType = 60; - } - // If Ethereum, use the standard `addr(bytes32)` - if (coinType === 60) { - try { - // keccak256("addr(bytes32)") - const transaction = { - to: this.address, - data: ("0x3b3b57de" + (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_10__/* .namehash */ .V)(this.name).substring(2)) - }; - const hexBytes = yield this.provider.call(transaction); - // No address - if (hexBytes === "0x" || hexBytes === _ethersproject_constants__WEBPACK_IMPORTED_MODULE_11__/* .HashZero */ .R) { - return null; - } - return this.provider.formatter.callAddress(hexBytes); - } - catch (error) { - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION) { - return null; - } - throw error; - } - } - // keccak256("addr(bytes32,uint256") - const hexBytes = yield this._fetchBytes("0xf1cb7e06", bytes32ify(coinType)); - // No address - if (hexBytes == null || hexBytes === "0x") { - return null; - } - // Compute the address - const address = this._getAddress(coinType, hexBytes); - if (address == null) { - logger.throwError(`invalid or unsupported coin data`, _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: `getAddress(${coinType})`, - coinType: coinType, - data: hexBytes - }); - } - return address; - }); - } - getAvatar() { - return __awaiter(this, void 0, void 0, function* () { - const linkage = [{ type: "name", content: this.name }]; - try { - // test data for ricmoo.eth - //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233"; - 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": { - // Depending on the ERC type, use tokenURI(uint256) or url(uint256) - const selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c"; - linkage.push({ type: scheme, content: avatar }); - // The owner of this name - 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 = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(comps[1]).toHexString(), 32); - // Check that this account owns the token - if (scheme === "erc721") { - // ownerOf(uint256 tokenId) - const tokenOwner = this.provider.formatter.callAddress(yield this.provider.call({ - to: addr, data: (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)(["0x6352211e", tokenId]) - })); - if (owner !== tokenOwner) { - return null; - } - linkage.push({ type: "owner", content: tokenOwner }); - } - else if (scheme === "erc1155") { - // balanceOf(address owner, uint256 tokenId) - const balance = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(yield this.provider.call({ - to: addr, data: (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)(["0x00fdd58e", (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)(owner, 32), tokenId]) - })); - if (balance.isZero()) { - return null; - } - linkage.push({ type: "balance", content: balance.toString() }); - } - // Call the token contract for the metadata URL - const tx = { - to: this.provider.formatter.address(comps[0]), - data: (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexConcat */ .xs)([selector, tokenId]) - }; - let metadataUrl = _parseString(yield this.provider.call(tx)); - if (metadataUrl == null) { - return null; - } - linkage.push({ type: "metadata-url-base", content: metadataUrl }); - // ERC-1155 allows a generic {id} in the URL - if (scheme === "erc1155") { - metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2)); - linkage.push({ type: "metadata-url-expanded", content: metadataUrl }); - } - // Transform IPFS metadata links - if (metadataUrl.match(/^ipfs:/i)) { - metadataUrl = getIpfsLink(metadataUrl); - } - linkage.push({ type: "metadata-url", content: metadataUrl }); - // Get the token metadata - const metadata = yield (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_12__/* .fetchJson */ .rd)(metadataUrl); - if (!metadata) { - return null; - } - linkage.push({ type: "metadata", content: JSON.stringify(metadata) }); - // Pull the image URL out - let imageUrl = metadata.image; - if (typeof (imageUrl) !== "string") { - return null; - } - if (imageUrl.match(/^(https:\/\/|data:)/i)) { - // Allow - } - else { - // Transform IPFS link to gateway - 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; - }); - } - getContentHash() { - return __awaiter(this, void 0, void 0, function* () { - // keccak256("contenthash()") - const hexBytes = yield this._fetchBytes("0xbc1c58d1"); - // No contenthash - if (hexBytes == null || hexBytes === "0x") { - return null; - } - // IPFS (CID: 1, Type: DAG-PB) - 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:/\/" + _ethersproject_basex__WEBPACK_IMPORTED_MODULE_7__/* .Base58.encode */ .eU.encode("0x" + ipfs[1]); - } - } - // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32) - const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); - if (swarm) { - if (swarm[1].length === (32 * 2)) { - return "bzz:/\/" + swarm[1]; - } - } - return logger.throwError(`invalid or unsupported content hash data`, _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: "getContentHash()", - data: hexBytes - }); - }); - } - getText(key) { - return __awaiter(this, void 0, void 0, function* () { - // The key encoded as parameter to fetchBytes - let keyBytes = (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_9__/* .toUtf8Bytes */ .Y0)(key); - // The nodehash consumes the first slot, so the string pointer targets - // offset 64, with the length at offset 64 and data starting at offset 96 - keyBytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([bytes32ify(64), bytes32ify(keyBytes.length), keyBytes]); - // Pad to word-size (32 bytes) - if ((keyBytes.length % 32) !== 0) { - keyBytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .concat */ .zo)([keyBytes, (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexZeroPad */ .$m)("0x", 32 - (key.length % 32))]); - } - const hexBytes = yield this._fetchBytes("0x59d1d43c", (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(keyBytes)); - if (hexBytes == null || hexBytes === "0x") { - return null; - } - return (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_9__/* .toUtf8String */ .ZN)(hexBytes); - }); - } -} -let defaultFormatter = null; -let nextPollId = 1; -class BaseProvider extends _ethersproject_abstract_provider__WEBPACK_IMPORTED_MODULE_4__/* .Provider */ .zt { - /** - * ready - * - * A Promise that resolves only once the provider is ready. - * - * Sub-classes that call the super with a network without a chainId - * MUST set this. Standard named networks have a known chainId. - * - */ - constructor(network) { - logger.checkNew(new.target, _ethersproject_abstract_provider__WEBPACK_IMPORTED_MODULE_4__/* .Provider */ .zt); - super(); - // Events being listened to - this._events = []; - this._emitted = { block: -2 }; - this.formatter = new.target.getFormatter(); - // If network is any, this Provider allows the underlying - // network to change dynamically, and we auto-detect the - // current network - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "anyNetwork", (network === "any")); - if (this.anyNetwork) { - network = this.detectNetwork(); - } - if (network instanceof Promise) { - this._networkPromise = network; - // Squash any "unhandled promise" errors; that do not need to be handled - network.catch((error) => { }); - // Trigger initial network setting (async) - this._ready().catch((error) => { }); - } - else { - const knownNetwork = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .getStatic */ .tu)(new.target, "getNetwork")(network); - if (knownNetwork) { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "_network", knownNetwork); - this.emit("network", knownNetwork, null); - } - else { - logger.throwArgumentError("invalid network", "network", network); - } - } - this._maxInternalBlockNumber = -1024; - this._lastBlockNumber = -2; - this._pollingInterval = 4000; - this._fastQueryDate = 0; - } - _ready() { - return __awaiter(this, void 0, void 0, function* () { - if (this._network == null) { - let network = null; - if (this._networkPromise) { - try { - network = yield this._networkPromise; - } - catch (error) { } - } - // Try the Provider's network detection (this MUST throw if it cannot) - if (network == null) { - network = yield this.detectNetwork(); - } - // This should never happen; every Provider sub-class should have - // suggested a network by here (or have thrown). - if (!network) { - logger.throwError("no network detected", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNKNOWN_ERROR */ .Yd.errors.UNKNOWN_ERROR, {}); - } - // Possible this call stacked so do not call defineReadOnly again - if (this._network == null) { - if (this.anyNetwork) { - this._network = network; - } - else { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .defineReadOnly */ .zG)(this, "_network", network); - } - this.emit("network", network, null); - } - } - return this._network; - }); - } - // This will always return the most recently established network. - // For "any", this can change (a "network" event is emitted before - // any change is reflected); otherwise this cannot change - get ready() { - return (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_12__/* .poll */ .$l)(() => { - return this._ready().then((network) => { - return network; - }, (error) => { - // If the network isn't running yet, we will wait - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.NETWORK_ERROR */ .Yd.errors.NETWORK_ERROR && error.event === "noNetwork") { - return undefined; - } - throw error; - }); - }); - } - // @TODO: Remove this and just create a singleton formatter - static getFormatter() { - if (defaultFormatter == null) { - defaultFormatter = new _formatter__WEBPACK_IMPORTED_MODULE_13__/* .Formatter */ .Mb(); - } - return defaultFormatter; - } - // @TODO: Remove this and just use getNetwork - static getNetwork(network) { - return (0,_ethersproject_networks__WEBPACK_IMPORTED_MODULE_14__/* .getNetwork */ .H)((network == null) ? "homestead" : network); - } - // Fetches the blockNumber, but will reuse any result that is less - // than maxAge old or has been requested since the last request - _getInternalBlockNumber(maxAge) { - return __awaiter(this, void 0, void 0, function* () { - yield this._ready(); - // Allowing stale data up to maxAge old - if (maxAge > 0) { - // While there are pending internal block requests... - while (this._internalBlockNumber) { - // ..."remember" which fetch we started with - const internalBlockNumber = this._internalBlockNumber; - try { - // Check the result is not too stale - const result = yield internalBlockNumber; - if ((getTime() - result.respTime) <= maxAge) { - return result.blockNumber; - } - // Too old; fetch a new value - break; - } - catch (error) { - // The fetch rejected; if we are the first to get the - // rejection, drop through so we replace it with a new - // fetch; all others blocked will then get that fetch - // which won't match the one they "remembered" and loop - if (this._internalBlockNumber === internalBlockNumber) { - break; - } - } - } - } - const reqTime = getTime(); - const checkInternalBlockNumber = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - blockNumber: this.perform("getBlockNumber", {}), - networkError: this.getNetwork().then((network) => (null), (error) => (error)) - }).then(({ blockNumber, networkError }) => { - if (networkError) { - // Unremember this bad internal block number - if (this._internalBlockNumber === checkInternalBlockNumber) { - this._internalBlockNumber = null; - } - throw networkError; - } - const respTime = getTime(); - blockNumber = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(blockNumber).toNumber(); - if (blockNumber < this._maxInternalBlockNumber) { - blockNumber = this._maxInternalBlockNumber; - } - this._maxInternalBlockNumber = blockNumber; - this._setFastBlockNumber(blockNumber); // @TODO: Still need this? - return { blockNumber, reqTime, respTime }; - }); - this._internalBlockNumber = checkInternalBlockNumber; - // Swallow unhandled exceptions; if needed they are handled else where - checkInternalBlockNumber.catch((error) => { - // Don't null the dead (rejected) fetch, if it has already been updated - if (this._internalBlockNumber === checkInternalBlockNumber) { - this._internalBlockNumber = null; - } - }); - return (yield checkInternalBlockNumber).blockNumber; - }); - } - poll() { - return __awaiter(this, void 0, void 0, function* () { - const pollId = nextPollId++; - // Track all running promises, so we can trigger a post-poll once they are complete - const runners = []; - let blockNumber = null; - try { - blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2); - } - catch (error) { - this.emit("error", error); - return; - } - this._setFastBlockNumber(blockNumber); - // Emit a poll event after we have the latest (fast) block number - this.emit("poll", pollId, blockNumber); - // If the block has not changed, meh. - if (blockNumber === this._lastBlockNumber) { - this.emit("didPoll", pollId); - return; - } - // First polling cycle, trigger a "block" events - if (this._emitted.block === -2) { - this._emitted.block = blockNumber - 1; - } - if (Math.abs((this._emitted.block) - blockNumber) > 1000) { - logger.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`); - this.emit("error", logger.makeError("network block skew detected", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.NETWORK_ERROR */ .Yd.errors.NETWORK_ERROR, { - blockNumber: blockNumber, - event: "blockSkew", - previousBlockNumber: this._emitted.block - })); - this.emit("block", blockNumber); - } - else { - // Notify all listener for each block that has passed - for (let i = this._emitted.block + 1; i <= blockNumber; i++) { - this.emit("block", i); - } - } - // The emitted block was updated, check for obsolete events - if (this._emitted.block !== blockNumber) { - this._emitted.block = blockNumber; - Object.keys(this._emitted).forEach((key) => { - // The block event does not expire - if (key === "block") { - return; - } - // The block we were at when we emitted this event - const eventBlockNumber = this._emitted[key]; - // We cannot garbage collect pending transactions or blocks here - // They should be garbage collected by the Provider when setting - // "pending" events - if (eventBlockNumber === "pending") { - return; - } - // Evict any transaction hashes or block hashes over 12 blocks - // old, since they should not return null anyways - if (blockNumber - eventBlockNumber > 12) { - delete this._emitted[key]; - } - }); - } - // First polling cycle - if (this._lastBlockNumber === -2) { - this._lastBlockNumber = blockNumber - 1; - } - // Find all transaction hashes we are waiting on - this._events.forEach((event) => { - switch (event.type) { - case "tx": { - const hash = event.hash; - let runner = this.getTransactionReceipt(hash).then((receipt) => { - if (!receipt || receipt.blockNumber == null) { - return null; - } - this._emitted["t:" + hash] = receipt.blockNumber; - this.emit(hash, receipt); - return null; - }).catch((error) => { this.emit("error", error); }); - runners.push(runner); - break; - } - case "filter": { - const filter = event.filter; - filter.fromBlock = this._lastBlockNumber + 1; - filter.toBlock = blockNumber; - const runner = this.getLogs(filter).then((logs) => { - if (logs.length === 0) { - return; - } - logs.forEach((log) => { - this._emitted["b:" + log.blockHash] = log.blockNumber; - this._emitted["t:" + log.transactionHash] = log.blockNumber; - this.emit(filter, log); - }); - }).catch((error) => { this.emit("error", error); }); - runners.push(runner); - break; - } - } - }); - this._lastBlockNumber = blockNumber; - // Once all events for this loop have been processed, emit "didPoll" - Promise.all(runners).then(() => { - this.emit("didPoll", pollId); - }).catch((error) => { this.emit("error", error); }); - return; - }); - } - // Deprecated; do not use this - resetEventsBlock(blockNumber) { - this._lastBlockNumber = blockNumber - 1; - if (this.polling) { - this.poll(); - } - } - get network() { - return this._network; - } - // This method should query the network if the underlying network - // can change, such as when connected to a JSON-RPC backend - detectNetwork() { - return __awaiter(this, void 0, void 0, function* () { - return logger.throwError("provider does not support network detection", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: "provider.detectNetwork" - }); - }); - } - getNetwork() { - return __awaiter(this, void 0, void 0, function* () { - const network = yield this._ready(); - // Make sure we are still connected to the same network; this is - // only an external call for backends which can have the underlying - // network change spontaneously - const currentNetwork = yield this.detectNetwork(); - if (network.chainId !== currentNetwork.chainId) { - // We are allowing network changes, things can get complex fast; - // make sure you know what you are doing if you use "any" - if (this.anyNetwork) { - this._network = currentNetwork; - // Reset all internal block number guards and caches - this._lastBlockNumber = -2; - this._fastBlockNumber = null; - this._fastBlockNumberPromise = null; - this._fastQueryDate = 0; - this._emitted.block = -2; - this._maxInternalBlockNumber = -1024; - this._internalBlockNumber = null; - // The "network" event MUST happen before this method resolves - // so any events have a chance to unregister, so we stall an - // additional event loop before returning from /this/ call - this.emit("network", currentNetwork, network); - yield stall(0); - return this._network; - } - const error = logger.makeError("underlying network changed", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.NETWORK_ERROR */ .Yd.errors.NETWORK_ERROR, { - event: "changed", - network: network, - detectedNetwork: currentNetwork - }); - this.emit("error", error); - throw error; - } - return 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(); - // We block additional polls until the polling interval - // is done, to prevent overwhelming the poll function - this._bootstrapPoll = setTimeout(() => { - // If polling was disabled, something may require a poke - // since starting the bootstrap poll and it was disabled - if (!this._poller) { - this.poll(); - } - // Clear out the bootstrap so we can do another - this._bootstrapPoll = null; - }, this.pollingInterval); - }, 0); - } - } - else if (!value && this._poller) { - clearInterval(this._poller); - this._poller = null; - } - } - get pollingInterval() { - return this._pollingInterval; - } - 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 now = getTime(); - // Stale block number, request a newer value - if ((now - this._fastQueryDate) > 2 * this._pollingInterval) { - this._fastQueryDate = now; - this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber) => { - if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { - this._fastBlockNumber = blockNumber; - } - return this._fastBlockNumber; - }); - } - return this._fastBlockNumberPromise; - } - _setFastBlockNumber(blockNumber) { - // Older block, maybe a stale request - if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) { - return; - } - // Update the time we updated the blocknumber - this._fastQueryDate = getTime(); - // Newer block number, use it - if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { - this._fastBlockNumber = blockNumber; - this._fastBlockNumberPromise = Promise.resolve(blockNumber); - } - } - waitForTransaction(transactionHash, confirmations, timeout) { - return __awaiter(this, void 0, void 0, function* () { - return this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null); - }); - } - _waitForTransaction(transactionHash, confirmations, timeout, replaceable) { - return __awaiter(this, void 0, void 0, function* () { - const receipt = yield this.getTransactionReceipt(transactionHash); - // Receipt is already good - if ((receipt ? receipt.confirmations : 0) >= confirmations) { - return receipt; - } - // Poll until the receipt is good... - 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 = (receipt) => { - if (receipt.confirmations < confirmations) { - return; - } - if (alreadyDone()) { - return; - } - resolve(receipt); - }; - this.on(transactionHash, minedHandler); - cancelFuncs.push(() => { this.removeListener(transactionHash, minedHandler); }); - if (replaceable) { - let lastBlockNumber = replaceable.startBlock; - let scannedBlock = null; - const replaceHandler = (blockNumber) => __awaiter(this, void 0, void 0, function* () { - if (done) { - return; - } - // Wait 1 second; this is only used in the case of a fault, so - // we will trade off a little bit of latency for more consistent - // results and fewer JSON-RPC calls - yield stall(1000); - this.getTransactionCount(replaceable.from).then((nonce) => __awaiter(this, void 0, void 0, function* () { - if (done) { - return; - } - if (nonce <= replaceable.nonce) { - lastBlockNumber = blockNumber; - } - else { - // First check if the transaction was mined - { - const mined = yield this.getTransaction(transactionHash); - if (mined && mined.blockNumber != null) { - return; - } - } - // First time scanning. We start a little earlier for some - // wiggle room here to handle the eventually consistent nature - // of blockchain (e.g. the getTransactionCount was for a - // different block) - 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]; - // Successfully mined! - if (tx.hash === transactionHash) { - return; - } - // Matches our transaction from and nonce; its a replacement - if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) { - if (done) { - return; - } - // Get the receipt of the replacement - const receipt = yield this.waitForTransaction(tx.hash, confirmations); - // Already resolved or rejected (prolly a timeout) - if (alreadyDone()) { - return; - } - // The reason we were replaced - 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"; - } - // Explain why we were replaced - reject(logger.makeError("transaction was replaced", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.TRANSACTION_REPLACED */ .Yd.errors.TRANSACTION_REPLACED, { - cancelled: (reason === "replaced" || reason === "cancelled"), - reason, - replacement: this._wrapTransaction(tx), - hash: transactionHash, - receipt - })); - 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 timer = setTimeout(() => { - if (alreadyDone()) { - return; - } - reject(logger.makeError("timeout exceeded", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.TIMEOUT */ .Yd.errors.TIMEOUT, { timeout: timeout })); - }, timeout); - if (timer.unref) { - timer.unref(); - } - cancelFuncs.push(() => { clearTimeout(timer); }); - } - }); - }); - } - getBlockNumber() { - return __awaiter(this, void 0, void 0, function* () { - return this._getInternalBlockNumber(0); - }); - } - getGasPrice() { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const result = yield this.perform("getGasPrice", {}); - try { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "getGasPrice", - result, error - }); - } - }); - } - getBalance(addressOrName, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) - }); - const result = yield this.perform("getBalance", params); - try { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "getBalance", - params, result, error - }); - } - }); - } - getTransactionCount(addressOrName, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) - }); - const result = yield this.perform("getTransactionCount", params); - try { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(result).toNumber(); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "getTransactionCount", - params, result, error - }); - } - }); - } - getCode(addressOrName, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) - }); - const result = yield this.perform("getCode", params); - try { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "getCode", - params, result, error - }); - } - }); - } - getStorageAt(addressOrName, position, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag), - position: Promise.resolve(position).then((p) => (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexValue */ .$P)(p)) - }); - const result = yield this.perform("getStorageAt", params); - try { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "getStorageAt", - params, result, error - }); - } - }); - } - // This should be called by any subclass wrapping a TransactionResponse - _wrapTransaction(tx, hash, startBlock) { - if (hash != null && (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexDataLength */ .E1)(hash) !== 32) { - throw new Error("invalid response - sendTransaction"); - } - const result = tx; - // Check the hash we expect is the same as the hash the server reported - if (hash != null && tx.hash !== hash) { - logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNKNOWN_ERROR */ .Yd.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash }); - } - result.wait = (confirms, timeout) => __awaiter(this, void 0, void 0, function* () { - if (confirms == null) { - confirms = 1; - } - if (timeout == null) { - timeout = 0; - } - // Get the details to detect replacement - let replacement = undefined; - 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; - } - // No longer pending, allow the polling loop to garbage collect this - this._emitted["t:" + tx.hash] = receipt.blockNumber; - if (receipt.status === 0) { - logger.throwError("transaction failed", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION, { - transactionHash: tx.hash, - transaction: tx, - receipt: receipt - }); - } - return receipt; - }); - return result; - } - sendTransaction(signedTransaction) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const hexTx = yield Promise.resolve(signedTransaction).then(t => (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(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 hash = yield this.perform("sendTransaction", { signedTransaction: hexTx }); - return this._wrapTransaction(tx, hash, blockNumber); - } - catch (error) { - error.transaction = tx; - error.transactionHash = tx.hash; - throw error; - } - }); - } - _getTransactionRequest(transaction) { - return __awaiter(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 ? _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.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 ? (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(v) : null)); - }); - return this.formatter.transactionRequest(yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)(tx)); - }); - } - _getFilter(filter) { - return __awaiter(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 (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)(result)); - }); - } - call(transaction, blockTag) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - transaction: this._getTransactionRequest(transaction), - blockTag: this._getBlockTag(blockTag) - }); - const result = yield this.perform("call", params); - try { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .hexlify */ .Dv)(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "call", - params, result, error - }); - } - }); - } - estimateGas(transaction) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ - transaction: this._getTransactionRequest(transaction) - }); - const result = yield this.perform("estimateGas", params); - try { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(result); - } - catch (error) { - return logger.throwError("bad result from backend", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR, { - method: "estimateGas", - params, result, error - }); - } - }); - } - _getAddress(addressOrName) { - return __awaiter(this, void 0, void 0, function* () { - addressOrName = yield addressOrName; - if (typeof (addressOrName) !== "string") { - logger.throwArgumentError("invalid address or ENS name", "name", addressOrName); - } - const address = yield this.resolveName(addressOrName); - if (address == null) { - logger.throwError("ENS name not configured", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: `resolveName(${JSON.stringify(addressOrName)})` - }); - } - return address; - }); - } - _getBlock(blockHashOrBlockTag, includeTransactions) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - blockHashOrBlockTag = yield blockHashOrBlockTag; - // If blockTag is a number (not "latest", etc), this is the block number - let blockNumber = -128; - const params = { - includeTransactions: !!includeTransactions - }; - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(blockHashOrBlockTag, 32)) { - params.blockHash = blockHashOrBlockTag; - } - else { - try { - params.blockTag = yield this._getBlockTag(blockHashOrBlockTag); - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(params.blockTag)) { - blockNumber = parseInt(params.blockTag.substring(2), 16); - } - } - catch (error) { - logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag); - } - } - return (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_12__/* .poll */ .$l)(() => __awaiter(this, void 0, void 0, function* () { - const block = yield this.perform("getBlock", params); - // Block was not found - if (block == null) { - // For blockhashes, if we didn't say it existed, that blockhash may - // not exist. If we did see it though, perhaps from a log, we know - // it exists, and this node is just not caught up yet. - if (params.blockHash != null) { - if (this._emitted["b:" + params.blockHash] == null) { - return null; - } - } - // For block tags, if we are asking for a future block, we return null - if (params.blockTag != null) { - if (blockNumber > this._emitted.block) { - return null; - } - } - // Retry on the next block - return undefined; - } - // Add transactions - if (includeTransactions) { - let blockNumber = 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 (blockNumber == null) { - blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - } - // Add the confirmations using the fast block number (pessimistic) - let confirmations = (blockNumber - 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 __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - transactionHash = yield transactionHash; - const params = { transactionHash: this.formatter.hash(transactionHash, true) }; - return (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_12__/* .poll */ .$l)(() => __awaiter(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 undefined; - } - 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); - // Add the confirmations using the fast block number (pessimistic) - let confirmations = (blockNumber - tx.blockNumber) + 1; - if (confirmations <= 0) { - confirmations = 1; - } - tx.confirmations = confirmations; - } - return this._wrapTransaction(tx); - }), { oncePoll: this }); - }); - } - getTransactionReceipt(transactionHash) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - transactionHash = yield transactionHash; - const params = { transactionHash: this.formatter.hash(transactionHash, true) }; - return (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_12__/* .poll */ .$l)(() => __awaiter(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 undefined; - } - // "geth-etc" returns receipts before they are ready - if (result.blockHash == null) { - return undefined; - } - 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); - // Add the confirmations using the fast block number (pessimistic) - let confirmations = (blockNumber - receipt.blockNumber) + 1; - if (confirmations <= 0) { - confirmations = 1; - } - receipt.confirmations = confirmations; - } - return receipt; - }), { oncePoll: this }); - }); - } - getLogs(filter) { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - const params = yield (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_5__/* .resolveProperties */ .mE)({ filter: this._getFilter(filter) }); - const logs = yield this.perform("getLogs", params); - logs.forEach((log) => { - if (log.removed == null) { - log.removed = false; - } - }); - return _formatter__WEBPACK_IMPORTED_MODULE_13__/* .Formatter.arrayOf */ .Mb.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs); - }); - } - getEtherPrice() { - return __awaiter(this, void 0, void 0, function* () { - yield this.getNetwork(); - return this.perform("getEtherPrice", {}); - }); - } - _getBlockTag(blockTag) { - return __awaiter(this, void 0, void 0, function* () { - blockTag = yield blockTag; - if (typeof (blockTag) === "number" && blockTag < 0) { - if (blockTag % 1) { - logger.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); - }); - } - getResolver(name) { - return __awaiter(this, void 0, void 0, function* () { - try { - const address = yield this._getResolver(name); - if (address == null) { - return null; - } - return new Resolver(this, address, name); - } - catch (error) { - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION) { - return null; - } - throw error; - } - }); - } - _getResolver(name) { - return __awaiter(this, void 0, void 0, function* () { - // Get the resolver from the blockchain - const network = yield this.getNetwork(); - // No ENS... - if (!network.ensAddress) { - logger.throwError("network does not support ENS", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { operation: "ENS", network: network.name }); - } - // keccak256("resolver(bytes32)") - const transaction = { - to: network.ensAddress, - data: ("0x0178b8bf" + (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_10__/* .namehash */ .V)(name).substring(2)) - }; - try { - return this.formatter.callAddress(yield this.call(transaction)); - } - catch (error) { - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION) { - return null; - } - throw error; - } - }); - } - resolveName(name) { - return __awaiter(this, void 0, void 0, function* () { - name = yield name; - // If it is already an address, nothing to resolve - try { - return Promise.resolve(this.formatter.address(name)); - } - catch (error) { - // If is is a hexstring, the address is bad (See #694) - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(name)) { - throw error; - } - } - if (typeof (name) !== "string") { - logger.throwArgumentError("invalid ENS name", "name", name); - } - // Get the addr from the resovler - const resolver = yield this.getResolver(name); - if (!resolver) { - return null; - } - return yield resolver.getAddress(); - }); - } - lookupAddress(address) { - return __awaiter(this, void 0, void 0, function* () { - address = yield address; - address = this.formatter.address(address); - const reverseName = address.substring(2).toLowerCase() + ".addr.reverse"; - const resolverAddress = yield this._getResolver(reverseName); - if (!resolverAddress) { - return null; - } - // keccak("name(bytes32)") - let bytes = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .arrayify */ .lE)(yield this.call({ - to: resolverAddress, - data: ("0x691f3431" + (0,_ethersproject_hash__WEBPACK_IMPORTED_MODULE_10__/* .namehash */ .V)(reverseName).substring(2)) - })); - // Strip off the dynamic string pointer (0x20) - if (bytes.length < 32 || !_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(bytes.slice(0, 32)).eq(32)) { - return null; - } - bytes = bytes.slice(32); - // Not a length-prefixed string - if (bytes.length < 32) { - return null; - } - // Get the length of the string (from the length-prefix) - const length = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_6__/* .BigNumber.from */ .O$.from(bytes.slice(0, 32)).toNumber(); - bytes = bytes.slice(32); - // Length longer than available data - if (length > bytes.length) { - return null; - } - const name = (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_9__/* .toUtf8String */ .ZN)(bytes.slice(0, length)); - // Make sure the reverse record matches the foward record - const addr = yield this.resolveName(name); - if (addr != address) { - return null; - } - return name; - }); - } - getAvatar(nameOrAddress) { - return __awaiter(this, void 0, void 0, function* () { - let resolver = null; - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_3__/* .isHexString */ .A7)(nameOrAddress)) { - // Address; reverse lookup - const address = this.formatter.address(nameOrAddress); - const reverseName = address.substring(2).toLowerCase() + ".addr.reverse"; - const resolverAddress = yield this._getResolver(reverseName); - if (!resolverAddress) { - return null; - } - resolver = new Resolver(this, resolverAddress, "_", address); - } - else { - // ENS name; forward lookup - resolver = yield this.getResolver(nameOrAddress); - if (!resolver) { - return null; - } - } - const avatar = yield resolver.getAvatar(); - if (avatar == null) { - return null; - } - return avatar.url; - }); - } - perform(method, params) { - return logger.throwError(method + " not implemented", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_1__/* .Logger.errors.NOT_IMPLEMENTED */ .Yd.errors.NOT_IMPLEMENTED, { operation: method }); - } - _startEvent(event) { - this.polling = (this._events.filter((e) => e.pollable()).length > 0); - } - _stopEvent(event) { - this.polling = (this._events.filter((e) => e.pollable()).length > 0); - } - _addEventListener(eventName, listener, once) { - const event = new Event(getEventTag(eventName), listener, once); - this._events.push(event); - this._startEvent(event); - return this; - } - on(eventName, listener) { - return this._addEventListener(eventName, listener, false); - } - once(eventName, listener) { - return this._addEventListener(eventName, listener, true); - } - emit(eventName, ...args) { - let result = false; - let stopped = []; - let eventTag = getEventTag(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; - } - listenerCount(eventName) { - if (!eventName) { - return this._events.length; - } - let eventTag = getEventTag(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 = getEventTag(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 = getEventTag(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 = getEventTag(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; - } -} -//# sourceMappingURL=base-provider.js.map - -/***/ }), - -/***/ 8523: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Ed": () => (/* binding */ isCommunityResourcable), -/* harmony export */ "Gp": () => (/* binding */ isCommunityResource), -/* harmony export */ "Mb": () => (/* binding */ Formatter), -/* harmony export */ "vh": () => (/* binding */ showThrottleMessage) -/* harmony export */ }); -/* harmony import */ var _ethersproject_address__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(9808); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1210); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_transactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9165); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2405); - - - - - - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); -class Formatter { - constructor() { - logger.checkNew(new.target, Formatter); - this.formats = this.getDefaultFormats(); - } - getDefaultFormats() { - const formats = ({}); - const address = this.address.bind(this); - const bigNumber = this.bigNumber.bind(this); - const blockTag = this.blockTag.bind(this); - const data = this.data.bind(this); - const hash = 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: hash, - type: type, - accessList: Formatter.allowNull(this.accessList.bind(this), null), - blockHash: Formatter.allowNull(hash, null), - blockNumber: Formatter.allowNull(number, null), - transactionIndex: Formatter.allowNull(number, null), - confirmations: Formatter.allowNull(number, null), - from: address, - // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) - // must be set - gasPrice: Formatter.allowNull(bigNumber), - maxPriorityFeePerGas: Formatter.allowNull(bigNumber), - maxFeePerGas: Formatter.allowNull(bigNumber), - gasLimit: bigNumber, - to: Formatter.allowNull(address, null), - value: bigNumber, - nonce: number, - data: data, - r: Formatter.allowNull(this.uint256), - s: Formatter.allowNull(this.uint256), - v: Formatter.allowNull(number), - creates: Formatter.allowNull(address, null), - raw: Formatter.allowNull(data), - }; - formats.transactionRequest = { - from: Formatter.allowNull(address), - nonce: Formatter.allowNull(number), - gasLimit: Formatter.allowNull(bigNumber), - gasPrice: Formatter.allowNull(bigNumber), - maxPriorityFeePerGas: Formatter.allowNull(bigNumber), - maxFeePerGas: Formatter.allowNull(bigNumber), - to: Formatter.allowNull(address), - 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: hash, - address: address, - topics: Formatter.arrayOf(hash), - data: data, - logIndex: number, - blockHash: hash, - }; - formats.receipt = { - to: Formatter.allowNull(this.address, null), - from: Formatter.allowNull(this.address, null), - contractAddress: Formatter.allowNull(address, null), - transactionIndex: number, - // should be allowNull(hash), but broken-EIP-658 support is handled in receipt - root: Formatter.allowNull(hex), - gasUsed: bigNumber, - logsBloom: Formatter.allowNull(data), - blockHash: hash, - transactionHash: hash, - 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: type - }; - formats.block = { - hash: hash, - parentHash: hash, - number: number, - timestamp: number, - nonce: Formatter.allowNull(hex), - difficulty: this.difficulty.bind(this), - gasLimit: bigNumber, - gasUsed: bigNumber, - miner: address, - extraData: data, - transactions: Formatter.allowNull(Formatter.arrayOf(hash)), - baseFeePerGas: Formatter.allowNull(bigNumber) - }; - formats.blockWithTransactions = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .shallowCopy */ .DC)(formats.block); - formats.blockWithTransactions.transactions = Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this))); - formats.filter = { - fromBlock: Formatter.allowNull(blockTag, undefined), - toBlock: Formatter.allowNull(blockTag, undefined), - blockHash: Formatter.allowNull(hash, undefined), - address: Formatter.allowNull(address, undefined), - topics: Formatter.allowNull(this.topics.bind(this), undefined), - }; - formats.filterLog = { - blockNumber: Formatter.allowNull(number), - blockHash: Formatter.allowNull(hash), - transactionIndex: number, - removed: Formatter.allowNull(this.boolean.bind(this)), - address: address, - data: Formatter.allowFalsish(data, "0x"), - topics: Formatter.arrayOf(hash), - transactionHash: hash, - logIndex: number, - }; - return formats; - } - accessList(accessList) { - return (0,_ethersproject_transactions__WEBPACK_IMPORTED_MODULE_3__/* .accessListify */ .z7)(accessList || []); - } - // Requires a BigNumberish that is within the IEEE754 safe integer range; returns a number - // Strict! Used on input. - number(number) { - if (number === "0x") { - return 0; - } - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(number).toNumber(); - } - type(number) { - if (number === "0x" || number == null) { - return 0; - } - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(number).toNumber(); - } - // Strict! Used on input. - bigNumber(value) { - return _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(value); - } - // Requires a boolean, "true" or "false"; returns a boolean - 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; - } - } - throw new Error("invalid boolean - " + value); - } - hex(value, strict) { - if (typeof (value) === "string") { - if (!strict && value.substring(0, 2) !== "0x") { - value = "0x" + value; - } - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(value)) { - return value.toLowerCase(); - } - } - return logger.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; - } - // Requires an address - // Strict! Used on input. - address(value) { - return (0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_6__/* .getAddress */ .Kn)(value); - } - callAddress(value) { - if (!(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(value, 32)) { - return null; - } - const address = (0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_6__/* .getAddress */ .Kn)((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .hexDataSlice */ .p3)(value, 12)); - return (address === _ethersproject_constants__WEBPACK_IMPORTED_MODULE_7__/* .AddressZero */ .d) ? null : address; - } - contractAddress(value) { - return (0,_ethersproject_address__WEBPACK_IMPORTED_MODULE_6__/* .getContractAddress */ .CR)(value); - } - // Strict! Used on input. - blockTag(blockTag) { - if (blockTag == null) { - return "latest"; - } - if (blockTag === "earliest") { - return "0x0"; - } - if (blockTag === "latest" || blockTag === "pending") { - return blockTag; - } - if (typeof (blockTag) === "number" || (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(blockTag)) { - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .hexValue */ .$P)(blockTag); - } - throw new Error("invalid blockTag"); - } - // Requires a hash, optionally requires 0x prefix; returns prefixed lowercase hash. - hash(value, strict) { - const result = this.hex(value, strict); - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .hexDataLength */ .E1)(result) !== 32) { - return logger.throwArgumentError("invalid hash", "value", value); - } - return result; - } - // Returns the difficulty as a number, or if too large (i.e. PoA network) null - difficulty(value) { - if (value == null) { - return null; - } - const v = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(value); - try { - return v.toNumber(); - } - catch (error) { } - return null; - } - uint256(value) { - if (!(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(value)) { - throw new Error("invalid uint256"); - } - return (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .hexZeroPad */ .$m)(value, 32); - } - _block(value, format) { - if (value.author != null && value.miner == null) { - value.miner = value.author; - } - // The difficulty may need to come from _difficulty in recursed blocks - const difficulty = (value._difficulty != null) ? value._difficulty : value.difficulty; - const result = Formatter.check(format, value); - result._difficulty = ((difficulty == null) ? null : _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(difficulty)); - return result; - } - block(value) { - return this._block(value, this.formats.block); - } - blockWithTransactions(value) { - return this._block(value, this.formats.blockWithTransactions); - } - // Strict! Used on input. - transactionRequest(value) { - return Formatter.check(this.formats.transactionRequest, value); - } - transactionResponse(transaction) { - // Rename gas to gasLimit - if (transaction.gas != null && transaction.gasLimit == null) { - transaction.gasLimit = transaction.gas; - } - // Some clients (TestRPC) do strange things like return 0x0 for the - // 0 address; correct this to be a real address - if (transaction.to && _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(transaction.to).isZero()) { - transaction.to = "0x0000000000000000000000000000000000000000"; - } - // Rename input to data - if (transaction.input != null && transaction.data == null) { - transaction.data = transaction.input; - } - // If to and creates are empty, populate the creates from the transaction - 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 ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(chainId)) { - chainId = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(chainId).toNumber(); - } - result.chainId = chainId; - } - else { - let chainId = transaction.networkId; - // geth-etc returns chainId - if (chainId == null && result.v == null) { - chainId = transaction.chainId; - } - if ((0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_5__/* .isHexString */ .A7)(chainId)) { - chainId = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.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; - } - // 0x0000... should actually be null - if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") { - result.blockHash = null; - } - return result; - } - transaction(value) { - return (0,_ethersproject_transactions__WEBPACK_IMPORTED_MODULE_3__/* .parse */ .Qc)(value); - } - receiptLog(value) { - return Formatter.check(this.formats.receiptLog, value); - } - receipt(value) { - const result = Formatter.check(this.formats.receipt, value); - // RSK incorrectly implemented EIP-658, so we munge things a bit here for it - if (result.root != null) { - if (result.root.length <= 4) { - // Could be 0x00, 0x0, 0x01 or 0x1 - const value = _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_4__/* .BigNumber.from */ .O$.from(result.root).toNumber(); - if (value === 0 || value === 1) { - // Make sure if both are specified, they match - if (result.status != null && (result.status !== value)) { - logger.throwArgumentError("alt-root-status/status mismatch", "value", { root: result.root, status: result.status }); - } - result.status = value; - delete result.root; - } - else { - logger.throwArgumentError("invalid alt-root-status", "value.root", result.root); - } - } - else if (result.root.length !== 66) { - // Must be a valid bytes32 - logger.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 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 !== undefined) { - result[key] = value; - } - } - catch (error) { - error.checkKey = key; - error.checkValue = object[key]; - throw error; - } - } - return result; - } - // if value is null-ish, nullValue is returned - static allowNull(format, nullValue) { - return (function (value) { - if (value == null) { - return nullValue; - } - return format(value); - }); - } - // If value is false-ish, replaceValue is returned - static allowFalsish(format, replaceValue) { - return (function (value) { - if (!value) { - return replaceValue; - } - return format(value); - }); - } - // Requires an Array satisfying check - 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; - }); - } -} -function isCommunityResourcable(value) { - return (value && typeof (value.isCommunityResource) === "function"); -} -function isCommunityResource(value) { - return (isCommunityResourcable(value) && value.isCommunityResource()); -} -// Show the throttle message only once -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("=========================="); -} -//# sourceMappingURL=formatter.js.map - -/***/ }), - -/***/ 7100: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "C": () => (/* binding */ JsonRpcSigner), -/* harmony export */ "r": () => (/* binding */ JsonRpcProvider) -/* harmony export */ }); -/* harmony import */ var _ethersproject_abstract_signer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4502); -/* harmony import */ var _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(3922); -/* harmony import */ var _ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3756); -/* harmony import */ var _ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(506); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_strings__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(5804); -/* harmony import */ var _ethersproject_transactions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(9165); -/* harmony import */ var _ethersproject_web__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2585); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2405); -/* harmony import */ var _base_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2001); - -var __awaiter = (undefined && undefined.__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 logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); - -const errorGas = ["call", "estimateGas"]; -function checkError(method, error, params) { - // Undo the "convenience" some nodes are attempting to prevent backwards - // incompatibility; maybe for v6 consider forwarding reverts as errors - if (method === "call" && error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.SERVER_ERROR */ .Yd.errors.SERVER_ERROR) { - const e = error.error; - if (e && e.message.match("reverted") && (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__/* .isHexString */ .A7)(e.data)) { - return e.data; - } - logger.throwError("missing revert data in call exception", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.CALL_EXCEPTION */ .Yd.errors.CALL_EXCEPTION, { - error, data: "0x" - }); - } - let message = error.message; - if (error.code === _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.SERVER_ERROR */ .Yd.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(); - const transaction = params.transaction || params.signedTransaction; - // "insufficient funds for gas * price + value + cost(data)" - if (message.match(/insufficient funds|base fee exceeds gas limit/)) { - logger.throwError("insufficient funds for intrinsic transaction cost", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.INSUFFICIENT_FUNDS */ .Yd.errors.INSUFFICIENT_FUNDS, { - error, method, transaction - }); - } - // "nonce too low" - if (message.match(/nonce too low/)) { - logger.throwError("nonce has already been used", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.NONCE_EXPIRED */ .Yd.errors.NONCE_EXPIRED, { - error, method, transaction - }); - } - // "replacement transaction underpriced" - if (message.match(/replacement transaction underpriced/)) { - logger.throwError("replacement fee too low", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.REPLACEMENT_UNDERPRICED */ .Yd.errors.REPLACEMENT_UNDERPRICED, { - error, method, transaction - }); - } - // "replacement transaction underpriced" - if (message.match(/only replay-protected/)) { - logger.throwError("legacy pre-eip-155 transactions not supported", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - error, method, transaction - }); - } - if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) { - logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNPREDICTABLE_GAS_LIMIT */ .Yd.errors.UNPREDICTABLE_GAS_LIMIT, { - error, method, transaction - }); - } - throw error; -} -function timer(timeout) { - return new Promise(function (resolve) { - setTimeout(resolve, timeout); - }); -} -function getResult(payload) { - if (payload.error) { - // @TODO: not any - const error = new Error(payload.error.message); - error.code = payload.error.code; - error.data = payload.error.data; - throw error; - } - return payload.result; -} -function getLowerCase(value) { - if (value) { - return value.toLowerCase(); - } - return value; -} -const _constructorGuard = {}; -class JsonRpcSigner extends _ethersproject_abstract_signer__WEBPACK_IMPORTED_MODULE_3__/* .Signer */ .E { - constructor(constructorGuard, provider, addressOrIndex) { - logger.checkNew(new.target, JsonRpcSigner); - super(); - if (constructorGuard !== _constructorGuard) { - throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner"); - } - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "provider", provider); - if (addressOrIndex == null) { - addressOrIndex = 0; - } - if (typeof (addressOrIndex) === "string") { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "_address", this.provider.formatter.address(addressOrIndex)); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "_index", null); - } - else if (typeof (addressOrIndex) === "number") { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "_index", addressOrIndex); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "_address", null); - } - else { - logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex); - } - } - connect(provider) { - return logger.throwError("cannot alter JSON-RPC Signer connection", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: "connect" - }); - } - connectUnchecked() { - return new UncheckedJsonRpcSigner(_constructorGuard, 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.throwError("unknown account #" + this._index, _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: "getAddress" - }); - } - return this.provider.formatter.address(accounts[this._index]); - }); - } - sendUncheckedTransaction(transaction) { - transaction = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(transaction); - const fromAddress = this.getAddress().then((address) => { - if (address) { - address = address.toLowerCase(); - } - return address; - }); - // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user - // wishes to use this, it is easy to specify explicitly, otherwise - // we look it up for them. - if (transaction.gasLimit == null) { - const estimate = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(transaction); - estimate.from = fromAddress; - transaction.gasLimit = this.provider.estimateGas(estimate); - } - if (transaction.to != null) { - transaction.to = Promise.resolve(transaction.to).then((to) => __awaiter(this, void 0, void 0, function* () { - if (to == null) { - return null; - } - const address = yield this.provider.resolveName(to); - if (address == null) { - logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to); - } - return address; - })); - } - return (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .resolveProperties */ .mE)({ - tx: (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .resolveProperties */ .mE)(transaction), - sender: fromAddress - }).then(({ tx, sender }) => { - if (tx.from != null) { - if (tx.from.toLowerCase() !== sender) { - logger.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((hash) => { - return hash; - }, (error) => { - return checkError("sendTransaction", error, hexTx); - }); - }); - } - signTransaction(transaction) { - return logger.throwError("signing transactions is unsupported", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.UNSUPPORTED_OPERATION */ .Yd.errors.UNSUPPORTED_OPERATION, { - operation: "signTransaction" - }); - } - sendTransaction(transaction) { - return __awaiter(this, void 0, void 0, function* () { - // This cannot be mined any earlier than any recent block - const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval); - // Send the transaction - const hash = yield this.sendUncheckedTransaction(transaction); - try { - // Unfortunately, JSON-RPC only provides and opaque transaction hash - // for a response, and we need the actual transaction, so we poll - // for it; it should show up very quickly - return yield (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_5__/* .poll */ .$l)(() => __awaiter(this, void 0, void 0, function* () { - const tx = yield this.provider.getTransaction(hash); - if (tx === null) { - return undefined; - } - return this.provider._wrapTransaction(tx, hash, blockNumber); - }), { oncePoll: this.provider }); - } - catch (error) { - error.transactionHash = hash; - throw error; - } - }); - } - signMessage(message) { - return __awaiter(this, void 0, void 0, function* () { - const data = ((typeof (message) === "string") ? (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_6__/* .toUtf8Bytes */ .Y0)(message) : message); - const address = yield this.getAddress(); - return yield this.provider.send("personal_sign", [(0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .Dv)(data), address.toLowerCase()]); - }); - } - _legacySignMessage(message) { - return __awaiter(this, void 0, void 0, function* () { - const data = ((typeof (message) === "string") ? (0,_ethersproject_strings__WEBPACK_IMPORTED_MODULE_6__/* .toUtf8Bytes */ .Y0)(message) : message); - const address = yield this.getAddress(); - // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign - return yield this.provider.send("eth_sign", [address.toLowerCase(), (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .Dv)(data)]); - }); - } - _signTypedData(domain, types, value) { - return __awaiter(this, void 0, void 0, function* () { - // Populate any ENS names (in-place) - const populated = yield _ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__/* .TypedDataEncoder.resolveNames */ .E.resolveNames(domain, types, value, (name) => { - return this.provider.resolveName(name); - }); - const address = yield this.getAddress(); - return yield this.provider.send("eth_signTypedData_v4", [ - address.toLowerCase(), - JSON.stringify(_ethersproject_hash__WEBPACK_IMPORTED_MODULE_7__/* .TypedDataEncoder.getPayload */ .E.getPayload(populated.domain, types, populated.value)) - ]); - }); - } - unlock(password) { - return __awaiter(this, void 0, void 0, function* () { - const provider = this.provider; - const address = yield this.getAddress(); - return provider.send("personal_unlockAccount", [address.toLowerCase(), password, null]); - }); - } -} -class UncheckedJsonRpcSigner extends JsonRpcSigner { - sendTransaction(transaction) { - return this.sendUncheckedTransaction(transaction).then((hash) => { - return { - hash: hash, - nonce: null, - gasLimit: null, - gasPrice: null, - data: null, - value: null, - chainId: null, - confirmations: 0, - from: null, - wait: (confirmations) => { return this.provider.waitForTransaction(hash, confirmations); } - }; - }); - } -} -const allowedTransactionKeys = { - 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 _base_provider__WEBPACK_IMPORTED_MODULE_8__/* .BaseProvider */ .Zk { - constructor(url, network) { - logger.checkNew(new.target, JsonRpcProvider); - let networkOrReady = network; - // The network is unknown, query the JSON-RPC for it - if (networkOrReady == null) { - networkOrReady = new Promise((resolve, reject) => { - setTimeout(() => { - this.detectNetwork().then((network) => { - resolve(network); - }, (error) => { - reject(error); - }); - }, 0); - }); - } - super(networkOrReady); - // Default URL - if (!url) { - url = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .getStatic */ .tu)(this.constructor, "defaultUrl")(); - } - if (typeof (url) === "string") { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "connection", Object.freeze({ - url: url - })); - } - else { - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .defineReadOnly */ .zG)(this, "connection", Object.freeze((0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(url))); - } - this._nextId = 42; - } - get _cache() { - if (this._eventLoopCache == null) { - this._eventLoopCache = {}; - } - return this._eventLoopCache; - } - static defaultUrl() { - return "http:/\/localhost:8545"; - } - detectNetwork() { - if (!this._cache["detectNetwork"]) { - this._cache["detectNetwork"] = this._uncachedDetectNetwork(); - // Clear this cache at the beginning of the next event loop - setTimeout(() => { - this._cache["detectNetwork"] = null; - }, 0); - } - return this._cache["detectNetwork"]; - } - _uncachedDetectNetwork() { - return __awaiter(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 (error) { } - } - if (chainId != null) { - const getNetwork = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .getStatic */ .tu)(this.constructor, "getNetwork"); - try { - return getNetwork(_ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_9__/* .BigNumber.from */ .O$.from(chainId).toNumber()); - } - catch (error) { - return logger.throwError("could not detect network", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.NETWORK_ERROR */ .Yd.errors.NETWORK_ERROR, { - chainId: chainId, - event: "invalidNetwork", - serverError: error - }); - } - } - return logger.throwError("could not detect network", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.NETWORK_ERROR */ .Yd.errors.NETWORK_ERROR, { - event: "noNetwork" - }); - }); - } - getSigner(addressOrIndex) { - return new JsonRpcSigner(_constructorGuard, 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: method, - params: params, - id: (this._nextId++), - jsonrpc: "2.0" - }; - this.emit("debug", { - action: "request", - request: (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .deepCopy */ .p$)(request), - provider: this - }); - // We can expand this in the future to any call, but for now these - // are the biggest wins and do not require any serializing parameters. - const cache = (["eth_chainId", "eth_blockNumber"].indexOf(method) >= 0); - if (cache && this._cache[method]) { - return this._cache[method]; - } - const result = (0,_ethersproject_web__WEBPACK_IMPORTED_MODULE_5__/* .fetchJson */ .rd)(this.connection, JSON.stringify(request), getResult).then((result) => { - this.emit("debug", { - action: "response", - request: request, - response: result, - provider: this - }); - return result; - }, (error) => { - this.emit("debug", { - action: "response", - error: error, - request: request, - provider: this - }); - throw error; - }); - // Cache the fetch, but clear it on the next event loop - if (cache) { - this._cache[method] = result; - setTimeout(() => { - this._cache[method] = null; - }, 0); - } - return result; - } - 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), params.position, 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 = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .getStatic */ .tu)(this.constructor, "hexlifyTransaction"); - return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]]; - } - case "estimateGas": { - const hexlifyTransaction = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .getStatic */ .tu)(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]]; - default: - break; - } - return null; - } - perform(method, params) { - return __awaiter(this, void 0, void 0, function* () { - // Legacy networks do not like the type field being passed along (which - // is fair), so we delete type if it is 0 and a non-EIP-1559 network - if (method === "call" || method === "estimateGas") { - const tx = params.transaction; - if (tx && tx.type != null && _ethersproject_bignumber__WEBPACK_IMPORTED_MODULE_9__/* .BigNumber.from */ .O$.from(tx.type).isZero()) { - // If there are no EIP-1559 properties, it might be non-EIP-a559 - if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = yield this.getFeeData(); - if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { - // Network doesn't know about EIP-1559 (and hence type) - params = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(params); - params.transaction = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(tx); - delete params.transaction.type; - } - } - } - } - const args = this.prepareRequest(method, params); - if (args == null) { - logger.throwError(method + " not implemented", _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger.errors.NOT_IMPLEMENTED */ .Yd.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(); - } - super._startEvent(event); - } - _startPending() { - if (this._pendingFilter != null) { - return; - } - const self = this; - const pendingFilter = this.send("eth_newPendingTransactionFilter", []); - this._pendingFilter = pendingFilter; - pendingFilter.then(function (filterId) { - function poll() { - self.send("eth_getFilterChanges", [filterId]).then(function (hashes) { - if (self._pendingFilter != pendingFilter) { - return null; - } - let seq = Promise.resolve(); - hashes.forEach(function (hash) { - // @TODO: This should be garbage collected at some point... How? When? - self._emitted["t:" + hash.toLowerCase()] = "pending"; - seq = seq.then(function () { - return self.getTransaction(hash).then(function (tx) { - self.emit("pending", tx); - return null; - }); - }); - }); - return seq.then(function () { - return timer(1000); - }); - }).then(function () { - if (self._pendingFilter != pendingFilter) { - self.send("eth_uninstallFilter", [filterId]); - return; - } - setTimeout(function () { poll(); }, 0); - return null; - }).catch((error) => { }); - } - poll(); - return filterId; - }).catch((error) => { }); - } - _stopEvent(event) { - if (event.tag === "pending" && this.listenerCount("pending") === 0) { - this._pendingFilter = null; - } - super._stopEvent(event); - } - // Convert an ethers.js transaction into a JSON-RPC transaction - // - gasLimit => gas - // - All values hexlified - // - All numeric values zero-striped - // - All addresses are lowercased - // NOTE: This allows a TransactionRequest, but all values should be resolved - // before this is called - // @TODO: This will likely be removed in future versions and prepareRequest - // will be the preferred method for this. - static hexlifyTransaction(transaction, allowExtra) { - // Check only allowed properties are given - const allowed = (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .shallowCopy */ .DC)(allowedTransactionKeys); - if (allowExtra) { - for (const key in allowExtra) { - if (allowExtra[key]) { - allowed[key] = true; - } - } - } - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_4__/* .checkProperties */ .uj)(transaction, allowed); - const result = {}; - // Some nodes (INFURA ropsten; INFURA mainnet is fine) do not like leading zeros. - ["gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function (key) { - if (transaction[key] == null) { - return; - } - const value = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__/* .hexValue */ .$P)(transaction[key]); - if (key === "gasLimit") { - key = "gas"; - } - result[key] = value; - }); - ["from", "to", "data"].forEach(function (key) { - if (transaction[key] == null) { - return; - } - result[key] = (0,_ethersproject_bytes__WEBPACK_IMPORTED_MODULE_2__/* .hexlify */ .Dv)(transaction[key]); - }); - if (transaction.accessList) { - result["accessList"] = (0,_ethersproject_transactions__WEBPACK_IMPORTED_MODULE_10__/* .accessListify */ .z7)(transaction.accessList); - } - return result; - } -} -//# sourceMappingURL=json-rpc-provider.js.map - -/***/ }), - -/***/ 9450: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Q": () => (/* binding */ Web3Provider) -/* harmony export */ }); -/* harmony import */ var _ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(300); -/* harmony import */ var _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1424); -/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2405); -/* harmony import */ var _json_rpc_provider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7100); - - - - -const logger = new _ethersproject_logger__WEBPACK_IMPORTED_MODULE_0__/* .Logger */ .Yd(_version__WEBPACK_IMPORTED_MODULE_1__/* .version */ .i); - -let _nextId = 1; -function buildWeb3LegacyFetcher(provider, sendFunc) { - const fetcher = "Web3LegacyFetcher"; - return function (method, params) { - const request = { - method: method, - params: params, - id: (_nextId++), - jsonrpc: "2.0" - }; - return new Promise((resolve, reject) => { - this.emit("debug", { - action: "request", - fetcher, - request: (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .deepCopy */ .p$)(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 error = new Error(response.error.message); - error.code = response.error.code; - error.data = response.error.data; - return reject(error); - } - resolve(response.result); - }); - }); - }; -} -function buildEip1193Fetcher(provider) { - return function (method, params) { - if (params == null) { - params = []; - } - const request = { method, params }; - this.emit("debug", { - action: "request", - fetcher: "Eip1193Fetcher", - request: (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .deepCopy */ .p$)(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 _json_rpc_provider__WEBPACK_IMPORTED_MODULE_3__/* .JsonRpcProvider */ .r { - constructor(provider, network) { - logger.checkNew(new.target, Web3Provider); - if (provider == null) { - logger.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.throwArgumentError("unsupported provider", "provider", provider); - } - if (!path) { - path = "unknown:"; - } - } - super(path, network); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "jsonRpcFetchFunc", jsonRpcFetchFunc); - (0,_ethersproject_properties__WEBPACK_IMPORTED_MODULE_2__/* .defineReadOnly */ .zG)(this, "provider", subprovider); - } - send(method, params) { - return this.jsonRpcFetchFunc(method, params); - } -} -//# sourceMappingURL=web3-provider.js.map - -/***/ }), - -/***/ 6868: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "decode": () => (/* binding */ decode), - "encode": () => (/* binding */ encode) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/rlp/lib.esm/_version.js -const version = "rlp/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/rlp/lib.esm/index.js - -//See: https://github.com/ethereum/wiki/wiki/RLP - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -function arrayifyInteger(value) { - const result = []; - while (value) { - result.unshift(value & 0xff); - 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(0xc0 + payload.length); - return payload; - } - const length = arrayifyInteger(payload.length); - length.unshift(0xf7 + length.length); - return length.concat(payload); - } - if (!(0,lib_esm/* isBytesLike */.Zq)(object)) { - logger.throwArgumentError("RLP object must be BytesLike", "object", object); - } - const data = Array.prototype.slice.call((0,lib_esm/* arrayify */.lE)(object)); - if (data.length === 1 && data[0] <= 0x7f) { - return data; - } - else if (data.length <= 55) { - data.unshift(0x80 + data.length); - return data; - } - const length = arrayifyInteger(data.length); - length.unshift(0xb7 + length.length); - return length.concat(data); -} -function encode(object) { - return (0,lib_esm/* hexlify */.Dv)(_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) { - logger.throwError("child data too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - } - return { consumed: (1 + length), result: result }; -} -// returns { consumed: number, result: Object } -function _decode(data, offset) { - if (data.length === 0) { - logger.throwError("data too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - // Array with extra length prefix - if (data[offset] >= 0xf8) { - const lengthLength = data[offset] - 0xf7; - if (offset + 1 + lengthLength > data.length) { - logger.throwError("data short segment too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - const length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - logger.throwError("data long segment too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); - } - else if (data[offset] >= 0xc0) { - const length = data[offset] - 0xc0; - if (offset + 1 + length > data.length) { - logger.throwError("data array too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - return _decodeChildren(data, offset, offset + 1, length); - } - else if (data[offset] >= 0xb8) { - const lengthLength = data[offset] - 0xb7; - if (offset + 1 + lengthLength > data.length) { - logger.throwError("data array too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - const length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - logger.throwError("data array too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - const result = (0,lib_esm/* hexlify */.Dv)(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); - return { consumed: (1 + lengthLength + length), result: result }; - } - else if (data[offset] >= 0x80) { - const length = data[offset] - 0x80; - if (offset + 1 + length > data.length) { - logger.throwError("data too short", logger_lib_esm/* Logger.errors.BUFFER_OVERRUN */.Yd.errors.BUFFER_OVERRUN, {}); - } - const result = (0,lib_esm/* hexlify */.Dv)(data.slice(offset + 1, offset + 1 + length)); - return { consumed: (1 + length), result: result }; - } - return { consumed: 1, result: (0,lib_esm/* hexlify */.Dv)(data[offset]) }; -} -function decode(data) { - const bytes = (0,lib_esm/* arrayify */.lE)(data); - const decoded = _decode(bytes, 0); - if (decoded.consumed !== bytes.length) { - logger.throwArgumentError("invalid rlp data", "data", data); - } - return decoded.result; -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9088: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Gy": () => (/* binding */ computeHmac), - "bP": () => (/* binding */ ripemd160), - "JQ": () => (/* binding */ sha256), - "o": () => (/* binding */ sha512) -}); - -// EXTERNAL MODULE: ../node_modules/hash.js/lib/hash.js -var hash = __webpack_require__(5294); -var hash_default = /*#__PURE__*/__webpack_require__.n(hash); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/sha2/lib.esm/types.js -var types = __webpack_require__(7082); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/sha2/lib.esm/_version.js -const version = "sha2/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/sha2/lib.esm/sha2.js - - -//const _ripemd160 = _hash.ripemd160; - - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -function ripemd160(data) { - return "0x" + (hash_default().ripemd160().update((0,lib_esm/* arrayify */.lE)(data)).digest("hex")); -} -function sha256(data) { - return "0x" + (hash_default().sha256().update((0,lib_esm/* arrayify */.lE)(data)).digest("hex")); -} -function sha512(data) { - return "0x" + (hash_default().sha512().update((0,lib_esm/* arrayify */.lE)(data)).digest("hex")); -} -function computeHmac(algorithm, key, data) { - if (!types/* SupportedAlgorithm */.p[algorithm]) { - logger.throwError("unsupported algorithm " + algorithm, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "hmac", - algorithm: algorithm - }); - } - return "0x" + hash_default().hmac((hash_default())[algorithm], (0,lib_esm/* arrayify */.lE)(key)).update((0,lib_esm/* arrayify */.lE)(data)).digest("hex"); -} -//# sourceMappingURL=sha2.js.map - -/***/ }), - -/***/ 7082: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "p": () => (/* binding */ SupportedAlgorithm) -/* harmony export */ }); -var SupportedAlgorithm; -(function (SupportedAlgorithm) { - SupportedAlgorithm["sha256"] = "sha256"; - SupportedAlgorithm["sha512"] = "sha512"; -})(SupportedAlgorithm || (SupportedAlgorithm = {})); -; -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 9947: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Et": () => (/* binding */ SigningKey), - "VW": () => (/* binding */ computePublicKey), - "LO": () => (/* binding */ recoverPublicKey) -}); - -// EXTERNAL MODULE: ../node_modules/bn.js/lib/bn.js -var bn = __webpack_require__(3785); -var bn_default = /*#__PURE__*/__webpack_require__.n(bn); -// EXTERNAL MODULE: ../node_modules/hash.js/lib/hash.js -var hash = __webpack_require__(5294); -var hash_default = /*#__PURE__*/__webpack_require__.n(hash); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/signing-key/lib.esm/elliptic.js - - - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); - } - }, fn(module, module.exports), module.exports; -} - -function getDefaultExportFromNamespaceIfPresent (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; -} - -function getDefaultExportFromNamespaceIfNotNamed (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; -} - -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var minimalisticAssert = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -var utils_1 = createCommonjsModule(function (module, exports) { -'use strict'; - -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 & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - 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 encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; -}); - -var utils_1$1 = createCommonjsModule(function (module, exports) { -'use strict'; - -var utils = exports; - - - - -utils.assert = minimalisticAssert; -utils.toArray = utils_1.toArray; -utils.zero2 = utils_1.zero2; -utils.toHex = utils_1.toHex; -utils.encode = utils_1.encode; - -// Represent num in a w-NAF form -function getNAF(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; - } - - naf[i] = z; - k.iushrn(1); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(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) { - // First phase - 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; - } else { - m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - 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 = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new (bn_default())(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; -}); - -'use strict'; - - - -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_default())(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn_default().red(conf.prime) : bn_default().mont(this.p); - - // Useful for many curves - this.zero = new (bn_default())(0).toRed(this.red); - this.one = new (bn_default())(1).toRed(this.red); - this.two = new (bn_default())(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new (bn_default())(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - 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; - - // Generalized Greg Maxwell's trick - 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; - - // Translate into more windowed form - 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; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w, this._bitLength); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - 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') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - 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; - - // Fill all arrays - 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; - } - - // Comb small window NAFs - 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], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; - - // Try to avoid Projective points, if possible - 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 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3, /* 1 1 */ - ]; - - 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]; - p; - 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); - } - } - // Zeroify references - 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(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils_1$1.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert$1(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$1(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - 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() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].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: 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 dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: 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_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - 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 { - // old school shim for old browsers - 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; - } - }; -} -}); - -'use strict'; - - - - - - -var assert$2 = utils_1$1.assert; - -function ShortCurve(conf) { - base.call(this, 'short', conf); - - this.a = new (bn_default())(conf.a, 16).toRed(this.red); - this.b = new (bn_default())(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; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits_browser(ShortCurve, base); -var short_1 = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new (bn_default())(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new (bn_default())(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - 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); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new (bn_default())(vec.a, 16), - b: new (bn_default())(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis, - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn_default().mont(num); - var tinv = new (bn_default())(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new (bn_default())(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) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new (bn_default())(1); - var y1 = new (bn_default())(0); - var x2 = new (bn_default())(0); - var y2 = new (bn_default())(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - 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; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - 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); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new (bn_default())(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'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.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); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - 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_default())(x, 16); - this.y = new (bn_default())(y, 16); - // Force redgomery representation when loading from JSON - 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; - } -} -inherits_browser(Point, base.BasePoint); - -ShortCurve.prototype.point = function point(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 _getBeta() { - 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), - }, - } ]; -}; - -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(obj) { - return curve.point(obj[0], obj[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) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - 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; - - // 2P = O - 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_default())(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 eq(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 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_default())(0); - } else { - this.x = new (bn_default())(x, 16); - this.y = new (bn_default())(y, 16); - this.z = new (bn_default())(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_browser(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 neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - 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) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - 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 dblp(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; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - 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(); - - // Reuse results - 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 dbl() { - 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; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - 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; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - 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; - - // 4M + 6S + 10A - 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); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - 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); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - 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); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - 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); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new (bn_default())(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - 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; - - // y1 * z2^3 == y2 * z1^3 - 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 inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -var curve_1 = createCommonjsModule(function (module, exports) { -'use strict'; - -var curve = exports; - -curve.base = base; -curve.short = short_1; -curve.mont = /*RicMoo:ethers:require(./mont)*/(null); -curve.edwards = /*RicMoo:ethers:require(./edwards)*/(null); -}); - -var curves_1 = createCommonjsModule(function (module, exports) { -'use strict'; - -var curves = exports; - - - - - -var assert = 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; - - assert(this.g.validate(), 'Invalid curve'); - assert(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_default()).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_default()).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_default()).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_default()).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_default()).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_default()).sha256, - gRed: false, - g: [ - '9', - ], -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: (hash_default()).sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658', - ], -}); - -var pre; -try { - pre = /*RicMoo:ethers:require(./precomputed/secp256k1)*/(null).crash(); -} catch (e) { - pre = undefined; -} - -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_default()).sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3', - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15', - }, - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre, - ], -}); -}); - -'use strict'; - - - - - -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'); - minimalisticAssert(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] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new (hash_default()).hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - 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([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils_1.toArray(entropy, entropyEnc); - add = utils_1.toArray(add, addEnc); - - minimalisticAssert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils_1.toArray(add, addEnc || 'hex'); - this._update(add); - } - - 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(add); - this._reseed++; - return utils_1.encode(res, enc); -}; - -'use strict'; - - - -var assert$3 = utils_1$1.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - 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(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc, - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc, - }); -}; - -KeyPair.prototype.validate = function validate() { - 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) { - // compact is optional argument - 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(key, enc) { - this.priv = new (bn_default())(key, enc || 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert$3(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$3(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$3(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -'use strict'; - - - - -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_default())(options.r, 16); - this.s = new (bn_default())(options.s, 16); - if (options.recoveryParam === undefined) - 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 & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - - // Indefinite length or overflow - 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; - } - - // Leading zeroes - if (val <= 0x7f) { - return false; - } - - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && 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++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if (len === false) { - return false; - } - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - 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++] !== 0x02) { - 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] & 0x80) { - r = r.slice(1); - } else { - // Leading zeroes - return false; - } - } - if (s[0] === 0) { - if (s[1] & 0x80) { - s = s.slice(1); - } else { - // Leading zeroes - return false; - } - } - - this.r = new (bn_default())(r); - this.s = new (bn_default())(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); -}; - -'use strict'; - - - - - -var rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); }); -var assert$5 = utils_1$1.assert; - - - - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$5(Object.prototype.hasOwnProperty.call(curves_1, options), - 'Unknown curve ' + options); - - options = curves_1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - 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; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash for function for DRBG - 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 = {}; - - // Instantiate Hmac_DRBG - 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 bytes = this.n.byteLength(); - var ns2 = this.n.sub(new (bn_default())(2)); - for (;;) { - var priv = new (bn_default())(drbg.generate(bytes)); - 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 sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new (bn_default())(msg, 16)); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new (bn_default())(1)); - - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new (bn_default())(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(key.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); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature$1, key, enc) { - msg = this._truncateToN(new (bn_default())(msg, 16)); - key = this.keyFromPublic(key, enc); - signature$1 = new signature(signature$1, 'hex'); - - // Perform primitive values validation - 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; - - // Validate signature - 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, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - 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_default())(msg); - var r = signature$1.r; - var s = signature$1.s; - - // A set LSB signifies that the y-coordinate is odd - 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'); - - // 1.1. Let x = r + jn. - 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); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - 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 (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -var elliptic_1 = createCommonjsModule(function (module, exports) { -'use strict'; - -var elliptic = exports; - -elliptic.version = /*RicMoo:ethers*/{ version: "6.5.4" }.version; -elliptic.utils = utils_1$1; -elliptic.rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); }); -elliptic.curve = curve_1; -elliptic.curves = curves_1; - -// Protocols -elliptic.ec = ec; -elliptic.eddsa = /*RicMoo:ethers:require(./elliptic/eddsa)*/(null); -}); - -var EC$1 = elliptic_1.ec; - - -//# sourceMappingURL=elliptic.js.map - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/signing-key/lib.esm/_version.js -const version = "signing-key/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/signing-key/lib.esm/index.js - - - - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -let _curve = null; -function getCurve() { - if (!_curve) { - _curve = new EC$1("secp256k1"); - } - return _curve; -} -class SigningKey { - constructor(privateKey) { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "curve", "secp256k1"); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "privateKey", (0,lib_esm/* hexlify */.Dv)(privateKey)); - const keyPair = getCurve().keyFromPrivate((0,lib_esm/* arrayify */.lE)(this.privateKey)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "publicKey", "0x" + keyPair.getPublic(false, "hex")); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "compressedPublicKey", "0x" + keyPair.getPublic(true, "hex")); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_isSigningKey", true); - } - _addPoint(other) { - const p0 = getCurve().keyFromPublic((0,lib_esm/* arrayify */.lE)(this.publicKey)); - const p1 = getCurve().keyFromPublic((0,lib_esm/* arrayify */.lE)(other)); - return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex"); - } - signDigest(digest) { - const keyPair = getCurve().keyFromPrivate((0,lib_esm/* arrayify */.lE)(this.privateKey)); - const digestBytes = (0,lib_esm/* arrayify */.lE)(digest); - if (digestBytes.length !== 32) { - logger.throwArgumentError("bad digest length", "digest", digest); - } - const signature = keyPair.sign(digestBytes, { canonical: true }); - return (0,lib_esm/* splitSignature */.N)({ - recoveryParam: signature.recoveryParam, - r: (0,lib_esm/* hexZeroPad */.$m)("0x" + signature.r.toString(16), 32), - s: (0,lib_esm/* hexZeroPad */.$m)("0x" + signature.s.toString(16), 32), - }); - } - computeSharedSecret(otherKey) { - const keyPair = getCurve().keyFromPrivate((0,lib_esm/* arrayify */.lE)(this.privateKey)); - const otherKeyPair = getCurve().keyFromPublic((0,lib_esm/* arrayify */.lE)(computePublicKey(otherKey))); - return (0,lib_esm/* hexZeroPad */.$m)("0x" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32); - } - static isSigningKey(value) { - return !!(value && value._isSigningKey); - } -} -function recoverPublicKey(digest, signature) { - const sig = (0,lib_esm/* splitSignature */.N)(signature); - const rs = { r: (0,lib_esm/* arrayify */.lE)(sig.r), s: (0,lib_esm/* arrayify */.lE)(sig.s) }; - return "0x" + getCurve().recoverPubKey((0,lib_esm/* arrayify */.lE)(digest), rs, sig.recoveryParam).encode("hex", false); -} -function computePublicKey(key, compressed) { - const bytes = (0,lib_esm/* arrayify */.lE)(key); - if (bytes.length === 32) { - const signingKey = new SigningKey(bytes); - if (compressed) { - return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex"); - } - return signingKey.publicKey; - } - else if (bytes.length === 33) { - if (compressed) { - return (0,lib_esm/* hexlify */.Dv)(bytes); - } - return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex"); - } - else if (bytes.length === 65) { - if (!compressed) { - return (0,lib_esm/* hexlify */.Dv)(bytes); - } - return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex"); - } - return logger.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 592: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Ll": () => (/* binding */ nameprep) -/* harmony export */ }); -/* unused harmony exports _nameprepTableA1, _nameprepTableB2, _nameprepTableC */ -/* harmony import */ var _utf8__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5804); - - -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"); -// @TODO: Make this relative... -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((value) => { accum.push(value); }); - 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) { - // This allows platforms with incomplete normalize to bypass - // it for very basic names which the built-in toLowerCase - // will certainly handle correctly - if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) { - return value.toLowerCase(); - } - // Get the code points (keeping the current normalization) - let codes = (0,_utf8__WEBPACK_IMPORTED_MODULE_0__/* .toUtf8CodePoints */ .XL)(value); - codes = flatten(codes.map((code) => { - // Substitute Table B.1 (Maps to Nothing) - if (Table_B_1_flags.indexOf(code) >= 0) { - return []; - } - if (code >= 0xfe00 && code <= 0xfe0f) { - return []; - } - // Substitute Table B.2 (Case Folding) - let codesTableB2 = _nameprepTableB2(code); - if (codesTableB2) { - return codesTableB2; - } - // No Substitution - return [code]; - })); - // Normalize using form KC - codes = (0,_utf8__WEBPACK_IMPORTED_MODULE_0__/* .toUtf8CodePoints */ .XL)((0,_utf8__WEBPACK_IMPORTED_MODULE_0__/* ._toUtf8String */ .uu)(codes), _utf8__WEBPACK_IMPORTED_MODULE_0__/* .UnicodeNormalizationForm.NFKC */ .Uj.NFKC); - // Prohibit Tables C.1.2, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8, C.9 - codes.forEach((code) => { - if (_nameprepTableC(code)) { - throw new Error("STRINGPREP_CONTAINS_PROHIBITED"); - } - }); - // Prohibit Unassigned Code Points (Table A.1) - codes.forEach((code) => { - if (_nameprepTableA1(code)) { - throw new Error("STRINGPREP_CONTAINS_UNASSIGNED"); - } - }); - // IDNA extras - let name = (0,_utf8__WEBPACK_IMPORTED_MODULE_0__/* ._toUtf8String */ .uu)(codes); - // IDNA: 4.2.3.1 - if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") { - throw new Error("invalid hyphen"); - } - // IDNA: 4.2.4 - if (name.length > 63) { - throw new Error("too long"); - } - return name; -} -//# sourceMappingURL=idna.js.map - -/***/ }), - -/***/ 5804: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Uj": () => (/* binding */ UnicodeNormalizationForm), - "te": () => (/* binding */ Utf8ErrorFuncs), - "Uw": () => (/* binding */ Utf8ErrorReason), - "U$": () => (/* binding */ _toEscapedUtf8String), - "uu": () => (/* binding */ _toUtf8String), - "Y0": () => (/* binding */ toUtf8Bytes), - "XL": () => (/* binding */ toUtf8CodePoints), - "ZN": () => (/* binding */ toUtf8String) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/strings/lib.esm/_version.js -const version = "strings/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/strings/lib.esm/utf8.js - - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -/////////////////////////////// -var UnicodeNormalizationForm; -(function (UnicodeNormalizationForm) { - UnicodeNormalizationForm["current"] = ""; - UnicodeNormalizationForm["NFC"] = "NFC"; - UnicodeNormalizationForm["NFD"] = "NFD"; - UnicodeNormalizationForm["NFKC"] = "NFKC"; - UnicodeNormalizationForm["NFKD"] = "NFKD"; -})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); -; -var Utf8ErrorReason; -(function (Utf8ErrorReason) { - // A continuation byte was present where there was nothing to continue - // - offset = the index the codepoint began in - Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; - // An invalid (non-continuation) byte to start a UTF-8 codepoint was found - // - offset = the index the codepoint began in - Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix"; - // The string is too short to process the expected codepoint - // - offset = the index the codepoint began in - Utf8ErrorReason["OVERRUN"] = "string overrun"; - // A missing continuation byte was expected but not found - // - offset = the index the continuation byte was expected at - Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte"; - // The computed code point is outside the range for UTF-8 - // - offset = start of this codepoint - // - badCodepoint = the computed codepoint; outside the UTF-8 range - Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range"; - // UTF-8 strings may not contain UTF-16 surrogate pairs - // - offset = start of this codepoint - // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range - Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate"; - // The string is an overlong representation - // - offset = start of this codepoint - // - badCodepoint = the computed codepoint; already bounds checked - Utf8ErrorReason["OVERLONG"] = "overlong representation"; -})(Utf8ErrorReason || (Utf8ErrorReason = {})); -; -function errorFunc(reason, offset, bytes, output, badCodepoint) { - return logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); -} -function ignoreFunc(reason, offset, bytes, output, badCodepoint) { - // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes - if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { - let i = 0; - for (let o = offset + 1; o < bytes.length; o++) { - if (bytes[o] >> 6 !== 0x02) { - break; - } - i++; - } - return i; - } - // This byte runs us past the end of the string, so just jump to the end - // (but the first byte was read already read and therefore skipped) - if (reason === Utf8ErrorReason.OVERRUN) { - return bytes.length - offset - 1; - } - // Nothing to skip - return 0; -} -function replaceFunc(reason, offset, bytes, output, badCodepoint) { - // Overlong representations are otherwise "valid" code points; just non-deistingtished - if (reason === Utf8ErrorReason.OVERLONG) { - output.push(badCodepoint); - return 0; - } - // Put the replacement character into the output - output.push(0xfffd); - // Otherwise, process as if ignoring errors - return ignoreFunc(reason, offset, bytes, output, badCodepoint); -} -// Common error handing strategies -const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc -}); -// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 -function getUtf8CodePoints(bytes, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; - } - bytes = (0,lib_esm/* arrayify */.lE)(bytes); - const result = []; - let i = 0; - // Invalid bytes are ignored - while (i < bytes.length) { - const c = bytes[i++]; - // 0xxx xxxx - if (c >> 7 === 0) { - result.push(c); - continue; - } - // Multibyte; how many bytes left for this character? - let extraLength = null; - let overlongMask = null; - // 110x xxxx 10xx xxxx - if ((c & 0xe0) === 0xc0) { - extraLength = 1; - overlongMask = 0x7f; - // 1110 xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf0) === 0xe0) { - extraLength = 2; - overlongMask = 0x7ff; - // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf8) === 0xf0) { - extraLength = 3; - overlongMask = 0xffff; - } - else { - if ((c & 0xc0) === 0x80) { - i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result); - } - else { - i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result); - } - continue; - } - // Do we have enough bytes in our data? - if (i - 1 + extraLength >= bytes.length) { - i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result); - continue; - } - // Remove the length prefix from the char - let res = c & ((1 << (8 - extraLength - 1)) - 1); - for (let j = 0; j < extraLength; j++) { - let nextChar = bytes[i]; - // Invalid continuation byte - if ((nextChar & 0xc0) != 0x80) { - i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result); - res = null; - break; - } - ; - res = (res << 6) | (nextChar & 0x3f); - i++; - } - // See above loop for invalid continuation byte - if (res === null) { - continue; - } - // Maximum code point - if (res > 0x10ffff) { - i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res); - continue; - } - // Reserved for UTF-16 surrogate halves - if (res >= 0xd800 && res <= 0xdfff) { - i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res); - continue; - } - // Check for overlong sequences (more bytes than needed) - if (res <= overlongMask) { - i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res); - continue; - } - result.push(res); - } - return result; -} -// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array -function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { - if (form != UnicodeNormalizationForm.current) { - logger.checkNormalize(); - str = str.normalize(form); - } - let result = []; - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c < 0x80) { - result.push(c); - } - else if (c < 0x800) { - result.push((c >> 6) | 0xc0); - result.push((c & 0x3f) | 0x80); - } - else if ((c & 0xfc00) == 0xd800) { - i++; - const c2 = str.charCodeAt(i); - if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) { - throw new Error("invalid utf-8 string"); - } - // Surrogate Pair - const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); - result.push((pair >> 18) | 0xf0); - result.push(((pair >> 12) & 0x3f) | 0x80); - result.push(((pair >> 6) & 0x3f) | 0x80); - result.push((pair & 0x3f) | 0x80); - } - else { - result.push((c >> 12) | 0xe0); - result.push(((c >> 6) & 0x3f) | 0x80); - result.push((c & 0x3f) | 0x80); - } - } - return (0,lib_esm/* arrayify */.lE)(result); -} -; -function escapeChar(value) { - const hex = ("0000" + value.toString(16)); - return "\\u" + hex.substring(hex.length - 4); -} -function _toEscapedUtf8String(bytes, onError) { - return '"' + getUtf8CodePoints(bytes, 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 <= 0xffff) { - return escapeChar(codePoint); - } - codePoint -= 0x10000; - return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00); - }).join("") + '"'; -} -function _toUtf8String(codePoints) { - return codePoints.map((codePoint) => { - if (codePoint <= 0xffff) { - return String.fromCharCode(codePoint); - } - codePoint -= 0x10000; - return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00)); - }).join(""); -} -function toUtf8String(bytes, onError) { - return _toUtf8String(getUtf8CodePoints(bytes, onError)); -} -function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) { - return getUtf8CodePoints(toUtf8Bytes(str, form)); -} -//# sourceMappingURL=utf8.js.map - -/***/ }), - -/***/ 9165: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "em": () => (/* binding */ TransactionTypes), - "z7": () => (/* binding */ accessListify), - "db": () => (/* binding */ computeAddress), - "Qc": () => (/* binding */ parse), - "RJ": () => (/* binding */ recoverAddress), - "qC": () => (/* binding */ serialize) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/address/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(9808); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var bytes_lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/constants/lib.esm/bignumbers.js -var bignumbers = __webpack_require__(5733); -// EXTERNAL MODULE: ../node_modules/@ethersproject/keccak256/lib.esm/index.js -var keccak256_lib_esm = __webpack_require__(2677); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/rlp/lib.esm/index.js + 1 modules -var rlp_lib_esm = __webpack_require__(6868); -// EXTERNAL MODULE: ../node_modules/@ethersproject/signing-key/lib.esm/index.js + 2 modules -var signing_key_lib_esm = __webpack_require__(9947); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/transactions/lib.esm/_version.js -const version = "transactions/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/transactions/lib.esm/index.js - - - - - - - - - - - -const logger = new logger_lib_esm/* Logger */.Yd(version); -var TransactionTypes; -(function (TransactionTypes) { - TransactionTypes[TransactionTypes["legacy"] = 0] = "legacy"; - TransactionTypes[TransactionTypes["eip2930"] = 1] = "eip2930"; - TransactionTypes[TransactionTypes["eip1559"] = 2] = "eip1559"; -})(TransactionTypes || (TransactionTypes = {})); -; -/////////////////////////////// -function handleAddress(value) { - if (value === "0x") { - return null; - } - return (0,lib_esm/* getAddress */.Kn)(value); -} -function handleNumber(value) { - if (value === "0x") { - return bignumbers/* Zero */._Y; - } - return bignumber/* BigNumber.from */.O$.from(value); -} -// Legacy Transaction Fields -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 allowedTransactionKeys = { - chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, type: true, value: true -}; -function computeAddress(key) { - const publicKey = (0,signing_key_lib_esm/* computePublicKey */.VW)(key); - return (0,lib_esm/* getAddress */.Kn)((0,bytes_lib_esm/* hexDataSlice */.p3)((0,keccak256_lib_esm/* keccak256 */.w)((0,bytes_lib_esm/* hexDataSlice */.p3)(publicKey, 1)), 12)); -} -function recoverAddress(digest, signature) { - return computeAddress((0,signing_key_lib_esm/* recoverPublicKey */.LO)((0,bytes_lib_esm/* arrayify */.lE)(digest), signature)); -} -function formatNumber(value, name) { - const result = (0,bytes_lib_esm/* stripZeros */.G1)(bignumber/* BigNumber.from */.O$.from(value).toHexString()); - if (result.length > 32) { - logger.throwArgumentError("invalid length for " + name, ("transaction:" + name), value); - } - return result; -} -function accessSetify(addr, storageKeys) { - return { - address: (0,lib_esm/* getAddress */.Kn)(addr), - storageKeys: (storageKeys || []).map((storageKey, index) => { - if ((0,bytes_lib_esm/* hexDataLength */.E1)(storageKey) !== 32) { - logger.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) { - logger.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 there is an explicit gasPrice, make sure it matches the - // EIP-1559 fees; otherwise they may not understand what they - // think they are setting in terms of fee. - if (transaction.gasPrice != null) { - const gasPrice = bignumber/* BigNumber.from */.O$.from(transaction.gasPrice); - const maxFeePerGas = bignumber/* BigNumber.from */.O$.from(transaction.maxFeePerGas || 0); - if (!gasPrice.eq(maxFeePerGas)) { - logger.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) ? (0,lib_esm/* getAddress */.Kn)(transaction.to) : "0x"), - formatNumber(transaction.value || 0, "value"), - (transaction.data || "0x"), - (formatAccessList(transaction.accessList || [])) - ]; - if (signature) { - const sig = (0,bytes_lib_esm/* splitSignature */.N)(signature); - fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); - fields.push((0,bytes_lib_esm/* stripZeros */.G1)(sig.r)); - fields.push((0,bytes_lib_esm/* stripZeros */.G1)(sig.s)); - } - return (0,bytes_lib_esm/* hexConcat */.xs)(["0x02", rlp_lib_esm.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) ? (0,lib_esm/* getAddress */.Kn)(transaction.to) : "0x"), - formatNumber(transaction.value || 0, "value"), - (transaction.data || "0x"), - (formatAccessList(transaction.accessList || [])) - ]; - if (signature) { - const sig = (0,bytes_lib_esm/* splitSignature */.N)(signature); - fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); - fields.push((0,bytes_lib_esm/* stripZeros */.G1)(sig.r)); - fields.push((0,bytes_lib_esm/* stripZeros */.G1)(sig.s)); - } - return (0,bytes_lib_esm/* hexConcat */.xs)(["0x01", rlp_lib_esm.encode(fields)]); -} -// Legacy Transactions and EIP-155 -function _serialize(transaction, signature) { - (0,properties_lib_esm/* checkProperties */.uj)(transaction, allowedTransactionKeys); - const raw = []; - transactionFields.forEach(function (fieldInfo) { - let value = transaction[fieldInfo.name] || ([]); - const options = {}; - if (fieldInfo.numeric) { - options.hexPad = "left"; - } - value = (0,bytes_lib_esm/* arrayify */.lE)((0,bytes_lib_esm/* hexlify */.Dv)(value, options)); - // Fixed-width field - if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) { - logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value); - } - // Variable-width (with a maximum) - if (fieldInfo.maxLength) { - value = (0,bytes_lib_esm/* stripZeros */.G1)(value); - if (value.length > fieldInfo.maxLength) { - logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value); - } - } - raw.push((0,bytes_lib_esm/* hexlify */.Dv)(value)); - }); - let chainId = 0; - if (transaction.chainId != null) { - // A chainId was provided; if non-zero we'll use EIP-155 - chainId = transaction.chainId; - if (typeof (chainId) !== "number") { - logger.throwArgumentError("invalid transaction.chainId", "transaction", transaction); - } - } - else if (signature && !(0,bytes_lib_esm/* isBytesLike */.Zq)(signature) && signature.v > 28) { - // No chainId provided, but the signature is signing with EIP-155; derive chainId - chainId = Math.floor((signature.v - 35) / 2); - } - // We have an EIP-155 transaction (chainId was specified and non-zero) - if (chainId !== 0) { - raw.push((0,bytes_lib_esm/* hexlify */.Dv)(chainId)); // @TODO: hexValue? - raw.push("0x"); - raw.push("0x"); - } - // Requesting an unsigned transaction - if (!signature) { - return rlp_lib_esm.encode(raw); - } - // The splitSignature will ensure the transaction has a recoveryParam in the - // case that the signTransaction function only adds a v. - const sig = (0,bytes_lib_esm/* splitSignature */.N)(signature); - // We pushed a chainId and null r, s on for hashing only; remove those - let v = 27 + sig.recoveryParam; - if (chainId !== 0) { - raw.pop(); - raw.pop(); - raw.pop(); - v += chainId * 2 + 8; - // If an EIP-155 v (directly or indirectly; maybe _vs) was provided, check it! - if (sig.v > 28 && sig.v !== v) { - logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); - } - } - else if (sig.v !== v) { - logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); - } - raw.push((0,bytes_lib_esm/* hexlify */.Dv)(v)); - raw.push((0,bytes_lib_esm/* stripZeros */.G1)((0,bytes_lib_esm/* arrayify */.lE)(sig.r))); - raw.push((0,bytes_lib_esm/* stripZeros */.G1)((0,bytes_lib_esm/* arrayify */.lE)(sig.s))); - return rlp_lib_esm.encode(raw); -} -function serialize(transaction, signature) { - // Legacy and EIP-155 Transactions - if (transaction.type == null || transaction.type === 0) { - if (transaction.accessList != null) { - logger.throwArgumentError("untyped transactions do not support accessList; include type: 1", "transaction", transaction); - } - return _serialize(transaction, signature); - } - // Typed Transactions (EIP-2718) - switch (transaction.type) { - case 1: - return _serializeEip2930(transaction, signature); - case 2: - return _serializeEip1559(transaction, signature); - default: - break; - } - return logger.throwError(`unsupported transaction type: ${transaction.type}`, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "serializeTransaction", - transactionType: transaction.type - }); -} -function _parseEipSignature(tx, fields, serialize) { - try { - const recid = handleNumber(fields[0]).toNumber(); - if (recid !== 0 && recid !== 1) { - throw new Error("bad recid"); - } - tx.v = recid; - } - catch (error) { - logger.throwArgumentError("invalid v for transaction type: 1", "v", fields[0]); - } - tx.r = (0,bytes_lib_esm/* hexZeroPad */.$m)(fields[1], 32); - tx.s = (0,bytes_lib_esm/* hexZeroPad */.$m)(fields[2], 32); - try { - const digest = (0,keccak256_lib_esm/* keccak256 */.w)(serialize(tx)); - tx.from = recoverAddress(digest, { r: tx.r, s: tx.s, recoveryParam: tx.v }); - } - catch (error) { - console.log(error); - } -} -function _parseEip1559(payload) { - const transaction = rlp_lib_esm.decode(payload.slice(1)); - if (transaction.length !== 9 && transaction.length !== 12) { - logger.throwArgumentError("invalid component count for transaction type: 2", "payload", (0,bytes_lib_esm/* hexlify */.Dv)(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: maxPriorityFeePerGas, - maxFeePerGas: maxFeePerGas, - gasPrice: null, - gasLimit: handleNumber(transaction[4]), - to: handleAddress(transaction[5]), - value: handleNumber(transaction[6]), - data: transaction[7], - accessList: accessListify(transaction[8]), - }; - // Unsigned EIP-1559 Transaction - if (transaction.length === 9) { - return tx; - } - tx.hash = (0,keccak256_lib_esm/* keccak256 */.w)(payload); - _parseEipSignature(tx, transaction.slice(9), _serializeEip1559); - return tx; -} -function _parseEip2930(payload) { - const transaction = rlp_lib_esm.decode(payload.slice(1)); - if (transaction.length !== 8 && transaction.length !== 11) { - logger.throwArgumentError("invalid component count for transaction type: 1", "payload", (0,bytes_lib_esm/* hexlify */.Dv)(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]) - }; - // Unsigned EIP-2930 Transaction - if (transaction.length === 8) { - return tx; - } - tx.hash = (0,keccak256_lib_esm/* keccak256 */.w)(payload); - _parseEipSignature(tx, transaction.slice(8), _serializeEip2930); - return tx; -} -// Legacy Transactions and EIP-155 -function _parse(rawTransaction) { - const transaction = rlp_lib_esm.decode(rawTransaction); - if (transaction.length !== 9 && transaction.length !== 6) { - logger.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 - }; - // Legacy unsigned transaction - if (transaction.length === 6) { - return tx; - } - try { - tx.v = bignumber/* BigNumber.from */.O$.from(transaction[6]).toNumber(); - } - catch (error) { - console.log(error); - return tx; - } - tx.r = (0,bytes_lib_esm/* hexZeroPad */.$m)(transaction[7], 32); - tx.s = (0,bytes_lib_esm/* hexZeroPad */.$m)(transaction[8], 32); - if (bignumber/* BigNumber.from */.O$.from(tx.r).isZero() && bignumber/* BigNumber.from */.O$.from(tx.s).isZero()) { - // EIP-155 unsigned transaction - tx.chainId = tx.v; - tx.v = 0; - } - else { - // Signed Transaction - 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((0,bytes_lib_esm/* hexlify */.Dv)(tx.chainId)); - raw.push("0x"); - raw.push("0x"); - recoveryParam -= tx.chainId * 2 + 8; - } - const digest = (0,keccak256_lib_esm/* keccak256 */.w)(rlp_lib_esm.encode(raw)); - try { - tx.from = recoverAddress(digest, { r: (0,bytes_lib_esm/* hexlify */.Dv)(tx.r), s: (0,bytes_lib_esm/* hexlify */.Dv)(tx.s), recoveryParam: recoveryParam }); - } - catch (error) { - console.log(error); - } - tx.hash = (0,keccak256_lib_esm/* keccak256 */.w)(rawTransaction); - } - tx.type = null; - return tx; -} -function parse(rawTransaction) { - const payload = (0,bytes_lib_esm/* arrayify */.lE)(rawTransaction); - // Legacy and EIP-155 Transactions - if (payload[0] > 0x7f) { - return _parse(payload); - } - // Typed Transaction (EIP-2718) - switch (payload[0]) { - case 1: - return _parseEip2930(payload); - case 2: - return _parseEip1559(payload); - default: - break; - } - return logger.throwError(`unsupported transaction type: ${payload[0]}`, logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "parseTransaction", - transactionType: payload[0] - }); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 2585: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "MY": () => (/* binding */ _fetchData), - "rd": () => (/* binding */ fetchJson), - "$l": () => (/* binding */ poll) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/base64/lib.esm/base64.js -var base64 = __webpack_require__(6284); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/strings/lib.esm/utf8.js + 1 modules -var utf8 = __webpack_require__(5804); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/web/lib.esm/_version.js -const version = "web/5.5.1"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/web/lib.esm/geturl.js - -var __awaiter = (undefined && undefined.__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()); - }); -}; - -function getUrl(href, options) { - return __awaiter(this, void 0, void 0, function* () { - if (options == null) { - options = {}; - } - const request = { - method: (options.method || "GET"), - headers: (options.headers || {}), - body: (options.body || undefined), - }; - if (options.skipFetchSetup !== true) { - request.mode = "cors"; // no-cors, cors, *same-origin - request.cache = "no-cache"; // *default, no-cache, reload, force-cache, only-if-cached - request.credentials = "same-origin"; // include, *same-origin, omit - request.redirect = "follow"; // manual, *follow, error - request.referrer = "client"; // no-referrer, *client - } - ; - 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: headers, - statusCode: response.status, - statusMessage: response.statusText, - body: (0,lib_esm/* arrayify */.lE)(new Uint8Array(body)), - }; - }); -} -//# sourceMappingURL=geturl.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/web/lib.esm/index.js - -var lib_esm_awaiter = (undefined && undefined.__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 logger = new logger_lib_esm/* Logger */.Yd(version); - -function staller(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); -} -function bodyify(value, type) { - if (value == null) { - return null; - } - if (typeof (value) === "string") { - return value; - } - if ((0,lib_esm/* isBytesLike */.Zq)(value)) { - if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) { - try { - return (0,utf8/* toUtf8String */.ZN)(value); - } - catch (error) { } - ; - } - return (0,lib_esm/* hexlify */.Dv)(value); - } - return value; -} -// This API is still a work in progress; the future changes will likely be: -// - ConnectionInfo => FetchDataRequest -// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array } -// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified) -// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T -// For this reason, it should be considered internal until the API is finalized -function _fetchData(connection, body, processFunc) { - // How many times to retry in the event of a throttle - const attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12; - logger.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); - logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval); - const headers = {}; - let url = null; - // @TODO: Allow ConnectionInfo to override some of these values - const options = { - method: "GET", - }; - let allow304 = false; - let timeout = 2 * 60 * 1000; - if (typeof (connection) === "string") { - url = connection; - } - else if (typeof (connection) === "object") { - if (connection == null || connection.url == null) { - logger.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: 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) { - logger.throwError("basic authentication requires a secure https url", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" }); - } - const authorization = connection.user + ":" + connection.password; - headers["authorization"] = { - key: "Authorization", - value: "Basic " + (0,base64/* encode */.c)((0,utf8/* toUtf8Bytes */.Y0)(authorization)) - }; - } - } - const reData = new RegExp("^data:([a-z0-9-]+/[a-z0-9-]+);base64,(.*)$", "i"); - const dataMatch = ((url) ? url.match(reData) : null); - if (dataMatch) { - try { - const response = { - statusCode: 200, - statusMessage: "OK", - headers: { "content-type": dataMatch[1] }, - body: (0,base64/* decode */.J)(dataMatch[2]) - }; - let result = response.body; - if (processFunc) { - result = processFunc(response.body, response); - } - return Promise.resolve(result); - } - catch (error) { - logger.throwError("processing response error", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - body: bodyify(dataMatch[1], dataMatch[2]), - error: error, - requestBody: null, - requestMethod: "GET", - url: 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(logger.makeError("timeout", logger_lib_esm/* Logger.errors.TIMEOUT */.Yd.errors.TIMEOUT, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - timeout: timeout, - url: url - })); - }, timeout); - } - }); - const cancel = function () { - if (timer == null) { - return; - } - clearTimeout(timer); - timer = null; - }; - return { promise, cancel }; - })(); - const runningFetch = (function () { - return lib_esm_awaiter(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) { - // Redirection; for now we only support absolute locataions - const location = response.headers.location || ""; - if (options.method === "GET" && location.match(/^https:/)) { - url = response.headers.location; - continue; - } - } - else if (response.statusCode === 429) { - // Exponential back-off throttling - 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) * 1000; - } - else { - stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); - } - //console.log("Stalling 429"); - yield staller(stall); - continue; - } - } - } - } - catch (error) { - response = error.response; - if (response == null) { - runningTimeout.cancel(); - logger.throwError("missing response", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - serverError: error, - url: url - }); - } - } - let body = response.body; - if (allow304 && response.statusCode === 304) { - body = null; - } - else if (response.statusCode < 200 || response.statusCode >= 300) { - runningTimeout.cancel(); - logger.throwError("bad response", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - status: response.statusCode, - headers: response.headers, - body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)), - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url: url - }); - } - if (processFunc) { - try { - const result = yield processFunc(body, response); - runningTimeout.cancel(); - return result; - } - catch (error) { - // Allow the processFunc to trigger a throttle - if (error.throttleRetry && attempt < attemptLimit) { - let tryAgain = true; - if (throttleCallback) { - tryAgain = yield throttleCallback(attempt, url); - } - if (tryAgain) { - const timeout = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); - //console.log("Stalling callback"); - yield staller(timeout); - continue; - } - } - runningTimeout.cancel(); - logger.throwError("processing response error", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)), - error: error, - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url: url - }); - } - } - runningTimeout.cancel(); - // If we had a processFunc, it either returned a T or threw above. - // The "body" is now a Uint8Array. - return body; - } - return logger.throwError("failed response", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url: 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((0,utf8/* toUtf8String */.ZN)(value)); - } - catch (error) { - logger.throwError("invalid JSON", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - body: value, - error: error - }); - } - } - if (processFunc) { - result = processFunc(result, response); - } - return result; - }; - // If we have json to send, we must - // - add content-type of application/json (unless already overridden) - // - convert the json to bytes - let body = null; - if (json != null) { - body = (0,utf8/* toUtf8Bytes */.Y0)(json); - // Create a connection with the content-type set for JSON - const updated = (typeof (connection) === "string") ? ({ url: connection }) : (0,properties_lib_esm/* shallowCopy */.DC)(connection); - if (updated.headers) { - const hasContentType = (Object.keys(updated.headers).filter((k) => (k.toLowerCase() === "content-type")).length) !== 0; - if (!hasContentType) { - updated.headers = (0,properties_lib_esm/* shallowCopy */.DC)(updated.headers); - updated.headers["content-type"] = "application/json"; - } - } - else { - updated.headers = { "content-type": "application/json" }; - } - connection = updated; - } - return _fetchData(connection, body, processJsonFunc); -} -function poll(func, options) { - if (!options) { - options = {}; - } - options = (0,properties_lib_esm/* shallowCopy */.DC)(options); - if (options.floor == null) { - options.floor = 0; - } - if (options.ceiling == null) { - options.ceiling = 10000; - } - if (options.interval == null) { - options.interval = 250; - } - return new Promise(function (resolve, reject) { - let timer = null; - let done = false; - // Returns true if cancel was successful. Unsuccessful cancel means we're already done. - 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 we have a result, or are allowed null then we're done - if (result !== undefined) { - if (cancel()) { - resolve(result); - } - } - else if (options.oncePoll) { - options.oncePoll.once("poll", check); - } - else if (options.onceBlock) { - options.onceBlock.once("block", check); - // Otherwise, exponential back-off (up to 10s) our next request - } - 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); - } - }); - } - check(); - }); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 7383: -/***/ ((module) => { - -"use strict"; - -module.exports = asPromise; - -/** - * Callback as used by {@link util.asPromise}. - * @typedef asPromiseCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {...*} params Additional arguments - * @returns {undefined} - */ - -/** - * Returns a promise from a node-style callback function. - * @memberof util - * @param {asPromiseCallback} fn Function to call - * @param {*} ctx Function context - * @param {...*} params Function arguments - * @returns {Promise<*>} Promisified function - */ -function asPromise(fn, ctx/*, varargs */) { - var params = new Array(arguments.length - 1), - offset = 0, - index = 2, - pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err/*, varargs */) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params = new Array(arguments.length - 1), - offset = 0; - while (offset < params.length) - params[offset++] = arguments[offset]; - resolve.apply(null, params); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); -} - - -/***/ }), - -/***/ 3417: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal base64 implementation for number arrays. - * @memberof util - * @namespace - */ -var base64 = exports; - -/** - * Calculates the byte length of a base64 encoded string. - * @param {string} string Base64 encoded string - * @returns {number} Byte length - */ -base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; -}; - -// Base64 encoding table -var b64 = new Array(64); - -// Base64 decoding table -var s64 = new Array(123); - -// 65..90, 97..122, 48..57, 43, 47 -for (var i = 0; i < 64;) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; - -/** - * Encodes a buffer to a base64 encoded string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} Base64 encoded string - */ -base64.encode = function encode(buffer, start, end) { - var parts = null, - chunk = []; - var i = 0, // output index - j = 0, // goto index - t; // temporary - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i++] = b64[t | b >> 6]; - chunk[i++] = b64[b & 63]; - j = 0; - break; - } - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (j) { - chunk[i++] = b64[t]; - chunk[i++] = 61; - if (j === 1) - chunk[i++] = 61; - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -var invalidEncoding = "invalid encoding"; - -/** - * Decodes a base64 encoded string to a buffer. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Number of bytes written - * @throws {Error} If encoding is invalid - */ -base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, // goto index - t; // temporary - for (var i = 0; i < string.length;) { - var c = string.charCodeAt(i++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === undefined) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } - } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; -}; - -/** - * Tests if the specified string appears to be base64 encoded. - * @param {string} string String to test - * @returns {boolean} `true` if probably base64 encoded, otherwise false - */ -base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); -}; - - -/***/ }), - -/***/ 7516: -/***/ ((module) => { - -"use strict"; - -module.exports = EventEmitter; - -/** - * Constructs a new event emitter instance. - * @classdesc A minimal event emitter. - * @memberof util - * @constructor - */ -function EventEmitter() { - - /** - * Registered listeners. - * @type {Object.} - * @private - */ - this._listeners = {}; -} - -/** - * Registers an event listener. - * @param {string} evt Event name - * @param {function} fn Listener - * @param {*} [ctx] Listener context - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn : fn, - ctx : ctx || this - }); - return this; -}; - -/** - * Removes an event listener or any matching listeners if arguments are omitted. - * @param {string} [evt] Event name. Removes all listeners if omitted. - * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.off = function off(evt, fn) { - if (evt === undefined) - this._listeners = {}; - else { - if (fn === undefined) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length;) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } - } - return this; -}; - -/** - * Emits an event by calling its listeners with the specified arguments. - * @param {string} evt Event name - * @param {...*} args Arguments - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], - i = 1; - for (; i < arguments.length;) - args.push(arguments[i++]); - for (i = 0; i < listeners.length;) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; -}; - - -/***/ }), - -/***/ 9787: -/***/ ((module) => { - -"use strict"; - - -module.exports = factory(factory); - -/** - * Reads / writes floats / doubles from / to buffers. - * @name util.float - * @namespace - */ - -/** - * Writes a 32 bit float to a buffer using little endian byte order. - * @name util.float.writeFloatLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 32 bit float to a buffer using big endian byte order. - * @name util.float.writeFloatBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 32 bit float from a buffer using little endian byte order. - * @name util.float.readFloatLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 32 bit float from a buffer using big endian byte order. - * @name util.float.readFloatBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Writes a 64 bit double to a buffer using little endian byte order. - * @name util.float.writeDoubleLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 64 bit double to a buffer using big endian byte order. - * @name util.float.writeDoubleBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 64 bit double from a buffer using little endian byte order. - * @name util.float.readDoubleLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 64 bit double from a buffer using big endian byte order. - * @name util.float.readDoubleBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -// Factory function for the purpose of node-based testing in modified global environments -function factory(exports) { - - // float: typed array - if (typeof Float32Array !== "undefined") (function() { - - var f32 = new Float32Array([ -0 ]), - f8b = new Uint8Array(f32.buffer), - le = f8b[3] === 128; - - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - /* istanbul ignore next */ - exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos ]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - - /* istanbul ignore next */ - exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - /* istanbul ignore next */ - exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - - // float: ieee754 - })(); else (function() { - - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 3.4028234663852886e+38) // +-Infinity - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 1.1754943508222875e-38) // denormal - writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), - mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - - exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), - sign = (uint >> 31) * 2 + 1, - exponent = uint >>> 23 & 255, - mantissa = uint & 8388607; - return exponent === 255 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 1.401298464324817e-45 * mantissa - : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - - exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - - })(); - - // double: typed array - if (typeof Float64Array !== "undefined") (function() { - - var f64 = new Float64Array([-0]), - f8b = new Uint8Array(f64.buffer), - le = f8b[7] === 128; - - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - /* istanbul ignore next */ - exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos ]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - - /* istanbul ignore next */ - exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - /* istanbul ignore next */ - exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - - // double: ieee754 - })(); else (function() { - - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 1.7976931348623157e+308) { // +-Infinity - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 2.2250738585072014e-308) { // denormal - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - - exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), - hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, - exponent = hi >>> 20 & 2047, - mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 5e-324 * mantissa - : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - - exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - - })(); - - return exports; -} - -// uint helpers - -function writeUintLE(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -function writeUintBE(val, buf, pos) { - buf[pos ] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; -} - -function readUintLE(buf, pos) { - return (buf[pos ] - | buf[pos + 1] << 8 - | buf[pos + 2] << 16 - | buf[pos + 3] << 24) >>> 0; -} - -function readUintBE(buf, pos) { - return (buf[pos ] << 24 - | buf[pos + 1] << 16 - | buf[pos + 2] << 8 - | buf[pos + 3]) >>> 0; -} - - -/***/ }), - -/***/ 2795: -/***/ ((module) => { - -"use strict"; - -module.exports = inquire; - -/** - * Requires a module only if available. - * @memberof util - * @param {string} moduleName Module to require - * @returns {?Object} Required module if available and not empty, otherwise `null` - */ -function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e) {} // eslint-disable-line no-empty - return null; -} - - -/***/ }), - -/***/ 4476: -/***/ ((module) => { - -"use strict"; - -module.exports = pool; - -/** - * An allocator as used by {@link util.pool}. - * @typedef PoolAllocator - * @type {function} - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ - -/** - * A slicer as used by {@link util.pool}. - * @typedef PoolSlicer - * @type {function} - * @param {number} start Start offset - * @param {number} end End offset - * @returns {Uint8Array} Buffer slice - * @this {Uint8Array} - */ - -/** - * A general purpose buffer pool. - * @memberof util - * @function - * @param {PoolAllocator} alloc Allocator - * @param {PoolSlicer} slice Slicer - * @param {number} [size=8192] Slab size - * @returns {PoolAllocator} Pooled allocator - */ -function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size) { - if (size < 1 || size > MAX) - return alloc(size); - if (offset + size > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size); - if (offset & 7) // align to 32 bit - offset = (offset | 7) + 1; - return buf; - }; -} - - -/***/ }), - -/***/ 1893: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal UTF8 implementation for number arrays. - * @memberof util - * @namespace - */ -var utf8 = exports; - -/** - * Calculates the UTF8 byte length of a string. - * @param {string} string String - * @returns {number} Byte length - */ -utf8.length = function utf8_length(string) { - var len = 0, - c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { - ++i; - len += 4; - } else - len += 3; - } - return len; -}; - -/** - * Reads UTF8 bytes as a string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} String read - */ -utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, - chunk = [], - i = 0, // char offset - t; // temporary - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -/** - * Writes a string as UTF8 bytes. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Bytes written - */ -utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, - c1, // character 1 - c2; // character 2 - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { - c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; -}; - - -/***/ }), - -/***/ 6264: -/***/ (function(module) { - -"use strict"; - - -(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) { - - // ArrayBuffer view - 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; - } - - // It's an array; check it is a valid representation of a byte - if (Array.isArray(arg)) { - if (!checkInts(arg)) { - throw new Error('Array contains invalid value: ' + arg); - } - - return new Uint8Array(arg); - } - - // Something else, but behaves like an array (maybe a Buffer? Arguments?) - 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 it is a % sign, encode the following 2 bytes as a hex value - if (c === 37) { - result.push(parseInt(text.substr(i, 2), 16)) - i += 2; - - // otherwise, just the actual byte - } 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 & 0x1f) << 6) | (bytes[i + 1] & 0x3f))); - i += 2; - } else { - result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f))); - i += 3; - } - } - - return result.join(''); - } - - return { - toBytes: toBytes, - fromBytes: 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; - } - - // http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html - var Hex = '0123456789abcdef'; - - function fromBytes(bytes) { - var result = []; - for (var i = 0; i < bytes.length; i++) { - var v = bytes[i]; - result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]); - } - return result.join(''); - } - - return { - toBytes: toBytes, - fromBytes: fromBytes, - } - })(); - - - // Number of rounds by keysize - var numberOfRounds = {16: 10, 24: 12, 32: 14} - - // Round constant words - var rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]; - - // S-box and Inverse S-box (S is for Substitution) - var S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]; - var Si =[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]; - - // Transformations for encryption - var T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a]; - var T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616]; - var T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16]; - var T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c]; - - // Transformations for decryption - var T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742]; - var T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857]; - var T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8]; - var T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0]; - - // Transformations for decryption key expansion - var U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]; - var U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697]; - var U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46]; - var U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d]; - - function convertToInt32(bytes) { - 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 AES = function(key) { - if (!(this instanceof AES)) { - throw Error('AES must be instanitated with `new`'); - } - - Object.defineProperty(this, 'key', { - value: coerceArray(key, true) - }); - - this._prepare(); - } - - - AES.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)'); - } - - // encryption round keys - this._Ke = []; - - // decryption round keys - 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; - - // convert the key into ints - var tk = convertToInt32(this.key); - - // copy values into round key arrays - 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]; - } - - // key expansion (fips-197 section 5.2) - var rconpointer = 0; - var t = KC, tt; - while (t < roundKeyCount) { - tt = tk[KC - 1]; - tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^ - (S[(tt >> 8) & 0xFF] << 16) ^ - (S[ tt & 0xFF] << 8) ^ - S[(tt >> 24) & 0xFF] ^ - (rcon[rconpointer] << 24)); - rconpointer += 1; - - // key expansion (for non-256 bit) - if (KC != 8) { - for (var i = 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - - // key expansion for 256-bit keys is "slightly different" (fips-197) - } else { - for (var i = 1; i < (KC / 2); i++) { - tk[i] ^= tk[i - 1]; - } - tt = tk[(KC / 2) - 1]; - - tk[KC / 2] ^= (S[ tt & 0xFF] ^ - (S[(tt >> 8) & 0xFF] << 8) ^ - (S[(tt >> 16) & 0xFF] << 16) ^ - (S[(tt >> 24) & 0xFF] << 24)); - - for (var i = (KC / 2) + 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - } - - // copy values into round key arrays - 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++; - } - } - - // inverse-cipher-ify the decryption round key (fips-197 section 5.3) - 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) & 0xFF] ^ - U2[(tt >> 16) & 0xFF] ^ - U3[(tt >> 8) & 0xFF] ^ - U4[ tt & 0xFF]); - } - } - } - - AES.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]; - - // convert plaintext to (ints ^ key) - var t = convertToInt32(plaintext); - for (var i = 0; i < 4; i++) { - t[i] ^= this._Ke[0][i]; - } - - // apply round transforms - for (var r = 1; r < rounds; r++) { - for (var i = 0; i < 4; i++) { - a[i] = (T1[(t[ i ] >> 24) & 0xff] ^ - T2[(t[(i + 1) % 4] >> 16) & 0xff] ^ - T3[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T4[ t[(i + 3) % 4] & 0xff] ^ - this._Ke[r][i]); - } - t = a.slice(); - } - - // the last round is special - var result = createArray(16), tt; - for (var i = 0; i < 4; i++) { - tt = this._Ke[rounds][i]; - result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff; - } - - return result; - } - - AES.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]; - - // convert plaintext to (ints ^ key) - var t = convertToInt32(ciphertext); - for (var i = 0; i < 4; i++) { - t[i] ^= this._Kd[0][i]; - } - - // apply round transforms - for (var r = 1; r < rounds; r++) { - for (var i = 0; i < 4; i++) { - a[i] = (T5[(t[ i ] >> 24) & 0xff] ^ - T6[(t[(i + 3) % 4] >> 16) & 0xff] ^ - T7[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T8[ t[(i + 1) % 4] & 0xff] ^ - this._Kd[r][i]); - } - t = a.slice(); - } - - // the last round is special - var result = createArray(16), tt; - for (var i = 0; i < 4; i++) { - tt = this._Kd[rounds][i]; - result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff; - } - - return result; - } - - - /** - * Mode Of Operation - Electonic Codebook (ECB) - */ - 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 AES(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; - } - - - /** - * Mode Of Operation - Cipher Block Chaining (CBC) - */ - 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 AES(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; - } - - - /** - * Mode Of Operation - Cipher Feedback (CFB) - */ - 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 AES(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]; - } - - // Shift the register - 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]; - } - - // Shift the register - copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); - copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize); - } - - return plaintext; - } - - /** - * Mode Of Operation - Output Feedback (OFB) - */ - 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 AES(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; - } - - // Decryption is symetric - ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt; - - - /** - * Counter object for CTR common mode of operation - */ - var Counter = function(initialValue) { - if (!(this instanceof Counter)) { - throw Error('Counter must be instanitated with `new`'); - } - - // We allow 0, but anything false-ish uses the default 1 - if (initialValue !== 0 && !initialValue) { initialValue = 1; } - - if (typeof(initialValue) === 'number') { - this._counter = createArray(16); - this.setValue(initialValue); - - } else { - this.setBytes(initialValue); - } - } - - Counter.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; - } - } - - Counter.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; - }; - - Counter.prototype.increment = function() { - for (var i = 15; i >= 0; i--) { - if (this._counter[i] === 255) { - this._counter[i] = 0; - } else { - this._counter[i]++; - break; - } - } - } - - - /** - * Mode Of Operation - Counter (CTR) - */ - 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 Counter)) { - counter = new Counter(counter) - } - - this._counter = counter; - - this._remainingCounter = null; - this._remainingCounterIndex = 16; - - this._aes = new AES(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; - } - - // Decryption is symetric - ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt; - - - /////////////////////// - // Padding - - // See:https://tools.ietf.org/html/rfc2315 - 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'); } - - 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; - } - - /////////////////////// - // Exporting - - - // The block cipher - var aesjs = { - AES: AES, - Counter: Counter, - - ModeOfOperation: { - ecb: ModeOfOperationECB, - cbc: ModeOfOperationCBC, - cfb: ModeOfOperationCFB, - ofb: ModeOfOperationOFB, - ctr: ModeOfOperationCTR - }, - - utils: { - hex: convertHex, - utf8: convertUtf8 - }, - - padding: { - pkcs7: { - pad: pkcs7pad, - strip: pkcs7strip - } - }, - - _arrayTest: { - coerceArray: coerceArray, - createArray: createArray, - copyArray: copyArray, - } - }; - - - // node.js - if (true) { - module.exports = aesjs - - // RequireJS/AMD - // http://www.requirejs.org/docs/api.html - // https://github.com/amdjs/amdjs-api/wiki/AMD - } else {} - - -})(this); - - -/***/ }), - -/***/ 1659: -/***/ ((module) => { - -/** - * Takes an array of AbortSignals and returns a single signal. - * If any signals are aborted, the returned signal will be aborted. - * @param {Array} signals - * @returns {AbortSignal} - */ -function anySignal (signals) { - const controller = new globalThis.AbortController() - - function onAbort () { - controller.abort() - - for (const signal of signals) { - if (!signal || !signal.removeEventListener) continue - signal.removeEventListener('abort', onAbort) - } - } - - for (const signal of signals) { - if (!signal || !signal.addEventListener) continue - if (signal.aborted) { - onAbort() - break - } - signal.addEventListener('abort', onAbort) - } - - return controller.signal -} - -module.exports = anySignal -module.exports.anySignal = anySignal - - -/***/ }), - -/***/ 4782: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - - -/***/ }), - -/***/ 8194: -/***/ ((module) => { - -"use strict"; - -var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l' - -// pre-compute lookup table -var ALPHABET_MAP = {} -for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z -} - -function polymodStep (pre) { - var b = pre >> 25 - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) -} - -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 & 0x1f) - } - return chk -} - -function encode (prefix, words, LIMIT) { - LIMIT = LIMIT || 90 - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - - prefix = prefix.toLowerCase() - - // determine chk mod - 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)) & 0x1f - 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' - - // don't allow mixed case - 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 === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v - - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v) - } - - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } -} - -function decodeUnsafe () { - var res = __decode.apply(null, arguments) - if (typeof res === 'object') return res -} - -function decode (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) -} - -module.exports = { - decodeUnsafe: decodeUnsafe, - decode: decode, - encode: encode, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords -} - - -/***/ }), - -/***/ 3133: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* eslint-env browser */ - - - -const browserReadableStreamToIt = __webpack_require__(2630) - -/** - * @param {Blob} blob - * @returns {AsyncIterable} - */ -function blobToIt (blob) { - if (typeof blob.stream === 'function') { - // @ts-ignore missing some properties - return browserReadableStreamToIt(blob.stream()) - } - - // firefox < 69 does not support blob.stream() - // @ts-ignore - response.body is optional, but in practice it's a stream. - return browserReadableStreamToIt(new Response(blob).body) -} - -module.exports = blobToIt - - -/***/ }), - -/***/ 3785: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* module decorator */ module = __webpack_require__.nmd(module); -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = (__webpack_require__(5545).Buffer); - } - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.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); - } - } - } - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - 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) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - 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) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // 'A' - 'F' - if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - // '0' - '9' - } else { - return (c - 48) & 0xf; - } - } - - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - 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; - } - - // 24-bits chunks - 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 & 0x3ffffff; - 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 & 0x3ffffff; - 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 len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; 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 < 0x4000000) { - 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 < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this.strip(); - }; - - BN.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; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - 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, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.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) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - 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 = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(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; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - 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'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.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] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.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; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.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(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - 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(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - 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(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.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(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - 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 & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.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); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - 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 & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - 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(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.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 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - 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 & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - 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; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.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; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - 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; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (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(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.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 = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } 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; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.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 = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - 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; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - 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; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - 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 { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.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 & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - 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 & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - 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; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(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) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - 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(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(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: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: 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: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - 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); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - 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 acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.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(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(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) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.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 BN(1); - var x2 = new BN(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; - }; - - BN.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; - - // Remove common factor of two - 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) { - // Swap `a` and `b` to make `a` always bigger than `b` - 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); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - 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 &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.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 <= 0x3ffffff, '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; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.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; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - 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; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.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); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.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); - }; - - BN.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); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - 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 !== undefined) { - // r is BN v4 instance - r.strip(); - } else { - // r is BN v5 instance - 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) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - 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; - } - - // Shift by 9 limbs - 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) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - 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 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._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); - return a.umod(this.m)._forceRed(this); - }; - - 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); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - 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 BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(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 BN(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 BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(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; - }; - - // - // Montgomery method engine - // - - BN.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 BN(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 BN(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) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})( false || module, this); - - -/***/ }), - -/***/ 2630: -/***/ ((module) => { - -"use strict"; - - -/** - * Turns a browser readable stream into an async iterable. Async iteration over - * returned iterable will lock give stream, preventing any other consumer from - * acquiring a reader. The lock will be released if iteration loop is broken. To - * prevent stream cancelling optional `{ preventCancel: true }` could be passed - * as a second argument. - * @template T - * @param {ReadableStream} stream - * @param {Object} [options] - * @param {boolean} [options.preventCancel=boolean] - * @returns {AsyncIterable} - */ -async function * browserReadableStreamToIt (stream, options = {}) { - const reader = stream.getReader() - - try { - while (true) { - const result = await reader.read() - - if (result.done) { - return - } - - yield result.value - } - } finally { - if (options.preventCancel !== true) { - reader.cancel() - } - - reader.releaseLock() - } -} - -module.exports = browserReadableStreamToIt - - -/***/ }), - -/***/ 816: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - - - -var base64 = __webpack_require__(4782) -var ieee754 = __webpack_require__(8898) -var customInspectSymbol = - (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation - ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - var proto = { foo: function () { return 42 } } - Object.setPrototypeOf(proto, Uint8Array.prototype) - Object.setPrototypeOf(arr, proto) - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - Object.setPrototypeOf(buf, Buffer.prototype) - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayView(value) - } - - if (value == null) { - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof SharedArrayBuffer !== 'undefined' && - (isInstance(value, SharedArrayBuffer) || - (value && isInstance(value.buffer, SharedArrayBuffer)))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) -Object.setPrototypeOf(Buffer, Uint8Array) - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayView (arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView) - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) - } - return fromArrayLike(arrayView) -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype) - - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos) - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ) - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } else { - buf.copy(buffer, pos) - } - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} -if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) - ? 4 - : (firstByte > 0xDF) - ? 3 - : (firstByte > 0xBF) - ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]] - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(newBuf, Buffer.prototype) - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUintLE = -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUintBE = -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUint8 = -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUint16LE = -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUint16BE = -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUint32LE = -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUint32BE = -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUintLE = -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUintBE = -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUint8 = -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUint16LE = -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUint16BE = -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUint32LE = -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUint32BE = -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } else if (typeof val === 'boolean') { - val = Number(val) - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -// Create lookup table for `toString('hex')` -// See: https://github.com/feross/buffer/issues/219 -var hexSliceLookupTable = (function () { - var alphabet = '0123456789abcdef' - var table = new Array(256) - for (var i = 0; i < 16; ++i) { - var i16 = i * 16 - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j] - } - } - return table -})() - - -/***/ }), - -/***/ 1766: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __webpack_require__(8582); -function fromSplit(split) { - const [protectedHeader, encrypted_key, iv, ciphertext, tag] = split; - const jwe = { - ciphertext, - iv, - protected: protectedHeader, - tag, - }; - if (encrypted_key) - jwe.recipients = [{ encrypted_key }]; - return jwe; -} -function encodeRecipient(recipient) { - const encRec = {}; - if (recipient.encrypted_key) - encRec.encrypted_key = utils_1.fromBase64url(recipient.encrypted_key); - if (recipient.header) - encRec.header = recipient.header; - return encRec; -} -function encode(jwe) { - const encJwe = { - ciphertext: utils_1.fromBase64url(jwe.ciphertext), - protected: utils_1.fromBase64url(jwe.protected), - iv: utils_1.fromBase64url(jwe.iv), - tag: utils_1.fromBase64url(jwe.tag), - }; - if (jwe.aad) - encJwe.aad = utils_1.fromBase64url(jwe.aad); - if (jwe.recipients) - encJwe.recipients = jwe.recipients.map(encodeRecipient); - if (jwe.unprotected) - encJwe.unprotected = jwe.unprotected; - return encJwe; -} -function decodeRecipient(encoded) { - const recipient = {}; - if (encoded.encrypted_key) - recipient.encrypted_key = utils_1.toBase64url(encoded.encrypted_key); - if (encoded.header) - recipient.header = encoded.header; - return recipient; -} -function decode(encoded) { - const jwe = { - ciphertext: utils_1.toBase64url(encoded.ciphertext), - protected: utils_1.toBase64url(encoded.protected), - iv: utils_1.toBase64url(encoded.iv), - tag: utils_1.toBase64url(encoded.tag), - }; - if (encoded.aad) - jwe.aad = utils_1.toBase64url(encoded.aad); - if (encoded.recipients) - jwe.recipients = encoded.recipients.map(decodeRecipient); - if (encoded.unprotected) - jwe.unprotected = encoded.unprotected; - return jwe; -} -exports["default"] = { - fromSplit, - decode, - encode, -}; -//# sourceMappingURL=encryption.js.map - -/***/ }), - -/***/ 3614: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decode = exports.encode = exports.toGeneral = exports.code = exports.name = void 0; -const signing_1 = __importDefault(__webpack_require__(5935)); -const encryption_1 = __importDefault(__webpack_require__(1766)); -const cbor = __importStar(__webpack_require__(7262)); -exports.name = 'dag-jose'; -exports.code = 133; -function isDagJWS(jose) { - return ('payload' in jose && - typeof jose.payload === 'string' && - 'signatures' in jose && - Array.isArray(jose.signatures)); -} -function isEncodedJWS(jose) { - return ('payload' in jose && - jose.payload instanceof Uint8Array && - 'signatures' in jose && - Array.isArray(jose.signatures)); -} -function isEncodedJWE(jose) { - return ('ciphertext' in jose && - jose.ciphertext instanceof Uint8Array && - 'iv' in jose && - jose.iv instanceof Uint8Array && - 'protected' in jose && - jose.protected instanceof Uint8Array && - 'tag' in jose && - jose.tag instanceof Uint8Array); -} -function isDagJWE(jose) { - return ('ciphertext' in jose && - typeof jose.ciphertext === 'string' && - 'iv' in jose && - typeof jose.iv === 'string' && - 'protected' in jose && - typeof jose.protected === 'string' && - 'tag' in jose && - typeof jose.tag === 'string'); -} -function toGeneral(jose) { - if (typeof jose === 'string') { - const split = jose.split('.'); - if (split.length === 3) { - return signing_1.default.fromSplit(split); - } - else if (split.length === 5) { - return encryption_1.default.fromSplit(split); - } - throw new Error('Not a valid JOSE string'); - } - if (isDagJWS(jose) || isDagJWE(jose)) { - return jose; - } - throw new Error('Not a valid unencoded JOSE object'); -} -exports.toGeneral = toGeneral; -function encode(obj) { - if (typeof obj === 'string') { - obj = toGeneral(obj); - } - let encodedJose; - if (isDagJWS(obj)) { - encodedJose = signing_1.default.encode(obj); - } - else if (isDagJWE(obj)) { - encodedJose = encryption_1.default.encode(obj); - } - else { - throw new Error('Not a valid JOSE object'); - } - return new Uint8Array(cbor.encode(encodedJose)); -} -exports.encode = encode; -function decode(data) { - let encoded; - try { - encoded = cbor.decode(data); - } - catch (e) { - throw new Error('Not a valid DAG-JOSE object'); - } - if (isEncodedJWS(encoded)) { - return signing_1.default.decode(encoded); - } - else if (isEncodedJWE(encoded)) { - return encryption_1.default.decode(encoded); - } - else { - throw new Error('Not a valid DAG-JOSE object'); - } -} -exports.decode = decode; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 5935: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __webpack_require__(8582); -const cid_1 = __webpack_require__(3036); -function fromSplit(split) { - const [protectedHeader, payload, signature] = split; - return { - payload, - signatures: [{ protected: protectedHeader, signature }], - link: cid_1.CID.decode(utils_1.fromBase64url(payload)), - }; -} -function encodeSignature(signature) { - const encoded = { - signature: utils_1.fromBase64url(signature.signature), - }; - if (signature.header) - encoded.header = signature.header; - if (signature.protected) - encoded.protected = utils_1.fromBase64url(signature.protected); - return encoded; -} -function encode(jws) { - const payload = utils_1.fromBase64url(jws.payload); - try { - cid_1.CID.decode(payload); - } - catch (e) { - throw new Error('Not a valid DagJWS'); - } - const encodedJws = { - payload, - signatures: jws.signatures.map(encodeSignature), - }; - return encodedJws; -} -function decodeSignature(encoded) { - const sign = { - signature: utils_1.toBase64url(encoded.signature), - }; - if (encoded.header) - sign.header = encoded.header; - if (encoded.protected) - sign.protected = utils_1.toBase64url(encoded.protected); - return sign; -} -function decode(encoded) { - const decoded = { - payload: utils_1.toBase64url(encoded.payload), - signatures: encoded.signatures.map(decodeSignature), - }; - decoded.link = cid_1.CID.decode(new Uint8Array(encoded.payload)); - return decoded; -} -exports["default"] = { - fromSplit, - encode, - decode, -}; -//# sourceMappingURL=signing.js.map - -/***/ }), - -/***/ 8582: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64url = exports.toBase64url = void 0; -const base64_1 = __webpack_require__(1453); -function toBase64url(b) { - return base64_1.base64url.encode(b).slice(1); -} -exports.toBase64url = toBase64url; -function fromBase64url(s) { - return base64_1.base64url.decode(`u${s}`); -} -exports.fromBase64url = fromBase64url; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 6292: -/***/ ((module, exports, __webpack_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(9374)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), - -/***/ 9374: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(8628); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), - -/***/ 8173: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -// https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* -syntax ::= RULE_EOL* rule+ -rule ::= " "* "<" rule-name ">" " "* "::=" firstExpression otherExpression* " "* RULE_EOL+ " "* -firstExpression ::= " "* list -otherExpression ::= " "* "|" " "* list -RULE_EOL ::= "\r" | "\n" -list ::= term " "* list | term -term ::= literal | "<" rule-name ">" -literal ::= '"' RULE_CHARACTER1* '"' | "'" RULE_CHARACTER2* "'" -RULE_CHARACTER ::= " " | RULE_LETTER | RULE_DIGIT | RULE_SYMBOL -RULE_LETTER ::= "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" -RULE_DIGIT ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" -RULE_SYMBOL ::= "-" | "_" | "!" | "#" | "$" | "%" | "&" | "(" | ")" | "*" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | "=" | ">" | "?" | "@" | "[" | "\" | "]" | "^" | "_" | "`" | "{" | "|" | "}" | "~" -RULE_CHARACTER1 ::= RULE_CHARACTER | "'" -RULE_CHARACTER2 ::= RULE_CHARACTER | '"' -rule-name ::= RULE_LETTER RULE_CHAR* -RULE_CHAR ::= RULE_LETTER | RULE_DIGIT | "_" | "-" -*/ -const SemanticHelpers_1 = __webpack_require__(7241); -const Parser_1 = __webpack_require__(489); -var BNF; -(function (BNF) { - BNF.RULES = [ - { - name: 'syntax', - bnf: [['RULE_EOL*', 'rule+']] - }, - { - name: 'rule', - bnf: [ - [ - '" "*', - '"<"', - 'rule-name', - '">"', - '" "*', - '"::="', - 'firstExpression', - 'otherExpression*', - '" "*', - 'RULE_EOL+', - '" "*' - ] - ] - }, - { - name: 'firstExpression', - bnf: [['" "*', 'list']] - }, - { - name: 'otherExpression', - bnf: [['" "*', '"|"', '" "*', 'list']] - }, - { - name: 'RULE_EOL', - bnf: [['"\\r"'], ['"\\n"']] - }, - { - name: 'list', - bnf: [['term', '" "*', 'list'], ['term']] - }, - { - name: 'term', - bnf: [['literal'], ['"<"', 'rule-name', '">"']] - }, - { - name: 'literal', - bnf: [[`'"'`, 'RULE_CHARACTER1*', `'"'`], [`"'"`, 'RULE_CHARACTER2*', `"'"`]] - }, - { - name: 'RULE_CHARACTER', - bnf: [['" "'], ['RULE_LETTER'], ['RULE_DIGIT'], ['RULE_SYMBOL']] - }, - { - name: 'RULE_LETTER', - bnf: [ - ['"A"'], - ['"B"'], - ['"C"'], - ['"D"'], - ['"E"'], - ['"F"'], - ['"G"'], - ['"H"'], - ['"I"'], - ['"J"'], - ['"K"'], - ['"L"'], - ['"M"'], - ['"N"'], - ['"O"'], - ['"P"'], - ['"Q"'], - ['"R"'], - ['"S"'], - ['"T"'], - ['"U"'], - ['"V"'], - ['"W"'], - ['"X"'], - ['"Y"'], - ['"Z"'], - ['"a"'], - ['"b"'], - ['"c"'], - ['"d"'], - ['"e"'], - ['"f"'], - ['"g"'], - ['"h"'], - ['"i"'], - ['"j"'], - ['"k"'], - ['"l"'], - ['"m"'], - ['"n"'], - ['"o"'], - ['"p"'], - ['"q"'], - ['"r"'], - ['"s"'], - ['"t"'], - ['"u"'], - ['"v"'], - ['"w"'], - ['"x"'], - ['"y"'], - ['"z"'] - ] - }, - { - name: 'RULE_DIGIT', - bnf: [['"0"'], ['"1"'], ['"2"'], ['"3"'], ['"4"'], ['"5"'], ['"6"'], ['"7"'], ['"8"'], ['"9"']] - }, - { - name: 'RULE_SYMBOL', - bnf: [ - ['"-"'], - ['"_"'], - ['"!"'], - ['"#"'], - ['"$"'], - ['"%"'], - ['"&"'], - ['"("'], - ['")"'], - ['"*"'], - ['"+"'], - ['","'], - ['"-"'], - ['"."'], - ['"/"'], - ['":"'], - ['";"'], - ['"<"'], - ['"="'], - ['">"'], - ['"?"'], - ['"@"'], - ['"["'], - ['"\\"'], - ['"]"'], - ['"^"'], - ['"_"'], - ['"`"'], - ['"{"'], - ['"|"'], - ['"}"'], - ['"~"'] - ] - }, - { - name: 'RULE_CHARACTER1', - bnf: [['RULE_CHARACTER'], [`"'"`]] - }, - { - name: 'RULE_CHARACTER2', - bnf: [['RULE_CHARACTER'], [`'"'`]] - }, - { - name: 'rule-name', - bnf: [['RULE_LETTER', 'RULE_CHAR*']] - }, - { - name: 'RULE_CHAR', - bnf: [['RULE_LETTER'], ['RULE_DIGIT'], ['"_"'], ['"-"']] - } - ]; - BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); - function getAllTerms(expr) { - let terms = SemanticHelpers_1.findChildrenByType(expr, 'term').map(term => { - return SemanticHelpers_1.findChildrenByType(term, 'literal').concat(SemanticHelpers_1.findChildrenByType(term, 'rule-name'))[0].text; - }); - SemanticHelpers_1.findChildrenByType(expr, 'list').forEach(expr => { - terms = terms.concat(getAllTerms(expr)); - }); - return terms; - } - function getRules(source, parser = BNF.defaultParser) { - let ast = parser.getAST(source); - if (!ast) - throw new Error('Could not parse ' + source); - if (ast.errors && ast.errors.length) { - throw ast.errors[0]; - } - let rules = SemanticHelpers_1.findChildrenByType(ast, 'rule'); - let ret = rules.map((rule) => { - let name = SemanticHelpers_1.findChildrenByType(rule, 'rule-name')[0].text; - let expressions = SemanticHelpers_1.findChildrenByType(rule, 'firstExpression').concat(SemanticHelpers_1.findChildrenByType(rule, 'otherExpression')); - let bnf = []; - expressions.forEach(expr => { - bnf.push(getAllTerms(expr)); - }); - return { - name: name, - bnf - }; - }); - if (!ret.some(x => x.name == 'EOL')) { - ret.push({ - name: 'EOL', - bnf: [['"\\r\\n"', '"\\r"', '"\\n"']] - }); - } - return ret; - } - BNF.getRules = getRules; - function Transform(source, subParser = BNF.defaultParser) { - return getRules(source.join(''), subParser); - } - BNF.Transform = Transform; - class Parser extends Parser_1.Parser { - constructor(source, options) { - const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; - super(getRules(source, subParser), options); - this.source = source; - } - emitSource() { - return this.source; - } - } - BNF.Parser = Parser; -})(BNF || (BNF = {})); -exports["default"] = BNF; -//# sourceMappingURL=BNF.js.map - -/***/ }), - -/***/ 1657: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -// https://www.w3.org/TR/REC-xml/#NT-Name -// http://www.bottlecaps.de/rr/ui -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Grammar ::= Production* -// Production ::= NCName '::=' Choice -// NCName ::= [http://www.w3.org/TR/xml-names/#NT-NCName] -// Choice ::= SequenceOrDifference ( '|' SequenceOrDifference )* -// SequenceOrDifference ::= (Item ( '-' Item | Item* ))? -// Item ::= Primary ( '?' | '*' | '+' )? -// Primary ::= NCName | StringLiteral | CharCode | CharClass | '(' Choice ')' -// StringLiteral ::= '"' [^"]* '"' | "'" [^']* "'" -// CharCode ::= '#x' [0-9a-fA-F]+ -// CharClass ::= '[' '^'? ( RULE_Char | CharCode | CharRange | CharCodeRange )+ ']' -// RULE_Char ::= [http://www.w3.org/TR/xml#NT-RULE_Char] -// CharRange ::= RULE_Char '-' ( RULE_Char - ']' ) -// CharCodeRange ::= CharCode '-' CharCode -// RULE_WHITESPACE ::= RULE_S | Comment -// RULE_S ::= #x9 | #xA | #xD | #x20 -// Comment ::= '/*' ( [^*] | '*'+ [^*/] )* '*'* '*/' -const TokenError_1 = __webpack_require__(4217); -const Parser_1 = __webpack_require__(489); -var BNF; -(function (BNF) { - BNF.RULES = [ - { - name: 'Grammar', - bnf: [['RULE_S*', 'Attributes?', 'RULE_S*', '%Atomic*', 'EOF']] - }, - { - name: '%Atomic', - bnf: [['Production', 'RULE_S*']], - fragment: true - }, - { - name: 'Production', - bnf: [ - [ - 'NCName', - 'RULE_S*', - '"::="', - 'RULE_WHITESPACE*', - '%Choice', - 'RULE_WHITESPACE*', - 'Attributes?', - 'RULE_EOL+', - 'RULE_S*' - ] - ] - }, - { - name: 'NCName', - bnf: [[/[a-zA-Z][a-zA-Z_0-9]*/]] - }, - { - name: 'Attributes', - bnf: [['"{"', 'Attribute', '%Attributes*', 'RULE_S*', '"}"']] - }, - { - name: '%Attributes', - bnf: [['RULE_S*', '","', 'Attribute']], - fragment: true - }, - { - name: 'Attribute', - bnf: [['RULE_S*', 'NCName', 'RULE_WHITESPACE*', '"="', 'RULE_WHITESPACE*', 'AttributeValue']] - }, - { - name: 'AttributeValue', - bnf: [['NCName'], [/[1-9][0-9]*/]] - }, - { - name: '%Choice', - bnf: [['SequenceOrDifference', '%_Choice_1*']], - fragment: true - }, - { - name: '%_Choice_1', - bnf: [['RULE_S*', '"|"', 'RULE_S*', 'SequenceOrDifference']], - fragment: true - }, - { - name: 'SequenceOrDifference', - bnf: [['%Item', 'RULE_WHITESPACE*', '%_Item_1?']] - }, - { - name: '%_Item_1', - bnf: [['Minus', '%Item'], ['%Item*']], - fragment: true - }, - { - name: 'Minus', - bnf: [['"-"']] - }, - { - name: '%Item', - bnf: [['RULE_WHITESPACE*', 'PrimaryPreDecoration?', '%Primary', 'PrimaryDecoration?']], - fragment: true - }, - { - name: 'PrimaryDecoration', - bnf: [['"?"'], ['"*"'], ['"+"']] - }, - { - name: 'PrimaryPreDecoration', - bnf: [['"&"'], ['"!"'], ['"~"']] - }, - { - name: '%Primary', - bnf: [['NCName'], ['StringLiteral'], ['CharCode'], ['CharClass'], ['SubItem']], - fragment: true - }, - { - name: 'SubItem', - bnf: [['"("', 'RULE_S*', '%Choice', 'RULE_S*', '")"']] - }, - { - name: 'StringLiteral', - bnf: [[`'"'`, /[^"]*/, `'"'`], [`"'"`, /[^']*/, `"'"`]] - }, - { - name: 'CharCode', - bnf: [['"#x"', /[0-9a-zA-Z]+/]] - }, - { - name: 'CharClass', - bnf: [["'['", "'^'?", '%RULE_CharClass_1+', '"]"']] - }, - { - name: '%RULE_CharClass_1', - bnf: [['CharCodeRange'], ['CharRange'], ['CharCode'], ['RULE_Char']], - fragment: true - }, - { - name: 'RULE_Char', - bnf: [[/\x09/], [/\x0A/], [/\x0D/], [/[\x20-\x5c]/], [/[\x5e-\uD7FF]/], [/[\uE000-\uFFFD]/]] - }, - { - name: 'CharRange', - bnf: [['RULE_Char', '"-"', 'RULE_Char']] - }, - { - name: 'CharCodeRange', - bnf: [['CharCode', '"-"', 'CharCode']] - }, - { - name: 'RULE_WHITESPACE', - bnf: [['%RULE_WHITESPACE_CHAR*'], ['Comment', 'RULE_WHITESPACE*']] - }, - { - name: 'RULE_S', - bnf: [['RULE_WHITESPACE', 'RULE_S*'], ['RULE_EOL', 'RULE_S*']] - }, - { - name: '%RULE_WHITESPACE_CHAR', - bnf: [[/\x09/], [/\x20/]], - fragment: true - }, - { - name: 'Comment', - bnf: [['"/*"', '%RULE_Comment_Body*', '"*/"']] - }, - { - name: '%RULE_Comment_Body', - bnf: [[/[^*]/], ['"*"+', /[^/]*/]], - fragment: true - }, - { - name: 'RULE_EOL', - bnf: [[/\x0D/, /\x0A/], [/\x0A/], [/\x0D/]] - }, - { - name: 'Link', - bnf: [["'['", 'Url', "']'"]] - }, - { - name: 'Url', - bnf: [[/[^\x5D:/?#]/, '"://"', /[^\x5D#]+/, '%Url1?']] - }, - { - name: '%Url1', - bnf: [['"#"', 'NCName']], - fragment: true - } - ]; - BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); - const preDecorationRE = /^(!|&)/; - const decorationRE = /(\?|\+|\*)$/; - const subExpressionRE = /^%/; - function getBNFRule(name, parser) { - if (typeof name == 'string') { - let decoration = decorationRE.exec(name); - let preDecoration = preDecorationRE.exec(name); - let preDecorationText = preDecoration ? preDecoration[0] : ''; - let decorationText = decoration ? decoration[0] + ' ' : ''; - let subexpression = subExpressionRE.test(name); - if (subexpression) { - let lonely = isLonelyRule(name, parser); - if (lonely) - return preDecorationText + getBNFBody(name, parser) + decorationText; - return preDecorationText + '(' + getBNFBody(name, parser) + ')' + decorationText; - } - return name.replace(preDecorationRE, preDecorationText); - } - else { - return name.source - .replace(/\\(?:x|u)([a-zA-Z0-9]+)/g, '#x$1') - .replace(/\[\\(?:x|u)([a-zA-Z0-9]+)-\\(?:x|u)([a-zA-Z0-9]+)\]/g, '[#x$1-#x$2]'); - } - } - /// Returns true if the rule is a string literal or regular expression without a descendant tree - function isLonelyRule(name, parser) { - let rule = Parser_1.findRuleByName(name, parser); - return (rule && - rule.bnf.length == 1 && - rule.bnf[0].length == 1 && - (rule.bnf[0][0] instanceof RegExp || rule.bnf[0][0][0] == '"' || rule.bnf[0][0][0] == "'")); - } - function getBNFChoice(rules, parser) { - return rules.map(x => getBNFRule(x, parser)).join(' '); - } - function getBNFBody(name, parser) { - let rule = Parser_1.findRuleByName(name, parser); - if (rule) - return rule.bnf.map(x => getBNFChoice(x, parser)).join(' | '); - return 'RULE_NOT_FOUND {' + name + '}'; - } - function emit(parser) { - let acumulator = []; - parser.grammarRules.forEach(l => { - if (!/^%/.test(l.name)) { - let recover = l.recover ? ' { recoverUntil=' + l.recover + ' }' : ''; - acumulator.push(l.name + ' ::= ' + getBNFBody(l.name, parser) + recover); - } - }); - return acumulator.join('\n'); - } - BNF.emit = emit; - let subitems = 0; - function restar(total, resta) { - console.log('reberia restar ' + resta + ' a ' + total); - throw new Error('Difference not supported yet'); - } - function convertRegex(txt) { - return new RegExp(txt - .replace(/#x([a-zA-Z0-9]{4})/g, '\\u$1') - .replace(/#x([a-zA-Z0-9]{3})/g, '\\u0$1') - .replace(/#x([a-zA-Z0-9]{2})/g, '\\x$1') - .replace(/#x([a-zA-Z0-9]{1})/g, '\\x0$1')); - } - function getSubItems(tmpRules, seq, parentName, parentAttributes) { - let anterior = null; - let bnfSeq = []; - seq.children.forEach((x, i) => { - if (x.type == 'Minus') { - restar(anterior, x); - } - else { - } - let decoration = seq.children[i + 1]; - decoration = (decoration && decoration.type == 'PrimaryDecoration' && decoration.text) || ''; - let preDecoration = ''; - if (anterior && anterior.type == 'PrimaryPreDecoration') { - preDecoration = anterior.text; - } - let pinned = preDecoration == '~' ? 1 : undefined; - if (pinned) { - preDecoration = ''; - } - switch (x.type) { - case 'SubItem': - let name = '%' + (parentName + subitems++); - createRule(tmpRules, x, name, parentAttributes); - bnfSeq.push(preDecoration + name + decoration); - break; - case 'NCName': - bnfSeq.push(preDecoration + x.text + decoration); - break; - case 'StringLiteral': - if (decoration || preDecoration || !/^['"/()a-zA-Z0-9&_.:=,+*\-\^\\]+$/.test(x.text)) { - bnfSeq.push(preDecoration + x.text + decoration); - } - else { - for (const c of x.text.slice(1, -1)) { - if (parentAttributes && parentAttributes["ignoreCase"] == "true" && /[a-zA-Z]/.test(c)) { - bnfSeq.push(new RegExp("[" + c.toUpperCase() + c.toLowerCase() + "]")); - } - else { - bnfSeq.push(new RegExp(Parser_1.escapeRegExp(c))); - } - } - } - break; - case 'CharCode': - case 'CharClass': - if (decoration || preDecoration) { - let newRule = { - name: '%' + (parentName + subitems++), - bnf: [[convertRegex(x.text)]], - pinned - }; - tmpRules.push(newRule); - bnfSeq.push(preDecoration + newRule.name + decoration); - } - else { - bnfSeq.push(convertRegex(x.text)); - } - break; - case 'PrimaryPreDecoration': - case 'PrimaryDecoration': - break; - default: - throw new Error(' HOW SHOULD I PARSE THIS? ' + x.type + ' -> ' + JSON.stringify(x.text)); - } - anterior = x; - }); - return bnfSeq; - } - function createRule(tmpRules, token, name, parentAttributes = undefined) { - let attrNode = token.children.filter(x => x.type == 'Attributes')[0]; - let attributes = {}; - if (attrNode) { - attrNode.children.forEach(x => { - let name = x.children.filter(x => x.type == 'NCName')[0].text; - if (name in attributes) { - throw new TokenError_1.TokenError('Duplicated attribute ' + name, x); - } - else { - attributes[name] = x.children.filter(x => x.type == 'AttributeValue')[0].text; - } - }); - } - let bnf = token.children.filter(x => x.type == 'SequenceOrDifference').map(s => getSubItems(tmpRules, s, name, parentAttributes ? parentAttributes : attributes)); - let rule = { - name, - bnf - }; - if (name.indexOf('%') == 0) - rule.fragment = true; - if (attributes['recoverUntil']) { - rule.recover = attributes['recoverUntil']; - if (rule.bnf.length > 1) - throw new TokenError_1.TokenError('only one-option productions are suitable for error recovering', token); - } - if ('pin' in attributes) { - let num = parseInt(attributes['pin']); - if (!isNaN(num)) { - rule.pinned = num; - } - if (rule.bnf.length > 1) - throw new TokenError_1.TokenError('only one-option productions are suitable for pinning', token); - } - if ('ws' in attributes) { - rule.implicitWs = attributes['ws'] != 'explicit'; - } - else { - rule.implicitWs = null; - } - rule.fragment = rule.fragment || attributes['fragment'] == 'true'; - rule.simplifyWhenOneChildren = attributes['simplifyWhenOneChildren'] == 'true'; - tmpRules.push(rule); - } - function getRules(source, parser = BNF.defaultParser) { - let ast = parser.getAST(source); - if (!ast) - throw new Error('Could not parse ' + source); - if (ast.errors && ast.errors.length) { - throw ast.errors[0]; - } - let implicitWs = null; - let attrNode = ast.children.filter(x => x.type == 'Attributes')[0]; - let attributes = {}; - if (attrNode) { - attrNode.children.forEach(x => { - let name = x.children.filter(x => x.type == 'NCName')[0].text; - if (name in attributes) { - throw new TokenError_1.TokenError('Duplicated attribute ' + name, x); - } - else { - attributes[name] = x.children.filter(x => x.type == 'AttributeValue')[0].text; - } - }); - } - implicitWs = attributes['ws'] == 'implicit'; - let tmpRules = []; - ast.children.filter(x => x.type == 'Production').map((x) => { - let name = x.children.filter(x => x.type == 'NCName')[0].text; - createRule(tmpRules, x, name); - }); - tmpRules.forEach(rule => { - if (rule.implicitWs === null) - rule.implicitWs = implicitWs; - }); - return tmpRules; - } - BNF.getRules = getRules; - function Transform(source, subParser = BNF.defaultParser) { - return getRules(source.join(''), subParser); - } - BNF.Transform = Transform; - class Parser extends Parser_1.Parser { - constructor(source, options) { - const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; - super(getRules(source, subParser), options); - } - emitSource() { - return emit(this); - } - } - BNF.Parser = Parser; -})(BNF || (BNF = {})); -exports["default"] = BNF; -//# sourceMappingURL=Custom.js.map - -/***/ }), - -/***/ 1575: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -// https://www.w3.org/TR/REC-xml/#NT-Name -// http://www.bottlecaps.de/rr/ui -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Grammar ::= Production* -// Production ::= NCName '::=' Choice -// NCName ::= [http://www.w3.org/TR/xml-names/#NT-NCName] -// Choice ::= SequenceOrDifference ( '|' SequenceOrDifference )* -// SequenceOrDifference ::= (Item ( '-' Item | Item* ))? -// Item ::= Primary ( '?' | '*' | '+' )? -// Primary ::= NCName | StringLiteral | CharCode | CharClass | '(' Choice ')' -// StringLiteral ::= '"' [^"]* '"' | "'" [^']* "'" -// CharCode ::= '#x' [0-9a-fA-F]+ -// CharClass ::= '[' '^'? ( RULE_Char | CharCode | CharRange | CharCodeRange )+ ']' -// RULE_Char ::= [http://www.w3.org/TR/xml#NT-RULE_Char] -// CharRange ::= RULE_Char '-' ( RULE_Char - ']' ) -// CharCodeRange ::= CharCode '-' CharCode -// RULE_WHITESPACE ::= RULE_S | Comment -// RULE_S ::= #x9 | #xA | #xD | #x20 -// Comment ::= '/*' ( [^*] | '*'+ [^*/] )* '*'* '*/' -const Parser_1 = __webpack_require__(489); -var BNF; -(function (BNF) { - BNF.RULES = [ - { - name: 'Grammar', - bnf: [['RULE_S*', '%Atomic*', 'EOF']] - }, - { - name: '%Atomic', - bnf: [['Production', 'RULE_S*']], - fragment: true - }, - { - name: 'Production', - bnf: [['NCName', 'RULE_S*', '"::="', 'RULE_WHITESPACE*', 'Choice', 'RULE_WHITESPACE*', 'RULE_EOL+', 'RULE_S*']] - }, - { - name: 'NCName', - bnf: [[/[a-zA-Z][a-zA-Z_0-9]*/]] - }, - { - name: 'Choice', - bnf: [['SequenceOrDifference', '%_Choice_1*']], - fragment: true - }, - { - name: '%_Choice_1', - bnf: [['RULE_WHITESPACE*', '"|"', 'RULE_WHITESPACE*', 'SequenceOrDifference']], - fragment: true - }, - { - name: 'SequenceOrDifference', - bnf: [['Item', 'RULE_WHITESPACE*', '%_Item_1?']] - }, - { - name: '%_Item_1', - bnf: [['Minus', 'Item'], ['Item*']], - fragment: true - }, - { - name: 'Minus', - bnf: [['"-"']] - }, - { - name: 'Item', - bnf: [['RULE_WHITESPACE*', '%Primary', 'PrimaryDecoration?']], - fragment: true - }, - { - name: 'PrimaryDecoration', - bnf: [['"?"'], ['"*"'], ['"+"']] - }, - { - name: 'DecorationName', - bnf: [['"ebnf://"', /[^\x5D#]+/]] - }, - { - name: '%Primary', - bnf: [['NCName'], ['StringLiteral'], ['CharCode'], ['CharClass'], ['SubItem']], - fragment: true - }, - { - name: 'SubItem', - bnf: [['"("', 'RULE_WHITESPACE*', 'Choice', 'RULE_WHITESPACE*', '")"']] - }, - { - name: 'StringLiteral', - bnf: [[`'"'`, /[^"]*/, `'"'`], [`"'"`, /[^']*/, `"'"`]], - pinned: 1 - }, - { - name: 'CharCode', - bnf: [['"#x"', /[0-9a-zA-Z]+/]] - }, - { - name: 'CharClass', - bnf: [["'['", "'^'?", '%RULE_CharClass_1+', '"]"']] - }, - { - name: '%RULE_CharClass_1', - bnf: [['CharCodeRange'], ['CharRange'], ['CharCode'], ['RULE_Char']], - fragment: true - }, - { - name: 'RULE_Char', - bnf: [[/\x09/], [/\x0A/], [/\x0D/], [/[\x20-\x5c]/], [/[\x5e-\uD7FF]/], [/[\uE000-\uFFFD]/]] - }, - { - name: 'CharRange', - bnf: [['RULE_Char', '"-"', 'RULE_Char']] - }, - { - name: 'CharCodeRange', - bnf: [['CharCode', '"-"', 'CharCode']] - }, - { - name: 'RULE_WHITESPACE', - bnf: [['%RULE_WHITESPACE_CHAR*'], ['Comment', 'RULE_WHITESPACE*']] - }, - { - name: 'RULE_S', - bnf: [['RULE_WHITESPACE', 'RULE_S*'], ['RULE_EOL', 'RULE_S*']] - }, - { - name: '%RULE_WHITESPACE_CHAR', - bnf: [[/\x09/], [/\x20/]], - fragment: true - }, - { - name: 'Comment', - bnf: [['"/*"', '%RULE_Comment_Body*', '"*/"']] - }, - { - name: '%RULE_Comment_Body', - bnf: [['!"*/"', /[^*]/]], - fragment: true - }, - { - name: 'RULE_EOL', - bnf: [[/\x0D/, /\x0A/], [/\x0A/], [/\x0D/]] - }, - { - name: 'Link', - bnf: [["'['", 'Url', "']'"]] - }, - { - name: 'Url', - bnf: [[/[^\x5D:/?#]/, '"://"', /[^\x5D#]+/, '%Url1?']] - }, - { - name: '%Url1', - bnf: [['"#"', 'NCName']], - fragment: true - } - ]; - BNF.defaultParser = new Parser_1.Parser(BNF.RULES, { debug: false }); - const preDecorationRE = /^(!|&)/; - const decorationRE = /(\?|\+|\*)$/; - const subExpressionRE = /^%/; - function getBNFRule(name, parser) { - if (typeof name == 'string') { - if (preDecorationRE.test(name)) - return ''; - let subexpression = subExpressionRE.test(name); - if (subexpression) { - let decoration = decorationRE.exec(name); - let decorationText = decoration ? decoration[0] + ' ' : ''; - let lonely = isLonelyRule(name, parser); - if (lonely) - return getBNFBody(name, parser) + decorationText; - return '(' + getBNFBody(name, parser) + ')' + decorationText; - } - return name; - } - else { - return name.source - .replace(/\\(?:x|u)([a-zA-Z0-9]+)/g, '#x$1') - .replace(/\[\\(?:x|u)([a-zA-Z0-9]+)-\\(?:x|u)([a-zA-Z0-9]+)\]/g, '[#x$1-#x$2]'); - } - } - /// Returns true if the rule is a string literal or regular expression without a descendant tree - function isLonelyRule(name, parser) { - let rule = Parser_1.findRuleByName(name, parser); - return (rule && - rule.bnf.length == 1 && - rule.bnf[0].length == 1 && - (rule.bnf[0][0] instanceof RegExp || rule.bnf[0][0][0] == '"' || rule.bnf[0][0][0] == "'")); - } - function getBNFChoice(rules, parser) { - return rules.map(x => getBNFRule(x, parser)).join(' '); - } - function getBNFBody(name, parser) { - let rule = Parser_1.findRuleByName(name, parser); - if (rule) - return rule.bnf.map(x => getBNFChoice(x, parser)).join(' | '); - return 'RULE_NOT_FOUND {' + name + '}'; - } - function emit(parser) { - let acumulator = []; - parser.grammarRules.forEach(l => { - if (!/^%/.test(l.name)) { - let recover = l.recover ? ' /* { recoverUntil=' + l.recover + ' } */' : ''; - acumulator.push(l.name + ' ::= ' + getBNFBody(l.name, parser) + recover); - } - }); - return acumulator.join('\n'); - } - BNF.emit = emit; - let subitems = 0; - function restar(total, resta) { - console.log('reberia restar ' + resta + ' a ' + total); - throw new Error('Difference not supported yet'); - } - function convertRegex(txt) { - return new RegExp(txt - .replace(/#x([a-zA-Z0-9]{4})/g, '\\u$1') - .replace(/#x([a-zA-Z0-9]{3})/g, '\\u0$1') - .replace(/#x([a-zA-Z0-9]{2})/g, '\\x$1') - .replace(/#x([a-zA-Z0-9]{1})/g, '\\x0$1')); - } - function getSubItems(tmpRules, seq, parentName) { - let anterior = null; - let bnfSeq = []; - seq.children.forEach((x, i) => { - if (x.type == 'Minus') { - restar(anterior, x); - } - else { - } - let decoration = seq.children[i + 1]; - decoration = (decoration && decoration.type == 'PrimaryDecoration' && decoration.text) || ''; - let preDecoration = ''; - switch (x.type) { - case 'SubItem': - let name = '%' + (parentName + subitems++); - createRule(tmpRules, x, name); - bnfSeq.push(preDecoration + name + decoration); - break; - case 'NCName': - case 'StringLiteral': - bnfSeq.push(preDecoration + x.text + decoration); - break; - case 'CharCode': - case 'CharClass': - if (decoration || preDecoration) { - let newRule = { - name: '%' + (parentName + subitems++), - bnf: [[convertRegex(x.text)]] - }; - tmpRules.push(newRule); - bnfSeq.push(preDecoration + newRule.name + decoration); - } - else { - bnfSeq.push(convertRegex(x.text)); - } - break; - case 'PrimaryDecoration': - break; - default: - throw new Error(' HOW SHOULD I PARSE THIS? ' + x.type + ' -> ' + JSON.stringify(x.text)); - } - anterior = x; - }); - return bnfSeq; - } - function createRule(tmpRules, token, name) { - let bnf = token.children.filter(x => x.type == 'SequenceOrDifference').map(s => getSubItems(tmpRules, s, name)); - let rule = { - name, - bnf - }; - let recover = null; - bnf.forEach(x => { - recover = recover || x['recover']; - delete x['recover']; - }); - if (name.indexOf('%') == 0) - rule.fragment = true; - if (recover) - rule.recover = recover; - tmpRules.push(rule); - } - function getRules(source, parser = BNF.defaultParser) { - let ast = parser.getAST(source); - if (!ast) - throw new Error('Could not parse ' + source); - if (ast.errors && ast.errors.length) { - throw ast.errors[0]; - } - let tmpRules = []; - ast.children.filter(x => x.type == 'Production').map((x) => { - let name = x.children.filter(x => x.type == 'NCName')[0].text; - createRule(tmpRules, x, name); - }); - return tmpRules; - } - BNF.getRules = getRules; - function Transform(source, subParser = BNF.defaultParser) { - return getRules(source.join(''), subParser); - } - BNF.Transform = Transform; - class Parser extends Parser_1.Parser { - constructor(source, options) { - const subParser = options && options.debugRulesParser === true ? new Parser_1.Parser(BNF.RULES, { debug: true }) : BNF.defaultParser; - super(getRules(source, subParser), options); - } - emitSource() { - return emit(this); - } - } - BNF.Parser = Parser; -})(BNF || (BNF = {})); -exports["default"] = BNF; -//# sourceMappingURL=W3CEBNF.js.map - -/***/ }), - -/***/ 9652: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var BNF_1 = __webpack_require__(8173); -Object.defineProperty(exports, "BNF", ({ enumerable: true, get: function () { return BNF_1.default; } })); -var W3CEBNF_1 = __webpack_require__(1575); -Object.defineProperty(exports, "W3C", ({ enumerable: true, get: function () { return W3CEBNF_1.default; } })); -var Custom_1 = __webpack_require__(1657); -Object.defineProperty(exports, "Custom", ({ enumerable: true, get: function () { return Custom_1.default; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 489: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -// https://www.ics.uci.edu/~pattis/ICS-33/lectures/ebnf.pdf -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Parser = exports.findRuleByName = exports.parseRuleName = exports.escapeRegExp = exports.readToken = void 0; -const UPPER_SNAKE_RE = /^[A-Z0-9_]+$/; -const decorationRE = /(\?|\+|\*)$/; -const preDecorationRE = /^(@|&|!)/; -const WS_RULE = 'WS'; -const TokenError_1 = __webpack_require__(4217); -function readToken(txt, expr) { - let result = expr.exec(txt); - if (result && result.index == 0) { - if (result[0].length == 0 && expr.source.length > 0) - return null; - return { - type: null, - text: result[0], - rest: txt.substr(result[0].length), - start: 0, - end: result[0].length - 1, - fullText: result[0], - errors: [], - children: [], - parent: null - }; - } - return null; -} -exports.readToken = readToken; -function escapeRegExp(str) { - return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); -} -exports.escapeRegExp = escapeRegExp; -function fixRest(token) { - token.rest = ''; - token.children && token.children.forEach(c => fixRest(c)); -} -function fixPositions(token, start) { - token.start += start; - token.end += start; - token.children && token.children.forEach(c => fixPositions(c, token.start)); -} -function agregateErrors(errors, token) { - if (token.errors && token.errors.length) - token.errors.forEach(err => errors.push(err)); - token.children && token.children.forEach(tok => agregateErrors(errors, tok)); -} -function parseRuleName(name) { - let postDecoration = decorationRE.exec(name); - let preDecoration = preDecorationRE.exec(name); - let postDecorationText = (postDecoration && postDecoration[0]) || ''; - let preDecorationText = (preDecoration && preDecoration[0]) || ''; - let out = { - raw: name, - name: name.replace(decorationRE, '').replace(preDecorationRE, ''), - isOptional: postDecorationText == '?' || postDecorationText == '*', - allowRepetition: postDecorationText == '+' || postDecorationText == '*', - atLeastOne: postDecorationText == '+', - lookupPositive: preDecorationText == '&', - lookupNegative: preDecorationText == '!', - pinned: preDecorationText == '@', - lookup: false, - isLiteral: false - }; - out.isLiteral = out.name[0] == "'" || out.name[0] == '"'; - out.lookup = out.lookupNegative || out.lookupPositive; - return out; -} -exports.parseRuleName = parseRuleName; -function findRuleByName(name, parser) { - let parsed = parseRuleName(name); - return parser.cachedRules[parsed.name] || null; -} -exports.findRuleByName = findRuleByName; -/// Removes all the nodes starting with 'RULE_' -function stripRules(token, re) { - if (token.children) { - let localRules = token.children.filter(x => x.type && re.test(x.type)); - for (let i = 0; i < localRules.length; i++) { - let indexOnChildren = token.children.indexOf(localRules[i]); - if (indexOnChildren != -1) { - token.children.splice(indexOnChildren, 1); - } - } - token.children.forEach(c => stripRules(c, re)); - } -} -const ignoreMissingRules = ['EOF']; -class Parser { - constructor(grammarRules, options) { - this.grammarRules = grammarRules; - this.options = options; - this.cachedRules = {}; - this.debug = options ? options.debug === true : false; - let errors = []; - let neededRules = []; - grammarRules.forEach(rule => { - let parsedName = parseRuleName(rule.name); - if (parsedName.name in this.cachedRules) { - errors.push('Duplicated rule ' + parsedName.name); - return; - } - else { - this.cachedRules[parsedName.name] = rule; - } - if (!rule.bnf || !rule.bnf.length) { - let error = 'Missing rule content, rule: ' + rule.name; - if (errors.indexOf(error) == -1) - errors.push(error); - } - else { - rule.bnf.forEach(options => { - if (typeof options[0] === 'string') { - let parsed = parseRuleName(options[0]); - if (parsed.name == rule.name) { - let error = 'Left recursion is not allowed, rule: ' + rule.name; - if (errors.indexOf(error) == -1) - errors.push(error); - } - } - options.forEach(option => { - if (typeof option == 'string') { - let name = parseRuleName(option); - if (!name.isLiteral && - neededRules.indexOf(name.name) == -1 && - ignoreMissingRules.indexOf(name.name) == -1) - neededRules.push(name.name); - } - }); - }); - } - if (WS_RULE == rule.name) - rule.implicitWs = false; - if (rule.implicitWs) { - if (neededRules.indexOf(WS_RULE) == -1) - neededRules.push(WS_RULE); - } - if (rule.recover) { - if (neededRules.indexOf(rule.recover) == -1) - neededRules.push(rule.recover); - } - }); - neededRules.forEach(ruleName => { - if (!(ruleName in this.cachedRules)) { - errors.push('Missing rule ' + ruleName); - } - }); - if (errors.length) - throw new Error(errors.join('\n')); - } - getAST(txt, target) { - if (!target) { - target = this.grammarRules.filter(x => !x.fragment && x.name.indexOf('%') != 0)[0].name; - } - let result = this.parse(txt, target); - if (result) { - agregateErrors(result.errors, result); - fixPositions(result, 0); - // REMOVE ALL THE TAGS MATCHING /^%/ - stripRules(result, /^%/); - if (!this.options || !this.options.keepUpperRules) - stripRules(result, UPPER_SNAKE_RE); - let rest = result.rest; - if (rest) { - new TokenError_1.TokenError('Unexpected end of input: \n' + rest, result); - } - fixRest(result); - result.rest = rest; - } - return result; - } - emitSource() { - return 'CANNOT EMIT SOURCE FROM BASE Parser'; - } - parse(txt, target, recursion = 0) { - let out = null; - let type = parseRuleName(target); - let expr; - let printable = this.debug && /*!isLiteral &*/ !UPPER_SNAKE_RE.test(type.name); - printable && - console.log(new Array(recursion).join('│ ') + 'Trying to get ' + target + ' from ' + JSON.stringify(txt.split('\n')[0])); - let realType = type.name; - let targetLex = findRuleByName(type.name, this); - if (type.name == 'EOF') { - if (txt.length) { - return null; - } - else if (txt.length == 0) { - return { - type: 'EOF', - text: '', - rest: '', - start: 0, - end: 0, - fullText: '', - errors: [], - children: [], - parent: null - }; - } - } - try { - if (!targetLex && type.isLiteral) { - // tslint:disable-next-line: no-eval - let src = eval(type.name); - if (src === '') { - return { - type: '%%EMPTY%%', - text: '', - rest: txt, - start: 0, - end: 0, - fullText: '', - errors: [], - children: [], - parent: null - }; - } - expr = new RegExp(escapeRegExp(src)); - realType = null; - } - } - catch (e) { - if (e instanceof ReferenceError) { - console.error(e); - } - return null; - } - if (expr) { - let result = readToken(txt, expr); - if (result) { - result.type = realType; - return result; - } - } - else { - let options = targetLex.bnf; - if (options instanceof Array) { - options.forEach(phases => { - if (out) - return; - let pinned = null; - let tmp = { - type: type.name, - text: '', - children: [], - end: 0, - errors: [], - fullText: '', - parent: null, - start: 0, - rest: txt - }; - if (targetLex.fragment) - tmp.fragment = true; - let tmpTxt = txt; - let position = 0; - let allOptional = phases.length > 0; - let foundSomething = false; - for (let i = 0; i < phases.length; i++) { - if (typeof phases[i] == 'string') { - let localTarget = parseRuleName(phases[i]); - allOptional = allOptional && localTarget.isOptional; - let got; - let foundAtLeastOne = false; - do { - got = null; - if (targetLex.implicitWs) { - got = this.parse(tmpTxt, localTarget.name, recursion + 1); - if (!got) { - let WS; - do { - WS = this.parse(tmpTxt, WS_RULE, recursion + 1); - if (WS) { - tmp.text = tmp.text + WS.text; - tmp.end = tmp.text.length; - WS.parent = tmp; - tmp.children.push(WS); - tmpTxt = tmpTxt.substr(WS.text.length); - position += WS.text.length; - } - else { - break; - } - } while (WS && WS.text.length); - } - } - got = got || this.parse(tmpTxt, localTarget.name, recursion + 1); - // rule ::= "true" ![a-zA-Z] - // negative lookup, if it does not match, we should continue - if (localTarget.lookupNegative) { - if (got) - return /* cancel this path */; - break; - } - if (localTarget.lookupPositive) { - if (!got) - return; - } - if (!got) { - if (localTarget.isOptional) - break; - if (localTarget.atLeastOne && foundAtLeastOne) - break; - } - if (got && targetLex.pinned == i + 1) { - pinned = got; - printable && console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' PINNED'); - } - if (!got) - got = this.parseRecovery(targetLex, tmpTxt, recursion + 1); - if (!got) { - if (pinned) { - out = tmp; - got = { - type: 'SyntaxError', - text: tmpTxt, - children: [], - end: tmpTxt.length, - errors: [], - fullText: '', - parent: null, - start: 0, - rest: '' - }; - if (tmpTxt.length) { - new TokenError_1.TokenError(`Unexpected end of input. Expecting ${localTarget.name} Got: ${tmpTxt}`, got); - } - else { - new TokenError_1.TokenError(`Unexpected end of input. Missing ${localTarget.name}`, got); - } - printable && - console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' ' + JSON.stringify(got.text)); - } - else { - return; - } - } - foundAtLeastOne = true; - foundSomething = true; - if (got.type == '%%EMPTY%%') { - break; - } - got.start += position; - got.end += position; - if (!localTarget.lookupPositive && got.type) { - if (got.fragment) { - got.children && - got.children.forEach(x => { - x.start += position; - x.end += position; - x.parent = tmp; - tmp.children.push(x); - }); - } - else { - got.parent = tmp; - tmp.children.push(got); - } - } - if (localTarget.lookup) - got.lookup = true; - printable && - console.log(new Array(recursion + 1).join('│ ') + '└─ ' + got.type + ' ' + JSON.stringify(got.text)); - // Eat it from the input stream, only if it is not a lookup - if (!localTarget.lookup && !got.lookup) { - tmp.text = tmp.text + got.text; - tmp.end = tmp.text.length; - tmpTxt = tmpTxt.substr(got.text.length); - position += got.text.length; - } - tmp.rest = tmpTxt; - } while (got && localTarget.allowRepetition && tmpTxt.length && !got.lookup); - } /* IS A REGEXP */ - else { - let got = readToken(tmpTxt, phases[i]); - if (!got) { - return; - } - printable && - console.log(new Array(recursion + 1).join('│ ') + '└> ' + JSON.stringify(got.text) + phases[i].source); - foundSomething = true; - got.start += position; - got.end += position; - tmp.text = tmp.text + got.text; - tmp.end = tmp.text.length; - tmpTxt = tmpTxt.substr(got.text.length); - position += got.text.length; - tmp.rest = tmpTxt; - } - } - if (foundSomething) { - out = tmp; - printable && - console.log(new Array(recursion).join('│ ') + '├<─┴< PUSHING ' + out.type + ' ' + JSON.stringify(out.text)); - } - }); - } - if (out && targetLex.simplifyWhenOneChildren && out.children.length == 1) { - out = out.children[0]; - } - } - if (!out) { - printable && console.log(target + ' NOT RESOLVED FROM ' + txt); - } - return out; - } - parseRecovery(recoverableToken, tmpTxt, recursion) { - if (recoverableToken.recover && tmpTxt.length) { - let printable = this.debug; - printable && - console.log(new Array(recursion + 1).join('│ ') + - 'Trying to recover until token ' + - recoverableToken.recover + - ' from ' + - JSON.stringify(tmpTxt.split('\n')[0] + tmpTxt.split('\n')[1])); - let tmp = { - type: 'SyntaxError', - text: '', - children: [], - end: 0, - errors: [], - fullText: '', - parent: null, - start: 0, - rest: '' - }; - let got; - do { - got = this.parse(tmpTxt, recoverableToken.recover, recursion + 1); - if (got) { - new TokenError_1.TokenError('Unexpected input: "' + tmp.text + `" Expecting: ${recoverableToken.name}`, tmp); - break; - } - else { - tmp.text = tmp.text + tmpTxt[0]; - tmp.end = tmp.text.length; - tmpTxt = tmpTxt.substr(1); - } - } while (!got && tmpTxt.length > 0); - if (tmp.text.length > 0 && got) { - printable && console.log(new Array(recursion + 1).join('│ ') + 'Recovered text: ' + JSON.stringify(tmp.text)); - return tmp; - } - } - return null; - } -} -exports.Parser = Parser; -exports["default"] = Parser; -//# sourceMappingURL=Parser.js.map - -/***/ }), - -/***/ 7241: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.findChildrenByType = void 0; -/** - * Finds all the direct childs of a specifyed type - */ -function findChildrenByType(token, type) { - return token.children ? token.children.filter(x => x.type == type) : []; -} -exports.findChildrenByType = findChildrenByType; -//# sourceMappingURL=SemanticHelpers.js.map - -/***/ }), - -/***/ 4217: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TokenError = void 0; -class TokenError extends Error { - constructor(message, token) { - super(message); - this.message = message; - this.token = token; - if (token && token.errors) - token.errors.push(this); - else - throw this; - } - inspect() { - return 'SyntaxError: ' + this.message; - } -} -exports.TokenError = TokenError; -//# sourceMappingURL=TokenError.js.map - -/***/ }), - -/***/ 1425: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var Parser_1 = __webpack_require__(489); -Object.defineProperty(exports, "Parser", ({ enumerable: true, get: function () { return Parser_1.Parser; } })); -var TokenError_1 = __webpack_require__(4217); -Object.defineProperty(exports, "TokenError", ({ enumerable: true, get: function () { return TokenError_1.TokenError; } })); -exports.Grammars = __webpack_require__(9652); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 118: -/***/ ((module) => { - -"use strict"; - - -/** - * @typedef {{ [key: string]: any }} Extensions - * @typedef {Error} Err - * @property {string} message - */ - -/** - * - * @param {Error} obj - * @param {Extensions} props - * @returns {Error & Extensions} - */ -function assign(obj, props) { - for (const key in props) { - Object.defineProperty(obj, key, { - value: props[key], - enumerable: true, - configurable: true, - }); - } - - return obj; -} - -/** - * - * @param {any} err - An Error - * @param {string|Extensions} code - A string code or props to set on the error - * @param {Extensions} [props] - Props to set on the error - * @returns {Error & Extensions} - */ -function createError(err, code, props) { - if (!err || typeof err === 'string') { - throw new TypeError('Please pass an Error to err-code'); - } - - if (!props) { - props = {}; - } - - if (typeof code === 'object') { - props = code; - code = ''; - } - - if (code) { - props.code = code; - } - - try { - return assign(err, props); - } catch (_) { - props.message = err.message; - props.stack = err.stack; - - const ErrClass = function () {}; - - ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); - - // @ts-ignore - const output = assign(new ErrClass(), props); - - return output; - } -} - -module.exports = createError; - - -/***/ }), - -/***/ 5341: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "BaseContract": () => (/* reexport */ lib_esm/* BaseContract */.VZ), - "BigNumber": () => (/* reexport */ bignumber/* BigNumber */.O$), - "Contract": () => (/* reexport */ lib_esm/* Contract */.CH), - "ContractFactory": () => (/* reexport */ lib_esm/* ContractFactory */.lV), - "FixedNumber": () => (/* reexport */ FixedNumber), - "Signer": () => (/* reexport */ abstract_signer_lib_esm/* Signer */.E), - "VoidSigner": () => (/* reexport */ abstract_signer_lib_esm/* VoidSigner */.b), - "Wallet": () => (/* reexport */ Wallet), - "Wordlist": () => (/* reexport */ Wordlist), - "constants": () => (/* reexport */ constants_lib_esm_namespaceObject), - "errors": () => (/* reexport */ logger_lib_esm/* ErrorCode */.jK), - "ethers": () => (/* reexport */ ethers_namespaceObject), - "getDefaultProvider": () => (/* reexport */ getDefaultProvider), - "logger": () => (/* reexport */ ethers_logger), - "providers": () => (/* reexport */ providers_lib_esm_namespaceObject), - "utils": () => (/* reexport */ lib_esm_utils_namespaceObject), - "version": () => (/* reexport */ ethers_lib_esm_version_version), - "wordlists": () => (/* reexport */ wordlists) -}); - -// NAMESPACE OBJECT: ../node_modules/@ethersproject/constants/lib.esm/index.js -var constants_lib_esm_namespaceObject = {}; -__webpack_require__.r(constants_lib_esm_namespaceObject); -__webpack_require__.d(constants_lib_esm_namespaceObject, { - "AddressZero": () => (addresses/* AddressZero */.d), - "EtherSymbol": () => (EtherSymbol), - "HashZero": () => (hashes/* HashZero */.R), - "MaxInt256": () => (bignumbers/* MaxInt256 */.PS), - "MaxUint256": () => (bignumbers/* MaxUint256 */.Bz), - "MinInt256": () => (bignumbers/* MinInt256 */.$B), - "NegativeOne": () => (bignumbers/* NegativeOne */.tL), - "One": () => (bignumbers/* One */.fh), - "Two": () => (bignumbers/* Two */.Py), - "WeiPerEther": () => (bignumbers/* WeiPerEther */.Ce), - "Zero": () => (bignumbers/* Zero */._Y) -}); - -// NAMESPACE OBJECT: ../node_modules/@ethersproject/providers/lib.esm/index.js -var providers_lib_esm_namespaceObject = {}; -__webpack_require__.r(providers_lib_esm_namespaceObject); -__webpack_require__.d(providers_lib_esm_namespaceObject, { - "AlchemyProvider": () => (AlchemyProvider), - "AlchemyWebSocketProvider": () => (AlchemyWebSocketProvider), - "BaseProvider": () => (base_provider/* BaseProvider */.Zk), - "CloudflareProvider": () => (CloudflareProvider), - "EtherscanProvider": () => (EtherscanProvider), - "FallbackProvider": () => (FallbackProvider), - "Formatter": () => (formatter/* Formatter */.Mb), - "InfuraProvider": () => (InfuraProvider), - "InfuraWebSocketProvider": () => (InfuraWebSocketProvider), - "IpcProvider": () => (IpcProvider), - "JsonRpcBatchProvider": () => (JsonRpcBatchProvider), - "JsonRpcProvider": () => (json_rpc_provider/* JsonRpcProvider */.r), - "JsonRpcSigner": () => (json_rpc_provider/* JsonRpcSigner */.C), - "NodesmithProvider": () => (NodesmithProvider), - "PocketProvider": () => (PocketProvider), - "Provider": () => (abstract_provider_lib_esm/* Provider */.zt), - "Resolver": () => (base_provider/* Resolver */.H2), - "StaticJsonRpcProvider": () => (StaticJsonRpcProvider), - "UrlJsonRpcProvider": () => (UrlJsonRpcProvider), - "Web3Provider": () => (web3_provider/* Web3Provider */.Q), - "WebSocketProvider": () => (WebSocketProvider), - "getDefaultProvider": () => (getDefaultProvider), - "getNetwork": () => (networks_lib_esm/* getNetwork */.H), - "isCommunityResourcable": () => (formatter/* isCommunityResourcable */.Ed), - "isCommunityResource": () => (formatter/* isCommunityResource */.Gp), - "showThrottleMessage": () => (formatter/* showThrottleMessage */.vh) -}); - -// NAMESPACE OBJECT: ../node_modules/@ethersproject/base64/lib.esm/index.js -var base64_lib_esm_namespaceObject = {}; -__webpack_require__.r(base64_lib_esm_namespaceObject); -__webpack_require__.d(base64_lib_esm_namespaceObject, { - "decode": () => (base64/* decode */.J), - "encode": () => (base64/* encode */.c) -}); - -// NAMESPACE OBJECT: ../node_modules/ethers/lib.esm/utils.js -var lib_esm_utils_namespaceObject = {}; -__webpack_require__.r(lib_esm_utils_namespaceObject); -__webpack_require__.d(lib_esm_utils_namespaceObject, { - "AbiCoder": () => (abi_coder/* AbiCoder */.R), - "ConstructorFragment": () => (fragments/* ConstructorFragment */.Xg), - "ErrorFragment": () => (fragments/* ErrorFragment */.IC), - "EventFragment": () => (fragments/* EventFragment */.QV), - "FormatTypes": () => (fragments/* FormatTypes */.pc), - "Fragment": () => (fragments/* Fragment */.HY), - "FunctionFragment": () => (fragments/* FunctionFragment */.YW), - "HDNode": () => (HDNode), - "Indexed": () => (lib_esm_interface/* Indexed */.Hk), - "Interface": () => (lib_esm_interface/* Interface */.vU), - "LogDescription": () => (lib_esm_interface/* LogDescription */.CC), - "Logger": () => (logger_lib_esm/* Logger */.Yd), - "ParamType": () => (fragments/* ParamType */._R), - "RLP": () => (rlp_lib_esm), - "SigningKey": () => (signing_key_lib_esm/* SigningKey */.Et), - "SupportedAlgorithm": () => (types/* SupportedAlgorithm */.p), - "TransactionDescription": () => (lib_esm_interface/* TransactionDescription */.vk), - "TransactionTypes": () => (transactions_lib_esm/* TransactionTypes */.em), - "UnicodeNormalizationForm": () => (utf8/* UnicodeNormalizationForm */.Uj), - "Utf8ErrorFuncs": () => (utf8/* Utf8ErrorFuncs */.te), - "Utf8ErrorReason": () => (utf8/* Utf8ErrorReason */.Uw), - "_TypedDataEncoder": () => (typed_data/* TypedDataEncoder */.E), - "_fetchData": () => (web_lib_esm/* _fetchData */.MY), - "_toEscapedUtf8String": () => (utf8/* _toEscapedUtf8String */.U$), - "accessListify": () => (transactions_lib_esm/* accessListify */.z7), - "arrayify": () => (bytes_lib_esm/* arrayify */.lE), - "base58": () => (basex_lib_esm/* Base58 */.eU), - "base64": () => (base64_lib_esm_namespaceObject), - "checkProperties": () => (properties_lib_esm/* checkProperties */.uj), - "checkResultErrors": () => (abstract_coder/* checkResultErrors */.BR), - "commify": () => (commify), - "computeAddress": () => (transactions_lib_esm/* computeAddress */.db), - "computeHmac": () => (sha2/* computeHmac */.Gy), - "computePublicKey": () => (signing_key_lib_esm/* computePublicKey */.VW), - "concat": () => (bytes_lib_esm/* concat */.zo), - "deepCopy": () => (properties_lib_esm/* deepCopy */.p$), - "defaultAbiCoder": () => (abi_coder/* defaultAbiCoder */.$), - "defaultPath": () => (defaultPath), - "defineReadOnly": () => (properties_lib_esm/* defineReadOnly */.zG), - "entropyToMnemonic": () => (entropyToMnemonic), - "fetchJson": () => (web_lib_esm/* fetchJson */.rd), - "formatBytes32String": () => (formatBytes32String), - "formatEther": () => (formatEther), - "formatUnits": () => (formatUnits), - "getAccountPath": () => (getAccountPath), - "getAddress": () => (address_lib_esm/* getAddress */.Kn), - "getContractAddress": () => (address_lib_esm/* getContractAddress */.CR), - "getCreate2Address": () => (address_lib_esm/* getCreate2Address */.hB), - "getIcapAddress": () => (address_lib_esm/* getIcapAddress */.vU), - "getJsonWalletAddress": () => (getJsonWalletAddress), - "getStatic": () => (properties_lib_esm/* getStatic */.tu), - "hashMessage": () => (hashMessage), - "hexConcat": () => (bytes_lib_esm/* hexConcat */.xs), - "hexDataLength": () => (bytes_lib_esm/* hexDataLength */.E1), - "hexDataSlice": () => (bytes_lib_esm/* hexDataSlice */.p3), - "hexStripZeros": () => (bytes_lib_esm/* hexStripZeros */.Ou), - "hexValue": () => (bytes_lib_esm/* hexValue */.$P), - "hexZeroPad": () => (bytes_lib_esm/* hexZeroPad */.$m), - "hexlify": () => (bytes_lib_esm/* hexlify */.Dv), - "id": () => (id.id), - "isAddress": () => (address_lib_esm/* isAddress */.UJ), - "isBytes": () => (bytes_lib_esm/* isBytes */._t), - "isBytesLike": () => (bytes_lib_esm/* isBytesLike */.Zq), - "isHexString": () => (bytes_lib_esm/* isHexString */.A7), - "isValidMnemonic": () => (isValidMnemonic), - "isValidName": () => (namehash/* isValidName */.r), - "joinSignature": () => (bytes_lib_esm/* joinSignature */.gV), - "keccak256": () => (keccak256_lib_esm/* keccak256 */.w), - "mnemonicToEntropy": () => (mnemonicToEntropy), - "mnemonicToSeed": () => (mnemonicToSeed), - "namehash": () => (namehash/* namehash */.V), - "nameprep": () => (idna/* nameprep */.Ll), - "parseBytes32String": () => (parseBytes32String), - "parseEther": () => (parseEther), - "parseTransaction": () => (transactions_lib_esm/* parse */.Qc), - "parseUnits": () => (parseUnits), - "poll": () => (web_lib_esm/* poll */.$l), - "randomBytes": () => (randomBytes), - "recoverAddress": () => (transactions_lib_esm/* recoverAddress */.RJ), - "recoverPublicKey": () => (signing_key_lib_esm/* recoverPublicKey */.LO), - "resolveProperties": () => (properties_lib_esm/* resolveProperties */.mE), - "ripemd160": () => (sha2/* ripemd160 */.bP), - "serializeTransaction": () => (transactions_lib_esm/* serialize */.qC), - "sha256": () => (sha2/* sha256 */.JQ), - "sha512": () => (sha2/* sha512 */.o), - "shallowCopy": () => (properties_lib_esm/* shallowCopy */.DC), - "shuffled": () => (shuffled), - "solidityKeccak256": () => (keccak256), - "solidityPack": () => (pack), - "soliditySha256": () => (sha256), - "splitSignature": () => (bytes_lib_esm/* splitSignature */.N), - "stripZeros": () => (bytes_lib_esm/* stripZeros */.G1), - "toUtf8Bytes": () => (utf8/* toUtf8Bytes */.Y0), - "toUtf8CodePoints": () => (utf8/* toUtf8CodePoints */.XL), - "toUtf8String": () => (utf8/* toUtf8String */.ZN), - "verifyMessage": () => (verifyMessage), - "verifyTypedData": () => (verifyTypedData), - "zeroPad": () => (bytes_lib_esm/* zeroPad */.Bu) -}); - -// NAMESPACE OBJECT: ../node_modules/ethers/lib.esm/ethers.js -var ethers_namespaceObject = {}; -__webpack_require__.r(ethers_namespaceObject); -__webpack_require__.d(ethers_namespaceObject, { - "BaseContract": () => (lib_esm/* BaseContract */.VZ), - "BigNumber": () => (bignumber/* BigNumber */.O$), - "Contract": () => (lib_esm/* Contract */.CH), - "ContractFactory": () => (lib_esm/* ContractFactory */.lV), - "FixedNumber": () => (FixedNumber), - "Signer": () => (abstract_signer_lib_esm/* Signer */.E), - "VoidSigner": () => (abstract_signer_lib_esm/* VoidSigner */.b), - "Wallet": () => (Wallet), - "Wordlist": () => (Wordlist), - "constants": () => (constants_lib_esm_namespaceObject), - "errors": () => (logger_lib_esm/* ErrorCode */.jK), - "getDefaultProvider": () => (getDefaultProvider), - "logger": () => (ethers_logger), - "providers": () => (providers_lib_esm_namespaceObject), - "utils": () => (lib_esm_utils_namespaceObject), - "version": () => (ethers_lib_esm_version_version), - "wordlists": () => (wordlists) -}); - -// EXTERNAL MODULE: ../node_modules/@ethersproject/contracts/lib.esm/index.js + 1 modules -var lib_esm = __webpack_require__(3726); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js -var bignumber = __webpack_require__(3922); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bytes/lib.esm/index.js + 1 modules -var bytes_lib_esm = __webpack_require__(3756); -// EXTERNAL MODULE: ../node_modules/@ethersproject/logger/lib.esm/index.js + 1 modules -var logger_lib_esm = __webpack_require__(1424); -// EXTERNAL MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/_version.js -var _version = __webpack_require__(9251); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/bignumber/lib.esm/fixednumber.js - - - - -const logger = new logger_lib_esm/* Logger */.Yd(_version/* version */.i); - -const _constructorGuard = {}; -const Zero = bignumber/* BigNumber.from */.O$.from(0); -const NegativeOne = bignumber/* BigNumber.from */.O$.from(-1); -function throwFault(message, fault, operation, value) { - const params = { fault: fault, operation: operation }; - if (value !== undefined) { - params.value = value; - } - return logger.throwError(message, logger_lib_esm/* Logger.errors.NUMERIC_FAULT */.Yd.errors.NUMERIC_FAULT, params); -} -// Constant to pull zeros from for multipliers -let zeros = "0"; -while (zeros.length < 256) { - zeros += zeros; -} -// Returns a string "1" followed by decimal "0"s -function getMultiplier(decimals) { - if (typeof (decimals) !== "number") { - try { - decimals = bignumber/* BigNumber.from */.O$.from(decimals).toNumber(); - } - catch (e) { } - } - if (typeof (decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) { - return ("1" + zeros.substring(0, decimals)); - } - return logger.throwArgumentError("invalid decimal size", "decimals", decimals); -} -function formatFixed(value, decimals) { - if (decimals == null) { - decimals = 0; - } - const multiplier = getMultiplier(decimals); - // Make sure wei is a big number (convert as necessary) - value = bignumber/* BigNumber.from */.O$.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; - } - // Strip training 0 - 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.throwArgumentError("invalid decimal value", "value", value); - } - // Is it negative? - const negative = (value.substring(0, 1) === "-"); - if (negative) { - value = value.substring(1); - } - if (value === ".") { - logger.throwArgumentError("missing value", "value", value); - } - // Split it into a whole and fractional part - const comps = value.split("."); - if (comps.length > 2) { - logger.throwArgumentError("too many decimal points", "value", value); - } - let whole = comps[0], fraction = comps[1]; - if (!whole) { - whole = "0"; - } - if (!fraction) { - fraction = "0"; - } - // Trim trailing zeros - while (fraction[fraction.length - 1] === "0") { - fraction = fraction.substring(0, fraction.length - 1); - } - // Check the fraction doesn't exceed our decimals size - if (fraction.length > multiplier.length - 1) { - throwFault("fractional component exceeds decimals", "underflow", "parseFixed"); - } - // If decimals is 0, we have an empty string for fraction - if (fraction === "") { - fraction = "0"; - } - // Fully pad the string with zeros to get to wei - while (fraction.length < multiplier.length - 1) { - fraction += "0"; - } - const wholeValue = bignumber/* BigNumber.from */.O$.from(whole); - const fractionValue = bignumber/* BigNumber.from */.O$.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) { - logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.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") { - // defaults... - } - else if (value === "ufixed") { - signed = false; - } - else { - const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - if (!match) { - logger.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.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.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); - } - if (decimals > 80) { - logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); - } - return new FixedFormat(_constructorGuard, signed, width, decimals); - } -} -class FixedNumber { - constructor(constructorGuard, hex, value, format) { - logger.checkNew(new.target, FixedNumber); - if (constructorGuard !== _constructorGuard) { - logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.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.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; - } - // @TODO: Support other rounding algorithms - round(decimals) { - if (decimals == null) { - decimals = 0; - } - // If we are already in range, we're done - const comps = this.toString().split("."); - if (comps.length === 1) { - comps.push("0"); - } - if (decimals < 0 || decimals > 80 || (decimals % 1)) { - logger.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.throwArgumentError("invalid byte width", "width", width); - } - const hex = bignumber/* BigNumber.from */.O$.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString(); - return (0,bytes_lib_esm/* hexZeroPad */.$m)(hex, width / 8); - } - toUnsafeFloat() { return parseFloat(this.toString()); } - toFormat(format) { - return FixedNumber.fromString(this._value, format); - } - static fromValue(value, decimals, format) { - // If decimals looks more like a format, and there is no format, shift the parameters - if (format == null && decimals != null && !(0,bignumber/* isBigNumberish */.Zm)(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("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 = (0,bytes_lib_esm/* hexZeroPad */.$m)(hex, fixedFormat.width / 8); - } - const decimal = formatFixed(numeric, fixedFormat.decimals); - return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat); - } - static fromBytes(value, format) { - if (format == null) { - format = "fixed"; - } - const fixedFormat = FixedFormat.from(format); - if ((0,bytes_lib_esm/* arrayify */.lE)(value).length > fixedFormat.width / 8) { - throw new Error("overflow"); - } - let numeric = bignumber/* BigNumber.from */.O$.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, hex, decimal, fixedFormat); - } - static from(value, format) { - if (typeof (value) === "string") { - return FixedNumber.fromString(value, format); - } - if ((0,bytes_lib_esm/* isBytes */._t)(value)) { - return FixedNumber.fromBytes(value, format); - } - try { - return FixedNumber.fromValue(value, 0, format); - } - catch (error) { - // Allow NUMERIC_FAULT to bubble up - if (error.code !== logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT) { - throw error; - } - } - return logger.throwArgumentError("invalid FixedNumber value", "value", value); - } - static isFixedNumber(value) { - return !!(value && value._isFixedNumber); - } -} -const ONE = FixedNumber.from(1); -const BUMP = FixedNumber.from("0.5"); -//# sourceMappingURL=fixednumber.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/abstract-signer/lib.esm/index.js + 1 modules -var abstract_signer_lib_esm = __webpack_require__(4502); -// EXTERNAL MODULE: ../node_modules/@ethersproject/address/lib.esm/index.js + 1 modules -var address_lib_esm = __webpack_require__(9808); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abstract-provider/lib.esm/index.js + 1 modules -var abstract_provider_lib_esm = __webpack_require__(2639); -// EXTERNAL MODULE: ../node_modules/@ethersproject/keccak256/lib.esm/index.js -var keccak256_lib_esm = __webpack_require__(2677); -// EXTERNAL MODULE: ../node_modules/@ethersproject/strings/lib.esm/utf8.js + 1 modules -var utf8 = __webpack_require__(5804); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/hash/lib.esm/message.js - - - -const messagePrefix = "\x19Ethereum Signed Message:\n"; -function hashMessage(message) { - if (typeof (message) === "string") { - message = (0,utf8/* toUtf8Bytes */.Y0)(message); - } - return (0,keccak256_lib_esm/* keccak256 */.w)((0,bytes_lib_esm/* concat */.zo)([ - (0,utf8/* toUtf8Bytes */.Y0)(messagePrefix), - (0,utf8/* toUtf8Bytes */.Y0)(String(message.length)), - message - ])); -} -//# sourceMappingURL=message.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/hash/lib.esm/typed-data.js -var typed_data = __webpack_require__(506); -// EXTERNAL MODULE: ../node_modules/@ethersproject/basex/lib.esm/index.js -var basex_lib_esm = __webpack_require__(3581); -// EXTERNAL MODULE: ../node_modules/@ethersproject/sha2/lib.esm/sha2.js + 1 modules -var sha2 = __webpack_require__(9088); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/pbkdf2/lib.esm/pbkdf2.js - - - -function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) { - password = (0,bytes_lib_esm/* arrayify */.lE)(password); - salt = (0,bytes_lib_esm/* arrayify */.lE)(salt); - let hLen; - let l = 1; - const DK = new Uint8Array(keylen); - const block1 = new Uint8Array(salt.length + 4); - block1.set(salt); - //salt.copy(block1, 0, 0, salt.length) - let r; - let T; - for (let i = 1; i <= l; i++) { - //block1.writeUInt32BE(i, salt.length) - block1[salt.length] = (i >> 24) & 0xff; - block1[salt.length + 1] = (i >> 16) & 0xff; - block1[salt.length + 2] = (i >> 8) & 0xff; - block1[salt.length + 3] = i & 0xff; - //let U = createHmac(password).update(block1).digest(); - let U = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* computeHmac */.Gy)(hashAlgorithm, password, block1)); - if (!hLen) { - hLen = U.length; - T = new Uint8Array(hLen); - l = Math.ceil(keylen / hLen); - r = keylen - (l - 1) * hLen; - } - //U.copy(T, 0, 0, hLen) - T.set(U); - for (let j = 1; j < iterations; j++) { - //U = createHmac(password).update(U).digest(); - U = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* computeHmac */.Gy)(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); - //T.copy(DK, destPos, 0, len) - DK.set((0,bytes_lib_esm/* arrayify */.lE)(T).slice(0, len), destPos); - } - return (0,bytes_lib_esm/* hexlify */.Dv)(DK); -} -//# sourceMappingURL=pbkdf2.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/properties/lib.esm/index.js + 1 modules -var properties_lib_esm = __webpack_require__(300); -// EXTERNAL MODULE: ../node_modules/@ethersproject/signing-key/lib.esm/index.js + 2 modules -var signing_key_lib_esm = __webpack_require__(9947); -// EXTERNAL MODULE: ../node_modules/@ethersproject/sha2/lib.esm/types.js -var types = __webpack_require__(7082); -// EXTERNAL MODULE: ../node_modules/@ethersproject/transactions/lib.esm/index.js + 1 modules -var transactions_lib_esm = __webpack_require__(9165); -// EXTERNAL MODULE: ../node_modules/@ethersproject/hash/lib.esm/id.js -var id = __webpack_require__(14); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wordlists/lib.esm/_version.js -const version = "wordlists/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wordlists/lib.esm/wordlist.js - -// This gets overridden by rollup -const exportWordlist = false; - - - - -const wordlist_logger = new logger_lib_esm/* Logger */.Yd(version); -class Wordlist { - constructor(locale) { - wordlist_logger.checkAbstract(new.target, Wordlist); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "locale", locale); - } - // Subclasses may override this - split(mnemonic) { - return mnemonic.toLowerCase().split(/ +/g); - } - // Subclasses may override this - join(words) { - return words.join(" "); - } - static check(wordlist) { - const words = []; - for (let i = 0; i < 2048; i++) { - const word = wordlist.getWord(i); - /* istanbul ignore if */ - if (i !== wordlist.getWordIndex(word)) { - return "0x"; - } - words.push(word); - } - return (0,id.id)(words.join("\n") + "\n"); - } - static register(lang, name) { - if (!name) { - name = lang.locale; - } - /* istanbul ignore if */ - if (exportWordlist) { - try { - const anyGlobal = window; - if (anyGlobal._ethers && anyGlobal._ethers.wordlists) { - if (!anyGlobal._ethers.wordlists[name]) { - (0,properties_lib_esm/* defineReadOnly */.zG)(anyGlobal._ethers.wordlists, name, lang); - } - } - } - catch (error) { } - } - } -} -//# sourceMappingURL=wordlist.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wordlists/lib.esm/lang-en.js - - -const words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo"; -let wordlist = null; -function loadWords(lang) { - if (wordlist != null) { - return; - } - wordlist = words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" "); - // Verify the computed list matches the official list - /* istanbul ignore if */ - 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); - -//# sourceMappingURL=lang-en.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wordlists/lib.esm/wordlists.js - - -const wordlists = { - en: langEn -}; -//# sourceMappingURL=wordlists.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/hdnode/lib.esm/_version.js -const _version_version = "hdnode/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/hdnode/lib.esm/index.js - - - - - - - - - - - - - -const lib_esm_logger = new logger_lib_esm/* Logger */.Yd(_version_version); -const N = bignumber/* BigNumber.from */.O$.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -// "Bitcoin seed" -const MasterSecret = (0,utf8/* toUtf8Bytes */.Y0)("Bitcoin seed"); -const HardenedBit = 0x80000000; -// Returns a byte with the MSB bits set -function getUpperMask(bits) { - return ((1 << bits) - 1) << (8 - bits); -} -// Returns a byte with the LSB bits set -function getLowerMask(bits) { - return (1 << bits) - 1; -} -function bytes32(value) { - return (0,bytes_lib_esm/* hexZeroPad */.$m)((0,bytes_lib_esm/* hexlify */.Dv)(value), 32); -} -function base58check(data) { - return basex_lib_esm/* Base58.encode */.eU.encode((0,bytes_lib_esm/* concat */.zo)([data, (0,bytes_lib_esm/* hexDataSlice */.p3)((0,sha2/* sha256 */.JQ)((0,sha2/* sha256 */.JQ)(data)), 0, 4)])); -} -function getWordlist(wordlist) { - if (wordlist == null) { - return wordlists.en; - } - if (typeof (wordlist) === "string") { - const words = wordlists[wordlist]; - if (words == null) { - lib_esm_logger.throwArgumentError("unknown locale", "wordlist", wordlist); - } - return words; - } - return wordlist; -} -const lib_esm_constructorGuard = {}; -const defaultPath = "m/44'/60'/0'/0/0"; -; -class HDNode { - /** - * This constructor should not be called directly. - * - * Please use: - * - fromMnemonic - * - fromSeed - */ - constructor(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath) { - lib_esm_logger.checkNew(new.target, HDNode); - /* istanbul ignore if */ - if (constructorGuard !== lib_esm_constructorGuard) { - throw new Error("HDNode constructor cannot be called directly"); - } - if (privateKey) { - const signingKey = new signing_key_lib_esm/* SigningKey */.Et(privateKey); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "privateKey", signingKey.privateKey); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "publicKey", signingKey.compressedPublicKey); - } - else { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "privateKey", null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "publicKey", (0,bytes_lib_esm/* hexlify */.Dv)(publicKey)); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "parentFingerprint", parentFingerprint); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "fingerprint", (0,bytes_lib_esm/* hexDataSlice */.p3)((0,sha2/* ripemd160 */.bP)((0,sha2/* sha256 */.JQ)(this.publicKey)), 0, 4)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", (0,transactions_lib_esm/* computeAddress */.db)(this.publicKey)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "chainCode", chainCode); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "index", index); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "depth", depth); - if (mnemonicOrPath == null) { - // From a source that does not preserve the path (e.g. extended keys) - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "mnemonic", null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "path", null); - } - else if (typeof (mnemonicOrPath) === "string") { - // From a source that does not preserve the mnemonic (e.g. neutered) - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "mnemonic", null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "path", mnemonicOrPath); - } - else { - // From a fully qualified source - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "mnemonic", mnemonicOrPath); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "path", mnemonicOrPath.path); - } - } - get extendedKey() { - // We only support the mainnet values for now, but if anyone needs - // testnet values, let me know. I believe current sentiment is that - // we should always use mainnet, and use BIP-44 to derive the network - // - Mainnet: public=0x0488B21E, private=0x0488ADE4 - // - Testnet: public=0x043587CF, private=0x04358394 - if (this.depth >= 256) { - throw new Error("Depth too large!"); - } - return base58check((0,bytes_lib_esm/* concat */.zo)([ - ((this.privateKey != null) ? "0x0488ADE4" : "0x0488B21E"), - (0,bytes_lib_esm/* hexlify */.Dv)(this.depth), - this.parentFingerprint, - (0,bytes_lib_esm/* hexZeroPad */.$m)((0,bytes_lib_esm/* hexlify */.Dv)(this.index), 4), - this.chainCode, - ((this.privateKey != null) ? (0,bytes_lib_esm/* concat */.zo)(["0x00", this.privateKey]) : this.publicKey), - ])); - } - neuter() { - return new HDNode(lib_esm_constructorGuard, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path); - } - _derive(index) { - if (index > 0xffffffff) { - throw new Error("invalid index - " + String(index)); - } - // Base path - let path = this.path; - if (path) { - path += "/" + (index & ~HardenedBit); - } - const data = new Uint8Array(37); - if (index & HardenedBit) { - if (!this.privateKey) { - throw new Error("cannot derive child of neutered node"); - } - // Data = 0x00 || ser_256(k_par) - data.set((0,bytes_lib_esm/* arrayify */.lE)(this.privateKey), 1); - // Hardened path - if (path) { - path += "'"; - } - } - else { - // Data = ser_p(point(k_par)) - data.set((0,bytes_lib_esm/* arrayify */.lE)(this.publicKey)); - } - // Data += ser_32(i) - for (let i = 24; i >= 0; i -= 8) { - data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); - } - const I = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* computeHmac */.Gy)(types/* SupportedAlgorithm.sha512 */.p.sha512, this.chainCode, data)); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // The private key - let ki = null; - // The public key - let Ki = null; - if (this.privateKey) { - ki = bytes32(bignumber/* BigNumber.from */.O$.from(IL).add(this.privateKey).mod(N)); - } - else { - const ek = new signing_key_lib_esm/* SigningKey */.Et((0,bytes_lib_esm/* hexlify */.Dv)(IL)); - Ki = ek._addPoint(this.publicKey); - } - let mnemonicOrPath = path; - const srcMnemonic = this.mnemonic; - if (srcMnemonic) { - mnemonicOrPath = Object.freeze({ - phrase: srcMnemonic.phrase, - path: path, - locale: (srcMnemonic.locale || "en") - }); - } - return new HDNode(lib_esm_constructorGuard, 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 >= HardenedBit) { - throw new Error("invalid path index - " + component); - } - result = result._derive(HardenedBit + index); - } - else if (component.match(/^[0-9]+$/)) { - const index = parseInt(component); - if (index >= HardenedBit) { - throw new Error("invalid path index - " + component); - } - result = result._derive(index); - } - else { - throw new Error("invalid path component - " + component); - } - } - return result; - } - static _fromSeed(seed, mnemonic) { - const seedArray = (0,bytes_lib_esm/* arrayify */.lE)(seed); - if (seedArray.length < 16 || seedArray.length > 64) { - throw new Error("invalid seed"); - } - const I = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* computeHmac */.Gy)(types/* SupportedAlgorithm.sha512 */.p.sha512, MasterSecret, seedArray)); - return new HDNode(lib_esm_constructorGuard, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic); - } - static fromMnemonic(mnemonic, password, wordlist) { - // If a locale name was passed in, find the associated wordlist - wordlist = getWordlist(wordlist); - // Normalize the case and spacing in the mnemonic (throws if the mnemonic is invalid) - mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist); - return HDNode._fromSeed(mnemonicToSeed(mnemonic, password), { - phrase: mnemonic, - path: "m", - locale: wordlist.locale - }); - } - static fromSeed(seed) { - return HDNode._fromSeed(seed, null); - } - static fromExtendedKey(extendedKey) { - const bytes = basex_lib_esm/* Base58.decode */.eU.decode(extendedKey); - if (bytes.length !== 82 || base58check(bytes.slice(0, 78)) !== extendedKey) { - lib_esm_logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); - } - const depth = bytes[4]; - const parentFingerprint = (0,bytes_lib_esm/* hexlify */.Dv)(bytes.slice(5, 9)); - const index = parseInt((0,bytes_lib_esm/* hexlify */.Dv)(bytes.slice(9, 13)).substring(2), 16); - const chainCode = (0,bytes_lib_esm/* hexlify */.Dv)(bytes.slice(13, 45)); - const key = bytes.slice(45, 78); - switch ((0,bytes_lib_esm/* hexlify */.Dv)(bytes.slice(0, 4))) { - // Public Key - case "0x0488b21e": - case "0x043587cf": - return new HDNode(lib_esm_constructorGuard, null, (0,bytes_lib_esm/* hexlify */.Dv)(key), parentFingerprint, chainCode, index, depth, null); - // Private Key - case "0x0488ade4": - case "0x04358394 ": - if (key[0] !== 0) { - break; - } - return new HDNode(lib_esm_constructorGuard, (0,bytes_lib_esm/* hexlify */.Dv)(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null); - } - return lib_esm_logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); - } -} -function mnemonicToSeed(mnemonic, password) { - if (!password) { - password = ""; - } - const salt = (0,utf8/* toUtf8Bytes */.Y0)("mnemonic" + password, utf8/* UnicodeNormalizationForm.NFKD */.Uj.NFKD); - return pbkdf2((0,utf8/* toUtf8Bytes */.Y0)(mnemonic, utf8/* UnicodeNormalizationForm.NFKD */.Uj.NFKD), salt, 2048, 64, "sha512"); -} -function mnemonicToEntropy(mnemonic, wordlist) { - wordlist = getWordlist(wordlist); - lib_esm_logger.checkNormalize(); - const words = wordlist.split(mnemonic); - if ((words.length % 3) !== 0) { - throw new Error("invalid mnemonic"); - } - const entropy = (0,bytes_lib_esm/* arrayify */.lE)(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 = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* sha256 */.JQ)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; - if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { - throw new Error("invalid checksum"); - } - return (0,bytes_lib_esm/* hexlify */.Dv)(entropy.slice(0, entropyBits / 8)); -} -function entropyToMnemonic(entropy, wordlist) { - wordlist = getWordlist(wordlist); - entropy = (0,bytes_lib_esm/* arrayify */.lE)(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++) { - // Consume the whole byte (with still more to go) - if (remainingBits > 8) { - indices[indices.length - 1] <<= 8; - indices[indices.length - 1] |= entropy[i]; - remainingBits -= 8; - // This byte will complete an 11-bit index - } - else { - indices[indices.length - 1] <<= remainingBits; - indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); - // Start the next word - indices.push(entropy[i] & getLowerMask(8 - remainingBits)); - remainingBits += 3; - } - } - // Compute the checksum bits - const checksumBits = entropy.length / 4; - const checksum = (0,bytes_lib_esm/* arrayify */.lE)((0,sha2/* sha256 */.JQ)(entropy))[0] & getUpperMask(checksumBits); - // Shift the checksum into the word indices - indices[indices.length - 1] <<= checksumBits; - indices[indices.length - 1] |= (checksum >> (8 - checksumBits)); - return wordlist.join(indices.map((index) => wordlist.getWord(index))); -} -function isValidMnemonic(mnemonic, wordlist) { - try { - mnemonicToEntropy(mnemonic, wordlist); - return true; - } - catch (error) { } - return false; -} -function getAccountPath(index) { - if (typeof (index) !== "number" || index < 0 || index >= HardenedBit || index % 1) { - lib_esm_logger.throwArgumentError("invalid account index", "index", index); - } - return `m/44'/60'/${index}'/0/0`; -} -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/random/lib.esm/_version.js -const lib_esm_version_version = "random/5.5.1"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/random/lib.esm/random.js - - - - -const random_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version_version); -// Debugging line for testing browser lib in node -//const window = { crypto: { getRandomValues: () => { } } }; -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis -function getGlobal() { - if (typeof self !== 'undefined') { - return self; - } - if (typeof window !== 'undefined') { - return window; - } - if (typeof __webpack_require__.g !== 'undefined') { - return __webpack_require__.g; - } - throw new Error('unable to locate global object'); -} -; -const anyGlobal = getGlobal(); -let random_crypto = anyGlobal.crypto || anyGlobal.msCrypto; -if (!random_crypto || !random_crypto.getRandomValues) { - random_logger.warn("WARNING: Missing strong random number source"); - random_crypto = { - getRandomValues: function (buffer) { - return random_logger.throwError("no secure random source avaialble", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "crypto.getRandomValues" - }); - } - }; -} -function randomBytes(length) { - if (length <= 0 || length > 1024 || (length % 1) || length != length) { - random_logger.throwArgumentError("invalid length", "length", length); - } - const result = new Uint8Array(length); - random_crypto.getRandomValues(result); - return (0,bytes_lib_esm/* arrayify */.lE)(result); -} -; -//# sourceMappingURL=random.js.map -// EXTERNAL MODULE: ../node_modules/aes-js/index.js -var aes_js = __webpack_require__(6264); -var aes_js_default = /*#__PURE__*/__webpack_require__.n(aes_js); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/_version.js -const json_wallets_lib_esm_version_version = "json-wallets/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/utils.js - - - -function looseArrayify(hexString) { - if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') { - hexString = '0x' + hexString; - } - return (0,bytes_lib_esm/* arrayify */.lE)(hexString); -} -function zpad(value, length) { - value = String(value); - while (value.length < length) { - value = '0' + value; - } - return value; -} -function getPassword(password) { - if (typeof (password) === 'string') { - return (0,utf8/* toUtf8Bytes */.Y0)(password, utf8/* UnicodeNormalizationForm.NFKC */.Uj.NFKC); - } - return (0,bytes_lib_esm/* arrayify */.lE)(password); -} -function searchPath(object, path) { - let currentChild = object; - const comps = path.toLowerCase().split('/'); - for (let i = 0; i < comps.length; i++) { - // Search for a child object with a case-insensitive matching key - let matchingChild = null; - for (const key in currentChild) { - if (key.toLowerCase() === comps[i]) { - matchingChild = currentChild[key]; - break; - } - } - // Didn't find one. :'( - if (matchingChild === null) { - return null; - } - // Now check this child... - currentChild = matchingChild; - } - return currentChild; -} -// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4) -function uuidV4(randomBytes) { - const bytes = (0,bytes_lib_esm/* arrayify */.lE)(randomBytes); - // Section: 4.1.3: - // - time_hi_and_version[12:16] = 0b0100 - bytes[6] = (bytes[6] & 0x0f) | 0x40; - // Section 4.4 - // - clock_seq_hi_and_reserved[6] = 0b0 - // - clock_seq_hi_and_reserved[7] = 0b1 - bytes[8] = (bytes[8] & 0x3f) | 0x80; - const value = (0,bytes_lib_esm/* hexlify */.Dv)(bytes); - return [ - value.substring(2, 10), - value.substring(10, 14), - value.substring(14, 18), - value.substring(18, 22), - value.substring(22, 34), - ].join("-"); -} -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/crowdsale.js - - - - - - - - - - -const crowdsale_logger = new logger_lib_esm/* Logger */.Yd(json_wallets_lib_esm_version_version); - -class CrowdsaleAccount extends properties_lib_esm/* Description */.dk { - isCrowdsaleAccount(value) { - return !!(value && value._isCrowdsaleAccount); - } -} -// See: https://github.com/ethereum/pyethsaletool -function decrypt(json, password) { - const data = JSON.parse(json); - password = getPassword(password); - // Ethereum Address - const ethaddr = (0,address_lib_esm/* getAddress */.Kn)(searchPath(data, "ethaddr")); - // Encrypted Seed - const encseed = looseArrayify(searchPath(data, "encseed")); - if (!encseed || (encseed.length % 16) !== 0) { - crowdsale_logger.throwArgumentError("invalid encseed", "json", json); - } - const key = (0,bytes_lib_esm/* arrayify */.lE)(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16); - const iv = encseed.slice(0, 16); - const encryptedSeed = encseed.slice(16); - // Decrypt the seed - const aesCbc = new (aes_js_default()).ModeOfOperation.cbc(key, iv); - const seed = aes_js_default().padding.pkcs7.strip((0,bytes_lib_esm/* arrayify */.lE)(aesCbc.decrypt(encryptedSeed))); - // This wallet format is weird... Convert the binary encoded hex to a string. - let seedHex = ""; - for (let i = 0; i < seed.length; i++) { - seedHex += String.fromCharCode(seed[i]); - } - const seedHexBytes = (0,utf8/* toUtf8Bytes */.Y0)(seedHex); - const privateKey = (0,keccak256_lib_esm/* keccak256 */.w)(seedHexBytes); - return new CrowdsaleAccount({ - _isCrowdsaleAccount: true, - address: ethaddr, - privateKey: privateKey - }); -} -//# sourceMappingURL=crowdsale.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/inspect.js - - -function isCrowdsaleWallet(json) { - let data = null; - try { - data = JSON.parse(json); - } - catch (error) { - return false; - } - return (data.encseed && data.ethaddr); -} -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; - } - // @TODO: Put more checks to make sure it has kdf, iv and all that good stuff - return true; -} -//export function isJsonWallet(json: string): boolean { -// return (isSecretStorageWallet(json) || isCrowdsaleWallet(json)); -//} -function getJsonWalletAddress(json) { - if (isCrowdsaleWallet(json)) { - try { - return (0,address_lib_esm/* getAddress */.Kn)(JSON.parse(json).ethaddr); - } - catch (error) { - return null; - } - } - if (isKeystoreWallet(json)) { - try { - return (0,address_lib_esm/* getAddress */.Kn)(JSON.parse(json).address); - } - catch (error) { - return null; - } - } - return null; -} -//# sourceMappingURL=inspect.js.map -// EXTERNAL MODULE: ../node_modules/scrypt-js/scrypt.js -var scrypt = __webpack_require__(8186); -var scrypt_default = /*#__PURE__*/__webpack_require__.n(scrypt); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/keystore.js - -var __awaiter = (undefined && undefined.__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 keystore_logger = new logger_lib_esm/* Logger */.Yd(json_wallets_lib_esm_version_version); -// Exported Types -function hasMnemonic(value) { - return (value != null && value.mnemonic && value.mnemonic.phrase); -} -class KeystoreAccount extends properties_lib_esm/* Description */.dk { - isKeystoreAccount(value) { - return !!(value && value._isKeystoreAccount); - } -} -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 (aes_js_default()).Counter(iv); - const aesCtr = new (aes_js_default()).ModeOfOperation.ctr(key, counter); - return (0,bytes_lib_esm/* arrayify */.lE)(aesCtr.decrypt(ciphertext)); - } - return null; -} -function _getAccount(data, key) { - const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext")); - const computedMAC = (0,bytes_lib_esm/* hexlify */.Dv)((0,keccak256_lib_esm/* keccak256 */.w)((0,bytes_lib_esm/* concat */.zo)([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) { - keystore_logger.throwError("unsupported cipher", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "decrypt" - }); - } - const mnemonicKey = key.slice(32, 64); - const address = (0,transactions_lib_esm/* computeAddress */.db)(privateKey); - if (data.address) { - let check = data.address.toLowerCase(); - if (check.substring(0, 2) !== "0x") { - check = "0x" + check; - } - if ((0,address_lib_esm/* getAddress */.Kn)(check) !== address) { - throw new Error("address mismatch"); - } - } - const account = { - _isKeystoreAccount: true, - address: address, - privateKey: (0,bytes_lib_esm/* hexlify */.Dv)(privateKey) - }; - // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase - 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 (aes_js_default()).Counter(mnemonicIv); - const mnemonicAesCtr = new (aes_js_default()).ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); - const path = searchPath(data, "x-ethers/path") || defaultPath; - const locale = searchPath(data, "x-ethers/locale") || "en"; - const entropy = (0,bytes_lib_esm/* arrayify */.lE)(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 we don't have the locale wordlist installed to - // read this mnemonic, just bail and don't set the - // mnemonic - if (error.code !== logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT || error.argument !== "wordlist") { - throw error; - } - } - } - return new KeystoreAccount(account); -} -function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) { - return (0,bytes_lib_esm/* arrayify */.lE)(pbkdf2(passwordBytes, salt, count, dkLen, prfFunc)); -} -function keystore_pbkdf2(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 keystore_logger.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")); - // Check for all required parameters - if (!N || !r || !p) { - throwError("kdf", kdf); - } - // Make sure N is a power of 2 - 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); - } - } - return keystore_logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf); -} -function decryptSync(json, password) { - const data = JSON.parse(json); - const key = _computeKdfKey(data, password, pbkdf2Sync, (scrypt_default()).syncScrypt); - return _getAccount(data, key); -} -function keystore_decrypt(json, password, progressCallback) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.parse(json); - const key = yield _computeKdfKey(data, password, keystore_pbkdf2, (scrypt_default()).scrypt, progressCallback); - return _getAccount(data, key); - }); -} -function encrypt(account, password, options, progressCallback) { - try { - // Check the address matches the private key - if ((0,address_lib_esm/* getAddress */.Kn)(account.address) !== (0,transactions_lib_esm/* computeAddress */.db)(account.privateKey)) { - throw new Error("address/privateKey mismatch"); - } - // Check the mnemonic (if any) matches the private key - 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); - } - // The options are optional, so adjust the call as needed - if (typeof (options) === "function" && !progressCallback) { - progressCallback = options; - options = {}; - } - if (!options) { - options = {}; - } - const privateKey = (0,bytes_lib_esm/* arrayify */.lE)(account.privateKey); - const passwordBytes = getPassword(password); - let entropy = null; - let path = null; - let locale = null; - if (hasMnemonic(account)) { - const srcMnemonic = account.mnemonic; - entropy = (0,bytes_lib_esm/* arrayify */.lE)(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); - path = srcMnemonic.path || defaultPath; - locale = srcMnemonic.locale || "en"; - } - let client = options.client; - if (!client) { - client = "ethers.js"; - } - // Check/generate the salt - let salt = null; - if (options.salt) { - salt = (0,bytes_lib_esm/* arrayify */.lE)(options.salt); - } - else { - salt = randomBytes(32); - ; - } - // Override initialization vector - let iv = null; - if (options.iv) { - iv = (0,bytes_lib_esm/* arrayify */.lE)(options.iv); - if (iv.length !== 16) { - throw new Error("invalid iv"); - } - } - else { - iv = randomBytes(16); - } - // Override the uuid - let uuidRandom = null; - if (options.uuid) { - uuidRandom = (0,bytes_lib_esm/* arrayify */.lE)(options.uuid); - if (uuidRandom.length !== 16) { - throw new Error("invalid uuid"); - } - } - else { - uuidRandom = randomBytes(16); - } - // Override the scrypt password-based key derivation function parameters - let N = (1 << 17), r = 8, p = 1; - if (options.scrypt) { - if (options.scrypt.N) { - N = options.scrypt.N; - } - if (options.scrypt.r) { - r = options.scrypt.r; - } - if (options.scrypt.p) { - p = options.scrypt.p; - } - } - // We take 64 bytes: - // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) - // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet) - return scrypt_default().scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then((key) => { - key = (0,bytes_lib_esm/* arrayify */.lE)(key); - // This will be used to encrypt the wallet (as per Web3 secret storage) - const derivedKey = key.slice(0, 16); - const macPrefix = key.slice(16, 32); - // This will be used to encrypt the mnemonic phrase (if any) - const mnemonicKey = key.slice(32, 64); - // Encrypt the private key - const counter = new (aes_js_default()).Counter(iv); - const aesCtr = new (aes_js_default()).ModeOfOperation.ctr(derivedKey, counter); - const ciphertext = (0,bytes_lib_esm/* arrayify */.lE)(aesCtr.encrypt(privateKey)); - // Compute the message authentication code, used to check the password - const mac = (0,keccak256_lib_esm/* keccak256 */.w)((0,bytes_lib_esm/* concat */.zo)([macPrefix, ciphertext])); - // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition - const data = { - address: account.address.substring(2).toLowerCase(), - id: uuidV4(uuidRandom), - version: 3, - Crypto: { - cipher: "aes-128-ctr", - cipherparams: { - iv: (0,bytes_lib_esm/* hexlify */.Dv)(iv).substring(2), - }, - ciphertext: (0,bytes_lib_esm/* hexlify */.Dv)(ciphertext).substring(2), - kdf: "scrypt", - kdfparams: { - salt: (0,bytes_lib_esm/* hexlify */.Dv)(salt).substring(2), - n: N, - dklen: 32, - p: p, - r: r - }, - mac: mac.substring(2) - } - }; - // If we have a mnemonic, encrypt it into the JSON wallet - if (entropy) { - const mnemonicIv = randomBytes(16); - const mnemonicCounter = new (aes_js_default()).Counter(mnemonicIv); - const mnemonicAesCtr = new (aes_js_default()).ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); - const mnemonicCiphertext = (0,bytes_lib_esm/* arrayify */.lE)(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: client, - gethFilename: ("UTC--" + timestamp + "--" + data.address), - mnemonicCounter: (0,bytes_lib_esm/* hexlify */.Dv)(mnemonicIv).substring(2), - mnemonicCiphertext: (0,bytes_lib_esm/* hexlify */.Dv)(mnemonicCiphertext).substring(2), - path: path, - locale: locale, - version: "0.1" - }; - } - return JSON.stringify(data); - }); -} -//# sourceMappingURL=keystore.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/json-wallets/lib.esm/index.js - - - - -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 keystore_decrypt(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"); -} - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wallet/lib.esm/_version.js -const wallet_lib_esm_version_version = "wallet/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/wallet/lib.esm/index.js - -var lib_esm_awaiter = (undefined && undefined.__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 wallet_lib_esm_logger = new logger_lib_esm/* Logger */.Yd(wallet_lib_esm_version_version); -function isAccount(value) { - return (value != null && (0,bytes_lib_esm/* isHexString */.A7)(value.privateKey, 32) && value.address != null); -} -function lib_esm_hasMnemonic(value) { - const mnemonic = value.mnemonic; - return (mnemonic && mnemonic.phrase); -} -class Wallet extends abstract_signer_lib_esm/* Signer */.E { - constructor(privateKey, provider) { - wallet_lib_esm_logger.checkNew(new.target, Wallet); - super(); - if (isAccount(privateKey)) { - const signingKey = new signing_key_lib_esm/* SigningKey */.Et(privateKey.privateKey); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_signingKey", () => signingKey); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", (0,transactions_lib_esm/* computeAddress */.db)(this.publicKey)); - if (this.address !== (0,address_lib_esm/* getAddress */.Kn)(privateKey.address)) { - wallet_lib_esm_logger.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]"); - } - if (lib_esm_hasMnemonic(privateKey)) { - const srcMnemonic = privateKey.mnemonic; - (0,properties_lib_esm/* defineReadOnly */.zG)(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 ((0,transactions_lib_esm/* computeAddress */.db)(node.privateKey) !== this.address) { - wallet_lib_esm_logger.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]"); - } - } - else { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_mnemonic", () => null); - } - } - else { - if (signing_key_lib_esm/* SigningKey.isSigningKey */.Et.isSigningKey(privateKey)) { - /* istanbul ignore if */ - if (privateKey.curve !== "secp256k1") { - wallet_lib_esm_logger.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]"); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_signingKey", () => privateKey); - } - else { - // A lot of common tools do not prefix private keys with a 0x (see: #1166) - if (typeof (privateKey) === "string") { - if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) { - privateKey = "0x" + privateKey; - } - } - const signingKey = new signing_key_lib_esm/* SigningKey */.Et(privateKey); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_signingKey", () => signingKey); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_mnemonic", () => null); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "address", (0,transactions_lib_esm/* computeAddress */.db)(this.publicKey)); - } - /* istanbul ignore if */ - if (provider && !abstract_provider_lib_esm/* Provider.isProvider */.zt.isProvider(provider)) { - wallet_lib_esm_logger.throwArgumentError("invalid provider", "provider", provider); - } - (0,properties_lib_esm/* defineReadOnly */.zG)(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); - } - signTransaction(transaction) { - return (0,properties_lib_esm/* resolveProperties */.mE)(transaction).then((tx) => { - if (tx.from != null) { - if ((0,address_lib_esm/* getAddress */.Kn)(tx.from) !== this.address) { - wallet_lib_esm_logger.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from); - } - delete tx.from; - } - const signature = this._signingKey().signDigest((0,keccak256_lib_esm/* keccak256 */.w)((0,transactions_lib_esm/* serialize */.qC)(tx))); - return (0,transactions_lib_esm/* serialize */.qC)(tx, signature); - }); - } - signMessage(message) { - return lib_esm_awaiter(this, void 0, void 0, function* () { - return (0,bytes_lib_esm/* joinSignature */.gV)(this._signingKey().signDigest(hashMessage(message))); - }); - } - _signTypedData(domain, types, value) { - return lib_esm_awaiter(this, void 0, void 0, function* () { - // Populate any ENS names - const populated = yield typed_data/* TypedDataEncoder.resolveNames */.E.resolveNames(domain, types, value, (name) => { - if (this.provider == null) { - wallet_lib_esm_logger.throwError("cannot resolve ENS names without a provider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "resolveName", - value: name - }); - } - return this.provider.resolveName(name); - }); - return (0,bytes_lib_esm/* joinSignature */.gV)(this._signingKey().signDigest(typed_data/* TypedDataEncoder.hash */.E.hash(populated.domain, types, populated.value))); - }); - } - encrypt(password, options, progressCallback) { - if (typeof (options) === "function" && !progressCallback) { - progressCallback = options; - options = {}; - } - if (progressCallback && typeof (progressCallback) !== "function") { - throw new Error("invalid callback"); - } - if (!options) { - options = {}; - } - return encrypt(this, password, options, progressCallback); - } - /** - * Static methods to create Wallet instances. - */ - static createRandom(options) { - let entropy = randomBytes(16); - if (!options) { - options = {}; - } - if (options.extraEntropy) { - entropy = (0,bytes_lib_esm/* arrayify */.lE)((0,bytes_lib_esm/* hexDataSlice */.p3)((0,keccak256_lib_esm/* keccak256 */.w)((0,bytes_lib_esm/* concat */.zo)([entropy, options.extraEntropy])), 0, 16)); - } - const mnemonic = entropyToMnemonic(entropy, options.locale); - return Wallet.fromMnemonic(mnemonic, options.path, options.locale); - } - static fromEncryptedJson(json, password, progressCallback) { - return decryptJsonWallet(json, password, progressCallback).then((account) => { - return new Wallet(account); - }); - } - static fromEncryptedJsonSync(json, password) { - return new Wallet(decryptJsonWalletSync(json, password)); - } - static fromMnemonic(mnemonic, path, wordlist) { - if (!path) { - path = defaultPath; - } - return new Wallet(HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path)); - } -} -function verifyMessage(message, signature) { - return (0,transactions_lib_esm/* recoverAddress */.RJ)(hashMessage(message), signature); -} -function verifyTypedData(domain, types, value, signature) { - return (0,transactions_lib_esm/* recoverAddress */.RJ)(typed_data/* TypedDataEncoder.hash */.E.hash(domain, types, value), signature); -} -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/constants/lib.esm/addresses.js -var addresses = __webpack_require__(1210); -// EXTERNAL MODULE: ../node_modules/@ethersproject/constants/lib.esm/bignumbers.js -var bignumbers = __webpack_require__(5733); -// EXTERNAL MODULE: ../node_modules/@ethersproject/constants/lib.esm/hashes.js -var hashes = __webpack_require__(2728); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/constants/lib.esm/strings.js -// NFKC (composed) // (decomposed) -const EtherSymbol = "\u039e"; // "\uD835\uDF63"; -//# sourceMappingURL=strings.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/constants/lib.esm/index.js - - - - - -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/networks/lib.esm/index.js + 1 modules -var networks_lib_esm = __webpack_require__(7357); -// EXTERNAL MODULE: ../node_modules/@ethersproject/providers/lib.esm/base-provider.js -var base_provider = __webpack_require__(2001); -// EXTERNAL MODULE: ../node_modules/@ethersproject/providers/lib.esm/formatter.js -var formatter = __webpack_require__(8523); -// EXTERNAL MODULE: ../node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js -var json_rpc_provider = __webpack_require__(7100); -// EXTERNAL MODULE: ../node_modules/@ethersproject/providers/lib.esm/_version.js -var lib_esm_version = __webpack_require__(2405); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/ws.js - - - -let WS = null; -try { - WS = WebSocket; - if (WS == null) { - throw new Error("inject please"); - } -} -catch (error) { - const logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - WS = function () { - logger.throwError("WebSockets not supported in this environment", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "new WebSocket()" - }); - }; -} -//export default WS; -//module.exports = WS; - -//# sourceMappingURL=ws.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/websocket-provider.js - -var websocket_provider_awaiter = (undefined && undefined.__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 websocket_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); -/** - * Notes: - * - * This provider differs a bit from the polling providers. One main - * difference is how it handles consistency. The polling providers - * will stall responses to ensure a consistent state, while this - * WebSocket provider assumes the connected backend will manage this. - * - * For example, if a polling provider emits an event which indicates - * the event occurred in blockhash XXX, a call to fetch that block by - * its hash XXX, if not present will retry until it is present. This - * can occur when querying a pool of nodes that are mildly out of sync - * with each other. - */ -let NextId = 1; -// For more info about the Real-time Event API see: -// https://geth.ethereum.org/docs/rpc/pubsub -class WebSocketProvider extends json_rpc_provider/* JsonRpcProvider */.r { - constructor(url, network) { - // This will be added in the future; please open an issue to expedite - if (network === "any") { - websocket_provider_logger.throwError("WebSocketProvider does not support 'any' network yet", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "network:any" - }); - } - super(url, network); - this._pollingInterval = -1; - this._wsReady = false; - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_websocket", new WS(this.connection.url)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_requests", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_subs", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_subIds", {}); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_detectNetwork", super.detectNetwork()); - // Stall sending requests until the socket is open... - 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 !== undefined) { - 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"); - (0,properties_lib_esm/* defineReadOnly */.zG)(error, "code", result.error.code || null); - (0,properties_lib_esm/* defineReadOnly */.zG)(error, "response", data); - } - else { - error = new Error("unknown error"); - } - request.callback(error, undefined); - this.emit("debug", { - action: "response", - error: error, - request: JSON.parse(request.payload), - provider: this - }); - } - } - else if (result.method === "eth_subscription") { - // Subscription... - const sub = this._subs[result.params.subscription]; - if (sub) { - //this.emit.apply(this, ); - sub.processFunc(result.params.result); - } - } - else { - console.warn("this should not happen"); - } - }; - // This Provider does not actually poll, but we want to trigger - // poll events for things that depend on them (like stalling for - // block and transaction lookups) - const fauxPoll = setInterval(() => { - this.emit("poll"); - }, 1000); - if (fauxPoll.unref) { - fauxPoll.unref(); - } - } - detectNetwork() { - return this._detectNetwork; - } - get pollingInterval() { - return 0; - } - resetEventsBlock(blockNumber) { - websocket_provider_logger.throwError("cannot reset events block on WebSocketProvider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "resetEventBlock" - }); - } - set pollingInterval(value) { - websocket_provider_logger.throwError("cannot set polling interval on WebSocketProvider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "setPollingInterval" - }); - } - poll() { - return websocket_provider_awaiter(this, void 0, void 0, function* () { - return null; - }); - } - set polling(value) { - if (!value) { - return; - } - websocket_provider_logger.throwError("cannot set polling on WebSocketProvider", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "setPolling" - }); - } - 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: method, - params: 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); - } - }); - } - static defaultUrl() { - return "ws:/\/localhost:8546"; - } - _subscribe(tag, param, processFunc) { - return websocket_provider_awaiter(this, void 0, void 0, function* () { - let subIdPromise = this._subIds[tag]; - if (subIdPromise == null) { - subIdPromise = Promise.all(param).then((param) => { - return this.send("eth_subscribe", param); - }); - 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/* BigNumber.from */.O$.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 = (event) => { - const hash = event.hash; - this.getTransactionReceipt(hash).then((receipt) => { - if (!receipt) { - return; - } - this.emit(hash, receipt); - }); - }; - // In case it is already mined - emitReceipt(event); - // To keep things simple, we start up a single newHeads subscription - // to keep an eye out for transactions we are watching for. - // Starting a subscription for an event (i.e. "tx") that is already - // running is (basically) a nop. - this._subscribe("tx", ["newHeads"], (result) => { - this._events.filter((e) => (e.type === "tx")).forEach(emitReceipt); - }); - break; - } - // Nothing is needed - case "debug": - case "poll": - case "willPoll": - case "didPoll": - case "error": - break; - default: - console.log("unhandled:", event); - break; - } - } - _stopEvent(event) { - let tag = event.tag; - if (event.type === "tx") { - // There are remaining transaction event listeners - if (this._events.filter((e) => (e.type === "tx")).length) { - return; - } - tag = "tx"; - } - else if (this.listenerCount(event.event)) { - // There are remaining event listeners - return; - } - const subId = this._subIds[tag]; - if (!subId) { - return; - } - delete this._subIds[tag]; - subId.then((subId) => { - if (!this._subs[subId]) { - return; - } - delete this._subs[subId]; - this.send("eth_unsubscribe", [subId]); - }); - } - destroy() { - return websocket_provider_awaiter(this, void 0, void 0, function* () { - // Wait until we have connected before trying to disconnect - if (this._websocket.readyState === WS.CONNECTING) { - yield (new Promise((resolve) => { - this._websocket.onopen = function () { - resolve(true); - }; - this._websocket.onerror = function () { - resolve(false); - }; - })); - } - // Hangup - // See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes - this._websocket.close(1000); - }); - } -} -//# sourceMappingURL=websocket-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/url-json-rpc-provider.js - -var url_json_rpc_provider_awaiter = (undefined && undefined.__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 url_json_rpc_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - -// A StaticJsonRpcProvider is useful when you *know* for certain that -// the backend will never change, as it never calls eth_chainId to -// verify its backend. However, if the backend does change, the effects -// are undefined and may include: -// - inconsistent results -// - locking up the UI -// - block skew warnings -// - wrong results -// If the network is not explicit (i.e. auto-detection is expected), the -// node MUST be running and available to respond to requests BEFORE this -// is instantiated. -class StaticJsonRpcProvider extends json_rpc_provider/* JsonRpcProvider */.r { - detectNetwork() { - const _super = Object.create(null, { - detectNetwork: { get: () => super.detectNetwork } - }); - return url_json_rpc_provider_awaiter(this, void 0, void 0, function* () { - let network = this.network; - if (network == null) { - network = yield _super.detectNetwork.call(this); - if (!network) { - url_json_rpc_provider_logger.throwError("no network detected", logger_lib_esm/* Logger.errors.UNKNOWN_ERROR */.Yd.errors.UNKNOWN_ERROR, {}); - } - // If still not set, set it - if (this._network == null) { - // A static network does not support "any" - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "_network", network); - this.emit("network", network, null); - } - } - return network; - }); - } -} -class UrlJsonRpcProvider extends StaticJsonRpcProvider { - constructor(network, apiKey) { - url_json_rpc_provider_logger.checkAbstract(new.target, UrlJsonRpcProvider); - // Normalize the Network and API Key - network = (0,properties_lib_esm/* getStatic */.tu)(new.target, "getNetwork")(network); - apiKey = (0,properties_lib_esm/* getStatic */.tu)(new.target, "getApiKey")(apiKey); - const connection = (0,properties_lib_esm/* getStatic */.tu)(new.target, "getUrl")(network, apiKey); - super(connection, network); - if (typeof (apiKey) === "string") { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "apiKey", apiKey); - } - else if (apiKey != null) { - Object.keys(apiKey).forEach((key) => { - (0,properties_lib_esm/* defineReadOnly */.zG)(this, key, apiKey[key]); - }); - } - } - _startPending() { - url_json_rpc_provider_logger.warn("WARNING: API provider does not support pending filters"); - } - isCommunityResource() { - return false; - } - getSigner(address) { - return url_json_rpc_provider_logger.throwError("API provider does not support signing", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { operation: "getSigner" }); - } - listAccounts() { - return Promise.resolve([]); - } - // Return a defaultApiKey if null, otherwise validate the API key - static getApiKey(apiKey) { - return apiKey; - } - // Returns the url or connection for the given network and API key. The - // API key will have been sanitized by the getApiKey first, so any validation - // or transformations can be done there. - static getUrl(network, apiKey) { - return url_json_rpc_provider_logger.throwError("not implemented; sub-classes must override getUrl", logger_lib_esm/* Logger.errors.NOT_IMPLEMENTED */.Yd.errors.NOT_IMPLEMENTED, { - operation: "getUrl" - }); - } -} -//# sourceMappingURL=url-json-rpc-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/alchemy-provider.js - - - - - - -const alchemy_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - -// This key was provided to ethers.js by Alchemy to be used by the -// default provider, but it is recommended that for your own -// production environments, that you acquire your own API key at: -// https://dashboard.alchemyapi.io -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); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "apiKey", provider.apiKey); - } - isCommunityResource() { - return (this.apiKey === defaultApiKey); - } -} -class AlchemyProvider extends UrlJsonRpcProvider { - static getWebSocketProvider(network, apiKey) { - return new AlchemyWebSocketProvider(network, apiKey); - } - static getApiKey(apiKey) { - if (apiKey == null) { - return defaultApiKey; - } - if (apiKey && typeof (apiKey) !== "string") { - alchemy_provider_logger.throwArgumentError("invalid apiKey", "apiKey", apiKey); - } - return apiKey; - } - static getUrl(network, apiKey) { - let host = null; - switch (network.name) { - case "homestead": - host = "eth-mainnet.alchemyapi.io/v2/"; - break; - case "ropsten": - host = "eth-ropsten.alchemyapi.io/v2/"; - break; - case "rinkeby": - host = "eth-rinkeby.alchemyapi.io/v2/"; - break; - case "goerli": - host = "eth-goerli.alchemyapi.io/v2/"; - break; - case "kovan": - host = "eth-kovan.alchemyapi.io/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-rinkeby": - host = "arb-rinkeby.g.alchemy.com/v2/"; - break; - case "optimism": - host = "opt-mainnet.g.alchemy.com/v2/"; - break; - case "optimism-kovan": - host = "opt-kovan.g.alchemy.com/v2/"; - break; - default: - alchemy_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]); - } - return { - allowGzip: true, - url: ("https:/" + "/" + host + apiKey), - throttleCallback: (attempt, url) => { - if (apiKey === defaultApiKey) { - (0,formatter/* showThrottleMessage */.vh)(); - } - return Promise.resolve(true); - } - }; - } - isCommunityResource() { - return (this.apiKey === defaultApiKey); - } -} -//# sourceMappingURL=alchemy-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/cloudflare-provider.js - -var cloudflare_provider_awaiter = (undefined && undefined.__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 cloudflare_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); -class CloudflareProvider extends UrlJsonRpcProvider { - static getApiKey(apiKey) { - if (apiKey != null) { - cloudflare_provider_logger.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: - cloudflare_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]); - } - return host; - } - perform(method, params) { - const _super = Object.create(null, { - perform: { get: () => super.perform } - }); - return cloudflare_provider_awaiter(this, void 0, void 0, function* () { - // The Cloudflare provider does not support eth_blockNumber, - // so we get the latest block and pull it from that - if (method === "getBlockNumber") { - const block = yield _super.perform.call(this, "getBlock", { blockTag: "latest" }); - return block.number; - } - return _super.perform.call(this, method, params); - }); - } -} -//# sourceMappingURL=cloudflare-provider.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/web/lib.esm/index.js + 2 modules -var web_lib_esm = __webpack_require__(2585); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/etherscan-provider.js - -var etherscan_provider_awaiter = (undefined && undefined.__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 etherscan_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - -// The transaction has already been sanitized by the calls in Provider -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; - } - // Quantity-types require no leading zero, unless 0 - if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) { - value = (0,bytes_lib_esm/* hexValue */.$P)((0,bytes_lib_esm/* hexlify */.Dv)(value)); - } - else if (key === "accessList") { - value = "[" + (0,transactions_lib_esm/* accessListify */.z7)(value).map((set) => { - return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; - }).join(",") + "]"; - } - else { - value = (0,bytes_lib_esm/* hexlify */.Dv)(value); - } - result[key] = value; - } - return result; -} -function getResult(result) { - // getLogs, getHistory have weird success responses - if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { - return result.result; - } - if (result.status != 1 || result.message != "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; - } - return result.result; -} -function getJsonResult(result) { - // This response indicates we are being throttled - 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") { - // @TODO: not any - const error = new Error("invalid response"); - error.result = JSON.stringify(result); - throw error; - } - if (result.error) { - // @TODO: not any - 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; - } - return result.result; -} -// The blockTag was normalized as a string by the Provider pre-perform operations -function checkLogTag(blockTag) { - if (blockTag === "pending") { - throw new Error("pending not supported"); - } - if (blockTag === "latest") { - return blockTag; - } - return parseInt(blockTag.substring(2), 16); -} -const etherscan_provider_defaultApiKey = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB"; -function checkError(method, error, transaction) { - // Undo the "convenience" some nodes are attempting to prevent backwards - // incompatibility; maybe for v6 consider forwarding reverts as errors - if (method === "call" && error.code === logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR) { - const e = error.error; - // Etherscan keeps changing their string - if (e && (e.message.match(/reverted/i) || e.message.match(/VM execution error/i))) { - // Etherscan prefixes the data like "Reverted 0x1234" - let data = e.data; - if (data) { - data = "0x" + data.replace(/^.*0x/i, ""); - } - if ((0,bytes_lib_esm/* isHexString */.A7)(data)) { - return data; - } - etherscan_provider_logger.throwError("missing revert data in call exception", logger_lib_esm/* Logger.errors.CALL_EXCEPTION */.Yd.errors.CALL_EXCEPTION, { - error, data: "0x" - }); - } - } - // Get the message from any nested error structure - let message = error.message; - if (error.code === logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.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; - } - } - message = (message || "").toLowerCase(); - // "Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 21464000000000 and got: 0" - if (message.match(/insufficient funds/)) { - etherscan_provider_logger.throwError("insufficient funds for intrinsic transaction cost", logger_lib_esm/* Logger.errors.INSUFFICIENT_FUNDS */.Yd.errors.INSUFFICIENT_FUNDS, { - error, method, transaction - }); - } - // "Transaction with the same hash was already imported." - if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { - etherscan_provider_logger.throwError("nonce has already been used", logger_lib_esm/* Logger.errors.NONCE_EXPIRED */.Yd.errors.NONCE_EXPIRED, { - error, method, transaction - }); - } - // "Transaction gas price is too low. There is another transaction with same nonce in the queue. Try increasing the gas price or incrementing the nonce." - if (message.match(/another transaction with same nonce/)) { - etherscan_provider_logger.throwError("replacement fee too low", logger_lib_esm/* Logger.errors.REPLACEMENT_UNDERPRICED */.Yd.errors.REPLACEMENT_UNDERPRICED, { - error, method, transaction - }); - } - if (message.match(/execution failed due to an exception|execution reverted/)) { - etherscan_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", logger_lib_esm/* Logger.errors.UNPREDICTABLE_GAS_LIMIT */.Yd.errors.UNPREDICTABLE_GAS_LIMIT, { - error, method, transaction - }); - } - throw error; -} -class EtherscanProvider extends base_provider/* BaseProvider */.Zk { - constructor(network, apiKey) { - etherscan_provider_logger.checkNew(new.target, EtherscanProvider); - super(network); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "baseUrl", this.getBaseUrl()); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "apiKey", apiKey || etherscan_provider_defaultApiKey); - } - getBaseUrl() { - switch (this.network ? this.network.name : "invalid") { - case "homestead": - return "https:/\/api.etherscan.io"; - case "ropsten": - return "https:/\/api-ropsten.etherscan.io"; - case "rinkeby": - return "https:/\/api-rinkeby.etherscan.io"; - case "kovan": - return "https:/\/api-kovan.etherscan.io"; - case "goerli": - return "https:/\/api-goerli.etherscan.io"; - default: - } - return etherscan_provider_logger.throwArgumentError("unsupported network", "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 etherscan_provider_awaiter(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; - this.emit("debug", { - action: "request", - request: url, - provider: this - }); - const connection = { - url: url, - throttleSlotInterval: 1000, - throttleCallback: (attempt, url) => { - if (this.isCommunityResource()) { - (0,formatter/* showThrottleMessage */.vh)(); - } - return Promise.resolve(true); - } - }; - 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 (0,web_lib_esm/* fetchJson */.rd)(connection, payloadStr, procFunc || getJsonResult); - this.emit("debug", { - action: "response", - request: url, - response: (0,properties_lib_esm/* deepCopy */.p$)(result), - provider: this - }); - return result; - }); - } - detectNetwork() { - return etherscan_provider_awaiter(this, void 0, void 0, function* () { - return this.network; - }); - } - perform(method, params) { - const _super = Object.create(null, { - perform: { get: () => super.perform } - }); - return etherscan_provider_awaiter(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": - // Returns base-10 result - 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("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("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("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; - } - // @TODO: We can handle slightly more complicated logs using the logs API - if (params.filter.topics && params.filter.topics.length > 0) { - if (params.filter.topics.length > 1) { - etherscan_provider_logger.throwError("unsupported topic count", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.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) { - etherscan_provider_logger.throwError("unsupported topic format", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { topic0: topic0 }); - } - args.topic0 = topic0; - } - } - const logs = yield this.fetch("logs", args); - // Cache txHash => blockHash - let blocks = {}; - // Add any missing blockHash to the logs - 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.0; - } - return parseFloat((yield this.fetch("stats", { action: "ethprice" })).ethusd); - default: - break; - } - return _super.perform.call(this, method, params); - }); - } - // Note: The `page` page parameter only allows pagination within the - // 10,000 window available without a page and offset parameter - // Error: Result window is too large, PageNo x Offset size must - // be less than or equal to 10000 - getHistory(addressOrName, startBlock, endBlock) { - return etherscan_provider_awaiter(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; - }); - }); - } - isCommunityResource() { - return (this.apiKey === etherscan_provider_defaultApiKey); - } -} -//# sourceMappingURL=etherscan-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/random/lib.esm/shuffle.js - -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; - } - return array; -} -//# sourceMappingURL=shuffle.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/fallback-provider.js - -var fallback_provider_awaiter = (undefined && undefined.__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 fallback_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); -function now() { return (new Date()).getTime(); } -// Returns to network as long as all agree, or null if any is null. -// Throws an error if any two networks do not match. -function checkNetworks(networks) { - let result = null; - for (let i = 0; i < networks.length; i++) { - const network = networks[i]; - // Null! We do not know our network; bail. - if (network == null) { - return null; - } - if (result) { - // Make sure the network matches the previous networks - if (!(result.name === network.name && result.chainId === network.chainId && - ((result.ensAddress === network.ensAddress) || (result.ensAddress == null && network.ensAddress == null)))) { - fallback_provider_logger.throwArgumentError("provider mismatch", "networks", networks); - } - } - else { - result = network; - } - } - return result; -} -function median(values, maxDelta) { - values = values.slice().sort(); - const middle = Math.floor(values.length / 2); - // Odd length; take the middle - if (values.length % 2) { - return values[middle]; - } - // Even length; take the average of the two middle - const a = values[middle - 1], b = values[middle]; - if (maxDelta != null && Math.abs(a - b) > maxDelta) { - return null; - } - return (a + b) / 2; -} -function serialize(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/* BigNumber.isBigNumber */.O$.isBigNumber(value)) { - return value.toString(); - } - else if (Array.isArray(value)) { - return JSON.stringify(value.map((i) => serialize(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 = serialize(v); - } - return JSON.stringify(key) + ":" + v; - }).join(",") + "}"; - } - throw new Error("unknown value type: " + typeof (value)); -} -// Next request ID to use for emitting debug info -let nextRid = 1; -; -function stall(duration) { - let cancel = null; - let timer = null; - let promise = (new Promise((resolve) => { - cancel = function () { - if (timer) { - clearTimeout(timer); - timer = null; - } - resolve(); - }; - timer = setTimeout(cancel, duration); - })); - const wait = (func) => { - promise = promise.then(func); - return promise; - }; - function getPromise() { - return promise; - } - return { cancel, getPromise, wait }; -} -const ForwardErrors = [ - logger_lib_esm/* Logger.errors.CALL_EXCEPTION */.Yd.errors.CALL_EXCEPTION, - logger_lib_esm/* Logger.errors.INSUFFICIENT_FUNDS */.Yd.errors.INSUFFICIENT_FUNDS, - logger_lib_esm/* Logger.errors.NONCE_EXPIRED */.Yd.errors.NONCE_EXPIRED, - logger_lib_esm/* Logger.errors.REPLACEMENT_UNDERPRICED */.Yd.errors.REPLACEMENT_UNDERPRICED, - logger_lib_esm/* Logger.errors.UNPREDICTABLE_GAS_LIMIT */.Yd.errors.UNPREDICTABLE_GAS_LIMIT -]; -const ForwardProperties = [ - "address", - "args", - "errorArgs", - "errorSignature", - "method", - "transaction", -]; -; -function exposeDebugConfig(config, now) { - const result = { - weight: config.weight - }; - Object.defineProperty(result, "provider", { get: () => config.provider }); - if (config.start) { - result.start = config.start; - } - if (now) { - result.duration = (now - config.start); - } - if (config.done) { - if (config.error) { - result.error = config.error; - } - else { - result.result = config.result || null; - } - } - return result; -} -function normalizedTally(normalize, quorum) { - return function (configs) { - // Count the votes for each result - const tally = {}; - configs.forEach((c) => { - const value = normalize(c.result); - if (!tally[value]) { - tally[value] = { count: 0, result: c.result }; - } - tally[value].count++; - }); - // Check for a quorum on any given result - 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; - } - } - // No quroum - return undefined; - }; -} -function getProcessFunc(provider, method, params) { - let normalize = serialize; - switch (method) { - case "getBlockNumber": - // Return the median value, unless there is (median + 1) is also - // present, in which case that is probably true and the median - // is going to be stale soon. In the event of a malicious node, - // the lie will be true soon enough. - return function (configs) { - const values = configs.map((c) => c.result); - // Get the median block number - let blockNumber = median(configs.map((c) => c.result), 2); - if (blockNumber == null) { - return undefined; - } - blockNumber = Math.ceil(blockNumber); - // If the next block height is present, its prolly safe to use - if (values.indexOf(blockNumber + 1) >= 0) { - blockNumber++; - } - // Don't ever roll back the blockNumber - if (blockNumber >= provider._highestBlockNumber) { - provider._highestBlockNumber = blockNumber; - } - return provider._highestBlockNumber; - }; - case "getGasPrice": - // Return the middle (round index up) value, similar to median - // but do not average even entries and choose the higher. - // Malicious actors must compromise 50% of the nodes to lie. - return function (configs) { - const values = configs.map((c) => c.result); - values.sort(); - return values[Math.floor(values.length / 2)]; - }; - case "getEtherPrice": - // Returns the median price. Malicious actors must compromise at - // least 50% of the nodes to lie (in a meaningful way). - return function (configs) { - return median(configs.map((c) => c.result)); - }; - // No additional normalizing required; serialize is enough - case "getBalance": - case "getTransactionCount": - case "getCode": - case "getStorageAt": - case "call": - case "estimateGas": - case "getLogs": - break; - // We drop the confirmations from transactions as it is approximate - case "getTransaction": - case "getTransactionReceipt": - normalize = function (tx) { - if (tx == null) { - return null; - } - tx = (0,properties_lib_esm/* shallowCopy */.DC)(tx); - tx.confirmations = -1; - return serialize(tx); - }; - break; - // We drop the confirmations from transactions as it is approximate - case "getBlock": - // We drop the confirmations from transactions as it is approximate - if (params.includeTransactions) { - normalize = function (block) { - if (block == null) { - return null; - } - block = (0,properties_lib_esm/* shallowCopy */.DC)(block); - block.transactions = block.transactions.map((tx) => { - tx = (0,properties_lib_esm/* shallowCopy */.DC)(tx); - tx.confirmations = -1; - return tx; - }); - return serialize(block); - }; - } - else { - normalize = function (block) { - if (block == null) { - return null; - } - return serialize(block); - }; - } - break; - default: - throw new Error("unknown method: " + method); - } - // Return the result if and only if the expected quorum is - // satisfied and agreed upon for the final result. - return normalizedTally(normalize, provider.quorum); -} -// If we are doing a blockTag query, we need to make sure the backend is -// caught up to the FallbackProvider, before sending a request to it. -function waitForSync(config, blockNumber) { - return fallback_provider_awaiter(this, void 0, void 0, function* () { - const provider = (config.provider); - if ((provider.blockNumber != null && provider.blockNumber >= blockNumber) || blockNumber === -1) { - return provider; - } - return (0,web_lib_esm/* poll */.$l)(() => { - return new Promise((resolve, reject) => { - setTimeout(function () { - // We are synced - if (provider.blockNumber >= blockNumber) { - return resolve(provider); - } - // We're done; just quit - if (config.cancelled) { - return resolve(null); - } - // Try again, next block - return resolve(undefined); - }, 0); - }); - }, { oncePoll: provider }); - }); -} -function getRunner(config, currentBlockNumber, method, params) { - return fallback_provider_awaiter(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(); - } - break; - case "getBalance": - case "getTransactionCount": - case "getCode": - if (params.blockTag && (0,bytes_lib_esm/* isHexString */.A7)(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider[method](params.address, params.blockTag || "latest"); - case "getStorageAt": - if (params.blockTag && (0,bytes_lib_esm/* isHexString */.A7)(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider.getStorageAt(params.address, params.position, params.blockTag || "latest"); - case "getBlock": - if (params.blockTag && (0,bytes_lib_esm/* isHexString */.A7)(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider[(params.includeTransactions ? "getBlockWithTransactions" : "getBlock")](params.blockTag || params.blockHash); - case "call": - case "estimateGas": - if (params.blockTag && (0,bytes_lib_esm/* isHexString */.A7)(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider[method](params.transaction); - case "getTransaction": - case "getTransactionReceipt": - return provider[method](params.transactionHash); - case "getLogs": { - let filter = params.filter; - if ((filter.fromBlock && (0,bytes_lib_esm/* isHexString */.A7)(filter.fromBlock)) || (filter.toBlock && (0,bytes_lib_esm/* isHexString */.A7)(filter.toBlock))) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider.getLogs(filter); - } - } - return fallback_provider_logger.throwError("unknown method error", logger_lib_esm/* Logger.errors.UNKNOWN_ERROR */.Yd.errors.UNKNOWN_ERROR, { - method: method, - params: params - }); - }); -} -class FallbackProvider extends base_provider/* BaseProvider */.Zk { - constructor(providers, quorum) { - fallback_provider_logger.checkNew(new.target, FallbackProvider); - if (providers.length === 0) { - fallback_provider_logger.throwArgumentError("missing providers", "providers", providers); - } - const providerConfigs = providers.map((configOrProvider, index) => { - if (abstract_provider_lib_esm/* Provider.isProvider */.zt.isProvider(configOrProvider)) { - const stallTimeout = (0,formatter/* isCommunityResource */.Gp)(configOrProvider) ? 2000 : 750; - const priority = 1; - return Object.freeze({ provider: configOrProvider, weight: 1, stallTimeout, priority }); - } - const config = (0,properties_lib_esm/* shallowCopy */.DC)(configOrProvider); - if (config.priority == null) { - config.priority = 1; - } - if (config.stallTimeout == null) { - config.stallTimeout = (0,formatter/* isCommunityResource */.Gp)(configOrProvider) ? 2000 : 750; - } - if (config.weight == null) { - config.weight = 1; - } - const weight = config.weight; - if (weight % 1 || weight > 512 || weight < 1) { - fallback_provider_logger.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) { - fallback_provider_logger.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum); - } - // Are all providers' networks are known - let networkOrReady = checkNetworks(providerConfigs.map((c) => (c.provider).network)); - // Not all networks are known; we must stall - if (networkOrReady == null) { - networkOrReady = new Promise((resolve, reject) => { - setTimeout(() => { - this.detectNetwork().then(resolve, reject); - }, 0); - }); - } - super(networkOrReady); - // Preserve a copy, so we do not get mutated - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "providerConfigs", Object.freeze(providerConfigs)); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "quorum", quorum); - this._highestBlockNumber = -1; - } - detectNetwork() { - return fallback_provider_awaiter(this, void 0, void 0, function* () { - const networks = yield Promise.all(this.providerConfigs.map((c) => c.provider.getNetwork())); - return checkNetworks(networks); - }); - } - perform(method, params) { - return fallback_provider_awaiter(this, void 0, void 0, function* () { - // Sending transactions is special; always broadcast it to all backends - 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; - }); - })); - // Any success is good enough (other errors are likely "already seen" errors - for (let i = 0; i < results.length; i++) { - const result = results[i]; - if (typeof (result) === "string") { - return result; - } - } - // They were all an error; pick the first error - throw results[0]; - } - // We need to make sure we are in sync with our backends, so we need - // to know this before we can make a lot of calls - if (this._highestBlockNumber === -1 && method !== "getBlockNumber") { - yield this.getBlockNumber(); - } - const processFunc = getProcessFunc(this, method, params); - // Shuffle the providers and then sort them by their priority; we - // shallowCopy them since we will store the result in them too - const configs = shuffled(this.providerConfigs.map(properties_lib_esm/* shallowCopy */.DC)); - configs.sort((a, b) => (a.priority - b.priority)); - const currentBlockNumber = this._highestBlockNumber; - let i = 0; - let first = true; - while (true) { - const t0 = now(); - // Compute the inflight weight (exclude anything past) - let inflightWeight = configs.filter((c) => (c.runner && ((t0 - c.start) < c.stallTimeout))) - .reduce((accum, c) => (accum + c.weight), 0); - // Start running enough to meet quorum - while (inflightWeight < this.quorum && i < configs.length) { - const config = configs[i++]; - const rid = nextRid++; - config.start = now(); - config.staller = stall(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: rid, - backend: exposeDebugConfig(config, now()), - request: { method: method, params: (0,properties_lib_esm/* deepCopy */.p$)(params) }, - provider: this - }); - } - }, (error) => { - config.done = true; - config.error = error; - if (this.listenerCount("debug")) { - this.emit("debug", { - action: "request", - rid: rid, - backend: exposeDebugConfig(config, now()), - request: { method: method, params: (0,properties_lib_esm/* deepCopy */.p$)(params) }, - provider: this - }); - } - }); - if (this.listenerCount("debug")) { - this.emit("debug", { - action: "request", - rid: rid, - backend: exposeDebugConfig(config, null), - request: { method: method, params: (0,properties_lib_esm/* deepCopy */.p$)(params) }, - provider: this - }); - } - inflightWeight += config.weight; - } - // Wait for anything meaningful to finish or stall out - 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); - } - // Check the quorum and process the results; the process function - // may additionally decide the quorum is not met - const results = configs.filter((c) => (c.done && c.error == null)); - if (results.length >= this.quorum) { - const result = processFunc(results); - if (result !== undefined) { - // Shut down any stallers - configs.forEach(c => { - if (c.staller) { - c.staller.cancel(); - } - c.cancelled = true; - }); - return result; - } - if (!first) { - yield stall(100).getPromise(); - } - first = false; - } - // No result, check for errors that should be forwarded - 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; - } - // Shut down any stallers - 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]; - }); - fallback_provider_logger.throwError(e.reason || e.message, errorCode, props); - }); - // All configs have run to completion; we will never get more data - if (configs.filter((c) => !c.done).length === 0) { - break; - } - } - // Shut down any stallers; shouldn't be any - configs.forEach(c => { - if (c.staller) { - c.staller.cancel(); - } - c.cancelled = true; - }); - return fallback_provider_logger.throwError("failed to meet quorum", logger_lib_esm/* Logger.errors.SERVER_ERROR */.Yd.errors.SERVER_ERROR, { - method: method, - params: params, - //results: configs.map((c) => c.result), - //errors: configs.map((c) => c.error), - results: configs.map((c) => exposeDebugConfig(c)), - provider: this - }); - }); - } -} -//# sourceMappingURL=fallback-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/ipc-provider.js - -const IpcProvider = null; - -//# sourceMappingURL=ipc-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/infura-provider.js - - - - - - -const infura_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - -const defaultProjectId = "84842078b09946638c03157f83405213"; -class InfuraWebSocketProvider extends WebSocketProvider { - constructor(network, apiKey) { - const provider = new InfuraProvider(network, apiKey); - const connection = provider.connection; - if (connection.password) { - infura_provider_logger.throwError("INFURA WebSocket project secrets unsupported", logger_lib_esm/* Logger.errors.UNSUPPORTED_OPERATION */.Yd.errors.UNSUPPORTED_OPERATION, { - operation: "InfuraProvider.getWebSocketProvider()" - }); - } - const url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); - super(url, network); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "apiKey", provider.projectId); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "projectId", provider.projectId); - (0,properties_lib_esm/* defineReadOnly */.zG)(this, "projectSecret", provider.projectSecret); - } - isCommunityResource() { - return (this.projectId === defaultProjectId); - } -} -class InfuraProvider extends UrlJsonRpcProvider { - static getWebSocketProvider(network, apiKey) { - return new InfuraWebSocketProvider(network, apiKey); - } - 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) { - infura_provider_logger.assertArgument((typeof (apiKey.projectId) === "string"), "projectSecret requires a projectId", "projectId", apiKey.projectId); - infura_provider_logger.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 "ropsten": - host = "ropsten.infura.io"; - break; - case "rinkeby": - host = "rinkeby.infura.io"; - break; - case "kovan": - host = "kovan.infura.io"; - break; - case "goerli": - host = "goerli.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-kovan": - host = "optimism-kovan.infura.io"; - break; - case "arbitrum": - host = "arbitrum-mainnet.infura.io"; - break; - case "arbitrum-rinkeby": - host = "arbitrum-rinkeby.infura.io"; - break; - default: - infura_provider_logger.throwError("unsupported network", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "network", - value: network - }); - } - const connection = { - allowGzip: true, - url: ("https:/" + "/" + host + "/v3/" + apiKey.projectId), - throttleCallback: (attempt, url) => { - if (apiKey.projectId === defaultProjectId) { - (0,formatter/* showThrottleMessage */.vh)(); - } - return Promise.resolve(true); - } - }; - if (apiKey.projectSecret != null) { - connection.user = ""; - connection.password = apiKey.projectSecret; - } - return connection; - } - isCommunityResource() { - return (this.projectId === defaultProjectId); - } -} -//# sourceMappingURL=infura-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/json-rpc-batch-provider.js - - - -// Experimental -class JsonRpcBatchProvider extends json_rpc_provider/* JsonRpcProvider */.r { - send(method, params) { - const request = { - method: method, - params: params, - id: (this._nextId++), - jsonrpc: "2.0" - }; - if (this._pendingBatch == null) { - this._pendingBatch = []; - } - 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) { - // Schedule batch for next event loop + short duration - this._pendingBatchAggregator = setTimeout(() => { - // Get teh current batch and clear it, so new requests - // go into the next batch - const batch = this._pendingBatch; - this._pendingBatch = null; - this._pendingBatchAggregator = null; - // Get the request as an array of requests - const request = batch.map((inflight) => inflight.request); - this.emit("debug", { - action: "requestBatch", - request: (0,properties_lib_esm/* deepCopy */.p$)(request), - provider: this - }); - return (0,web_lib_esm/* fetchJson */.rd)(this.connection, JSON.stringify(request)).then((result) => { - this.emit("debug", { - action: "response", - request: request, - response: result, - provider: this - }); - // For each result, feed it to the correct Promise, depending - // on whether it was a success or error - batch.forEach((inflightRequest, 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; - inflightRequest.reject(error); - } - else { - inflightRequest.resolve(payload.result); - } - }); - }, (error) => { - this.emit("debug", { - action: "response", - error: error, - request: request, - provider: this - }); - batch.forEach((inflightRequest) => { - inflightRequest.reject(error); - }); - }); - }, 10); - } - return promise; - } -} -//# sourceMappingURL=json-rpc-batch-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/nodesmith-provider.js -/* istanbul ignore file */ - - - - -const nodesmith_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); -// Special API key provided by Nodesmith for ethers.js -const nodesmith_provider_defaultApiKey = "ETHERS_JS_SHARED"; -class NodesmithProvider extends UrlJsonRpcProvider { - static getApiKey(apiKey) { - if (apiKey && typeof (apiKey) !== "string") { - nodesmith_provider_logger.throwArgumentError("invalid apiKey", "apiKey", apiKey); - } - return apiKey || nodesmith_provider_defaultApiKey; - } - static getUrl(network, apiKey) { - nodesmith_provider_logger.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: - nodesmith_provider_logger.throwArgumentError("unsupported network", "network", arguments[0]); - } - return (host + "?apiKey=" + apiKey); - } -} -//# sourceMappingURL=nodesmith-provider.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/pocket-provider.js - - - - -const pocket_provider_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); - -// These are load-balancer-based application IDs -const defaultApplicationIds = { - homestead: "6004bcd10040261633ade990", - ropsten: "6004bd4d0040261633ade991", - rinkeby: "6004bda20040261633ade994", - goerli: "6004bd860040261633ade992", -}; -class PocketProvider extends UrlJsonRpcProvider { - constructor(network, apiKey) { - // We need a bit of creativity in the constructor because - // Pocket uses different default API keys based on the network - if (apiKey == null) { - const n = (0,properties_lib_esm/* getStatic */.tu)(new.target, "getNetwork")(network); - if (n) { - const applicationId = defaultApplicationIds[n.name]; - if (applicationId) { - apiKey = { - applicationId: applicationId, - loadBalancer: true - }; - } - } - // If there was any issue above, we don't know this network - if (apiKey == null) { - pocket_provider_logger.throwError("unsupported network", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "network", - value: network - }); - } - } - super(network, apiKey); - } - static getApiKey(apiKey) { - // Most API Providers allow null to get the default configuration, but - // Pocket requires the network to decide the default provider, so we - // rely on hijacking the constructor to add a sensible default for us - if (apiKey == null) { - pocket_provider_logger.throwArgumentError("PocketProvider.getApiKey does not support null apiKey", "apiKey", apiKey); - } - const apiKeyObj = { - applicationId: null, - loadBalancer: false, - applicationSecretKey: null - }; - // Parse applicationId and applicationSecretKey - if (typeof (apiKey) === "string") { - apiKeyObj.applicationId = apiKey; - } - else if (apiKey.applicationSecretKey != null) { - pocket_provider_logger.assertArgument((typeof (apiKey.applicationId) === "string"), "applicationSecretKey requires an applicationId", "applicationId", apiKey.applicationId); - pocket_provider_logger.assertArgument((typeof (apiKey.applicationSecretKey) === "string"), "invalid applicationSecretKey", "applicationSecretKey", "[REDACTED]"); - apiKeyObj.applicationId = apiKey.applicationId; - apiKeyObj.applicationSecretKey = apiKey.applicationSecretKey; - apiKeyObj.loadBalancer = !!apiKey.loadBalancer; - } - else if (apiKey.applicationId) { - pocket_provider_logger.assertArgument((typeof (apiKey.applicationId) === "string"), "apiKey.applicationId must be a string", "apiKey.applicationId", apiKey.applicationId); - apiKeyObj.applicationId = apiKey.applicationId; - apiKeyObj.loadBalancer = !!apiKey.loadBalancer; - } - else { - pocket_provider_logger.throwArgumentError("unsupported PocketProvider apiKey", "apiKey", apiKey); - } - return apiKeyObj; - } - static getUrl(network, apiKey) { - let host = null; - switch (network ? network.name : "unknown") { - case "homestead": - host = "eth-mainnet.gateway.pokt.network"; - break; - case "ropsten": - host = "eth-ropsten.gateway.pokt.network"; - break; - case "rinkeby": - host = "eth-rinkeby.gateway.pokt.network"; - break; - case "goerli": - host = "eth-goerli.gateway.pokt.network"; - break; - default: - pocket_provider_logger.throwError("unsupported network", logger_lib_esm/* Logger.errors.INVALID_ARGUMENT */.Yd.errors.INVALID_ARGUMENT, { - argument: "network", - value: network - }); - } - let url = null; - if (apiKey.loadBalancer) { - url = `https:/\/${host}/v1/lb/${apiKey.applicationId}`; - } - else { - url = `https:/\/${host}/v1/${apiKey.applicationId}`; - } - const connection = { url }; - // Initialize empty headers - connection.headers = {}; - // Apply application secret key - if (apiKey.applicationSecretKey != null) { - connection.user = ""; - connection.password = apiKey.applicationSecretKey; - } - return connection; - } - isCommunityResource() { - return (this.applicationId === defaultApplicationIds[this.network.name]); - } -} -//# sourceMappingURL=pocket-provider.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/providers/lib.esm/web3-provider.js -var web3_provider = __webpack_require__(9450); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/providers/lib.esm/index.js - - - - - - - - - - - - - - - - - - - - -const providers_lib_esm_logger = new logger_lib_esm/* Logger */.Yd(lib_esm_version/* version */.i); -//////////////////////// -// Helper Functions -function getDefaultProvider(network, options) { - if (network == null) { - network = "homestead"; - } - // If passed a URL, figure out the right type of provider based on the scheme - if (typeof (network) === "string") { - // @TODO: Add support for IpcProvider; maybe if it ends in ".ipc"? - // Handle http and ws (and their secure variants) - const match = network.match(/^(ws|http)s?:/i); - if (match) { - switch (match[1]) { - case "http": - return new json_rpc_provider/* JsonRpcProvider */.r(network); - case "ws": - return new WebSocketProvider(network); - default: - providers_lib_esm_logger.throwArgumentError("unsupported URL scheme", "network", network); - } - } - } - const n = (0,networks_lib_esm/* getNetwork */.H)(network); - if (!n || !n._defaultProvider) { - providers_lib_esm_logger.throwError("unsupported getDefaultProvider network", logger_lib_esm/* Logger.errors.NETWORK_ERROR */.Yd.errors.NETWORK_ERROR, { - operation: "getDefaultProvider", - network: network - }); - } - return n._defaultProvider({ - FallbackProvider: FallbackProvider, - AlchemyProvider: AlchemyProvider, - CloudflareProvider: CloudflareProvider, - EtherscanProvider: EtherscanProvider, - InfuraProvider: InfuraProvider, - JsonRpcProvider: json_rpc_provider/* JsonRpcProvider */.r, - NodesmithProvider: NodesmithProvider, - PocketProvider: PocketProvider, - Web3Provider: web3_provider/* Web3Provider */.Q, - IpcProvider: IpcProvider, - }, options); -} -//////////////////////// -// Exports - -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/abi-coder.js + 10 modules -var abi_coder = __webpack_require__(786); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/fragments.js -var fragments = __webpack_require__(7755); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js -var abstract_coder = __webpack_require__(4364); -// EXTERNAL MODULE: ../node_modules/@ethersproject/abi/lib.esm/interface.js -var lib_esm_interface = __webpack_require__(3017); -// EXTERNAL MODULE: ../node_modules/@ethersproject/base64/lib.esm/base64.js -var base64 = __webpack_require__(6284); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/base64/lib.esm/index.js - - -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/hash/lib.esm/namehash.js -var namehash = __webpack_require__(3314); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/solidity/lib.esm/_version.js -const solidity_lib_esm_version_version = "solidity/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/solidity/lib.esm/index.js - - - - - - -const regexBytes = new RegExp("^bytes([0-9]+)$"); -const regexNumber = new RegExp("^(u?int)([0-9]*)$"); -const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); -const Zeros = "0000000000000000000000000000000000000000000000000000000000000000"; - - -const solidity_lib_esm_logger = new logger_lib_esm/* Logger */.Yd(solidity_lib_esm_version_version); -function _pack(type, value, isArray) { - switch (type) { - case "address": - if (isArray) { - return (0,bytes_lib_esm/* zeroPad */.Bu)(value, 32); - } - return (0,bytes_lib_esm/* arrayify */.lE)(value); - case "string": - return (0,utf8/* toUtf8Bytes */.Y0)(value); - case "bytes": - return (0,bytes_lib_esm/* arrayify */.lE)(value); - case "bool": - value = (value ? "0x01" : "0x00"); - if (isArray) { - return (0,bytes_lib_esm/* zeroPad */.Bu)(value, 32); - } - return (0,bytes_lib_esm/* arrayify */.lE)(value); - } - let match = type.match(regexNumber); - if (match) { - //let signed = (match[1] === "int") - let size = parseInt(match[2] || "256"); - if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) { - solidity_lib_esm_logger.throwArgumentError("invalid number type", "type", type); - } - if (isArray) { - size = 256; - } - value = bignumber/* BigNumber.from */.O$.from(value).toTwos(size); - return (0,bytes_lib_esm/* zeroPad */.Bu)(value, size / 8); - } - match = type.match(regexBytes); - if (match) { - const size = parseInt(match[1]); - if (String(size) !== match[1] || size === 0 || size > 32) { - solidity_lib_esm_logger.throwArgumentError("invalid bytes type", "type", type); - } - if ((0,bytes_lib_esm/* arrayify */.lE)(value).byteLength !== size) { - solidity_lib_esm_logger.throwArgumentError(`invalid value for ${type}`, "value", value); - } - if (isArray) { - return (0,bytes_lib_esm/* arrayify */.lE)((value + Zeros).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) { - solidity_lib_esm_logger.throwArgumentError(`invalid array length for ${type}`, "value", value); - } - const result = []; - value.forEach(function (value) { - result.push(_pack(baseType, value, true)); - }); - return (0,bytes_lib_esm/* concat */.zo)(result); - } - return solidity_lib_esm_logger.throwArgumentError("invalid type", "type", type); -} -// @TODO: Array Enum -function pack(types, values) { - if (types.length != values.length) { - solidity_lib_esm_logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); - } - const tight = []; - types.forEach(function (type, index) { - tight.push(_pack(type, values[index])); - }); - return (0,bytes_lib_esm/* hexlify */.Dv)((0,bytes_lib_esm/* concat */.zo)(tight)); -} -function keccak256(types, values) { - return (0,keccak256_lib_esm/* keccak256 */.w)(pack(types, values)); -} -function sha256(types, values) { - return (0,sha2/* sha256 */.JQ)(pack(types, values)); -} -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ../node_modules/@ethersproject/rlp/lib.esm/index.js + 1 modules -var rlp_lib_esm = __webpack_require__(6868); -// EXTERNAL MODULE: ../node_modules/@ethersproject/strings/lib.esm/idna.js -var idna = __webpack_require__(592); -;// CONCATENATED MODULE: ../node_modules/@ethersproject/strings/lib.esm/bytes32.js - - - - -function formatBytes32String(text) { - // Get the bytes - const bytes = (0,utf8/* toUtf8Bytes */.Y0)(text); - // Check we have room for null-termination - if (bytes.length > 31) { - throw new Error("bytes32 string must be less than 32 bytes"); - } - // Zero-pad (implicitly null-terminates) - return (0,bytes_lib_esm/* hexlify */.Dv)((0,bytes_lib_esm/* concat */.zo)([bytes, hashes/* HashZero */.R]).slice(0, 32)); -} -function parseBytes32String(bytes) { - const data = (0,bytes_lib_esm/* arrayify */.lE)(bytes); - // Must be 32 bytes with a null-termination - if (data.length !== 32) { - throw new Error("invalid bytes32 - not 32 bytes long"); - } - if (data[31] !== 0) { - throw new Error("invalid bytes32 string - no null terminator"); - } - // Find the null termination - let length = 31; - while (data[length - 1] === 0) { - length--; - } - // Determine the string value - return (0,utf8/* toUtf8String */.ZN)(data.slice(0, length)); -} -//# sourceMappingURL=bytes32.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/units/lib.esm/_version.js -const units_lib_esm_version_version = "units/5.5.0"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/@ethersproject/units/lib.esm/index.js - - - - -const units_lib_esm_logger = new logger_lib_esm/* Logger */.Yd(units_lib_esm_version_version); -const names = [ - "wei", - "kwei", - "mwei", - "gwei", - "szabo", - "finney", - "ether", -]; -// Some environments have issues with RegEx that contain back-tracking, so we cannot -// use them. -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 === "-.") { - units_lib_esm_logger.throwArgumentError("invalid value", "value", value); - } - // Make sure we have at least one whole digit (0 if none) - let whole = comps[0]; - let negative = ""; - if (whole.substring(0, 1) === "-") { - negative = "-"; - whole = whole.substring(1); - } - // Make sure we have at least 1 whole digit with no leading zeros - 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") { - units_lib_esm_logger.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); -} -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ../node_modules/ethers/lib.esm/utils.js - - - - - - - - - - - - - - - - - - - - - - -//////////////////////// -// Enums - - -//////////////////////// -// Exports - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ../node_modules/ethers/lib.esm/_version.js -const ethers_lib_esm_version_version = "ethers/5.5.4"; -//# sourceMappingURL=_version.js.map -;// CONCATENATED MODULE: ../node_modules/ethers/lib.esm/ethers.js - - - - - - - - - - - -//////////////////////// -// Compile-Time Constants -// This is generated by "npm run dist" - -const ethers_logger = new logger_lib_esm/* Logger */.Yd(ethers_lib_esm_version_version); -//////////////////////// -// Exports - -//# sourceMappingURL=ethers.js.map -;// CONCATENATED MODULE: ../node_modules/ethers/lib.esm/index.js - -// To modify this file, you must update ./misc/admin/lib/cmds/update-exports.js - -try { - const anyGlobal = window; - if (anyGlobal._ethers == null) { - anyGlobal._ethers = ethers_namespaceObject; - } -} -catch (error) { } - - -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 5294: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var hash = exports; - -hash.utils = __webpack_require__(8626); -hash.common = __webpack_require__(8717); -hash.sha = __webpack_require__(2589); -hash.ripemd = __webpack_require__(8494); -hash.hmac = __webpack_require__(2750); - -// Proxy hash functions to the main object -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; - - -/***/ }), - -/***/ 8717: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var assert = __webpack_require__(7859); - -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; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, 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()); - assert(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] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - 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) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - - -/***/ }), - -/***/ 2750: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var assert = __webpack_require__(7859); - -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)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - - -/***/ }), - -/***/ 8494: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var common = __webpack_require__(8717); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(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( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(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 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 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 -]; - - -/***/ }), - -/***/ 2589: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -exports.sha1 = __webpack_require__(9330); -exports.sha224 = __webpack_require__(5168); -exports.sha256 = __webpack_require__(375); -exports.sha384 = __webpack_require__(8899); -exports.sha512 = __webpack_require__(790); - - -/***/ }), - -/***/ 9330: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var common = __webpack_require__(8717); -var shaCommon = __webpack_require__(8156); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_5 = utils.sum32_5; -var ft_1 = shaCommon.ft_1; -var BlockHash = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -module.exports = 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(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 s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - - -/***/ }), - -/***/ 5168: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var SHA256 = __webpack_require__(375); - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, SHA256); -module.exports = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - - - -/***/ }), - -/***/ 375: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var common = __webpack_require__(8717); -var shaCommon = __webpack_require__(8156); -var assert = __webpack_require__(7859); - -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var ch32 = shaCommon.ch32; -var maj32 = shaCommon.maj32; -var s0_256 = shaCommon.s0_256; -var s1_256 = shaCommon.s1_256; -var g0_256 = shaCommon.g0_256; -var g1_256 = shaCommon.g1_256; - -var BlockHash = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash); -module.exports = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.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] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(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 f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - assert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - - -/***/ }), - -/***/ 8899: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); - -var SHA512 = __webpack_require__(790); - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, SHA512); -module.exports = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - - -/***/ }), - -/***/ 790: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var common = __webpack_require__(8717); -var assert = __webpack_require__(7859); - -var rotr64_hi = utils.rotr64_hi; -var rotr64_lo = utils.rotr64_lo; -var shr64_hi = utils.shr64_hi; -var shr64_lo = utils.shr64_lo; -var sum64 = utils.sum64; -var sum64_hi = utils.sum64_hi; -var sum64_lo = utils.sum64_lo; -var sum64_4_hi = utils.sum64_4_hi; -var sum64_4_lo = utils.sum64_4_lo; -var sum64_5_hi = utils.sum64_5_hi; -var sum64_5_lo = utils.sum64_5_lo; - -var BlockHash = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash); -module.exports = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - 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]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(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]; - - assert(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, gl); - 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( - 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( - 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, cl); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64(this.h, 0, ah, al); - sum64(this.h, 2, bh, bl); - sum64(this.h, 4, ch, cl); - sum64(this.h, 6, dh, dl); - sum64(this.h, 8, eh, el); - sum64(this.h, 10, fh, fl); - sum64(this.h, 12, gh, gl); - sum64(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(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 r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28); - var c1_hi = rotr64_hi(xl, xh, 2); // 34 - var c2_hi = rotr64_hi(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28); - var c1_lo = rotr64_lo(xl, xh, 2); // 34 - var c2_lo = rotr64_lo(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14); - var c1_hi = rotr64_hi(xh, xl, 18); - var c2_hi = rotr64_hi(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14); - var c1_lo = rotr64_lo(xh, xl, 18); - var c2_lo = rotr64_lo(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1); - var c1_hi = rotr64_hi(xh, xl, 8); - var c2_hi = shr64_hi(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1); - var c1_lo = rotr64_lo(xh, xl, 8); - var c2_lo = shr64_lo(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19); - var c1_hi = rotr64_hi(xl, xh, 29); // 61 - var c2_hi = shr64_hi(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19); - var c1_lo = rotr64_lo(xl, xh, 29); // 61 - var c2_lo = shr64_lo(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - - -/***/ }), - -/***/ 8156: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(8626); -var rotr32 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -exports.ft_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -exports.ch32 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -exports.maj32 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -exports.p32 = p32; - -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} -exports.s0_256 = s0_256; - -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} -exports.s1_256 = s1_256; - -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} -exports.g0_256 = g0_256; - -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); -} -exports.g1_256 = g1_256; - - -/***/ }), - -/***/ 8626: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var assert = __webpack_require__(7859); -var inherits = __webpack_require__(87); - -exports.inherits = inherits; - -function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { - return false; - } - if (i < 0 || i + 1 >= msg.length) { - return false; - } - return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; -} - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - // Inspired by stringToUtf8ByteArray() in closure-library by Google - // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 - // Apache License 2.0 - // https://github.com/google/closure-library/blob/master/LICENSE - 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 = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); - 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; -} -exports.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -exports.toHex = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -exports.htonl = 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; -} -exports.toHex32 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -exports.zero2 = 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; -} -exports.zero8 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - assert(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; -} -exports.join32 = 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) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -exports.split32 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -exports.rotr32 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -exports.rotl32 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -exports.sum32 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -exports.sum32_3 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -exports.sum32_4 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -exports.sum32_5 = 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; -} -exports.sum64 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -exports.sum64_hi = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -exports.sum64_lo = 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; -} -exports.sum64_4_hi = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -exports.sum64_4_lo = 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; -} -exports.sum64_5_hi = 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; -} -exports.sum64_5_lo = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -exports.rotr64_hi = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.rotr64_lo = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -exports.shr64_hi = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.shr64_lo = shr64_lo; - - -/***/ }), - -/***/ 8898: -/***/ ((__unused_webpack_module, exports) => { - -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - - -/***/ }), - -/***/ 87: -/***/ ((module) => { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - 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 { - // old school shim for old browsers - 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 - } - } -} - - -/***/ }), - -/***/ 9331: -/***/ ((module) => { - -"use strict"; - - -const word = '[a-fA-F\\d:]'; -const b = options => options && options.includeBoundaries ? - `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` : - ''; - -const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}'; - -const v6seg = '[a-fA-F\\d]{1,4}'; -const v6 = ` -(?: -(?:${v6seg}:){7}(?:${v6seg}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 -(?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 -(?:${v6seg}:){5}(?::${v4}|(?::${v6seg}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 -(?:${v6seg}:){4}(?:(?::${v6seg}){0,1}:${v4}|(?::${v6seg}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 -(?:${v6seg}:){3}(?:(?::${v6seg}){0,2}:${v4}|(?::${v6seg}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 -(?:${v6seg}:){2}(?:(?::${v6seg}){0,3}:${v4}|(?::${v6seg}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 -(?:${v6seg}:){1}(?:(?::${v6seg}){0,4}:${v4}|(?::${v6seg}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 -(?::(?:(?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 -)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 -`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim(); - -// Pre-compile only the exact regexes because adding a global flag make regexes stateful -const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`); -const v4exact = new RegExp(`^${v4}$`); -const v6exact = new RegExp(`^${v6}$`); - -const ip = options => options && options.exact ? - v46Exact : - new RegExp(`(?:${b(options)}${v4}${b(options)})|(?:${b(options)}${v6}${b(options)})`, 'g'); - -ip.v4 = options => options && options.exact ? v4exact : new RegExp(`${b(options)}${v4}${b(options)}`, 'g'); -ip.v6 = options => options && options.exact ? v6exact : new RegExp(`${b(options)}${v6}${b(options)}`, 'g'); - -module.exports = ip; - - -/***/ }), - -/***/ 1823: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -const isElectron = __webpack_require__(3571) - -const IS_ENV_WITH_DOM = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9 -// @ts-ignore -const IS_ELECTRON = isElectron() -const IS_BROWSER = IS_ENV_WITH_DOM && !IS_ELECTRON -const IS_ELECTRON_MAIN = IS_ELECTRON && !IS_ENV_WITH_DOM -const IS_ELECTRON_RENDERER = IS_ELECTRON && IS_ENV_WITH_DOM -const IS_NODE = true && typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !IS_ELECTRON -// @ts-ignore - we either ignore worker scope or dom scope -const IS_WEBWORKER = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope -const IS_TEST = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env.NODE_ENV === 'test' -const IS_REACT_NATIVE = typeof navigator !== 'undefined' && navigator.product === 'ReactNative' - -module.exports = { - isTest: IS_TEST, - isElectron: IS_ELECTRON, - isElectronMain: IS_ELECTRON_MAIN, - isElectronRenderer: IS_ELECTRON_RENDERER, - isNode: IS_NODE, - /** - * Detects browser main thread **NOT** web worker or service worker - */ - isBrowser: IS_BROWSER, - isWebWorker: IS_WEBWORKER, - isEnvWithDom: IS_ENV_WITH_DOM, - isReactNative: IS_REACT_NATIVE -} - - -/***/ }), - -/***/ 4745: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const { isElectronMain } = __webpack_require__(1823) - -if (isElectronMain) { - module.exports = __webpack_require__(3034) -} else { -// use window.fetch if it is available, fall back to node-fetch if not - module.exports = __webpack_require__(6487) -} - - -/***/ }), - -/***/ 6417: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const HTTP = __webpack_require__(2722) - -/** - * - * @param {string} url - * @param {import("../types").HTTPOptions} [options] - * @returns {{ path: string; content?: AsyncIterable }} - */ -const urlSource = (url, options) => { - return { - path: decodeURIComponent(new URL(url).pathname.split('/').pop() || ''), - content: readURLContent(url, options) - } -} - -/** - * - * @param {string} url - * @param {import("../types").HTTPOptions} [options] - * @returns {AsyncIterable} - */ -async function * readURLContent (url, options) { - const http = new HTTP() - const response = await http.get(url, options) - - yield * response.iterator() -} - -module.exports = urlSource - - -/***/ }), - -/***/ 2722: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* eslint-disable no-undef */ - - -const { fetch, Request, Headers } = __webpack_require__(341) -const { TimeoutError, HTTPError } = __webpack_require__(5348) -const merge = (__webpack_require__(3224).bind)({ ignoreUndefined: true }) -const { URL, URLSearchParams } = __webpack_require__(4698) -const anySignal = __webpack_require__(1659) - -/** - * @typedef {import('stream').Readable} NodeReadableStream - * @typedef {import('./types').HTTPOptions} HTTPOptions - * @typedef {import('./types').ExtendedResponse} ExtendedResponse - */ - -/** - * @template TResponse - * @param {Promise} promise - * @param {number | undefined} ms - * @param {AbortController} abortController - * @returns {Promise} - */ -const timeout = (promise, ms, abortController) => { - if (ms === undefined) { - return promise - } - - const start = Date.now() - - const timedOut = () => { - const time = Date.now() - start - - return time >= ms - } - - return new Promise((resolve, reject) => { - const timeoutID = setTimeout(() => { - if (timedOut()) { - reject(new TimeoutError()) - abortController.abort() - } - }, ms) - - /** - * @param {(value: any) => void } next - */ - const after = (next) => { - /** - * @param {any} res - */ - const fn = (res) => { - clearTimeout(timeoutID) - - if (timedOut()) { - reject(new TimeoutError()) - return - } - - next(res) - } - return fn - } - - promise - .then(after(resolve), after(reject)) - }) -} - -const defaults = { - throwHttpErrors: true, - credentials: 'same-origin' -} - -class HTTP { - /** - * - * @param {HTTPOptions} options - */ - constructor (options = {}) { - /** @type {HTTPOptions} */ - this.opts = merge(defaults, options) - } - - /** - * Fetch - * - * @param {string | Request} resource - * @param {HTTPOptions} options - * @returns {Promise} - */ - async fetch (resource, options = {}) { - /** @type {HTTPOptions} */ - const opts = merge(this.opts, options) - const headers = new Headers(opts.headers) - - // validate resource type - if (typeof resource !== 'string' && !(resource instanceof URL || resource instanceof Request)) { - throw new TypeError('`resource` must be a string, URL, or Request') - } - - const url = new URL(resource.toString(), opts.base) - - const { - searchParams, - transformSearchParams, - json - } = opts - - if (searchParams) { - if (typeof transformSearchParams === 'function') { - // @ts-ignore - url.search = transformSearchParams(new URLSearchParams(opts.searchParams)) - } else { - // @ts-ignore - url.search = new URLSearchParams(opts.searchParams) - } - } - - if (json) { - opts.body = JSON.stringify(opts.json) - headers.set('content-type', 'application/json') - } - - const abortController = new AbortController() - // @ts-ignore - const signal = anySignal([abortController.signal, opts.signal]) - - const response = await timeout( - fetch( - url.toString(), - { - ...opts, - signal, - timeout: undefined, - headers - } - ), - opts.timeout, - abortController - ) - - if (!response.ok && opts.throwHttpErrors) { - if (opts.handleError) { - await opts.handleError(response) - } - throw new HTTPError(response) - } - - response.iterator = function () { - return fromStream(response.body) - } - - response.ndjson = async function * () { - for await (const chunk of ndjson(response.iterator())) { - if (options.transform) { - yield options.transform(chunk) - } else { - yield chunk - } - } - } - - return response - } - - /** - * @param {string | Request} resource - * @param {HTTPOptions} options - */ - post (resource, options = {}) { - return this.fetch(resource, { ...options, method: 'POST' }) - } - - /** - * @param {string | Request} resource - * @param {HTTPOptions} options - */ - get (resource, options = {}) { - return this.fetch(resource, { ...options, method: 'GET' }) - } - - /** - * @param {string | Request} resource - * @param {HTTPOptions} options - */ - put (resource, options = {}) { - return this.fetch(resource, { ...options, method: 'PUT' }) - } - - /** - * @param {string | Request} resource - * @param {HTTPOptions} options - */ - delete (resource, options = {}) { - return this.fetch(resource, { ...options, method: 'DELETE' }) - } - - /** - * @param {string | Request} resource - * @param {HTTPOptions} options - */ - options (resource, options = {}) { - return this.fetch(resource, { ...options, method: 'OPTIONS' }) - } -} - -/** - * Parses NDJSON chunks from an iterator - * - * @param {AsyncIterable} source - * @returns {AsyncIterable} - */ -const ndjson = async function * (source) { - const decoder = new TextDecoder() - let buf = '' - - for await (const chunk of source) { - buf += decoder.decode(chunk, { stream: true }) - const lines = buf.split(/\r?\n/) - - for (let i = 0; i < lines.length - 1; i++) { - const l = lines[i].trim() - if (l.length > 0) { - yield JSON.parse(l) - } - } - buf = lines[lines.length - 1] - } - buf += decoder.decode() - buf = buf.trim() - if (buf.length !== 0) { - yield JSON.parse(buf) - } -} - -/** - * Stream to AsyncIterable - * - * @template TChunk - * @param {ReadableStream | NodeReadableStream | null} source - * @returns {AsyncIterable} - */ -const fromStream = (source) => { - // Workaround for https://github.com/node-fetch/node-fetch/issues/766 - if (isNodeReadableStream(source)) { - const iter = source[Symbol.asyncIterator]() - return { - [Symbol.asyncIterator] () { - return { - next: iter.next.bind(iter), - return (value) { - source.destroy() - if (typeof iter.return === 'function') { - return iter.return() - } - return Promise.resolve({ done: true, value }) - } - } - } - } - } - - if (isWebReadableStream(source)) { - const reader = source.getReader() - return (async function * () { - try { - while (true) { - // Read from the stream - const { done, value } = await reader.read() - // Exit if we're done - if (done) return - // Else yield the chunk - if (value) { - yield value - } - } - } finally { - reader.releaseLock() - } - })() - } - - if (isAsyncIterable(source)) { - return source - } - - throw new TypeError('Body can\'t be converted to AsyncIterable') -} - -/** - * Check if it's an AsyncIterable - * - * @template {unknown} TChunk - * @template {any} Other - * @param {Other|AsyncIterable} value - * @returns {value is AsyncIterable} - */ -const isAsyncIterable = (value) => { - return typeof value === 'object' && - value !== null && - typeof /** @type {any} */(value)[Symbol.asyncIterator] === 'function' -} - -/** - * Check for web readable stream - * - * @template {unknown} TChunk - * @template {any} Other - * @param {Other|ReadableStream} value - * @returns {value is ReadableStream} - */ -const isWebReadableStream = (value) => { - return value && typeof /** @type {any} */(value).getReader === 'function' -} - -/** - * @param {any} value - * @returns {value is NodeReadableStream} - */ -const isNodeReadableStream = (value) => - Object.prototype.hasOwnProperty.call(value, 'readable') && - Object.prototype.hasOwnProperty.call(value, 'writable') - -HTTP.HTTPError = HTTPError -HTTP.TimeoutError = TimeoutError -HTTP.streamToAsyncIterator = fromStream - -/** - * @param {string | Request} resource - * @param {HTTPOptions} [options] - */ -HTTP.post = (resource, options) => new HTTP(options).post(resource, options) - -/** - * @param {string | Request} resource - * @param {HTTPOptions} [options] - */ -HTTP.get = (resource, options) => new HTTP(options).get(resource, options) - -/** - * @param {string | Request} resource - * @param {HTTPOptions} [options] - */ -HTTP.put = (resource, options) => new HTTP(options).put(resource, options) - -/** - * @param {string | Request} resource - * @param {HTTPOptions} [options] - */ -HTTP.delete = (resource, options) => new HTTP(options).delete(resource, options) - -/** - * @param {string | Request} resource - * @param {HTTPOptions} [options] - */ -HTTP.options = (resource, options) => new HTTP(options).options(resource, options) - -module.exports = HTTP - - -/***/ }), - -/***/ 5348: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -class TimeoutError extends Error { - constructor (message = 'Request timed out') { - super(message) - this.name = 'TimeoutError' - } -} -exports.TimeoutError = TimeoutError - -class AbortError extends Error { - constructor (message = 'The operation was aborted.') { - super(message) - this.name = 'AbortError' - } -} -exports.AbortError = AbortError - -class HTTPError extends Error { - /** - * @param {Response} response - */ - constructor (response) { - super(response.statusText) - this.name = 'HTTPError' - this.response = response - } -} -exports.HTTPError = HTTPError - - -/***/ }), - -/***/ 341: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const { TimeoutError, AbortError } = __webpack_require__(5348) -const { Response, Request, Headers, default: fetch } = __webpack_require__(4745) - -/** - * @typedef {import('../types').FetchOptions} FetchOptions - * @typedef {import('../types').ProgressFn} ProgressFn - */ - -/** - * Fetch with progress - * - * @param {string | Request} url - * @param {FetchOptions} [options] - * @returns {Promise} - */ -const fetchWithProgress = (url, options = {}) => { - const request = new XMLHttpRequest() - request.open(options.method || 'GET', url.toString(), true) - - const { timeout, headers } = options - - if (timeout && timeout > 0 && timeout < Infinity) { - request.timeout = timeout - } - - if (options.overrideMimeType != null) { - request.overrideMimeType(options.overrideMimeType) - } - - if (headers) { - for (const [name, value] of new Headers(headers)) { - request.setRequestHeader(name, value) - } - } - - if (options.signal) { - options.signal.onabort = () => request.abort() - } - - if (options.onUploadProgress) { - request.upload.onprogress = options.onUploadProgress - } - - // Note: Need to use `arraybuffer` here instead of `blob` because `Blob` - // instances coming from JSDOM are not compatible with `Response` from - // node-fetch (which is the setup we get when testing with jest because - // it uses JSDOM which does not provide a global fetch - // https://github.com/jsdom/jsdom/issues/1724) - request.responseType = 'arraybuffer' - - return new Promise((resolve, reject) => { - /** - * @param {Event} event - */ - const handleEvent = (event) => { - switch (event.type) { - case 'error': { - resolve(Response.error()) - break - } - case 'load': { - resolve( - new ResponseWithURL(request.responseURL, request.response, { - status: request.status, - statusText: request.statusText, - headers: parseHeaders(request.getAllResponseHeaders()) - }) - ) - break - } - case 'timeout': { - reject(new TimeoutError()) - break - } - case 'abort': { - reject(new AbortError()) - break - } - default: { - break - } - } - } - request.onerror = handleEvent - request.onload = handleEvent - request.ontimeout = handleEvent - request.onabort = handleEvent - - // @ts-expect-error options.body can be a node readable stream, which isn't compatible with XHR, but this - // file is a browser override so you won't get a node readable stream so ignore the error - request.send(options.body) - }) -} - -const fetchWithStreaming = fetch - -/** - * @param {string | Request} url - * @param {FetchOptions} options - */ -const fetchWith = (url, options = {}) => - (options.onUploadProgress != null) - ? fetchWithProgress(url, options) - : fetchWithStreaming(url, options) - -/** - * Parse Headers from a XMLHttpRequest - * - * @param {string} input - * @returns {Headers} - */ -const parseHeaders = (input) => { - const headers = new Headers() - for (const line of input.trim().split(/[\r\n]+/)) { - const index = line.indexOf(': ') - if (index > 0) { - headers.set(line.slice(0, index), line.slice(index + 1)) - } - } - - return headers -} - -class ResponseWithURL extends Response { - /** - * @param {string} url - * @param {BodyInit} body - * @param {ResponseInit} options - */ - constructor (url, body, options) { - super(body, options) - Object.defineProperty(this, 'url', { value: url }) - } -} - -module.exports = { - fetch: fetchWith, - Request, - Headers -} - - -/***/ }), - -/***/ 3571: -/***/ ((module) => { - -// https://github.com/electron/electron/issues/2288 -function isElectron() { - // Renderer process - if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') { - return true; - } - - // Main process - if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) { - return true; - } - - // Detect the user agent when the `nodeIntegration` option is set to false - if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) { - return true; - } - - return false; -} - -module.exports = isElectron; - - -/***/ }), - -/***/ 2478: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -const ipRegex = __webpack_require__(9331); - -const isIp = string => ipRegex({exact: true}).test(string); -isIp.v4 = string => ipRegex.v4({exact: true}).test(string); -isIp.v6 = string => ipRegex.v6({exact: true}).test(string); -isIp.version = string => isIp(string) ? (isIp.v4(string) ? 4 : 6) : undefined; - -module.exports = isIp; - - -/***/ }), - -/***/ 7760: -/***/ ((module) => { - -"use strict"; - - -module.exports = value => { - if (Object.prototype.toString.call(value) !== '[object Object]') { - return false; - } - - const prototype = Object.getPrototypeOf(value); - return prototype === null || prototype === Object.prototype; -}; - - -/***/ }), - -/***/ 4698: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const { - URLWithLegacySupport, - format, - URLSearchParams, - defaultBase -} = __webpack_require__(5053) -const relative = __webpack_require__(5784) - -module.exports = { - URL: URLWithLegacySupport, - URLSearchParams, - format, - relative, - defaultBase -} - - -/***/ }), - -/***/ 5784: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const { URLWithLegacySupport, format } = __webpack_require__(5053) - -/** - * @param {string | undefined} url - * @param {any} [location] - * @param {any} [protocolMap] - * @param {any} [defaultProtocol] - */ -module.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => { - let protocol = location.protocol - ? location.protocol.replace(':', '') - : 'http' - - // Check protocol map - protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':' - let urlParsed - - try { - urlParsed = new URLWithLegacySupport(url) - } catch (err) { - urlParsed = {} - } - - const base = Object.assign({}, location, { - protocol: protocol || urlParsed.protocol, - host: location.host || urlParsed.host - }) - - return new URLWithLegacySupport(url, format(base)).toString() -} - - -/***/ }), - -/***/ 5053: -/***/ ((module) => { - -"use strict"; - - -const isReactNative = - typeof navigator !== 'undefined' && - navigator.product === 'ReactNative' - -function getDefaultBase () { - if (isReactNative) { - return 'http://localhost' - } - // in some environments i.e. cloudflare workers location is not available - if (!self.location) { - return '' - } - - return self.location.protocol + '//' + self.location.host -} - -const URL = self.URL -const defaultBase = getDefaultBase() - -class URLWithLegacySupport { - constructor (url = '', base = defaultBase) { - this.super = new URL(url, base) - this.path = this.pathname + this.search - this.auth = - this.username && this.password - ? this.username + ':' + this.password - : null - - this.query = - this.search && this.search.startsWith('?') - ? this.search.slice(1) - : null - } - - get hash () { - return this.super.hash - } - - get host () { - return this.super.host - } - - get hostname () { - return this.super.hostname - } - - get href () { - return this.super.href - } - - get origin () { - return this.super.origin - } - - get password () { - return this.super.password - } - - get pathname () { - return this.super.pathname - } - - get port () { - return this.super.port - } - - get protocol () { - return this.super.protocol - } - - get search () { - return this.super.search - } - - get searchParams () { - return this.super.searchParams - } - - get username () { - return this.super.username - } - - set hash (hash) { - this.super.hash = hash - } - - set host (host) { - this.super.host = host - } - - set hostname (hostname) { - this.super.hostname = hostname - } - - set href (href) { - this.super.href = href - } - - set password (password) { - this.super.password = password - } - - set pathname (pathname) { - this.super.pathname = pathname - } - - set port (port) { - this.super.port = port - } - - set protocol (protocol) { - this.super.protocol = protocol - } - - set search (search) { - this.super.search = search - } - - set username (username) { - this.super.username = username - } - - /** - * @param {any} o - */ - static createObjectURL (o) { - return URL.createObjectURL(o) - } - - /** - * @param {string} o - */ - static revokeObjectURL (o) { - URL.revokeObjectURL(o) - } - - toJSON () { - return this.super.toJSON() - } - - toString () { - return this.super.toString() - } - - format () { - return this.toString() - } -} - -/** - * @param {string | import('url').UrlObject} obj - */ -function format (obj) { - if (typeof obj === 'string') { - const url = new URL(obj) - - return url.toString() - } - - if (!(obj instanceof URL)) { - const userPass = - // @ts-ignore its not supported in node but we normalise - obj.username && obj.password - // @ts-ignore its not supported in node but we normalise - ? `${obj.username}:${obj.password}@` - : '' - const auth = obj.auth ? obj.auth + '@' : '' - const port = obj.port ? ':' + obj.port : '' - const protocol = obj.protocol ? obj.protocol + '//' : '' - const host = obj.host || '' - const hostname = obj.hostname || '' - const search = obj.search || (obj.query ? '?' + obj.query : '') - const hash = obj.hash || '' - const pathname = obj.pathname || '' - // @ts-ignore - path is not supported in node but we normalise - const path = obj.path || pathname + search - - return `${protocol}${userPass || auth}${ - host || hostname + port - }${path}${hash}` - } -} - -module.exports = { - URLWithLegacySupport, - URLSearchParams: self.URLSearchParams, - defaultBase, - format -} - - -/***/ }), - -/***/ 1251: -/***/ ((module) => { - -"use strict"; - - -/** - * Collects all values from an (async) iterable into an array and returns it. - * - * @template T - * @param {AsyncIterable|Iterable} source - */ -const all = async (source) => { - const arr = [] - - for await (const entry of source) { - arr.push(entry) - } - - return arr -} - -module.exports = all - - -/***/ }), - -/***/ 6843: -/***/ ((module) => { - -"use strict"; - - -/** - * Returns the first result from an (async) iterable, unless empty, in which - * case returns `undefined`. - * - * @template T - * @param {AsyncIterable|Iterable} source - */ -const first = async (source) => { - for await (const entry of source) { // eslint-disable-line no-unreachable-loop - return entry - } - - return undefined -} - -module.exports = first - - -/***/ }), - -/***/ 1215: -/***/ ((module) => { - -"use strict"; - - -/** - * Returns the last item of an (async) iterable, unless empty, in which case - * return `undefined`. - * - * @template T - * @param {AsyncIterable|Iterable} source - */ -const last = async (source) => { - let res - - for await (const entry of source) { - res = entry - } - - return res -} - -module.exports = last - - -/***/ }), - -/***/ 8731: -/***/ ((module) => { - -"use strict"; - - -/** - * Takes an (async) iterable and returns one with each item mapped by the passed - * function. - * - * @template I,O - * @param {AsyncIterable|Iterable} source - * @param {function(I):O|Promise} func - * @returns {AsyncIterable} - */ -const map = async function * (source, func) { - for await (const val of source) { - yield func(val) - } -} - -module.exports = map - - -/***/ }), - -/***/ 3506: -/***/ ((module) => { - -"use strict"; - - -/** - * @template T - * @typedef {Object} Peek - * @property {() => IteratorResult} peek - */ - -/** - * @template T - * @typedef {Object} AsyncPeek - * @property {() => Promise>} peek - */ - -/** - * @template T - * @typedef {Object} Push - * @property {(value:T) => void} push - */ - -/** - * @template T - * @typedef {Iterable & Peek & Push & Iterator} Peekable - */ - -/** - * @template T - * @typedef {AsyncIterable & AsyncPeek & Push & AsyncIterator} AsyncPeekable - */ - -/** - * @template {Iterable | AsyncIterable} I - * @param {I} iterable - * @returns {I extends Iterable - * ? Peekable - * : I extends AsyncIterable - * ? AsyncPeekable - * : never - * } - */ -function peekableIterator (iterable) { - // @ts-ignore - const [iterator, symbol] = iterable[Symbol.asyncIterator] - // @ts-ignore - ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator] - // @ts-ignore - : [iterable[Symbol.iterator](), Symbol.iterator] - - /** @type {any[]} */ - const queue = [] - - // @ts-ignore - return { - peek: () => { - return iterator.next() - }, - push: (value) => { - queue.push(value) - }, - next: () => { - if (queue.length) { - return { - done: false, - value: queue.shift() - } - } - - return iterator.next() - }, - [symbol] () { - return this - } - } -} - -module.exports = peekableIterator - - -/***/ }), - -/***/ 338: -/***/ ((module, exports, __webpack_require__) => { - -var __WEBPACK_AMD_DEFINE_RESULT__;/** - * [js-sha3]{@link https://github.com/emn178/js-sha3} - * - * @version 0.8.0 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2015-2018 - * @license MIT - */ -/*jslint bitwise: true */ -(function () { - 'use strict'; - - 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 = __webpack_require__.g; - } else if (WEB_WORKER) { - root = self; - } - var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && "object" === 'object' && module.exports; - var AMD = true && __webpack_require__.amdO; - 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 (bits, padding, outputType) { - return function (message) { - return new Keccak(bits, padding, bits).update(message)[outputType](); - }; - }; - - var createShakeOutputMethod = function (bits, padding, outputType) { - return function (message, outputBits) { - return new Keccak(bits, padding, outputBits).update(message)[outputType](); - }; - }; - - var createCshakeOutputMethod = function (bits, padding, outputType) { - return function (message, outputBits, n, s) { - return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); - }; - }; - - var createKmacOutputMethod = function (bits, padding, outputType) { - return function (key, message, outputBits, s) { - return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); - }; - }; - - var createOutputMethods = function (method, createMethod, bits, padding) { - for (var i = 0; i < OUTPUT_TYPES.length; ++i) { - var type = OUTPUT_TYPES[i]; - method[type] = createMethod(bits, padding, type); - } - return method; - }; - - var createMethod = function (bits, padding) { - var method = createOutputMethod(bits, padding, 'hex'); - method.create = function () { - return new Keccak(bits, padding, bits); - }; - method.update = function (message) { - return method.create().update(message); - }; - return createOutputMethods(method, createOutputMethod, bits, padding); - }; - - var createShakeMethod = function (bits, padding) { - var method = createShakeOutputMethod(bits, padding, 'hex'); - method.create = function (outputBits) { - return new Keccak(bits, padding, outputBits); - }; - method.update = function (message, outputBits) { - return method.create(outputBits).update(message); - }; - return createOutputMethods(method, createShakeOutputMethod, bits, padding); - }; - - var createCshakeMethod = function (bits, padding) { - var w = CSHAKE_BYTEPAD[bits]; - var method = createCshakeOutputMethod(bits, padding, 'hex'); - method.create = function (outputBits, n, s) { - if (!n && !s) { - return methods['shake' + bits].create(outputBits); - } else { - return new Keccak(bits, 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, bits, padding); - }; - - var createKmacMethod = function (bits, padding) { - var w = CSHAKE_BYTEPAD[bits]; - var method = createKmacOutputMethod(bits, padding, 'hex'); - method.create = function (key, outputBits, s) { - return new Kmac(bits, 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, bits, padding); - }; - - var algorithms = [ - { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, - { name: 'sha3', padding: PADDING, bits: BITS, createMethod: 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(bits, 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 - (bits << 1)) >> 5; - this.byteCount = this.blockCount << 2; - this.outputBlocks = outputBits >> 5; - this.extraBytes = (outputBits & 31) >> 3; - - for (var i = 0; i < 50; ++i) { - this.s[i] = 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, i, code; - - while (index < length) { - if (this.reset) { - this.reset = false; - blocks[0] = this.block; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - if (notString) { - for (i = this.start; index < length && i < byteCount; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; - } - } else { - for (i = this.start; index < length && i < byteCount; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else { - code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - } - } - this.lastByteIndex = i; - if (i >= byteCount) { - this.start = i - byteCount; - this.block = blocks[blockCount]; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - this.reset = true; - } else { - this.start = i; - } - } - 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 i = 0; i < str.length; ++i) { - var code = str.charCodeAt(i); - if (code < 0x80) { - bytes += 1; - } else if (code < 0x800) { - bytes += 2; - } else if (code < 0xd800 || code >= 0xe000) { - bytes += 3; - } else { - code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); - 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 i = 0; i < strs.length; ++i) { - bytes += this.encodeString(strs[i]); - } - 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, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; - blocks[i >> 2] |= this.padding[i & 3]; - if (this.lastByteIndex === this.byteCount) { - blocks[0] = blocks[blockCount]; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - blocks[blockCount - 1] |= 0x80000000; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - }; - - Keccak.prototype.toString = Keccak.prototype.hex = function () { - this.finalize(); - - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, - extraBytes = this.extraBytes, i = 0, j = 0; - var hex = '', block; - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - block = s[i]; - hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + - HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + - HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + - HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; - } - if (j % blockCount === 0) { - f(s); - i = 0; - } - } - if (extraBytes) { - block = s[i]; - hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; - if (extraBytes > 1) { - hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; - } - if (extraBytes > 2) { - hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; - } - } - return hex; - }; - - Keccak.prototype.arrayBuffer = function () { - this.finalize(); - - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, - extraBytes = this.extraBytes, i = 0, j = 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 (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - array[j] = s[i]; - } - if (j % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - array[i] = s[i]; - 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, i = 0, j = 0; - var array = [], offset, block; - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - offset = j << 2; - block = s[i]; - array[offset] = block & 0xFF; - array[offset + 1] = (block >> 8) & 0xFF; - array[offset + 2] = (block >> 16) & 0xFF; - array[offset + 3] = (block >> 24) & 0xFF; - } - if (j % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - offset = j << 2; - block = s[i]; - array[offset] = block & 0xFF; - if (extraBytes > 1) { - array[offset + 1] = (block >> 8) & 0xFF; - } - if (extraBytes > 2) { - array[offset + 2] = (block >> 16) & 0xFF; - } - } - return array; - }; - - function Kmac(bits, padding, outputBits) { - Keccak.call(this, bits, 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]]; - } - if (AMD) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { - return methods; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } - } -})(); - - -/***/ }), - -/***/ 3224: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - -const isOptionObject = __webpack_require__(7760); - -const {hasOwnProperty} = Object.prototype; -const {propertyIsEnumerable} = Object; -const defineProperty = (object, name, value) => Object.defineProperty(object, name, { - value, - writable: true, - enumerable: true, - configurable: true -}); - -const globalThis = this; -const defaultMergeOptions = { - concatArrays: false, - ignoreUndefined: false -}; - -const getEnumerableOwnPropertyKeys = value => { - const keys = []; - - for (const key in value) { - if (hasOwnProperty.call(value, key)) { - keys.push(key); - } - } - - /* istanbul ignore else */ - if (Object.getOwnPropertySymbols) { - const symbols = Object.getOwnPropertySymbols(value); - - for (const symbol of symbols) { - if (propertyIsEnumerable.call(value, symbol)) { - keys.push(symbol); - } - } - } - - return keys; -}; - -function clone(value) { - if (Array.isArray(value)) { - return cloneArray(value); - } - - if (isOptionObject(value)) { - return cloneOptionObject(value); - } - - return value; -} - -function cloneArray(array) { - const result = array.slice(0, 0); - - getEnumerableOwnPropertyKeys(array).forEach(key => { - defineProperty(result, key, clone(array[key])); - }); - - return result; -} - -function cloneOptionObject(object) { - const result = Object.getPrototypeOf(object) === null ? Object.create(null) : {}; - - getEnumerableOwnPropertyKeys(object).forEach(key => { - defineProperty(result, key, clone(object[key])); - }); - - return result; -} - -/** - * @param {*} merged already cloned - * @param {*} source something to merge - * @param {string[]} keys keys to merge - * @param {Object} config Config Object - * @returns {*} cloned Object - */ -const mergeKeys = (merged, source, keys, config) => { - keys.forEach(key => { - if (typeof source[key] === 'undefined' && config.ignoreUndefined) { - return; - } - - // Do not recurse into prototype chain of merged - if (key in merged && merged[key] !== Object.getPrototypeOf(merged)) { - defineProperty(merged, key, merge(merged[key], source[key], config)); - } else { - defineProperty(merged, key, clone(source[key])); - } - }); - - return merged; -}; - -/** - * @param {*} merged already cloned - * @param {*} source something to merge - * @param {Object} config Config Object - * @returns {*} cloned Object - * - * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat) - */ -const concatArrays = (merged, source, config) => { - let result = merged.slice(0, 0); - let resultIndex = 0; - - [merged, source].forEach(array => { - const indices = []; - - // `result.concat(array)` with cloning - for (let k = 0; k < array.length; k++) { - if (!hasOwnProperty.call(array, k)) { - continue; - } - - indices.push(String(k)); - - if (array === merged) { - // Already cloned - defineProperty(result, resultIndex++, array[k]); - } else { - defineProperty(result, resultIndex++, clone(array[k])); - } - } - - // Merge non-index keys - result = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config); - }); - - return result; -}; - -/** - * @param {*} merged already cloned - * @param {*} source something to merge - * @param {Object} config Config Object - * @returns {*} cloned Object - */ -function merge(merged, source, config) { - if (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) { - return concatArrays(merged, source, config); - } - - if (!isOptionObject(source) || !isOptionObject(merged)) { - return clone(source); - } - - return mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config); -} - -module.exports = function (...options) { - const config = merge(clone(defaultMergeOptions), (this !== globalThis && this) || {}, defaultMergeOptions); - let merged = {_: {}}; - - for (const option of options) { - if (option === undefined) { - continue; - } - - if (!isOptionObject(option)) { - throw new TypeError('`' + option + '` is not an Option Object'); - } - - merged = merge(merged, {_: option}, config); - } - - return merged._; -}; - - -/***/ }), - -/***/ 7859: -/***/ ((module) => { - -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - - -/***/ }), - -/***/ 8628: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), - -/***/ 9546: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const { Multiaddr } = __webpack_require__(9038) - -const reduceValue = (_, v) => v -const tcpUri = (str, port, parts, opts) => { - // return tcp when explicitly requested - if (opts && opts.assumeHttp === false) return `tcp://${str}:${port}` - // check if tcp is the last protocol in multiaddr - let protocol = 'tcp' - let explicitPort = `:${port}` - const last = parts[parts.length - 1] - if (last.protocol === 'tcp') { - // assume http and produce clean urls - protocol = port === '443' ? 'https' : 'http' - explicitPort = port === '443' || port === '80' ? '' : explicitPort - } - return `${protocol}://${str}${explicitPort}` -} - -const Reducers = { - ip4: reduceValue, - ip6: (str, content, i, parts) => ( - parts.length === 1 && parts[0].protocol === 'ip6' - ? content - : `[${content}]` - ), - tcp: (str, content, i, parts, opts) => ( - parts.some(p => ['http', 'https', 'ws', 'wss'].includes(p.protocol)) - ? `${str}:${content}` - : tcpUri(str, content, parts, opts) - ), - udp: (str, content) => `udp://${str}:${content}`, - dnsaddr: reduceValue, - dns4: reduceValue, - dns6: reduceValue, - ipfs: (str, content) => `${str}/ipfs/${content}`, - p2p: (str, content) => `${str}/p2p/${content}`, - http: str => `http://${str}`, - https: str => `https://${str}`, - ws: str => `ws://${str}`, - wss: str => `wss://${str}`, - 'p2p-websocket-star': str => `${str}/p2p-websocket-star`, - 'p2p-webrtc-star': str => `${str}/p2p-webrtc-star`, - 'p2p-webrtc-direct': str => `${str}/p2p-webrtc-direct` -} - -module.exports = (multiaddr, opts) => { - const ma = new Multiaddr(multiaddr) - const parts = multiaddr.toString().split('/').slice(1) - return ma - .tuples() - .map(tuple => ({ - protocol: parts.shift(), - content: tuple[1] ? parts.shift() : null - })) - .reduce((str, part, i, parts) => { - const reduce = Reducers[part.protocol] - if (!reduce) throw new Error(`Unsupported protocol ${part.protocol}`) - return reduce(str, part.content, i, parts, opts) - }, '') -} - - -/***/ }), - -/***/ 984: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const convert = __webpack_require__(1868) -const protocols = __webpack_require__(8988) -const varint = __webpack_require__(1114) -const { concat: uint8ArrayConcat } = __webpack_require__(6729) -const { toString: uint8ArrayToString } = __webpack_require__(5824) - -// export codec -module.exports = { - stringToStringTuples, - stringTuplesToString, - - tuplesToStringTuples, - stringTuplesToTuples, - - bytesToTuples, - tuplesToBytes, - - bytesToString, - stringToBytes, - - fromString, - fromBytes, - validateBytes, - isValidBytes, - cleanPath, - - ParseError, - protoFromTuple, - - sizeForAddr -} - -// string -> [[str name, str addr]... ] -/** - * @param {string} str - */ -function stringToStringTuples (str) { - const tuples = [] - const parts = str.split('/').slice(1) // skip first empty elem - if (parts.length === 1 && parts[0] === '') { - return [] - } - - for (let p = 0; p < parts.length; p++) { - const part = parts[p] - const proto = protocols(part) - - if (proto.size === 0) { - tuples.push([part]) - continue - } - - p++ // advance addr part - if (p >= parts.length) { - throw ParseError('invalid address: ' + str) - } - - // if it's a path proto, take the rest - if (proto.path) { - tuples.push([ - part, - // TODO: should we need to check each path part to see if it's a proto? - // This would allow for other protocols to be added after a unix path, - // however it would have issues if the path had a protocol name in the path - cleanPath(parts.slice(p).join('/')) - ]) - break - } - - tuples.push([part, parts[p]]) - } - - return tuples -} - -// [[str name, str addr]... ] -> string -/** - * @param {[number, string?][]} tuples - */ -function stringTuplesToString (tuples) { - /** @type {Array} */ - const parts = [] - tuples.map((tup) => { - const proto = protoFromTuple(tup) - parts.push(proto.name) - if (tup.length > 1) { - parts.push(tup[1]) - } - return null - }) - - return cleanPath(parts.join('/')) -} - -// [[str name, str addr]... ] -> [[int code, Uint8Array]... ] -/** - * @param {Array} tuples - * @returns {[number , Uint8Array?][]} - */ -function stringTuplesToTuples (tuples) { - return tuples.map((tup) => { - if (!Array.isArray(tup)) { - tup = [tup] - } - const proto = protoFromTuple(tup) - if (tup.length > 1) { - return [proto.code, convert.toBytes(proto.code, tup[1])] - } - return [proto.code] - }) -} - -/** - * Convert tuples to string tuples - * - * [[int code, Uint8Array]... ] -> [[int code, str addr]... ] - * - * @param {Array<[number, Uint8Array?]>} tuples - * @returns {Array<[number, string?]>} - */ - -function tuplesToStringTuples (tuples) { - return tuples.map(tup => { - const proto = protoFromTuple(tup) - if (tup[1]) { - return [proto.code, convert.toString(proto.code, tup[1])] - } - return [proto.code] - }) -} - -// [[int code, Uint8Array ]... ] -> Uint8Array -/** - * @param {[number, Uint8Array?][]} tuples - */ -function tuplesToBytes (tuples) { - return fromBytes(uint8ArrayConcat(tuples.map((/** @type {any[]} */ tup) => { - const proto = protoFromTuple(tup) - let buf = Uint8Array.from(varint.encode(proto.code)) - - if (tup.length > 1) { - buf = uint8ArrayConcat([buf, tup[1]]) // add address buffer - } - - return buf - }))) -} - -/** - * @param {import("./types").Protocol} p - * @param {Uint8Array | number[]} addr - */ -function sizeForAddr (p, addr) { - if (p.size > 0) { - return p.size / 8 - } else if (p.size === 0) { - return 0 - } else { - const size = varint.decode(addr) - return size + varint.decode.bytes - } -} - -/** - * - * @param {Uint8Array} buf - * @returns {Array<[number, Uint8Array?]>} - */ -function bytesToTuples (buf) { - /** @type {Array<[number, Uint8Array?]>} */ - const tuples = [] - let i = 0 - while (i < buf.length) { - const code = varint.decode(buf, i) - const n = varint.decode.bytes - - const p = protocols(code) - - const size = sizeForAddr(p, buf.slice(i + n)) - - if (size === 0) { - tuples.push([code]) - i += n - continue - } - - const addr = buf.slice(i + n, i + n + size) - - i += (size + n) - - if (i > buf.length) { // did not end _exactly_ at buffer.length - throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16')) - } - - // ok, tuple seems good. - tuples.push([code, addr]) - } - - return tuples -} - -// Uint8Array -> String -/** - * @param {Uint8Array} buf - */ -function bytesToString (buf) { - const a = bytesToTuples(buf) - const b = tuplesToStringTuples(a) - return stringTuplesToString(b) -} - -// String -> Uint8Array -/** - * @param {string} str - */ -function stringToBytes (str) { - str = cleanPath(str) - const a = stringToStringTuples(str) - const b = stringTuplesToTuples(a) - - return tuplesToBytes(b) -} - -// String -> Uint8Array -/** - * @param {string} str - */ -function fromString (str) { - return stringToBytes(str) -} - -// Uint8Array -> Uint8Array -/** - * @param {Uint8Array} buf - */ -function fromBytes (buf) { - const err = validateBytes(buf) - if (err) throw err - return Uint8Array.from(buf) // copy -} - -/** - * @param {Uint8Array} buf - */ -function validateBytes (buf) { - try { - bytesToTuples(buf) // try to parse. will throw if breaks - } catch (err) { - return err - } -} - -/** - * @param {Uint8Array} buf - */ -function isValidBytes (buf) { - return validateBytes(buf) === undefined -} - -/** - * @param {string} str - */ -function cleanPath (str) { - return '/' + str.trim().split('/').filter((/** @type {any} */ a) => a).join('/') -} - -/** - * @param {string} str - */ -function ParseError (str) { - return new Error('Error parsing address: ' + str) -} - -/** - * @param {any[]} tup - */ -function protoFromTuple (tup) { - const proto = protocols(tup[0]) - return proto -} - - -/***/ }), - -/***/ 1868: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const ip = __webpack_require__(8373) -const protocols = __webpack_require__(8988) -const { CID } = __webpack_require__(3036) -const { base32 } = __webpack_require__(4052) -const { base58btc } = __webpack_require__(4749) -const Digest = __webpack_require__(9122) -const varint = __webpack_require__(1114) -const { toString: uint8ArrayToString } = __webpack_require__(5824) -const { fromString: uint8ArrayFromString } = __webpack_require__(4081) -const { concat: uint8ArrayConcat } = __webpack_require__(6729) - -module.exports = Convert - -// converts (serializes) addresses -/** - * @param {string} proto - * @param {string | Uint8Array} a - */ -function Convert (proto, a) { - if (a instanceof Uint8Array) { - return Convert.toString(proto, a) - } else { - return Convert.toBytes(proto, a) - } -} - -/** - * Convert [code,Uint8Array] to string - * - * @param {number|string} proto - * @param {Uint8Array} buf - * @returns {string} - */ -Convert.toString = function convertToString (proto, buf) { - const protocol = protocols(proto) - switch (protocol.code) { - case 4: // ipv4 - case 41: // ipv6 - return bytes2ip(buf) - - case 6: // tcp - case 273: // udp - case 33: // dccp - case 132: // sctp - return bytes2port(buf).toString() - - case 53: // dns - case 54: // dns4 - case 55: // dns6 - case 56: // dnsaddr - case 400: // unix - case 777: // memory - return bytes2str(buf) - - case 421: // ipfs - return bytes2mh(buf) - case 444: // onion - return bytes2onion(buf) - case 445: // onion3 - return bytes2onion(buf) - default: - return uint8ArrayToString(buf, 'base16') // no clue. convert to hex - } -} - -Convert.toBytes = function convertToBytes (/** @type {string | number } */ proto, /** @type {string} */ str) { - const protocol = protocols(proto) - switch (protocol.code) { - case 4: // ipv4 - return ip2bytes(str) - case 41: // ipv6 - return ip2bytes(str) - - case 6: // tcp - case 273: // udp - case 33: // dccp - case 132: // sctp - return port2bytes(parseInt(str, 10)) - - case 53: // dns - case 54: // dns4 - case 55: // dns6 - case 56: // dnsaddr - case 400: // unix - case 777: // memory - return str2bytes(str) - - case 421: // ipfs - return mh2bytes(str) - case 444: // onion - return onion2bytes(str) - case 445: // onion3 - return onion32bytes(str) - default: - return uint8ArrayFromString(str, 'base16') // no clue. convert from hex - } -} - -/** - * @param {string} ipString - */ -function ip2bytes (ipString) { - if (!ip.isIP(ipString)) { - throw new Error('invalid ip address') - } - return ip.toBytes(ipString) -} - -/** - * @param {Uint8Array} ipBuff - */ -function bytes2ip (ipBuff) { - const ipString = ip.toString(ipBuff) - if (!ipString || !ip.isIP(ipString)) { - throw new Error('invalid ip address') - } - return ipString -} - -/** - * @param {number} port - */ -function port2bytes (port) { - const buf = new ArrayBuffer(2) - const view = new DataView(buf) - view.setUint16(0, port) - - return new Uint8Array(buf) -} - -/** - * @param {Uint8Array} buf - */ -function bytes2port (buf) { - const view = new DataView(buf.buffer) - return view.getUint16(buf.byteOffset) -} - -/** - * @param {string} str - */ -function str2bytes (str) { - const buf = uint8ArrayFromString(str) - const size = Uint8Array.from(varint.encode(buf.length)) - return uint8ArrayConcat([size, buf], size.length + buf.length) -} - -/** - * @param {Uint8Array} buf - */ -function bytes2str (buf) { - const size = varint.decode(buf) - buf = buf.slice(varint.decode.bytes) - - if (buf.length !== size) { - throw new Error('inconsistent lengths') - } - - return uint8ArrayToString(buf) -} - -/** - * @param {string} hash - base58btc string - */ -function mh2bytes (hash) { - let mh - - if (hash[0] === 'Q' || hash[0] === '1') { - mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes - } else { - mh = CID.parse(hash).multihash.bytes - } - - // the address is a varint prefixed multihash string representation - const size = Uint8Array.from(varint.encode(mh.length)) - return uint8ArrayConcat([size, mh], size.length + mh.length) -} - -/** - * Converts bytes to bas58btc string - * - * @param {Uint8Array} buf - * @returns {string} base58btc string - */ -function bytes2mh (buf) { - const size = varint.decode(buf) - const address = buf.slice(varint.decode.bytes) - - if (address.length !== size) { - throw new Error('inconsistent lengths') - } - - return uint8ArrayToString(address, 'base58btc') -} - -/** - * @param {string} str - */ -function onion2bytes (str) { - const addr = str.split(':') - if (addr.length !== 2) { - throw new Error('failed to parse onion addr: ' + addr + ' does not contain a port number') - } - if (addr[0].length !== 16) { - throw new Error('failed to parse onion addr: ' + addr[0] + ' not a Tor onion address.') - } - - // onion addresses do not include the multibase prefix, add it before decoding - const buf = base32.decode('b' + addr[0]) - - // onion port number - const port = parseInt(addr[1], 10) - if (port < 1 || port > 65536) { - throw new Error('Port number is not in range(1, 65536)') - } - const portBuf = port2bytes(port) - return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length) -} - -/** - * @param {string} str - */ -function onion32bytes (str) { - const addr = str.split(':') - if (addr.length !== 2) { - throw new Error('failed to parse onion addr: ' + addr + ' does not contain a port number') - } - if (addr[0].length !== 56) { - throw new Error('failed to parse onion addr: ' + addr[0] + ' not a Tor onion3 address.') - } - // onion addresses do not include the multibase prefix, add it before decoding - const buf = base32.decode('b' + addr[0]) - - // onion port number - const port = parseInt(addr[1], 10) - if (port < 1 || port > 65536) { - throw new Error('Port number is not in range(1, 65536)') - } - const portBuf = port2bytes(port) - return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length) -} - -/** - * @param {Uint8Array} buf - */ -function bytes2onion (buf) { - const addrBytes = buf.slice(0, buf.length - 2) - const portBytes = buf.slice(buf.length - 2) - const addr = uint8ArrayToString(addrBytes, 'base32') - const port = bytes2port(portBytes) - return addr + ':' + port -} - - -/***/ }), - -/***/ 9038: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const codec = __webpack_require__(984) -const protocols = __webpack_require__(8988) -const varint = __webpack_require__(1114) -const { CID } = __webpack_require__(3036) -const { base58btc } = __webpack_require__(4749) -const errCode = __webpack_require__(118) -const inspect = Symbol.for('nodejs.util.inspect.custom') -const { toString: uint8ArrayToString } = __webpack_require__(5824) -const { equals: uint8ArrayEquals } = __webpack_require__(5732) - -/** - * @typedef {(addr: Multiaddr) => Promise} Resolver - * @typedef {string | Multiaddr | Uint8Array | null} MultiaddrInput - * @typedef {import('./types').MultiaddrObject} MultiaddrObject - * @typedef {import('./types').Protocol} Protocol - */ - -/** @type {Map} */ -const resolvers = new Map() -const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr') - -/** - * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from - * a Uint8Array, String or another Multiaddr instance - * public key. - * - */ -class Multiaddr { - /** - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001') - * // - * ``` - * - * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format) - */ - constructor (addr) { - // default - if (addr == null) { - addr = '' - } - - // Define symbol - Object.defineProperty(this, symbol, { value: true }) - - if (addr instanceof Uint8Array) { - /** @type {Uint8Array} - The raw bytes representing this multiaddress */ - this.bytes = codec.fromBytes(addr) - } else if (typeof addr === 'string') { - if (addr.length > 0 && addr.charAt(0) !== '/') { - throw new Error(`multiaddr "${addr}" must start with a "/"`) - } - this.bytes = codec.fromString(addr) - } else if (Multiaddr.isMultiaddr(addr)) { // Multiaddr - this.bytes = codec.fromBytes(addr.bytes) // validate + copy buffer - } else { - throw new Error('addr must be a string, Buffer, or another Multiaddr') - } - } - - /** - * Returns Multiaddr as a String - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').toString() - * // '/ip4/127.0.0.1/tcp/4001' - * ``` - */ - toString () { - return codec.bytesToString(this.bytes) - } - - /** - * Returns Multiaddr as a JSON encoded object - * - * @example - * ```js - * JSON.stringify(new Multiaddr('/ip4/127.0.0.1/tcp/4001')) - * // '/ip4/127.0.0.1/tcp/4001' - * ``` - */ - toJSON () { - return this.toString() - } - - /** - * Returns Multiaddr as a convinient options object to be used with net.createConnection - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions() - * // { family: 4, host: '127.0.0.1', transport: 'tcp', port: 4001 } - * ``` - */ - toOptions () { - /** @type {MultiaddrObject} */ - const opts = {} - const parsed = this.toString().split('/') - opts.family = parsed[1] === 'ip4' ? 4 : 6 - opts.host = parsed[2] - opts.transport = parsed[3] - opts.port = parseInt(parsed[4]) - return opts - } - - /** - * Returns the protocols the Multiaddr is defined with, as an array of objects, in - * left-to-right order. Each object contains the protocol code, protocol name, - * and the size of its address space in bits. - * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').protos() - * // [ { code: 4, size: 32, name: 'ip4' }, - * // { code: 6, size: 16, name: 'tcp' } ] - * ``` - * - * @returns {Protocol[]} protocols - All the protocols the address is composed of - */ - protos () { - return this.protoCodes().map(code => Object.assign({}, protocols(code))) - } - - /** - * Returns the codes of the protocols in left-to-right order. - * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) - * - * @example - * ```js - * Multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes() - * // [ 4, 6 ] - * ``` - * - * @returns {number[]} protocol codes - */ - protoCodes () { - const codes = [] - const buf = this.bytes - let i = 0 - while (i < buf.length) { - const code = varint.decode(buf, i) - const n = varint.decode.bytes - - const p = protocols(code) - const size = codec.sizeForAddr(p, buf.slice(i + n)) - - i += (size + n) - codes.push(code) - } - - return codes - } - - /** - * Returns the names of the protocols in left-to-right order. - * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames() - * // [ 'ip4', 'tcp' ] - * ``` - * - * @returns {string[]} protocol names - */ - protoNames () { - return this.protos().map(proto => proto.name) - } - - /** - * Returns a tuple of parts - * - * @example - * ```js - * new Multiaddr("/ip4/127.0.0.1/tcp/4001").tuples() - * // [ [ 4, ], [ 6, ] ] - * ``` - */ - tuples () { - return codec.bytesToTuples(this.bytes) - } - - /** - * Returns a tuple of string/number parts - * - tuples[][0] = code of protocol - * - tuples[][1] = contents of address - * - * @example - * ```js - * new Multiaddr("/ip4/127.0.0.1/tcp/4001").stringTuples() - * // [ [ 4, '127.0.0.1' ], [ 6, '4001' ] ] - * ``` - */ - stringTuples () { - const t = codec.bytesToTuples(this.bytes) - return codec.tuplesToStringTuples(t) - } - - /** - * Encapsulates a Multiaddr in another Multiaddr - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/8.8.8.8/tcp/1080') - * // - * - * const mh2 = new Multiaddr('/ip4/127.0.0.1/tcp/4001') - * // - * - * const mh3 = mh1.encapsulate(mh2) - * // - * - * mh3.toString() - * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001' - * ``` - * - * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr - */ - encapsulate (addr) { - addr = new Multiaddr(addr) - return new Multiaddr(this.toString() + addr.toString()) - } - - /** - * Decapsulates a Multiaddr from another Multiaddr - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/8.8.8.8/tcp/1080') - * // - * - * const mh2 = new Multiaddr('/ip4/127.0.0.1/tcp/4001') - * // - * - * const mh3 = mh1.encapsulate(mh2) - * // - * - * mh3.decapsulate(mh2).toString() - * // '/ip4/8.8.8.8/tcp/1080' - * ``` - * - * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr - * @returns {Multiaddr} - */ - decapsulate (addr) { - const addrString = addr.toString() - const s = this.toString() - const i = s.lastIndexOf(addrString) - if (i < 0) { - throw new Error('Address ' + this + ' does not contain subaddress: ' + addr) - } - return new Multiaddr(s.slice(0, i)) - } - - /** - * A more reliable version of `decapsulate` if you are targeting a - * specific code, such as 421 (the `p2p` protocol code). The last index of the code - * will be removed from the `Multiaddr`, and a new instance will be returned. - * If the code is not present, the original `Multiaddr` is returned. - * - * @example - * ```js - * const addr = new Multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC') - * // - * - * addr.decapsulateCode(421).toString() - * // '/ip4/0.0.0.0/tcp/8080' - * - * new Multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString() - * // '/ip4/127.0.0.1/tcp/8080' - * ``` - * - * @param {number} code - The code of the protocol to decapsulate from this Multiaddr - * @returns {Multiaddr} - */ - decapsulateCode (code) { - const tuples = this.tuples() - for (let i = tuples.length - 1; i >= 0; i--) { - if (tuples[i][0] === code) { - return new Multiaddr(codec.tuplesToBytes(tuples.slice(0, i))) - } - } - return this - } - - /** - * Extract the peerId if the multiaddr contains one - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string') - * // - * - * // should return QmValidBase58string or null if the id is missing or invalid - * const peerId = mh1.getPeerId() - * ``` - * - * @returns {string | null} peerId - The id of the peer or null if invalid or missing from the ma - */ - getPeerId () { - try { - const tuples = this.stringTuples().filter((tuple) => { - if (tuple[0] === protocols.names.ipfs.code) { - return true - } - return false - }) - - // Get the last ipfs tuple ['ipfs', 'peerid string'] - const tuple = tuples.pop() - if (tuple && tuple[1]) { - const peerIdStr = tuple[1] - - // peer id is base58btc encoded string but not multibase encoded so add the `z` - // prefix so we can validate that it is correctly encoded - if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') { - return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc') - } - - // try to parse peer id as CID - return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc') - } - - return null - } catch (e) { - return null - } - } - - /** - * Extract the path if the multiaddr contains one - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock') - * // - * - * // should return utf8 string or null if the id is missing or invalid - * const path = mh1.getPath() - * ```js - * - * @returns {string | null} path - The path of the multiaddr, or null if no path protocol is present - */ - getPath () { - let path = null - try { - path = this.stringTuples().filter((tuple) => { - const proto = protocols(tuple[0]) - if (proto.path) { - return true - } - return false - })[0][1] - - if (!path) { - path = null - } - } catch (e) { - path = null - } - return path - } - - /** - * Checks if two Multiaddrs are the same - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/8.8.8.8/tcp/1080') - * // - * - * const mh2 = new Multiaddr('/ip4/127.0.0.1/tcp/4001') - * // - * - * mh1.equals(mh1) - * // true - * - * mh1.equals(mh2) - * // false - * ``` - * - * @param {Multiaddr} addr - * @returns {boolean} - */ - equals (addr) { - return uint8ArrayEquals(this.bytes, addr.bytes) - } - - /** - * Resolve multiaddr if containing resolvable hostname. - * - * @example - * ```js - * Multiaddr.resolvers.set('dnsaddr', resolverFunction) - * const mh1 = new Multiaddr('/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb') - * const resolvedMultiaddrs = await mh1.resolve() - * // [ - * // , - * // , - * // - * // ] - * ``` - * - * @returns {Promise>} - */ - async resolve () { - const resolvableProto = this.protos().find((p) => p.resolvable) - - // Multiaddr is not resolvable? - if (!resolvableProto) { - return [this] - } - - const resolver = resolvers.get(resolvableProto.name) - if (!resolver) { - throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER') - } - - const addresses = await resolver(this) - return addresses.map((a) => new Multiaddr(a)) - } - - /** - * Gets a Multiaddrs node-friendly address object. Note that protocol information - * is left out: in Node (and most network systems) the protocol is unknowable - * given only the address. - * - * Has to be a ThinWaist Address, otherwise throws error - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress() - * // {family: 4, address: '127.0.0.1', port: 4001} - * ``` - * - * @returns {{family: 4 | 6, address: string, port: number}} - * @throws {Error} Throws error if Multiaddr is not a Thin Waist address - */ - nodeAddress () { - const codes = this.protoCodes() - const names = this.protoNames() - const parts = this.toString().split('/').slice(1) - - if (parts.length < 4) { - throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6}/{address}/{tcp, udp}/{port}".') - } else if (codes[0] !== 4 && codes[0] !== 41 && codes[0] !== 54 && codes[0] !== 55) { - throw new Error(`no protocol with name: "'${names[0]}'". Must have a valid family name: "{ip4, ip6, dns4, dns6}".`) - } else if (parts[2] !== 'tcp' && parts[2] !== 'udp') { - throw new Error(`no protocol with name: "'${names[1]}'". Must have a valid transport protocol: "{tcp, udp}".`) - } - - return { - family: (codes[0] === 41 || codes[0] === 55) ? 6 : 4, - address: parts[1], - port: parseInt(parts[3]) // tcp or udp port - } - } - - /** - * Returns if a Multiaddr is a Thin Waist address or not. - * - * Thin Waist is if a Multiaddr adheres to the standard combination of: - * - * `{IPv4, IPv6}/{TCP, UDP}` - * - * @example - * ```js - * const mh1 = new Multiaddr('/ip4/127.0.0.1/tcp/4001') - * // - * const mh2 = new Multiaddr('/ip4/192.168.2.1/tcp/5001') - * // - * const mh3 = mh1.encapsulate(mh2) - * // - * const mh4 = new Multiaddr('/ip4/127.0.0.1/tcp/2000/wss/p2p-webrtc-star/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo2a') - * // - * mh1.isThinWaistAddress() - * // true - * mh2.isThinWaistAddress() - * // true - * mh3.isThinWaistAddress() - * // false - * mh4.isThinWaistAddress() - * // false - * ``` - * - * @param {Multiaddr} [addr] - Defaults to using `this` instance - */ - isThinWaistAddress (addr) { - const protos = (addr || this).protos() - - if (protos.length !== 2) { - return false - } - - if (protos[0].code !== 4 && protos[0].code !== 41) { - return false - } - if (protos[1].code !== 6 && protos[1].code !== 273) { - return false - } - return true - } - - /** - * Creates a Multiaddr from a node-friendly address object - * - * @example - * ```js - * Multiaddr.fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp') - * // - * ``` - * - * @param {{family: 4 | 6, address: string, port: number}} addr - * @param {string} transport - */ - static fromNodeAddress (addr, transport) { - if (!addr) { throw new Error('requires node address object') } - if (!transport) { throw new Error('requires transport protocol') } - let ip - switch (addr.family) { - case 4: - ip = 'ip4' - break - case 6: - ip = 'ip6' - break - default: - throw Error(`Invalid addr family. Got '${addr.family}' instead of 4 or 6`) - } - return new Multiaddr('/' + [ip, addr.address, transport, addr.port].join('/')) - } - - /** - * Returns if something is a Multiaddr that is a name - * - * @param {Multiaddr} addr - * @returns {boolean} isName - */ - static isName (addr) { - if (!Multiaddr.isMultiaddr(addr)) { - return false - } - - // if a part of the multiaddr is resolvable, then return true - return addr.protos().some((proto) => proto.resolvable) - } - - /** - * Check if object is a CID instance - * - * @param {any} value - * @returns {value is Multiaddr} - */ - static isMultiaddr (value) { - return value instanceof Multiaddr || Boolean(value && value[symbol]) - } - - /** - * Returns Multiaddr as a human-readable string. - * For post Node.js v10.0.0. - * https://nodejs.org/api/deprecations.html#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect - * - * @example - * ```js - * console.log(new Multiaddr('/ip4/127.0.0.1/tcp/4001')) - * // '' - * ``` - * - * @returns {string} - */ - [inspect] () { - return '' - } - - /** - * Returns Multiaddr as a human-readable string. - * Fallback for pre Node.js v10.0.0. - * https://nodejs.org/api/deprecations.html#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect - * - * @example - * ```js - * new Multiaddr('/ip4/127.0.0.1/tcp/4001').inspect() - * // '' - * ``` - * - * @returns {string} - */ - inspect () { - return '' - } -} - -/** - * Object containing table, names and codes of all supported protocols. - * To get the protocol values from a Multiaddr, you can use - * [`.protos()`](#multiaddrprotos), - * [`.protoCodes()`](#multiaddrprotocodes) or - * [`.protoNames()`](#multiaddrprotonames) - * - * @returns {{table: Array, names: Object, codes: Object}} - */ -Multiaddr.protocols = protocols - -Multiaddr.resolvers = resolvers - -/** - * Static factory - * - * @param {MultiaddrInput} addr - */ -function multiaddr (addr) { - return new Multiaddr(addr) -} - -module.exports = { Multiaddr, multiaddr, protocols, resolvers } - - -/***/ }), - -/***/ 8373: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -const isIp = __webpack_require__(2478) -const { toString: uint8ArrayToString } = __webpack_require__(5824) - -const isIP = isIp -const isV4 = isIp.v4 -const isV6 = isIp.v6 - -// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7 -// @ts-ignore - this is copied from the link above better to keep it the same -const toBytes = function (ip, buff, offset) { - offset = ~~offset - - let result - - if (isV4(ip)) { - result = buff || new Uint8Array(offset + 4) - // @ts-ignore - // eslint-disable-next-line array-callback-return - ip.split(/\./g).map(function (byte) { - result[offset++] = parseInt(byte, 10) & 0xff - }) - } else if (isV6(ip)) { - const sections = ip.split(':', 8) - - let i - for (i = 0; i < sections.length; i++) { - const isv4 = isV4(sections[i]) - let v4Buffer - - if (isv4) { - v4Buffer = toBytes(sections[i]) - sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16') - } - - if (v4Buffer && ++i < 8) { - sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16')) - } - } - - if (sections[0] === '') { - while (sections.length < 8) sections.unshift('0') - } else if (sections[sections.length - 1] === '') { - while (sections.length < 8) sections.push('0') - } else if (sections.length < 8) { - for (i = 0; i < sections.length && sections[i] !== ''; i++); - const argv = [i, '1'] - for (i = 9 - sections.length; i > 0; i--) { - argv.push('0') - } - sections.splice.apply(sections, argv) - } - - result = buff || new Uint8Array(offset + 16) - for (i = 0; i < sections.length; i++) { - const word = parseInt(sections[i], 16) - result[offset++] = (word >> 8) & 0xff - result[offset++] = word & 0xff - } - } - - if (!result) { - throw Error('Invalid ip address: ' + ip) - } - - return result -} - -// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63 -// @ts-ignore - this is copied from the link above better to keep it the same -const toString = function (buff, offset, length) { - offset = ~~offset - length = length || (buff.length - offset) - - const result = [] - let string - const view = new DataView(buff.buffer) - if (length === 4) { - // IPv4 - for (let i = 0; i < length; i++) { - result.push(buff[offset + i]) - } - string = result.join('.') - } else if (length === 16) { - // IPv6 - for (let i = 0; i < length; i += 2) { - result.push(view.getUint16(offset + i).toString(16)) - } - string = result.join(':') - string = string.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3') - string = string.replace(/:{3,4}/, '::') - } - - return string -} - -module.exports = { - isIP, - isV4, - isV6, - toBytes, - toString -} - - -/***/ }), - -/***/ 8988: -/***/ ((module) => { - -"use strict"; - -/** @typedef {import("./types").Protocol} Protocol */ - -/** - * Protocols - * - * @param {number | string} proto - * @returns {Protocol} - */ -function Protocols (proto) { - if (typeof (proto) === 'number') { - if (Protocols.codes[proto]) { - return Protocols.codes[proto] - } - - throw new Error('no protocol with code: ' + proto) - } else if (typeof (proto) === 'string') { - if (Protocols.names[proto]) { - return Protocols.names[proto] - } - - throw new Error('no protocol with name: ' + proto) - } - - throw new Error('invalid protocol id type: ' + proto) -} - -const V = -1 -Protocols.lengthPrefixedVarSize = V -Protocols.V = V - -/** @type {Array<[number, number, string, (string|boolean)?, string?]>} */ -Protocols.table = [ - [4, 32, 'ip4'], - [6, 16, 'tcp'], - [33, 16, 'dccp'], - [41, 128, 'ip6'], - [42, V, 'ip6zone'], - [53, V, 'dns', 'resolvable'], - [54, V, 'dns4', 'resolvable'], - [55, V, 'dns6', 'resolvable'], - [56, V, 'dnsaddr', 'resolvable'], - [132, 16, 'sctp'], - [273, 16, 'udp'], - [275, 0, 'p2p-webrtc-star'], - [276, 0, 'p2p-webrtc-direct'], - [277, 0, 'p2p-stardust'], - [290, 0, 'p2p-circuit'], - [301, 0, 'udt'], - [302, 0, 'utp'], - [400, V, 'unix', false, 'path'], - // `ipfs` is added before `p2p` for legacy support. - // All text representations will default to `p2p`, but `ipfs` will - // still be supported - [421, V, 'ipfs'], - // `p2p` is the preferred name for 421, and is now the default - [421, V, 'p2p'], - [443, 0, 'https'], - [444, 96, 'onion'], - [445, 296, 'onion3'], - [446, V, 'garlic64'], - [460, 0, 'quic'], - [477, 0, 'ws'], - [478, 0, 'wss'], - [479, 0, 'p2p-websocket-star'], - [480, 0, 'http'], - [777, V, 'memory'] -] -/** @type {Record} */ -Protocols.names = {} -/** @type {Record} */ -Protocols.codes = {} - -// populate tables -Protocols.table.map(row => { - const proto = p.apply(null, row) - Protocols.codes[proto.code] = proto - Protocols.names[proto.name] = proto - return null -}) - -Protocols.object = p - -/** - * - * Create a protocol - * - * @param {number} code - * @param {number} size - * @param {string} name - * @param {any} [resolvable] - * @param {any} [path] - * @returns {Protocol} - */ -function p (code, size, name, resolvable, path) { - return { - code, - size, - name, - resolvable: Boolean(resolvable), - path: Boolean(path) - } -} - -module.exports = Protocols - - -/***/ }), - -/***/ 6487: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -if (globalThis.fetch && globalThis.Headers && globalThis.Request && globalThis.Response) { - module.exports = { - default: globalThis.fetch, - Headers: globalThis.Headers, - Request: globalThis.Request, - Response: globalThis.Response - } -} else { - module.exports = { - default: (__webpack_require__(759)["default"]), - Headers: (__webpack_require__(759).Headers), - Request: (__webpack_require__(759).Request), - Response: (__webpack_require__(759).Response) - } -} - - -/***/ }), - -/***/ 759: -/***/ ((module, exports) => { - -"use strict"; - - -// ref: https://github.com/tc39/proposal-global -var getGlobal = function () { - // the only reliable means to get the global object is - // `Function('return this')()` - // However, this causes CSP violations in Chrome apps. - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof global !== 'undefined') { return global; } - throw new Error('unable to locate global object'); -} - -var global = getGlobal(); - -module.exports = exports = global.fetch; - -// Needed for TypeScript and Webpack. -if (global.fetch) { - exports["default"] = global.fetch.bind(global); -} - -exports.Headers = global.Headers; -exports.Request = global.Request; -exports.Response = global.Response; - -/***/ }), - -/***/ 3967: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -// minimal library entry point. - - -module.exports = __webpack_require__(4365); - - -/***/ }), - -/***/ 4365: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -var protobuf = exports; - -/** - * Build type, one of `"full"`, `"light"` or `"minimal"`. - * @name build - * @type {string} - * @const - */ -protobuf.build = "minimal"; - -// Serialization -protobuf.Writer = __webpack_require__(2147); -protobuf.BufferWriter = __webpack_require__(5055); -protobuf.Reader = __webpack_require__(2074); -protobuf.BufferReader = __webpack_require__(69); - -// Utility -protobuf.util = __webpack_require__(8835); -protobuf.rpc = __webpack_require__(7876); -protobuf.roots = __webpack_require__(4007); -protobuf.configure = configure; - -/* istanbul ignore next */ -/** - * Reconfigures the library according to the environment. - * @returns {undefined} - */ -function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); -} - -// Set up buffer utility according to the environment -configure(); - - -/***/ }), - -/***/ 2074: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = Reader; - -var util = __webpack_require__(8835); - -var BufferReader; // cyclic - -var LongBits = util.LongBits, - utf8 = util.utf8; - -/* istanbul ignore next */ -function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); -} - -/** - * Constructs a new reader instance using the specified buffer. - * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. - * @constructor - * @param {Uint8Array} buffer Buffer to read from - */ -function Reader(buffer) { - - /** - * Read buffer. - * @type {Uint8Array} - */ - this.buf = buffer; - - /** - * Read buffer position. - * @type {number} - */ - this.pos = 0; - - /** - * Read buffer length. - * @type {number} - */ - this.len = buffer.length; -} - -var create_array = typeof Uint8Array !== "undefined" - ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - } - /* istanbul ignore next */ - : function create_array(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - -var create = function create() { - return util.Buffer - ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer) { - return util.Buffer.isBuffer(buffer) - ? new BufferReader(buffer) - /* istanbul ignore next */ - : create_array(buffer); - })(buffer); - } - /* istanbul ignore next */ - : create_array; -}; - -/** - * Creates a new reader using the specified buffer. - * @function - * @param {Uint8Array|Buffer} buffer Buffer to read from - * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} - * @throws {Error} If `buffer` is not a valid buffer - */ -Reader.create = create(); - -Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; - -/** - * Reads a varint as an unsigned 32 bit value. - * @function - * @returns {number} Value read - */ -Reader.prototype.uint32 = (function read_uint32_setup() { - var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) - return function read_uint32() { - value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; - - /* istanbul ignore if */ - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; -})(); - -/** - * Reads a varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; -}; - -/** - * Reads a zig-zag encoded varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readLongVarint() { - // tends to deopt with local vars for octet etc. - var bits = new LongBits(0, 0); - var i = 0; - if (this.len - this.pos > 4) { // fast route (lo) - for (; i < 4; ++i) { - // 1st..4th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 5th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i = 0; - } else { - for (; i < 3; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 1st..3th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 4th - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { // fast route (hi) - for (; i < 5; ++i) { - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i < 5; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } - /* istanbul ignore next */ - throw Error("invalid varint encoding"); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads a varint as a signed 64 bit value. - * @name Reader#int64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as an unsigned 64 bit value. - * @name Reader#uint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a zig-zag encoded varint as a signed 64 bit value. - * @name Reader#sint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as a boolean. - * @returns {boolean} Value read - */ -Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; -}; - -function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` - return (buf[end - 4] - | buf[end - 3] << 8 - | buf[end - 2] << 16 - | buf[end - 1] << 24) >>> 0; -} - -/** - * Reads fixed 32 bits as an unsigned 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.fixed32 = function read_fixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4); -}; - -/** - * Reads fixed 32 bits as a signed 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.sfixed32 = function read_sfixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readFixed64(/* this: Reader */) { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads fixed 64 bits. - * @name Reader#fixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads zig-zag encoded fixed 64 bits. - * @name Reader#sfixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a float (32 bit) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.float = function read_float() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; -}; - -/** - * Reads a double (64 bit float) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.double = function read_double() { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @returns {Uint8Array} Value read - */ -Reader.prototype.bytes = function read_bytes() { - var length = this.uint32(), - start = this.pos, - end = this.pos + length; - - /* istanbul ignore if */ - if (end > this.len) - throw indexOutOfRange(this, length); - - this.pos += length; - if (Array.isArray(this.buf)) // plain array - return this.buf.slice(start, end); - return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1 - ? new this.buf.constructor(0) - : this._slice.call(this.buf, start, end); -}; - -/** - * Reads a string preceeded by its byte length as a varint. - * @returns {string} Value read - */ -Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); -}; - -/** - * Skips the specified number of bytes if specified, otherwise skips a varint. - * @param {number} [length] Length if known, otherwise a varint is assumed - * @returns {Reader} `this` - */ -Reader.prototype.skip = function skip(length) { - if (typeof length === "number") { - /* istanbul ignore if */ - if (this.pos + length > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - } else { - do { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; -}; - -/** - * Skips the next element of the specified wire type. - * @param {number} wireType Wire type received - * @returns {Reader} `this` - */ -Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType); - } - break; - case 5: - this.skip(4); - break; - - /* istanbul ignore next */ - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; -}; - -Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create(); - BufferReader._configure(); - - var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; - util.merge(Reader.prototype, { - - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } - - }); -}; - - -/***/ }), - -/***/ 69: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = BufferReader; - -// extends Reader -var Reader = __webpack_require__(2074); -(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - -var util = __webpack_require__(8835); - -/** - * Constructs a new buffer reader instance. - * @classdesc Wire format reader using node buffers. - * @extends Reader - * @constructor - * @param {Buffer} buffer Buffer to read from - */ -function BufferReader(buffer) { - Reader.call(this, buffer); - - /** - * Read buffer. - * @name BufferReader#buf - * @type {Buffer} - */ -} - -BufferReader._configure = function () { - /* istanbul ignore else */ - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; -}; - - -/** - * @override - */ -BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); // modifies pos - return this.buf.utf8Slice - ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) - : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @name BufferReader#bytes - * @function - * @returns {Buffer} Value read - */ - -BufferReader._configure(); - - -/***/ }), - -/***/ 4007: -/***/ ((module) => { - -"use strict"; - -module.exports = {}; - -/** - * Named roots. - * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). - * Can also be used manually to make roots available accross modules. - * @name roots - * @type {Object.} - * @example - * // pbjs -r myroot -o compiled.js ... - * - * // in another module: - * require("./compiled.js"); - * - * // in any subsequent module: - * var root = protobuf.roots["myroot"]; - */ - - -/***/ }), - -/***/ 7876: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -/** - * Streaming RPC helpers. - * @namespace - */ -var rpc = exports; - -/** - * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. - * @typedef RPCImpl - * @type {function} - * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called - * @param {Uint8Array} requestData Request data - * @param {RPCImplCallback} callback Callback function - * @returns {undefined} - * @example - * function rpcImpl(method, requestData, callback) { - * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code - * throw Error("no such method"); - * asynchronouslyObtainAResponse(requestData, function(err, responseData) { - * callback(err, responseData); - * }); - * } - */ - -/** - * Node-style callback as used by {@link RPCImpl}. - * @typedef RPCImplCallback - * @type {function} - * @param {Error|null} error Error, if any, otherwise `null` - * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error - * @returns {undefined} - */ - -rpc.Service = __webpack_require__(1380); - - -/***/ }), - -/***/ 1380: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = Service; - -var util = __webpack_require__(8835); - -// Extends EventEmitter -(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - -/** - * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. - * - * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. - * @typedef rpc.ServiceMethodCallback - * @template TRes extends Message - * @type {function} - * @param {Error|null} error Error, if any - * @param {TRes} [response] Response message - * @returns {undefined} - */ - -/** - * A service method part of a {@link rpc.Service} as created by {@link Service.create}. - * @typedef rpc.ServiceMethod - * @template TReq extends Message - * @template TRes extends Message - * @type {function} - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message - * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` - */ - -/** - * Constructs a new RPC service instance. - * @classdesc An RPC service as returned by {@link Service#create}. - * @exports rpc.Service - * @extends util.EventEmitter - * @constructor - * @param {RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ -function Service(rpcImpl, requestDelimited, responseDelimited) { - - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - - util.EventEmitter.call(this); - - /** - * RPC implementation. Becomes `null` once the service is ended. - * @type {RPCImpl|null} - */ - this.rpcImpl = rpcImpl; - - /** - * Whether requests are length-delimited. - * @type {boolean} - */ - this.requestDelimited = Boolean(requestDelimited); - - /** - * Whether responses are length-delimited. - * @type {boolean} - */ - this.responseDelimited = Boolean(responseDelimited); -} - -/** - * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. - * @param {Method|rpc.ServiceMethod} method Reflected or static method - * @param {Constructor} requestCtor Request constructor - * @param {Constructor} responseCtor Response constructor - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} callback Service callback - * @returns {undefined} - * @template TReq extends Message - * @template TRes extends Message - */ -Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - - if (!request) - throw TypeError("request must be specified"); - - var self = this; - if (!callback) - return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); - - if (!self.rpcImpl) { - setTimeout(function() { callback(Error("already ended")); }, 0); - return undefined; - } - - try { - return self.rpcImpl( - method, - requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - - if (err) { - self.emit("error", err, method); - return callback(err); - } - - if (response === null) { - self.end(/* endedByRPC */ true); - return undefined; - } - - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err) { - self.emit("error", err, method); - return callback(err); - } - } - - self.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self.emit("error", err, method); - setTimeout(function() { callback(err); }, 0); - return undefined; - } -}; - -/** - * Ends this service and emits the `end` event. - * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. - * @returns {rpc.Service} `this` - */ -Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) // signal end to rpcImpl - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; -}; - - -/***/ }), - -/***/ 4600: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = LongBits; - -var util = __webpack_require__(8835); - -/** - * Constructs new long bits. - * @classdesc Helper class for working with the low and high bits of a 64 bit value. - * @memberof util - * @constructor - * @param {number} lo Low 32 bits, unsigned - * @param {number} hi High 32 bits, unsigned - */ -function LongBits(lo, hi) { - - // note that the casts below are theoretically unnecessary as of today, but older statically - // generated converter code might still call the ctor with signed 32bits. kept for compat. - - /** - * Low bits. - * @type {number} - */ - this.lo = lo >>> 0; - - /** - * High bits. - * @type {number} - */ - this.hi = hi >>> 0; -} - -/** - * Zero bits. - * @memberof util.LongBits - * @type {util.LongBits} - */ -var zero = LongBits.zero = new LongBits(0, 0); - -zero.toNumber = function() { return 0; }; -zero.zzEncode = zero.zzDecode = function() { return this; }; -zero.length = function() { return 1; }; - -/** - * Zero hash. - * @memberof util.LongBits - * @type {string} - */ -var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - -/** - * Constructs new long bits from the specified number. - * @param {number} value Value - * @returns {util.LongBits} Instance - */ -LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign = value < 0; - if (sign) - value = -value; - var lo = value >>> 0, - hi = (value - lo) / 4294967296 >>> 0; - if (sign) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); -}; - -/** - * Constructs new long bits from a number, long or string. - * @param {Long|number|string} value Value - * @returns {util.LongBits} Instance - */ -LongBits.from = function from(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - /* istanbul ignore else */ - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; -}; - -/** - * Converts this long bits to a possibly unsafe JavaScript number. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {number} Possibly unsafe number - */ -LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, - hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; -}; - -/** - * Converts this long bits to a long. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long} Long - */ -LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long - ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) - /* istanbul ignore next */ - : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; -}; - -var charCodeAt = String.prototype.charCodeAt; - -/** - * Constructs new long bits from the specified 8 characters long hash. - * @param {string} hash Hash - * @returns {util.LongBits} Bits - */ -LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - ( charCodeAt.call(hash, 0) - | charCodeAt.call(hash, 1) << 8 - | charCodeAt.call(hash, 2) << 16 - | charCodeAt.call(hash, 3) << 24) >>> 0 - , - ( charCodeAt.call(hash, 4) - | charCodeAt.call(hash, 5) << 8 - | charCodeAt.call(hash, 6) << 16 - | charCodeAt.call(hash, 7) << 24) >>> 0 - ); -}; - -/** - * Converts this long bits to a 8 characters long hash. - * @returns {string} Hash - */ -LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24 , - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); -}; - -/** - * Zig-zag encodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = ( this.lo << 1 ^ mask) >>> 0; - return this; -}; - -/** - * Zig-zag decodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = ( this.hi >>> 1 ^ mask) >>> 0; - return this; -}; - -/** - * Calculates the length of this longbits when encoded as a varint. - * @returns {number} Length - */ -LongBits.prototype.length = function length() { - var part0 = this.lo, - part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, - part2 = this.hi >>> 24; - return part2 === 0 - ? part1 === 0 - ? part0 < 16384 - ? part0 < 128 ? 1 : 2 - : part0 < 2097152 ? 3 : 4 - : part1 < 16384 - ? part1 < 128 ? 5 : 6 - : part1 < 2097152 ? 7 : 8 - : part2 < 128 ? 9 : 10; -}; - - -/***/ }), - -/***/ 8835: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var util = exports; - -// used to return a Promise where callback is omitted -util.asPromise = __webpack_require__(7383); - -// converts to / from base64 encoded strings -util.base64 = __webpack_require__(3417); - -// base class of rpc.Service -util.EventEmitter = __webpack_require__(7516); - -// float handling accross browsers -util.float = __webpack_require__(9787); - -// requires modules optionally and hides the call from bundlers -util.inquire = __webpack_require__(2795); - -// converts to / from utf8 encoded strings -util.utf8 = __webpack_require__(1893); - -// provides a node-like buffer pool in the browser -util.pool = __webpack_require__(4476); - -// utility to work with the low and high bits of a 64 bit value -util.LongBits = __webpack_require__(4600); - -/** - * Whether running within node or not. - * @memberof util - * @type {boolean} - */ -util.isNode = Boolean(typeof __webpack_require__.g !== "undefined" - && __webpack_require__.g - && __webpack_require__.g.process - && __webpack_require__.g.process.versions - && __webpack_require__.g.process.versions.node); - -/** - * Global object reference. - * @memberof util - * @type {Object} - */ -util.global = util.isNode && __webpack_require__.g - || typeof window !== "undefined" && window - || typeof self !== "undefined" && self - || this; // eslint-disable-line no-invalid-this - -/** - * An immuable empty array. - * @memberof util - * @type {Array.<*>} - * @const - */ -util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes - -/** - * An immutable empty object. - * @type {Object} - * @const - */ -util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes - -/** - * Tests if the specified value is an integer. - * @function - * @param {*} value Value to test - * @returns {boolean} `true` if the value is an integer - */ -util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; -}; - -/** - * Tests if the specified value is a string. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a string - */ -util.isString = function isString(value) { - return typeof value === "string" || value instanceof String; -}; - -/** - * Tests if the specified value is a non-null object. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a non-null object - */ -util.isObject = function isObject(value) { - return value && typeof value === "object"; -}; - -/** - * Checks if a property on a message is considered to be present. - * This is an alias of {@link util.isSet}. - * @function - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isset = - -/** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; -}; - -/** - * Any compatible Buffer instance. - * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. - * @interface Buffer - * @extends Uint8Array - */ - -/** - * Node's Buffer class if available. - * @type {Constructor} - */ -util.Buffer = (function() { - try { - var Buffer = util.inquire("buffer").Buffer; - // refuse to use non-node buffers if not explicitly assigned (perf reasons): - return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; - } catch (e) { - /* istanbul ignore next */ - return null; - } -})(); - -// Internal alias of or polyfull for Buffer.from. -util._Buffer_from = null; - -// Internal alias of or polyfill for Buffer.allocUnsafe. -util._Buffer_allocUnsafe = null; - -/** - * Creates a new buffer of whatever type supported by the environment. - * @param {number|number[]} [sizeOrArray=0] Buffer size or number array - * @returns {Uint8Array|Buffer} Buffer - */ -util.newBuffer = function newBuffer(sizeOrArray) { - /* istanbul ignore next */ - return typeof sizeOrArray === "number" - ? util.Buffer - ? util._Buffer_allocUnsafe(sizeOrArray) - : new util.Array(sizeOrArray) - : util.Buffer - ? util._Buffer_from(sizeOrArray) - : typeof Uint8Array === "undefined" - ? sizeOrArray - : new Uint8Array(sizeOrArray); -}; - -/** - * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. - * @type {Constructor} - */ -util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; - -/** - * Any compatible Long instance. - * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. - * @interface Long - * @property {number} low Low bits - * @property {number} high High bits - * @property {boolean} unsigned Whether unsigned or not - */ - -/** - * Long.js's Long class if available. - * @type {Constructor} - */ -util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long - || /* istanbul ignore next */ util.global.Long - || util.inquire("long"); - -/** - * Regular expression used to verify 2 bit (`bool`) map keys. - * @type {RegExp} - * @const - */ -util.key2Re = /^true|false|0|1$/; - -/** - * Regular expression used to verify 32 bit (`int32` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - -/** - * Regular expression used to verify 64 bit (`int64` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - -/** - * Converts a number or long to an 8 characters long hash string. - * @param {Long|number} value Value to convert - * @returns {string} Hash - */ -util.longToHash = function longToHash(value) { - return value - ? util.LongBits.from(value).toHash() - : util.LongBits.zeroHash; -}; - -/** - * Converts an 8 characters long hash string to a long or number. - * @param {string} hash Hash - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long|number} Original value - */ -util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); -}; - -/** - * Merges the properties of the source object into the destination object. - * @memberof util - * @param {Object.} dst Destination object - * @param {Object.} src Source object - * @param {boolean} [ifNotSet=false] Merges only if the key is not already set - * @returns {Object.} Destination object - */ -function merge(dst, src, ifNotSet) { // used by converters - for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) - if (dst[keys[i]] === undefined || !ifNotSet) - dst[keys[i]] = src[keys[i]]; - return dst; -} - -util.merge = merge; - -/** - * Converts the first character of a string to lower case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); -}; - -/** - * Creates a custom error constructor. - * @memberof util - * @param {string} name Error name - * @returns {Constructor} Custom error constructor - */ -function newError(name) { - - function CustomError(message, properties) { - - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - - // Error.call(this, message); - // ^ just returns a new error instance because the ctor can be called as a function - - Object.defineProperty(this, "message", { get: function() { return message; } }); - - /* istanbul ignore next */ - if (Error.captureStackTrace) // node - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - - if (properties) - merge(this, properties); - } - - (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; - - Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } }); - - CustomError.prototype.toString = function toString() { - return this.name + ": " + this.message; - }; - - return CustomError; -} - -util.newError = newError; - -/** - * Constructs a new protocol error. - * @classdesc Error subclass indicating a protocol specifc error. - * @memberof util - * @extends Error - * @template T extends Message - * @constructor - * @param {string} message Error message - * @param {Object.} [properties] Additional properties - * @example - * try { - * MyMessage.decode(someBuffer); // throws if required fields are missing - * } catch (e) { - * if (e instanceof ProtocolError && e.instance) - * console.log("decoded so far: " + JSON.stringify(e.instance)); - * } - */ -util.ProtocolError = newError("ProtocolError"); - -/** - * So far decoded message instance. - * @name util.ProtocolError#instance - * @type {Message} - */ - -/** - * A OneOf getter as returned by {@link util.oneOfGetter}. - * @typedef OneOfGetter - * @type {function} - * @returns {string|undefined} Set field name, if any - */ - -/** - * Builds a getter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfGetter} Unbound getter - */ -util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 1; - - /** - * @returns {string|undefined} Set field name, if any - * @this Object - * @ignore - */ - return function() { // eslint-disable-line consistent-return - for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) - if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) - return keys[i]; - }; -}; - -/** - * A OneOf setter as returned by {@link util.oneOfSetter}. - * @typedef OneOfSetter - * @type {function} - * @param {string|undefined} value Field name - * @returns {undefined} - */ - -/** - * Builds a setter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfSetter} Unbound setter - */ -util.oneOfSetter = function setOneOf(fieldNames) { - - /** - * @param {string} name Field name - * @returns {undefined} - * @this Object - * @ignore - */ - return function(name) { - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[fieldNames[i]]; - }; -}; - -/** - * Default conversion options used for {@link Message#toJSON} implementations. - * - * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: - * - * - Longs become strings - * - Enums become string keys - * - Bytes become base64 encoded strings - * - (Sub-)Messages become plain objects - * - Maps become plain objects with all string keys - * - Repeated fields become arrays - * - NaN and Infinity for float and double fields become strings - * - * @type {IConversionOptions} - * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json - */ -util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true -}; - -// Sets up buffer utility according to the environment (called in index-minimal) -util._configure = function() { - var Buffer = util.Buffer; - /* istanbul ignore if */ - if (!Buffer) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; - } - // because node 4.x buffers are incompatible & immutable - // see: https://github.com/dcodeIO/protobuf.js/pull/665 - util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || - /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer.allocUnsafe || - /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer(size); - }; -}; - - -/***/ }), - -/***/ 2147: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = Writer; - -var util = __webpack_require__(8835); - -var BufferWriter; // cyclic - -var LongBits = util.LongBits, - base64 = util.base64, - utf8 = util.utf8; - -/** - * Constructs a new writer operation instance. - * @classdesc Scheduled writer operation. - * @constructor - * @param {function(*, Uint8Array, number)} fn Function to call - * @param {number} len Value byte length - * @param {*} val Value to write - * @ignore - */ -function Op(fn, len, val) { - - /** - * Function to call. - * @type {function(Uint8Array, number, *)} - */ - this.fn = fn; - - /** - * Value byte length. - * @type {number} - */ - this.len = len; - - /** - * Next operation. - * @type {Writer.Op|undefined} - */ - this.next = undefined; - - /** - * Value to write. - * @type {*} - */ - this.val = val; // type varies -} - -/* istanbul ignore next */ -function noop() {} // eslint-disable-line no-empty-function - -/** - * Constructs a new writer state instance. - * @classdesc Copied writer state. - * @memberof Writer - * @constructor - * @param {Writer} writer Writer to copy state from - * @ignore - */ -function State(writer) { - - /** - * Current head. - * @type {Writer.Op} - */ - this.head = writer.head; - - /** - * Current tail. - * @type {Writer.Op} - */ - this.tail = writer.tail; - - /** - * Current buffer length. - * @type {number} - */ - this.len = writer.len; - - /** - * Next state. - * @type {State|null} - */ - this.next = writer.states; -} - -/** - * Constructs a new writer instance. - * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. - * @constructor - */ -function Writer() { - - /** - * Current length. - * @type {number} - */ - this.len = 0; - - /** - * Operations head. - * @type {Object} - */ - this.head = new Op(noop, 0, 0); - - /** - * Operations tail - * @type {Object} - */ - this.tail = this.head; - - /** - * Linked forked states. - * @type {Object|null} - */ - this.states = null; - - // When a value is written, the writer calculates its byte length and puts it into a linked - // list of operations to perform when finish() is called. This both allows us to allocate - // buffers of the exact required size and reduces the amount of work we have to do compared - // to first calculating over objects and then encoding over objects. In our case, the encoding - // part is just a linked list walk calling operations with already prepared values. -} - -var create = function create() { - return util.Buffer - ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); - } - /* istanbul ignore next */ - : function create_array() { - return new Writer(); - }; -}; - -/** - * Creates a new writer. - * @function - * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} - */ -Writer.create = create(); - -/** - * Allocates a buffer of the specified size. - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ -Writer.alloc = function alloc(size) { - return new util.Array(size); -}; - -// Use Uint8Array buffer pool in the browser, just like node does with buffers -/* istanbul ignore else */ -if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - -/** - * Pushes a new operation to the queue. - * @param {function(Uint8Array, number, *)} fn Function to call - * @param {number} len Value byte length - * @param {number} val Value to write - * @returns {Writer} `this` - * @private - */ -Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; -}; - -function writeByte(val, buf, pos) { - buf[pos] = val & 255; -} - -function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; -} - -/** - * Constructs a new varint writer operation instance. - * @classdesc Scheduled varint writer operation. - * @extends Op - * @constructor - * @param {number} len Value byte length - * @param {number} val Value to write - * @ignore - */ -function VarintOp(len, val) { - this.len = len; - this.next = undefined; - this.val = val; -} - -VarintOp.prototype = Object.create(Op.prototype); -VarintOp.prototype.fn = writeVarint32; - -/** - * Writes an unsigned 32 bit value as a varint. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.uint32 = function write_uint32(value) { - // here, the call to this.push has been inlined and a varint specific Op subclass is used. - // uint32 is by far the most frequently used operation and benefits significantly from this. - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) - < 128 ? 1 - : value < 16384 ? 2 - : value < 2097152 ? 3 - : value < 268435456 ? 4 - : 5, - value)).len; - return this; -}; - -/** - * Writes a signed 32 bit value as a varint. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.int32 = function write_int32(value) { - return value < 0 - ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec - : this.uint32(value); -}; - -/** - * Writes a 32 bit value as a varint, zig-zag encoded. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); -}; - -function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; -} - -/** - * Writes an unsigned 64 bit value as a varint. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a signed 64 bit value as a varint. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.int64 = Writer.prototype.uint64; - -/** - * Writes a signed 64 bit value as a varint, zig-zag encoded. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a boolish value as a varint. - * @param {boolean} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); -}; - -function writeFixed32(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -/** - * Writes an unsigned 32 bit value as fixed 32 bits. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); -}; - -/** - * Writes a signed 32 bit value as fixed 32 bits. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sfixed32 = Writer.prototype.fixed32; - -/** - * Writes an unsigned 64 bit value as fixed 64 bits. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); -}; - -/** - * Writes a signed 64 bit value as fixed 64 bits. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sfixed64 = Writer.prototype.fixed64; - -/** - * Writes a float (32 bit). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); -}; - -/** - * Writes a double (64 bit float). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); -}; - -var writeBytes = util.Array.prototype.set - ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); // also works for plain array values - } - /* istanbul ignore next */ - : function writeBytes_for(val, buf, pos) { - for (var i = 0; i < val.length; ++i) - buf[pos + i] = val[i]; - }; - -/** - * Writes a sequence of bytes. - * @param {Uint8Array|string} value Buffer or base64 encoded string to write - * @returns {Writer} `this` - */ -Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base64.length(value)); - base64.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); -}; - -/** - * Writes a string. - * @param {string} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len - ? this.uint32(len)._push(utf8.write, len, value) - : this._push(writeByte, 1, 0); -}; - -/** - * Forks this writer's state by pushing it to a stack. - * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. - * @returns {Writer} `this` - */ -Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; -}; - -/** - * Resets this instance to the last state. - * @returns {Writer} `this` - */ -Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; -}; - -/** - * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. - * @returns {Writer} `this` - */ -Writer.prototype.ldelim = function ldelim() { - var head = this.head, - tail = this.tail, - len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; // skip noop - this.tail = tail; - this.len += len; - } - return this; -}; - -/** - * Finishes the write operation. - * @returns {Uint8Array} Finished buffer - */ -Writer.prototype.finish = function finish() { - var head = this.head.next, // skip noop - buf = this.constructor.alloc(this.len), - pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - // this.head = this.tail = null; - return buf; -}; - -Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create(); - BufferWriter._configure(); -}; - - -/***/ }), - -/***/ 5055: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -module.exports = BufferWriter; - -// extends Writer -var Writer = __webpack_require__(2147); -(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - -var util = __webpack_require__(8835); - -/** - * Constructs a new buffer writer instance. - * @classdesc Wire format writer using node buffers. - * @extends Writer - * @constructor - */ -function BufferWriter() { - Writer.call(this); -} - -BufferWriter._configure = function () { - /** - * Allocates a buffer of the specified size. - * @function - * @param {number} size Buffer size - * @returns {Buffer} Buffer - */ - BufferWriter.alloc = util._Buffer_allocUnsafe; - - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" - ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) - // also works for plain array values - } - /* istanbul ignore next */ - : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) // Buffer values - val.copy(buf, pos, 0, val.length); - else for (var i = 0; i < val.length;) // plain array values - buf[pos++] = val[i++]; - }; -}; - - -/** - * @override - */ -BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; -}; - -function writeStringBuffer(val, buf, pos) { - if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); -} - -/** - * @override - */ -BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; -}; - - -/** - * Finishes the write operation. - * @name BufferWriter#finish - * @function - * @returns {Buffer} Finished buffer - */ - -BufferWriter._configure(); - - -/***/ }), - -/***/ 8186: -/***/ (function(module) { - -"use strict"; - - -(function(root) { - const MAX_VALUE = 0x7fffffff; - - // The SHA256 and PBKDF2 implementation are from scrypt-async-js: - // See: https://github.com/dchest/scrypt-async-js - function SHA256(m) { - const K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, - 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, - 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, - 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, - 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, - 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, - 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, - 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, - 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, - 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 - ]); - - let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a; - let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19; - const w = new Uint32Array(64); - - function blocks(p) { - let off = 0, len = p.length; - while (len >= 64) { - let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i, j, t1, t2; - - for (i = 0; i < 16; i++) { - j = off + i*4; - w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) | - ((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff); - } - - for (i = 16; i < 64; i++) { - u = w[i-2]; - t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10); - - u = w[i-15]; - t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3); - - w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0; - } - - for (i = 0; i < 64; i++) { - t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^ - ((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) + - ((h + ((K[i] + w[i]) | 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 / 0x20000000) | 0, - bitLenLo = m.length << 3, - numZeros = (bytesLeft < 56) ? 56 : 120, - p = m.slice(m.length - bytesLeft, m.length); - - p.push(0x80); - for (i = bytesLeft + 1; i < numZeros; i++) { p.push(0); } - p.push((bitLenHi >>> 24) & 0xff); - p.push((bitLenHi >>> 16) & 0xff); - p.push((bitLenHi >>> 8) & 0xff); - p.push((bitLenHi >>> 0) & 0xff); - p.push((bitLenLo >>> 24) & 0xff); - p.push((bitLenLo >>> 16) & 0xff); - p.push((bitLenLo >>> 8) & 0xff); - p.push((bitLenLo >>> 0) & 0xff); - - blocks(p); - - return [ - (h0 >>> 24) & 0xff, (h0 >>> 16) & 0xff, (h0 >>> 8) & 0xff, (h0 >>> 0) & 0xff, - (h1 >>> 24) & 0xff, (h1 >>> 16) & 0xff, (h1 >>> 8) & 0xff, (h1 >>> 0) & 0xff, - (h2 >>> 24) & 0xff, (h2 >>> 16) & 0xff, (h2 >>> 8) & 0xff, (h2 >>> 0) & 0xff, - (h3 >>> 24) & 0xff, (h3 >>> 16) & 0xff, (h3 >>> 8) & 0xff, (h3 >>> 0) & 0xff, - (h4 >>> 24) & 0xff, (h4 >>> 16) & 0xff, (h4 >>> 8) & 0xff, (h4 >>> 0) & 0xff, - (h5 >>> 24) & 0xff, (h5 >>> 16) & 0xff, (h5 >>> 8) & 0xff, (h5 >>> 0) & 0xff, - (h6 >>> 24) & 0xff, (h6 >>> 16) & 0xff, (h6 >>> 8) & 0xff, (h6 >>> 0) & 0xff, - (h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, (h7 >>> 0) & 0xff - ]; - } - - function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) { - // compress password if it's longer than hash block length - 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 = []; - - // inner = (password ^ ipad) || salt || counter - for (i = 0; i < 64; i++) { inner[i] = 0x36; } - 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; } - - // outerKey = password ^ opad - for (i = 0; i < 64; i++) outerKey[i] = 0x5c; - for (i = 0; i < password.length; i++) outerKey[i] ^= password[i]; - - // increments counter inside inner - function incrementCounter() { - for (let i = innerLen - 1; i >= innerLen - 4; i--) { - inner[i]++; - if (inner[i] <= 0xff) return; - inner[i] = 0; - } - } - - // output blocks = SHA256(outerKey || SHA256(inner)) ... - 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; - } - - // The following is an adaptation of scryptsy - // See: https://www.npmjs.com/package/scryptsy - 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]; - } - } - - // naive approach... going back to loop unrolling may yield additional performance - 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; - } - } - - return true; - } - - function ensureInteger(value, name) { - if (typeof(value) !== "number" || (value % 1)) { throw new Error('invalid ' + name); } - return value; - } - - // N = Cpu cost, r = Memory cost, p = parallelization cost - // callback(error, progress, key) - 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 > MAX_VALUE / 128 / r) { throw new Error('N too large'); } - if (r > MAX_VALUE / 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] & 0xff) << 24) | - ((b[j + 2] & 0xff) << 16) | - ((b[j + 1] & 0xff) << 8) | - ((b[j + 0] & 0xff) << 0); - } - - const XY = new Uint32Array(64 * r); - const V = new Uint32Array(32 * r * N); - - const Yi = 32 * r; - - // scratch space - const x = new Uint32Array(16); // salsa20_8 - const _X = new Uint32Array(16); // blockmix_salsa8 - - const totalOps = p * N * 2; - let currentOp = 0; - let lastPercent10 = null; - - // Set this to true to abandon the scrypt on the next step - let stop = false; - - // State information - let state = 0; - let i0 = 0, i1; - let Bi; - - // How many blockmix_salsa8 can we do per step? - const limit = callback ? parseInt(1000 / r): 0xffffffff; - - // Trick from scrypt-async; if there is a setImmediate shim in place, use it - const nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout; - - // This is really all I changed; making scryptsy a state machine so we occasionally - // stop and give other evnts on the evnt loop a chance to run. ~RicMoo - const incrementalSMix = function() { - if (stop) { - return callback(new Error('cancelled'), currentOp / totalOps); - } - - let steps; - - switch (state) { - case 0: - // for (var i = 0; i < p; i++)... - Bi = i0 * 32 * r; - - arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1 - - state = 1; // Move to ROMix 2 - i1 = 0; - - // Fall through - - case 1: - - // Run up to 1000 steps of the first inner smix loop - steps = N - i1; - if (steps > limit) { steps = limit; } - for (let i = 0; i < steps; i++) { // ROMix - 2 - arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3 - blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4 - } - - // for (var i = 0; i < N; i++) - i1 += steps; - currentOp += steps; - - if (callback) { - // Call the callback with the progress (optionally stopping us) - const percent10 = parseInt(1000 * currentOp / totalOps); - if (percent10 !== lastPercent10) { - stop = callback(null, currentOp / totalOps); - if (stop) { break; } - lastPercent10 = percent10; - } - } - - if (i1 < N) { break; } - - i1 = 0; // Move to ROMix 6 - state = 2; - - // Fall through - - case 2: - - // Run up to 1000 steps of the second inner smix loop - steps = N - i1; - if (steps > limit) { steps = limit; } - for (let i = 0; i < steps; i++) { // ROMix - 6 - const offset = (2 * r - 1) * 16; // ROMix - 7 - const j = XY[offset] & (N - 1); - blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner) - blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer) - } - - // for (var i = 0; i < N; i++)... - i1 += steps; - currentOp += steps; - - // Call the callback with the progress (optionally stopping us) - if (callback) { - const percent10 = parseInt(1000 * 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); // ROMix - 10 - - // for (var i = 0; i < p; i++)... - i0++; - if (i0 < p) { - state = 0; - break; - } - - b = []; - for (let i = 0; i < B.length; i++) { - b.push((B[i] >> 0) & 0xff); - b.push((B[i] >> 8) & 0xff); - b.push((B[i] >> 16) & 0xff); - b.push((B[i] >> 24) & 0xff); - } - - const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen); - - // Send the result to the callback - if (callback) { callback(null, 1.0, derivedKey); } - - // Done; don't break (which would reschedule) - return derivedKey; - } - - // Schedule the next steps - if (callback) { nextTick(incrementalSMix); } - } - - // Run the smix state machine until completion - if (!callback) { - while (true) { - const derivedKey = incrementalSMix(); - if (derivedKey != undefined) { return derivedKey; } - } - } - - // Bootstrap the async incremental smix - 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)); - } - }; - - // node.js - if (true) { - module.exports = lib; - - // RequireJS/AMD - // http://www.requirejs.org/docs/api.html - // https://github.com/amdjs/amdjs-api/wiki/AMD - } else {} - -})(this); - - -/***/ }), - -/***/ 4372: -/***/ ((module) => { - -module.exports = readable => { - // Node.js stream - if (readable[Symbol.asyncIterator]) return readable - - // Browser ReadableStream - if (readable.getReader) { - return (async function * () { - const reader = readable.getReader() - - try { - while (true) { - const { done, value } = await reader.read() - if (done) return - yield value - } - } finally { - reader.releaseLock() - } - })() - } - - throw new Error('unknown stream') -} - - -/***/ }), - -/***/ 3434: -/***/ ((module) => { - -module.exports = read - -var MSB = 0x80 - , REST = 0x7F - -function read(buf, offset) { - var res = 0 - , offset = offset || 0 - , shift = 0 - , counter = offset - , b - , l = buf.length - - do { - if (counter >= l || shift > 49) { - read.bytes = 0 - throw new RangeError('Could not decode varint') - } - b = buf[counter++] - res += shift < 28 - ? (b & REST) << shift - : (b & REST) * Math.pow(2, shift) - shift += 7 - } while (b >= MSB) - - read.bytes = counter - offset - - return res -} - - -/***/ }), - -/***/ 399: -/***/ ((module) => { - -module.exports = encode - -var MSB = 0x80 - , REST = 0x7F - , MSBALL = ~REST - , INT = Math.pow(2, 31) - -function encode(num, out, offset) { - if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) { - encode.bytes = 0 - throw new RangeError('Could not encode varint') - } - out = out || [] - offset = offset || 0 - var oldOffset = offset - - while(num >= INT) { - out[offset++] = (num & 0xFF) | MSB - num /= 128 - } - while(num & MSBALL) { - out[offset++] = (num & 0xFF) | MSB - num >>>= 7 - } - out[offset] = num | 0 - - encode.bytes = offset - oldOffset + 1 - - return out -} - - -/***/ }), - -/***/ 1114: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = { - encode: __webpack_require__(399) - , decode: __webpack_require__(3434) - , encodingLength: __webpack_require__(9581) -} - - -/***/ }), - -/***/ 9581: -/***/ ((module) => { - - -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) - -module.exports = 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 - ) -} - - -/***/ }), - -/***/ 308: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Dy": () => (/* reexport safe */ _lib_token_js__WEBPACK_IMPORTED_MODULE_2__.D), -/* harmony export */ "Jx": () => (/* reexport safe */ _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__.Jx), -/* harmony export */ "WU": () => (/* reexport safe */ _lib_token_js__WEBPACK_IMPORTED_MODULE_2__.W), -/* harmony export */ "cv": () => (/* reexport safe */ _lib_encode_js__WEBPACK_IMPORTED_MODULE_0__.cv) -/* harmony export */ }); -/* harmony import */ var _lib_encode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6456); -/* harmony import */ var _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2972); -/* harmony import */ var _lib_token_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1302); - - - - - -/***/ }), - -/***/ 7228: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Fh": () => (/* binding */ encodeUint), -/* harmony export */ "Jl": () => (/* binding */ readUint32), -/* harmony export */ "Km": () => (/* binding */ decodeUint8), -/* harmony export */ "Tp": () => (/* binding */ encodeUintValue), -/* harmony export */ "X0": () => (/* binding */ readUint16), -/* harmony export */ "YX": () => (/* binding */ readUint64), -/* harmony export */ "Zh": () => (/* binding */ decodeUint16), -/* harmony export */ "cs": () => (/* binding */ decodeUint32), -/* harmony export */ "kj": () => (/* binding */ readUint8), -/* harmony export */ "or": () => (/* binding */ uintBoundaries), -/* harmony export */ "uN": () => (/* binding */ decodeUint64) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3002); - - -const uintBoundaries = [ - 24, - 256, - 65536, - 4294967296, - BigInt('18446744073709551616') -]; -function readUint8(data, offset, options) { - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(data, offset, 1); - const value = data[offset]; - if (options.strict === true && value < uintBoundaries[0]) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } integer encoded in more bytes than necessary (strict decode)`); - } - return value; -} -function readUint16(data, offset, options) { - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(data, offset, 2); - const value = data[offset] << 8 | data[offset + 1]; - if (options.strict === true && value < uintBoundaries[1]) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } integer encoded in more bytes than necessary (strict decode)`); - } - return value; -} -function readUint32(data, offset, options) { - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(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(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } integer encoded in more bytes than necessary (strict decode)`); - } - return value; -} -function readUint64(data, offset, options) { - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(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(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } 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(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } integers outside of the safe integer range are not supported`); -} -function decodeUint8(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint, readUint8(data, pos + 1, options), 2); -} -function decodeUint16(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint, readUint16(data, pos + 1, options), 3); -} -function decodeUint32(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint, readUint32(data, pos + 1, options), 5); -} -function decodeUint64(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint, readUint64(data, pos + 1, options), 9); -} -function encodeUint(buf, token) { - return encodeUintValue(buf, 0, token.value); -} -function encodeUintValue(buf, major, uint) { - if (uint < uintBoundaries[0]) { - const nuint = Number(uint); - buf.push([major | nuint]); - } else if (uint < uintBoundaries[1]) { - const nuint = Number(uint); - buf.push([ - major | 24, - nuint - ]); - } else if (uint < uintBoundaries[2]) { - const nuint = Number(uint); - buf.push([ - major | 25, - nuint >>> 8, - nuint & 255 - ]); - } else if (uint < uintBoundaries[3]) { - const nuint = Number(uint); - buf.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; - buf.push(set); - } else { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } encountered BigInt larger than allowable range`); - } - } -} -encodeUint.encodedSize = function encodedSize(token) { - return encodeUintValue.encodedSize(token.value); -}; -encodeUintValue.encodedSize = function encodedSize(uint) { - if (uint < uintBoundaries[0]) { - return 1; - } - 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; -}; - -/***/ }), - -/***/ 608: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "UT": () => (/* binding */ encodeNegint), -/* harmony export */ "ec": () => (/* binding */ decodeNegint64), -/* harmony export */ "r0": () => (/* binding */ decodeNegint16), -/* harmony export */ "wy": () => (/* binding */ decodeNegint32), -/* harmony export */ "yr": () => (/* binding */ decodeNegint8) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7228); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3002); - - - -function decodeNegint8(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint8 */ .kj(data, pos + 1, options), 2); -} -function decodeNegint16(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint16 */ .X0(data, pos + 1, options), 3); -} -function decodeNegint32(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint32 */ .Jl(data, pos + 1, options), 5); -} -const neg1b = BigInt(-1); -const pos1b = BigInt(1); -function decodeNegint64(data, pos, _minor, options) { - const int = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint64 */ .YX(data, pos + 1, options); - if (typeof int !== 'bigint') { - const value = -1 - int; - if (value >= Number.MIN_SAFE_INTEGER) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, value, 9); - } - } - if (options.allowBigInt !== true) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeErrPrefix */ .IR } integers outside of the safe integer range are not supported`); - } - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, neg1b - BigInt(int), 9); -} -function encodeNegint(buf, token) { - const negint = token.value; - const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1; - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue */ .Tp(buf, token.type.majorEncoded, unsigned); -} -encodeNegint.encodedSize = function encodedSize(token) { - const negint = token.value; - const unsigned = typeof negint === 'bigint' ? negint * neg1b - pos1b : negint * -1 - 1; - if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .uintBoundaries[0] */ .or[0]) { - return 1; - } - if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .uintBoundaries[1] */ .or[1]) { - return 2; - } - if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .uintBoundaries[2] */ .or[2]) { - return 3; - } - if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .uintBoundaries[3] */ .or[3]) { - return 5; - } - return 9; -}; -encodeNegint.compareTokens = function compareTokens(tok1, tok2) { - return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0; -}; - -/***/ }), - -/***/ 622: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BS": () => (/* binding */ decodeBytes16), -/* harmony export */ "Ii": () => (/* binding */ decodeBytesCompact), -/* harmony export */ "ME": () => (/* binding */ decodeBytes64), -/* harmony export */ "UQ": () => (/* binding */ decodeBytes8), -/* harmony export */ "hg": () => (/* binding */ encodeBytes), -/* harmony export */ "zU": () => (/* binding */ decodeBytes32) -/* harmony export */ }); -/* unused harmony export compareBytes */ -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3002); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7228); -/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1926); - - - - -function toToken(data, pos, prefix, length) { - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(data, pos, prefix + length); - const buf = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .slice */ .tP)(data, pos + prefix, pos + prefix + length); - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.bytes */ .D.bytes, buf, 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, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint8 */ .kj(data, pos + 1, options)); -} -function decodeBytes16(data, pos, _minor, options) { - return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint16 */ .X0(data, pos + 1, options)); -} -function decodeBytes32(data, pos, _minor, options) { - return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint32 */ .Jl(data, pos + 1, options)); -} -function decodeBytes64(data, pos, _minor, options) { - const l = _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint64 */ .YX(data, pos + 1, options); - if (typeof l === 'bigint') { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } 64-bit integer bytes lengths not supported`); - } - return toToken(data, pos, 9, l); -} -function tokenBytes(token) { - if (token.encodedBytes === undefined) { - token.encodedBytes = token.type === _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.string */ .D.string ? (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .fromString */ .mL)(token.value) : token.value; - } - return token.encodedBytes; -} -function encodeBytes(buf, token) { - const bytes = tokenBytes(token); - _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .encodeUintValue */ .Tp(buf, token.type.majorEncoded, bytes.length); - buf.push(bytes); -} -encodeBytes.encodedSize = function encodedSize(token) { - const bytes = tokenBytes(token); - return _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .encodeUintValue.encodedSize */ .Tp.encodedSize(bytes.length) + bytes.length; -}; -encodeBytes.compareTokens = function compareTokens(tok1, tok2) { - return compareBytes(tokenBytes(tok1), tokenBytes(tok2)); -}; -function compareBytes(b1, b2) { - return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .compare */ .qu)(b1, b2); -} - -/***/ }), - -/***/ 1301: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Bq": () => (/* binding */ decodeString8), -/* harmony export */ "YW": () => (/* binding */ encodeString), -/* harmony export */ "bc": () => (/* binding */ decodeString64), -/* harmony export */ "h": () => (/* binding */ decodeString16), -/* harmony export */ "nt": () => (/* binding */ decodeStringCompact), -/* harmony export */ "q0": () => (/* binding */ decodeString32) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3002); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7228); -/* harmony import */ var _2bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(622); -/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1926); - - - - - -function toToken(data, pos, prefix, length, options) { - const totLength = prefix + length; - (0,_common_js__WEBPACK_IMPORTED_MODULE_1__/* .assertEnoughData */ .DO)(data, pos, totLength); - const tok = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.string */ .D.string, (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_4__/* .toString */ .BB)(data, pos + prefix, pos + totLength), totLength); - if (options.retainStringBytes === true) { - tok.byteValue = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_4__/* .slice */ .tP)(data, pos + prefix, pos + totLength); - } - return tok; -} -function decodeStringCompact(data, pos, minor, options) { - return toToken(data, pos, 1, minor, options); -} -function decodeString8(data, pos, _minor, options) { - return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint8 */ .kj(data, pos + 1, options), options); -} -function decodeString16(data, pos, _minor, options) { - return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint16 */ .X0(data, pos + 1, options), options); -} -function decodeString32(data, pos, _minor, options) { - return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint32 */ .Jl(data, pos + 1, options), options); -} -function decodeString64(data, pos, _minor, options) { - const l = _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .readUint64 */ .YX(data, pos + 1, options); - if (typeof l === 'bigint') { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } 64-bit integer string lengths not supported`); - } - return toToken(data, pos, 9, l, options); -} -const encodeString = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .encodeBytes */ .hg; - -/***/ }), - -/***/ 7656: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "HF": () => (/* binding */ encodeArray), -/* harmony export */ "Ju": () => (/* binding */ decodeArrayCompact), -/* harmony export */ "OC": () => (/* binding */ decodeArray16), -/* harmony export */ "a8": () => (/* binding */ decodeArray64), -/* harmony export */ "h7": () => (/* binding */ decodeArray8), -/* harmony export */ "lY": () => (/* binding */ decodeArray32), -/* harmony export */ "s5": () => (/* binding */ decodeArrayIndefinite) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7228); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3002); - - - -function toToken(_data, _pos, prefix, length) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.array */ .D.array, length, prefix); -} -function decodeArrayCompact(data, pos, minor, _options) { - return toToken(data, pos, 1, minor); -} -function decodeArray8(data, pos, _minor, options) { - return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint8 */ .kj(data, pos + 1, options)); -} -function decodeArray16(data, pos, _minor, options) { - return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint16 */ .X0(data, pos + 1, options)); -} -function decodeArray32(data, pos, _minor, options) { - return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint32 */ .Jl(data, pos + 1, options)); -} -function decodeArray64(data, pos, _minor, options) { - const l = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint64 */ .YX(data, pos + 1, options); - if (typeof l === 'bigint') { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeErrPrefix */ .IR } 64-bit integer array lengths not supported`); - } - return toToken(data, pos, 9, l); -} -function decodeArrayIndefinite(data, pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeErrPrefix */ .IR } indefinite length items not allowed`); - } - return toToken(data, pos, 1, Infinity); -} -function encodeArray(buf, token) { - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue */ .Tp(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.array.majorEncoded */ .D.array.majorEncoded, token.value); -} -encodeArray.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUint.compareTokens */ .Fh.compareTokens; -encodeArray.encodedSize = function encodedSize(token) { - return _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue.encodedSize */ .Tp.encodedSize(token.value); -}; - -/***/ }), - -/***/ 1613: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "F2": () => (/* binding */ decodeMap64), -/* harmony export */ "G": () => (/* binding */ decodeMap8), -/* harmony export */ "IY": () => (/* binding */ decodeMap32), -/* harmony export */ "KI": () => (/* binding */ encodeMap), -/* harmony export */ "_K": () => (/* binding */ decodeMapCompact), -/* harmony export */ "ng": () => (/* binding */ decodeMapIndefinite), -/* harmony export */ "qe": () => (/* binding */ decodeMap16) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7228); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3002); - - - -function toToken(_data, _pos, prefix, length) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.map */ .D.map, length, prefix); -} -function decodeMapCompact(data, pos, minor, _options) { - return toToken(data, pos, 1, minor); -} -function decodeMap8(data, pos, _minor, options) { - return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint8 */ .kj(data, pos + 1, options)); -} -function decodeMap16(data, pos, _minor, options) { - return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint16 */ .X0(data, pos + 1, options)); -} -function decodeMap32(data, pos, _minor, options) { - return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint32 */ .Jl(data, pos + 1, options)); -} -function decodeMap64(data, pos, _minor, options) { - const l = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint64 */ .YX(data, pos + 1, options); - if (typeof l === 'bigint') { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeErrPrefix */ .IR } 64-bit integer map lengths not supported`); - } - return toToken(data, pos, 9, l); -} -function decodeMapIndefinite(data, pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeErrPrefix */ .IR } indefinite length items not allowed`); - } - return toToken(data, pos, 1, Infinity); -} -function encodeMap(buf, token) { - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue */ .Tp(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.map.majorEncoded */ .D.map.majorEncoded, token.value); -} -encodeMap.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUint.compareTokens */ .Fh.compareTokens; -encodeMap.encodedSize = function encodedSize(token) { - return _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue.encodedSize */ .Tp.encodedSize(token.value); -}; - -/***/ }), - -/***/ 6589: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CF": () => (/* binding */ decodeTag16), -/* harmony export */ "MV": () => (/* binding */ decodeTag64), -/* harmony export */ "ZR": () => (/* binding */ decodeTag8), -/* harmony export */ "qJ": () => (/* binding */ decodeTagCompact), -/* harmony export */ "vP": () => (/* binding */ decodeTag32), -/* harmony export */ "xy": () => (/* binding */ encodeTag) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7228); - - -function decodeTagCompact(_data, _pos, minor, _options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .D.tag, minor, 1); -} -function decodeTag8(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .D.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint8 */ .kj(data, pos + 1, options), 2); -} -function decodeTag16(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .D.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint16 */ .X0(data, pos + 1, options), 3); -} -function decodeTag32(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .D.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint32 */ .Jl(data, pos + 1, options), 5); -} -function decodeTag64(data, pos, _minor, options) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .D.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .readUint64 */ .YX(data, pos + 1, options), 9); -} -function encodeTag(buf, token) { - _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue */ .Tp(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag.majorEncoded */ .D.tag.majorEncoded, token.value); -} -encodeTag.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUint.compareTokens */ .Fh.compareTokens; -encodeTag.encodedSize = function encodedSize(token) { - return _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeUintValue.encodedSize */ .Tp.encodedSize(token.value); -}; - -/***/ }), - -/***/ 3964: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GI": () => (/* binding */ decodeFloat32), -/* harmony export */ "h1": () => (/* binding */ decodeUndefined), -/* harmony export */ "mW": () => (/* binding */ decodeFloat16), -/* harmony export */ "tA": () => (/* binding */ encodeFloat), -/* harmony export */ "vV": () => (/* binding */ decodeFloat64), -/* harmony export */ "y7": () => (/* binding */ decodeBreak) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3002); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7228); - - - -const MINOR_FALSE = 20; -const MINOR_TRUE = 21; -const MINOR_NULL = 22; -const MINOR_UNDEFINED = 23; -function decodeUndefined(_data, _pos, _minor, options) { - if (options.allowUndefined === false) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } undefined values are not supported`); - } else if (options.coerceUndefinedToNull === true) { - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["null"] */ .D["null"], null, 1); - } - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.undefined */ .D.undefined, undefined, 1); -} -function decodeBreak(_data, _pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } indefinite length items not allowed`); - } - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["break"] */ .D["break"], undefined, 1); -} -function createToken(value, bytes, options) { - if (options) { - if (options.allowNaN === false && Number.isNaN(value)) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } NaN values are not supported`); - } - if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } Infinity values are not supported`); - } - } - return new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.float */ .D.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(buf, token, options) { - const float = token.value; - if (float === false) { - buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.float.majorEncoded */ .D.float.majorEncoded | MINOR_FALSE]); - } else if (float === true) { - buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.float.majorEncoded */ .D.float.majorEncoded | MINOR_TRUE]); - } else if (float === null) { - buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.float.majorEncoded */ .D.float.majorEncoded | MINOR_NULL]); - } else if (float === undefined) { - buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.float.majorEncoded */ .D.float.majorEncoded | MINOR_UNDEFINED]); - } 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; - buf.push(ui8a.slice(0, 3)); - success = true; - } else { - encodeFloat32(float); - decoded = readFloat32(ui8a, 1); - if (float === decoded) { - ui8a[0] = 250; - buf.push(ui8a.slice(0, 5)); - success = true; - } - } - } - if (!success) { - encodeFloat64(float); - decoded = readFloat64(ui8a, 1); - ui8a[0] = 251; - buf.push(ui8a.slice(0, 9)); - } - } -} -encodeFloat.encodedSize = function encodedSize(token, options) { - const float = token.value; - if (float === false || float === true || float === null || float === undefined) { - 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(ui8a, pos) { - if (ui8a.length - pos < 2) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } not enough data for float16`); - } - const half = (ui8a[pos] << 8) + ui8a[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(ui8a, pos) { - if (ui8a.length - pos < 4) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } not enough data for float32`); - } - const offset = (ui8a.byteOffset || 0) + pos; - return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false); -} -function encodeFloat64(inp) { - dataView.setFloat64(0, inp, false); -} -function readFloat64(ui8a, pos) { - if (ui8a.length - pos < 8) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeErrPrefix */ .IR } not enough data for float64`); - } - const offset = (ui8a.byteOffset || 0) + pos; - return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false); -} -encodeFloat.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_2__/* .encodeUint.compareTokens */ .Fh.compareTokens; - -/***/ }), - -/***/ 1926: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BB": () => (/* binding */ toString), -/* harmony export */ "Dz": () => (/* binding */ asU8A), -/* harmony export */ "Pu": () => (/* binding */ decodeCodePointsArray), -/* harmony export */ "mL": () => (/* binding */ fromString), -/* harmony export */ "nI": () => (/* binding */ fromArray), -/* harmony export */ "qu": () => (/* binding */ compare), -/* harmony export */ "tP": () => (/* binding */ slice), -/* harmony export */ "un": () => (/* binding */ alloc), -/* harmony export */ "zo": () => (/* binding */ concat) -/* harmony export */ }); -/* unused harmony exports useBuffer, toHex, fromHex */ -const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === 'function'; -const textDecoder = new TextDecoder(); -const textEncoder = new TextEncoder(); -function isBuffer(buf) { - return useBuffer && globalThis.Buffer.isBuffer(buf); -} -function asU8A(buf) { - if (!(buf instanceof Uint8Array)) { - return Uint8Array.from(buf); - } - return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf; -} -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 ? textDecoder.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(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); -}; -const toHex = (/* unused pure expression or super */ null && (useBuffer ? d => { - if (typeof d === 'string') { - return d; - } - return globalThis.Buffer.from(toBytes(d)).toString('hex'); -} : d => { - if (typeof d === 'string') { - return d; - } - return Array.prototype.reduce.call(toBytes(d), (p, c) => `${ p }${ c.toString(16).padStart(2, '0') }`, ''); -})); -const fromHex = (/* unused pure expression or super */ null && (useBuffer ? hex => { - if (hex instanceof Uint8Array) { - return hex; - } - return globalThis.Buffer.from(hex, 'hex'); -} : hex => { - if (hex instanceof Uint8Array) { - return hex; - } - if (!hex.length) { - return new Uint8Array(0); - } - return new Uint8Array(hex.split('').map((c, i, d) => i % 2 === 0 ? `0x${ c }${ d[i + 1] }` : '').filter(Boolean).map(e => parseInt(e, 16))); -})); -function toBytes(obj) { - if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') { - return obj; - } - if (obj instanceof ArrayBuffer) { - return new Uint8Array(obj); - } - if (ArrayBuffer.isView(obj)) { - return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength); - } - throw new Error('Unknown type, must be binary type'); -} -function compare(b1, b2) { - if (isBuffer(b1) && isBuffer(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(string, units = Infinity) { - let codePoint; - const length = string.length; - let leadSurrogate = null; - const bytes = []; - for (let i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i + 1 === length) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); - } else { - throw new Error('Invalid code point'); - } - } - return bytes; -} -function utf8Slice(buf, offset, end) { - const res = []; - while (offset < end) { - const firstByte = buf[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 = buf[offset + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[offset + 1]; - thirdByte = buf[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 = buf[offset + 1]; - thirdByte = buf[offset + 2]; - fourthByte = buf[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; - } - } - } - } - 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 <= MAX_ARGUMENTS_LENGTH) { - 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; -} - -/***/ }), - -/***/ 3002: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DO": () => (/* binding */ assertEnoughData), -/* harmony export */ "IR": () => (/* binding */ decodeErrPrefix), -/* harmony export */ "OO": () => (/* binding */ encodeErrPrefix) -/* harmony export */ }); -/* unused harmony export uintMinorPrefixBytes */ -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`); - } -} - - -/***/ }), - -/***/ 2972: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Jx": () => (/* binding */ decode) -/* harmony export */ }); -/* unused harmony exports Tokeniser, tokensToObject */ -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3002); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1302); -/* harmony import */ var _jump_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1266); - - - -const defaultDecodeOptions = { - strict: false, - allowIndefinite: true, - allowUndefined: true, - allowBigInt: true -}; -class Tokeniser { - constructor(data, options = {}) { - this.pos = 0; - this.data = data; - this.options = options; - } - done() { - return this.pos >= this.data.length; - } - next() { - const byt = this.data[this.pos]; - let token = _jump_js__WEBPACK_IMPORTED_MODULE_2__/* .quick */ .PS[byt]; - if (token === undefined) { - const decoder = _jump_js__WEBPACK_IMPORTED_MODULE_2__/* .jump */ .cW[byt]; - if (!decoder) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } 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; - } -} -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(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } got unexpected break to lengthed array`); - } - if (value === DONE) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } found array but not enough entries (got ${ i }, expected ${ token.value })`); - } - arr[i] = value; - } - return arr; -} -function tokenToMap(token, tokeniser, options) { - const useMaps = options.useMaps === true; - const obj = useMaps ? undefined : {}; - const m = useMaps ? new Map() : undefined; - for (let i = 0; i < token.value; i++) { - const key = tokensToObject(tokeniser, options); - if (key === BREAK) { - if (token.value === Infinity) { - break; - } - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } got unexpected break to lengthed map`); - } - if (key === DONE) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } found map but not enough entries (got ${ i } [no key], expected ${ token.value })`); - } - if (useMaps !== true && typeof key !== 'string') { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } non-string keys not supported (got ${ typeof key })`); - } - const value = tokensToObject(tokeniser, options); - if (value === DONE) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } found map but not enough entries (got ${ i } [no value], expected ${ token.value })`); - } - if (useMaps) { - m.set(key, value); - } else { - obj[key] = value; - } - } - return useMaps ? m : obj; -} -function tokensToObject(tokeniser, options) { - if (tokeniser.done()) { - return DONE; - } - const token = tokeniser.next(); - if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__/* .Type["break"] */ .D["break"]) { - return BREAK; - } - if (token.type.terminal) { - return token.value; - } - if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__/* .Type.array */ .D.array) { - return tokenToArray(token, tokeniser, options); - } - if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__/* .Type.map */ .D.map) { - return tokenToMap(token, tokeniser, options); - } - if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__/* .Type.tag */ .D.tag) { - if (options.tags && typeof options.tags[token.value] === 'function') { - const tagged = tokensToObject(tokeniser, options); - return options.tags[token.value](tagged); - } - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } tag not supported (${ token.value })`); - } - throw new Error('unsupported'); -} -function decode(data, options) { - if (!(data instanceof Uint8Array)) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } data to decode must be a Uint8Array`); - } - options = Object.assign({}, defaultDecodeOptions, options); - const tokeniser = options.tokenizer || new Tokeniser(data, options); - const decoded = tokensToObject(tokeniser, options); - if (decoded === DONE) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } did not find any content to decode`); - } - if (decoded === BREAK) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } got unexpected break`); - } - if (!tokeniser.done()) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_0__/* .decodeErrPrefix */ .IR } too many terminals, data makes no sense`); - } - return decoded; -} - - -/***/ }), - -/***/ 6456: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "cv": () => (/* binding */ encode), - "w$": () => (/* binding */ encodeCustom) -}); - -// UNUSED EXPORTS: Ref, makeCborEncoders, objectToTokens - -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/is.js -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 === undefined) { - 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 undefined; -} -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/token.js -var token = __webpack_require__(1302); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/byte-utils.js -var byte_utils = __webpack_require__(1926); -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/bl.js - -const defaultChunkSize = 256; -class Bl { - constructor(chunkSize = defaultChunkSize) { - 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; - } - } - if (bytes.length < 64 && bytes.length < this.chunkSize) { - topChunk = (0,byte_utils/* alloc */.un)(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 = (0,byte_utils/* slice */.tP)(chunk, 0, this.cursor); - } - } else { - byts = (0,byte_utils/* concat */.zo)(this.chunks, this.cursor); - } - if (reset) { - this.reset(); - } - return byts; - } -} -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/common.js -var common = __webpack_require__(3002); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/jump.js -var jump = __webpack_require__(1266); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/0uint.js -var _0uint = __webpack_require__(7228); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/1negint.js -var _1negint = __webpack_require__(608); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/2bytes.js -var _2bytes = __webpack_require__(622); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/3string.js -var _3string = __webpack_require__(1301); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/4array.js -var _4array = __webpack_require__(7656); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/5map.js -var _5map = __webpack_require__(1613); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/6tag.js -var _6tag = __webpack_require__(6589); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/7float.js -var _7float = __webpack_require__(3964); -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/encode.js - - - - - - - - - - - - - - -const defaultEncodeOptions = { - float64: false, - mapSorter, - quickEncodeToken: jump/* quickEncodeToken */.JN -}; -function makeCborEncoders() { - const encoders = []; - encoders[token/* Type.uint.major */.D.uint.major] = _0uint/* encodeUint */.Fh; - encoders[token/* Type.negint.major */.D.negint.major] = _1negint/* encodeNegint */.UT; - encoders[token/* Type.bytes.major */.D.bytes.major] = _2bytes/* encodeBytes */.hg; - encoders[token/* Type.string.major */.D.string.major] = _3string/* encodeString */.YW; - encoders[token/* Type.array.major */.D.array.major] = _4array/* encodeArray */.HF; - encoders[token/* Type.map.major */.D.map.major] = _5map/* encodeMap */.KI; - encoders[token/* Type.tag.major */.D.tag.major] = _6tag/* encodeTag */.xy; - encoders[token/* Type.float.major */.D.float.major] = _7float/* encodeFloat */.tA; - return encoders; -} -const cborEncoders = makeCborEncoders(); -const buf = new Bl(); -class Ref { - constructor(obj, parent) { - this.obj = obj; - this.parent = parent; - } - includes(obj) { - let p = this; - do { - if (p.obj === obj) { - return true; - } - } while (p = p.parent); - return false; - } - static createCheck(stack, obj) { - if (stack && stack.includes(obj)) { - throw new Error(`${ common/* encodeErrPrefix */.OO } object contains circular references`); - } - return new Ref(obj, stack); - } -} -const simpleTokens = { - null: new token/* Token */.W(token/* Type.null */.D["null"], null), - undefined: new token/* Token */.W(token/* Type.undefined */.D.undefined, undefined), - true: new token/* Token */.W(token/* Type.true */.D["true"], true), - false: new token/* Token */.W(token/* Type.false */.D["false"], false), - emptyArray: new token/* Token */.W(token/* Type.array */.D.array, 0), - emptyMap: new token/* Token */.W(token/* Type.map */.D.map, 0) -}; -const typeEncoders = { - number(obj, _typ, _options, _refStack) { - if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) { - return new token/* Token */.W(token/* Type.float */.D.float, obj); - } else if (obj >= 0) { - return new token/* Token */.W(token/* Type.uint */.D.uint, obj); - } else { - return new token/* Token */.W(token/* Type.negint */.D.negint, obj); - } - }, - bigint(obj, _typ, _options, _refStack) { - if (obj >= BigInt(0)) { - return new token/* Token */.W(token/* Type.uint */.D.uint, obj); - } else { - return new token/* Token */.W(token/* Type.negint */.D.negint, obj); - } - }, - Uint8Array(obj, _typ, _options, _refStack) { - return new token/* Token */.W(token/* Type.bytes */.D.bytes, obj); - }, - string(obj, _typ, _options, _refStack) { - return new token/* Token */.W(token/* Type.string */.D.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/* Token */.W(token/* Type.bytes */.D.bytes, new Uint8Array(obj)); - }, - DataView(obj, _typ, _options, _refStack) { - return new token/* Token */.W(token/* Type.bytes */.D.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/* Token */.W(token/* Type.break */.D["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/* Token */.W(token/* Type.array */.D.array, obj.length), - entries, - new token/* Token */.W(token/* Type.break */.D["break"]) - ]; - } - return [ - new token/* Token */.W(token/* Type.array */.D.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/* Token */.W(token/* Type.break */.D["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/* Token */.W(token/* Type.map */.D.map, length), - entries, - new token/* Token */.W(token/* Type.break */.D["break"]) - ]; - } - return [ - new token/* Token */.W(token/* Type.map */.D.map, length), - entries - ]; - } -}; -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; - } - } - const typeEncoder = typeEncoders[typ]; - if (!typeEncoder) { - throw new Error(`${ common/* encodeErrPrefix */.OO } unsupported type: ${ typ }`); - } - return typeEncoder(obj, typ, options, refStack); -} -function sortMapEntries(entries, options) { - if (options.mapSorter) { - entries.sort(options.mapSorter); - } -} -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); - } - 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 tokensToEncoded(buf, tokens, encoders, options) { - if (Array.isArray(tokens)) { - for (const token of tokens) { - tokensToEncoded(buf, token, encoders, options); - } - } else { - encoders[tokens.type.major](buf, tokens, options); - } -} -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 buf = new Bl(size); - encoder(buf, tokens, options); - if (buf.chunks.length !== 1) { - throw new Error(`Unexpected error: pre-calculated length for ${ tokens } was wrong`); - } - return (0,byte_utils/* asU8A */.Dz)(buf.chunks[0]); - } - } - buf.reset(); - tokensToEncoded(buf, tokens, encoders, options); - return buf.toBytes(true); -} -function encode(data, options) { - options = Object.assign({}, defaultEncodeOptions, options); - return encodeCustom(data, cborEncoders, options); -} - - -/***/ }), - -/***/ 1266: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "JN": () => (/* binding */ quickEncodeToken), -/* harmony export */ "PS": () => (/* binding */ quick), -/* harmony export */ "cW": () => (/* binding */ jump) -/* harmony export */ }); -/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1302); -/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7228); -/* harmony import */ var _1negint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(608); -/* harmony import */ var _2bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(622); -/* harmony import */ var _3string_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1301); -/* harmony import */ var _4array_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7656); -/* harmony import */ var _5map_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1613); -/* harmony import */ var _6tag_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(6589); -/* harmony import */ var _7float_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3964); -/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(3002); -/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1926); - - - - - - - - - - - -function invalidMinor(data, pos, minor) { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_9__/* .decodeErrPrefix */ .IR } encountered invalid minor (${ minor }) for major ${ data[pos] >>> 5 }`); -} -function errorer(msg) { - return () => { - throw new Error(`${ _common_js__WEBPACK_IMPORTED_MODULE_9__/* .decodeErrPrefix */ .IR } ${ msg }`); - }; -} -const jump = []; -for (let i = 0; i <= 23; i++) { - jump[i] = invalidMinor; -} -jump[24] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeUint8 */ .Km; -jump[25] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeUint16 */ .Zh; -jump[26] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeUint32 */ .cs; -jump[27] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__/* .decodeUint64 */ .uN; -jump[28] = invalidMinor; -jump[29] = invalidMinor; -jump[30] = invalidMinor; -jump[31] = invalidMinor; -for (let i = 32; i <= 55; i++) { - jump[i] = invalidMinor; -} -jump[56] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeNegint8 */ .yr; -jump[57] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeNegint16 */ .r0; -jump[58] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeNegint32 */ .wy; -jump[59] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__/* .decodeNegint64 */ .ec; -jump[60] = invalidMinor; -jump[61] = invalidMinor; -jump[62] = invalidMinor; -jump[63] = invalidMinor; -for (let i = 64; i <= 87; i++) { - jump[i] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .decodeBytesCompact */ .Ii; -} -jump[88] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .decodeBytes8 */ .UQ; -jump[89] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .decodeBytes16 */ .BS; -jump[90] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .decodeBytes32 */ .zU; -jump[91] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__/* .decodeBytes64 */ .ME; -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] = _3string_js__WEBPACK_IMPORTED_MODULE_4__/* .decodeStringCompact */ .nt; -} -jump[120] = _3string_js__WEBPACK_IMPORTED_MODULE_4__/* .decodeString8 */ .Bq; -jump[121] = _3string_js__WEBPACK_IMPORTED_MODULE_4__/* .decodeString16 */ .h; -jump[122] = _3string_js__WEBPACK_IMPORTED_MODULE_4__/* .decodeString32 */ .q0; -jump[123] = _3string_js__WEBPACK_IMPORTED_MODULE_4__/* .decodeString64 */ .bc; -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] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArrayCompact */ .Ju; -} -jump[152] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArray8 */ .h7; -jump[153] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArray16 */ .OC; -jump[154] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArray32 */ .lY; -jump[155] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArray64 */ .a8; -jump[156] = invalidMinor; -jump[157] = invalidMinor; -jump[158] = invalidMinor; -jump[159] = _4array_js__WEBPACK_IMPORTED_MODULE_5__/* .decodeArrayIndefinite */ .s5; -for (let i = 160; i <= 183; i++) { - jump[i] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMapCompact */ ._K; -} -jump[184] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMap8 */ .G; -jump[185] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMap16 */ .qe; -jump[186] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMap32 */ .IY; -jump[187] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMap64 */ .F2; -jump[188] = invalidMinor; -jump[189] = invalidMinor; -jump[190] = invalidMinor; -jump[191] = _5map_js__WEBPACK_IMPORTED_MODULE_6__/* .decodeMapIndefinite */ .ng; -for (let i = 192; i <= 215; i++) { - jump[i] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__/* .decodeTagCompact */ .qJ; -} -jump[216] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__/* .decodeTag8 */ .ZR; -jump[217] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__/* .decodeTag16 */ .CF; -jump[218] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__/* .decodeTag32 */ .vP; -jump[219] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__/* .decodeTag64 */ .MV; -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] = _7float_js__WEBPACK_IMPORTED_MODULE_8__/* .decodeUndefined */ .h1; -jump[248] = errorer('simple values are not supported'); -jump[249] = _7float_js__WEBPACK_IMPORTED_MODULE_8__/* .decodeFloat16 */ .mW; -jump[250] = _7float_js__WEBPACK_IMPORTED_MODULE_8__/* .decodeFloat32 */ .GI; -jump[251] = _7float_js__WEBPACK_IMPORTED_MODULE_8__/* .decodeFloat64 */ .vV; -jump[252] = invalidMinor; -jump[253] = invalidMinor; -jump[254] = invalidMinor; -jump[255] = _7float_js__WEBPACK_IMPORTED_MODULE_8__/* .decodeBreak */ .y7; -const quick = []; -for (let i = 0; i < 24; i++) { - quick[i] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint, i, 1); -} -for (let i = -1; i >= -24; i--) { - quick[31 - i] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint, i, 1); -} -quick[64] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.bytes */ .D.bytes, new Uint8Array(0), 1); -quick[96] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.string */ .D.string, '', 1); -quick[128] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.array */ .D.array, 0, 1); -quick[160] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.map */ .D.map, 0, 1); -quick[244] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["false"] */ .D["false"], false, 1); -quick[245] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["true"] */ .D["true"], true, 1); -quick[246] = new _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .W(_token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["null"] */ .D["null"], null, 1); -function quickEncodeToken(token) { - switch (token.type) { - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["false"] */ .D["false"]: - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([244]); - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["true"] */ .D["true"]: - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([245]); - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type["null"] */ .D["null"]: - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([246]); - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.bytes */ .D.bytes: - if (!token.value.length) { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([64]); - } - return; - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.string */ .D.string: - if (token.value === '') { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([96]); - } - return; - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.array */ .D.array: - if (token.value === 0) { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([128]); - } - return; - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.map */ .D.map: - if (token.value === 0) { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([160]); - } - return; - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.uint */ .D.uint: - if (token.value < 24) { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([Number(token.value)]); - } - return; - case _token_js__WEBPACK_IMPORTED_MODULE_0__/* .Type.negint */ .D.negint: - if (token.value >= -24) { - return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__/* .fromArray */ .nI)([31 - Number(token.value)]); - } - } -} - -/***/ }), - -/***/ 1302: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "D": () => (/* binding */ Type), -/* harmony export */ "W": () => (/* binding */ Token) -/* harmony export */ }); -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 = undefined; - this.byteValue = undefined; - } - toString() { - return `Token[${ this.type }].${ this.value }`; - } -} - - -/***/ }), - -/***/ 7262: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "code": () => (/* binding */ code), -/* harmony export */ "decode": () => (/* binding */ decode), -/* harmony export */ "encode": () => (/* binding */ encode), -/* harmony export */ "name": () => (/* binding */ name) -/* harmony export */ }); -/* harmony import */ var cborg__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(308); -/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3036); - - -const CID_CBOR_TAG = 42; -function cidEncoder(obj) { - if (obj.asCID !== obj) { - return null; - } - const cid = multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.asCID(obj); - if (!cid) { - return null; - } - const bytes = new Uint8Array(cid.bytes.byteLength + 1); - bytes.set(cid.bytes, 1); - return [ - new cborg__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .WU(cborg__WEBPACK_IMPORTED_MODULE_0__/* .Type.tag */ .Dy.tag, CID_CBOR_TAG), - new cborg__WEBPACK_IMPORTED_MODULE_0__/* .Token */ .WU(cborg__WEBPACK_IMPORTED_MODULE_0__/* .Type.bytes */ .Dy.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 - } -}; -function cidDecoder(bytes) { - if (bytes[0] !== 0) { - throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00'); - } - return multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.decode(bytes.subarray(1)); -} -const decodeOptions = { - allowIndefinite: false, - allowUndefined: false, - allowNaN: false, - allowInfinity: false, - allowBigInt: true, - strict: true, - useMaps: false, - tags: [] -}; -decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; -const name = 'dag-cbor'; -const code = 113; -const encode = node => cborg__WEBPACK_IMPORTED_MODULE_0__/* .encode */ .cv(node, encodeOptions); -const decode = data => cborg__WEBPACK_IMPORTED_MODULE_0__/* .decode */ .Jx(data, decodeOptions); - -/***/ }), - -/***/ 2708: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "CID": () => (/* reexport */ src_cid.CID), - "create": () => (/* binding */ create), - "globSource": () => (/* binding */ globSource), - "multiaddr": () => (/* reexport */ multiaddr_src.Multiaddr), - "urlSource": () => (/* reexport */ url_source) -}); - -// NAMESPACE OBJECT: ../node_modules/@ipld/dag-pb/esm/src/index.js -var src_namespaceObject = {}; -__webpack_require__.r(src_namespaceObject); -__webpack_require__.d(src_namespaceObject, { - "code": () => (code), - "createLink": () => (createLink), - "createNode": () => (createNode), - "decode": () => (decode), - "encode": () => (encode), - "name": () => (src_name), - "prepare": () => (prepare), - "validate": () => (validate) -}); - -// NAMESPACE OBJECT: ../node_modules/@ipld/dag-cbor/esm/index.js -var esm_namespaceObject = {}; -__webpack_require__.r(esm_namespaceObject); -__webpack_require__.d(esm_namespaceObject, { - "code": () => (esm_code), - "decode": () => (esm_decode), - "encode": () => (esm_encode), - "name": () => (esm_name) -}); - -// NAMESPACE OBJECT: ../node_modules/@ipld/dag-json/esm/index.js -var dag_json_esm_namespaceObject = {}; -__webpack_require__.r(dag_json_esm_namespaceObject); -__webpack_require__.d(dag_json_esm_namespaceObject, { - "code": () => (dag_json_esm_code), - "decode": () => (dag_json_esm_decode), - "encode": () => (dag_json_esm_encode), - "name": () => (dag_json_esm_name) -}); - -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/multibases.js -const LOAD_BASE = name => Promise.reject(new Error(`No base found for "${ name }"`)); -class Multibases { - constructor(options) { - this._basesByName = {}; - this._basesByPrefix = {}; - this._loadBase = options.loadBase || LOAD_BASE; - for (const base of options.bases) { - this.addBase(base); - } - } - addBase(base) { - if (this._basesByName[base.name] || this._basesByPrefix[base.prefix]) { - throw new Error(`Codec already exists for codec "${ base.name }"`); - } - this._basesByName[base.name] = base; - this._basesByPrefix[base.prefix] = base; - } - removeBase(base) { - delete this._basesByName[base.name]; - delete this._basesByPrefix[base.prefix]; - } - async getBase(nameOrPrefix) { - if (this._basesByName[nameOrPrefix]) { - return this._basesByName[nameOrPrefix]; - } - if (this._basesByPrefix[nameOrPrefix]) { - return this._basesByPrefix[nameOrPrefix]; - } - const base = await this._loadBase(nameOrPrefix); - if (this._basesByName[base.name] == null && this._basesByPrefix[base.prefix] == null) { - this.addBase(base); - } - return base; - } - listBases() { - return Object.values(this._basesByName); - } -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/multicodecs.js -const LOAD_CODEC = codeOrName => Promise.reject(new Error(`No codec found for "${ codeOrName }"`)); -class Multicodecs { - constructor(options) { - this._codecsByName = {}; - this._codecsByCode = {}; - this._loadCodec = options.loadCodec || LOAD_CODEC; - for (const codec of options.codecs) { - this.addCodec(codec); - } - } - addCodec(codec) { - if (this._codecsByName[codec.name] || this._codecsByCode[codec.code]) { - throw new Error(`Resolver already exists for codec "${ codec.name }"`); - } - this._codecsByName[codec.name] = codec; - this._codecsByCode[codec.code] = codec; - } - removeCodec(codec) { - delete this._codecsByName[codec.name]; - delete this._codecsByCode[codec.code]; - } - async getCodec(code) { - const table = typeof code === 'string' ? this._codecsByName : this._codecsByCode; - if (table[code]) { - return table[code]; - } - const codec = await this._loadCodec(code); - if (table[code] == null) { - this.addCodec(codec); - } - return codec; - } - listCodecs() { - return Object.values(this._codecsByName); - } -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/multihashes.js -const LOAD_HASHER = codeOrName => Promise.reject(new Error(`No hasher found for "${ codeOrName }"`)); -class Multihashes { - constructor(options) { - this._hashersByName = {}; - this._hashersByCode = {}; - this._loadHasher = options.loadHasher || LOAD_HASHER; - for (const hasher of options.hashers) { - this.addHasher(hasher); - } - } - addHasher(hasher) { - if (this._hashersByName[hasher.name] || this._hashersByCode[hasher.code]) { - throw new Error(`Resolver already exists for codec "${ hasher.name }"`); - } - this._hashersByName[hasher.name] = hasher; - this._hashersByCode[hasher.code] = hasher; - } - removeHasher(hasher) { - delete this._hashersByName[hasher.name]; - delete this._hashersByCode[hasher.code]; - } - async getHasher(code) { - const table = typeof code === 'string' ? this._hashersByName : this._hashersByCode; - if (table[code]) { - return table[code]; - } - const hasher = await this._loadHasher(code); - if (table[code] == null) { - this.addHasher(hasher); - } - return hasher; - } - listHashers() { - return Object.values(this._hashersByName); - } -} -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/cid.js -var src_cid = __webpack_require__(3036); -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-pb/esm/src/pb-decode.js -const textDecoder = new TextDecoder(); -function decodeVarint(bytes, offset) { - let v = 0; - for (let shift = 0;; shift += 7) { - if (shift >= 64) { - throw new Error('protobuf: varint overflow'); - } - if (offset >= bytes.length) { - throw new Error('protobuf: unexpected end of data'); - } - const b = bytes[offset++]; - v += shift < 28 ? (b & 127) << shift : (b & 127) * 2 ** shift; - if (b < 128) { - break; - } - } - return [ - v, - offset - ]; -} -function decodeBytes(bytes, offset) { - let byteLen; - [byteLen, offset] = decodeVarint(bytes, offset); - const postOffset = offset + byteLen; - if (byteLen < 0 || postOffset < 0) { - throw new Error('protobuf: invalid length'); - } - if (postOffset > bytes.length) { - throw new Error('protobuf: unexpected end of data'); - } - return [ - bytes.subarray(offset, postOffset), - postOffset - ]; -} -function decodeKey(bytes, index) { - let wire; - [wire, index] = decodeVarint(bytes, index); - return [ - wire & 7, - wire >> 3, - index - ]; -} -function decodeLink(bytes) { - const link = {}; - const l = bytes.length; - let index = 0; - while (index < l) { - let wireType, fieldNum; - [wireType, fieldNum, index] = decodeKey(bytes, index); - if (fieldNum === 1) { - if (link.Hash) { - throw new Error('protobuf: (PBLink) duplicate Hash section'); - } - if (wireType !== 2) { - throw new Error(`protobuf: (PBLink) wrong wireType (${ wireType }) for Hash`); - } - if (link.Name !== undefined) { - throw new Error('protobuf: (PBLink) invalid order, found Name before Hash'); - } - if (link.Tsize !== undefined) { - throw new Error('protobuf: (PBLink) invalid order, found Tsize before Hash'); - } - ; - [link.Hash, index] = decodeBytes(bytes, index); - } else if (fieldNum === 2) { - if (link.Name !== undefined) { - throw new Error('protobuf: (PBLink) duplicate Name section'); - } - if (wireType !== 2) { - throw new Error(`protobuf: (PBLink) wrong wireType (${ wireType }) for Name`); - } - if (link.Tsize !== undefined) { - throw new Error('protobuf: (PBLink) invalid order, found Tsize before Name'); - } - let byts; - [byts, index] = decodeBytes(bytes, index); - link.Name = textDecoder.decode(byts); - } else if (fieldNum === 3) { - if (link.Tsize !== undefined) { - throw new Error('protobuf: (PBLink) duplicate Tsize section'); - } - if (wireType !== 0) { - throw new Error(`protobuf: (PBLink) wrong wireType (${ wireType }) for Tsize`); - } - ; - [link.Tsize, index] = decodeVarint(bytes, index); - } else { - throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${ fieldNum }`); - } - } - if (index > l) { - throw new Error('protobuf: (PBLink) unexpected end of data'); - } - return link; -} -function decodeNode(bytes) { - const l = bytes.length; - let index = 0; - let links; - let linksBeforeData = false; - let data; - while (index < l) { - let wireType, fieldNum; - [wireType, fieldNum, index] = decodeKey(bytes, index); - if (wireType !== 2) { - throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${ wireType }`); - } - if (fieldNum === 1) { - if (data) { - throw new Error('protobuf: (PBNode) duplicate Data section'); - } - ; - [data, index] = decodeBytes(bytes, index); - if (links) { - linksBeforeData = true; - } - } else if (fieldNum === 2) { - if (linksBeforeData) { - throw new Error('protobuf: (PBNode) duplicate Links section'); - } else if (!links) { - links = []; - } - let byts; - [byts, index] = decodeBytes(bytes, index); - links.push(decodeLink(byts)); - } else { - throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${ fieldNum }`); - } - } - if (index > l) { - throw new Error('protobuf: (PBNode) unexpected end of data'); - } - const node = {}; - if (data) { - node.Data = data; - } - node.Links = links || []; - return node; -} -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-pb/esm/src/pb-encode.js -const textEncoder = new TextEncoder(); -const maxInt32 = 2 ** 32; -const maxUInt32 = 2 ** 31; -function encodeLink(link, bytes) { - let i = bytes.length; - if (typeof link.Tsize === 'number') { - if (link.Tsize < 0) { - throw new Error('Tsize cannot be negative'); - } - if (!Number.isSafeInteger(link.Tsize)) { - throw new Error('Tsize too large for encoding'); - } - i = encodeVarint(bytes, i, link.Tsize) - 1; - bytes[i] = 24; - } - if (typeof link.Name === 'string') { - const nameBytes = textEncoder.encode(link.Name); - i -= nameBytes.length; - bytes.set(nameBytes, i); - i = encodeVarint(bytes, i, nameBytes.length) - 1; - bytes[i] = 18; - } - if (link.Hash) { - i -= link.Hash.length; - bytes.set(link.Hash, i); - i = encodeVarint(bytes, i, link.Hash.length) - 1; - bytes[i] = 10; - } - return bytes.length - i; -} -function encodeNode(node) { - const size = sizeNode(node); - const bytes = new Uint8Array(size); - let i = size; - if (node.Data) { - i -= node.Data.length; - bytes.set(node.Data, i); - i = encodeVarint(bytes, i, node.Data.length) - 1; - bytes[i] = 10; - } - if (node.Links) { - for (let index = node.Links.length - 1; index >= 0; index--) { - const size = encodeLink(node.Links[index], bytes.subarray(0, i)); - i -= size; - i = encodeVarint(bytes, i, size) - 1; - bytes[i] = 18; - } - } - return bytes; -} -function sizeLink(link) { - let n = 0; - if (link.Hash) { - const l = link.Hash.length; - n += 1 + l + sov(l); - } - if (typeof link.Name === 'string') { - const l = textEncoder.encode(link.Name).length; - n += 1 + l + sov(l); - } - if (typeof link.Tsize === 'number') { - n += 1 + sov(link.Tsize); - } - return n; -} -function sizeNode(node) { - let n = 0; - if (node.Data) { - const l = node.Data.length; - n += 1 + l + sov(l); - } - if (node.Links) { - for (const link of node.Links) { - const l = sizeLink(link); - n += 1 + l + sov(l); - } - } - return n; -} -function encodeVarint(bytes, offset, v) { - offset -= sov(v); - const base = offset; - while (v >= maxUInt32) { - bytes[offset++] = v & 127 | 128; - v /= 128; - } - while (v >= 128) { - bytes[offset++] = v & 127 | 128; - v >>>= 7; - } - bytes[offset] = v; - return base; -} -function sov(x) { - if (x % 2 === 0) { - x++; - } - return Math.floor((len64(x) + 6) / 7); -} -function len64(x) { - let n = 0; - if (x >= maxInt32) { - x = Math.floor(x / maxInt32); - n = 32; - } - if (x >= 1 << 16) { - x >>>= 16; - n += 16; - } - if (x >= 1 << 8) { - x >>>= 8; - n += 8; - } - return n + len8tab[x]; -} -const len8tab = [ - 0, - 1, - 2, - 2, - 3, - 3, - 3, - 3, - 4, - 4, - 4, - 4, - 4, - 4, - 4, - 4, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 7, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8, - 8 -]; -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-pb/esm/src/util.js - -const pbNodeProperties = [ - 'Data', - 'Links' -]; -const pbLinkProperties = [ - 'Hash', - 'Name', - 'Tsize' -]; -const util_textEncoder = new TextEncoder(); -function linkComparator(a, b) { - if (a === b) { - return 0; - } - const abuf = a.Name ? util_textEncoder.encode(a.Name) : []; - const bbuf = b.Name ? util_textEncoder.encode(b.Name) : []; - let x = abuf.length; - let y = bbuf.length; - for (let i = 0, len = Math.min(x, y); i < len; ++i) { - if (abuf[i] !== bbuf[i]) { - x = abuf[i]; - y = bbuf[i]; - break; - } - } - return x < y ? -1 : y < x ? 1 : 0; -} -function hasOnlyProperties(node, properties) { - return !Object.keys(node).some(p => !properties.includes(p)); -} -function asLink(link) { - if (typeof link.asCID === 'object') { - const Hash = src_cid.CID.asCID(link); - if (!Hash) { - throw new TypeError('Invalid DAG-PB form'); - } - return { Hash }; - } - if (typeof link !== 'object' || Array.isArray(link)) { - throw new TypeError('Invalid DAG-PB form'); - } - const pbl = {}; - if (link.Hash) { - let cid = src_cid.CID.asCID(link.Hash); - try { - if (!cid) { - if (typeof link.Hash === 'string') { - cid = src_cid.CID.parse(link.Hash); - } else if (link.Hash instanceof Uint8Array) { - cid = src_cid.CID.decode(link.Hash); - } - } - } catch (e) { - throw new TypeError(`Invalid DAG-PB form: ${ e.message }`); - } - if (cid) { - pbl.Hash = cid; - } - } - if (!pbl.Hash) { - throw new TypeError('Invalid DAG-PB form'); - } - if (typeof link.Name === 'string') { - pbl.Name = link.Name; - } - if (typeof link.Tsize === 'number') { - pbl.Tsize = link.Tsize; - } - return pbl; -} -function prepare(node) { - if (node instanceof Uint8Array || typeof node === 'string') { - node = { Data: node }; - } - if (typeof node !== 'object' || Array.isArray(node)) { - throw new TypeError('Invalid DAG-PB form'); - } - const pbn = {}; - if (node.Data !== undefined) { - if (typeof node.Data === 'string') { - pbn.Data = util_textEncoder.encode(node.Data); - } else if (node.Data instanceof Uint8Array) { - pbn.Data = node.Data; - } else { - throw new TypeError('Invalid DAG-PB form'); - } - } - if (node.Links !== undefined) { - if (Array.isArray(node.Links)) { - pbn.Links = node.Links.map(asLink); - pbn.Links.sort(linkComparator); - } else { - throw new TypeError('Invalid DAG-PB form'); - } - } else { - pbn.Links = []; - } - return pbn; -} -function validate(node) { - if (!node || typeof node !== 'object' || Array.isArray(node)) { - throw new TypeError('Invalid DAG-PB form'); - } - if (!hasOnlyProperties(node, pbNodeProperties)) { - throw new TypeError('Invalid DAG-PB form (extraneous properties)'); - } - if (node.Data !== undefined && !(node.Data instanceof Uint8Array)) { - throw new TypeError('Invalid DAG-PB form (Data must be a Uint8Array)'); - } - if (!Array.isArray(node.Links)) { - throw new TypeError('Invalid DAG-PB form (Links must be an array)'); - } - for (let i = 0; i < node.Links.length; i++) { - const link = node.Links[i]; - if (!link || typeof link !== 'object' || Array.isArray(link)) { - throw new TypeError('Invalid DAG-PB form (bad link object)'); - } - if (!hasOnlyProperties(link, pbLinkProperties)) { - throw new TypeError('Invalid DAG-PB form (extraneous properties on link object)'); - } - if (!link.Hash) { - throw new TypeError('Invalid DAG-PB form (link must have a Hash)'); - } - if (link.Hash.asCID !== link.Hash) { - throw new TypeError('Invalid DAG-PB form (link Hash must be a CID)'); - } - if (link.Name !== undefined && typeof link.Name !== 'string') { - throw new TypeError('Invalid DAG-PB form (link Name must be a string)'); - } - if (link.Tsize !== undefined && (typeof link.Tsize !== 'number' || link.Tsize % 1 !== 0)) { - throw new TypeError('Invalid DAG-PB form (link Tsize must be an integer)'); - } - if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) { - throw new TypeError('Invalid DAG-PB form (links must be sorted by Name bytes)'); - } - } -} -function createNode(data, links = []) { - return prepare({ - Data: data, - Links: links - }); -} -function createLink(name, size, cid) { - return asLink({ - Hash: cid, - Name: name, - Tsize: size - }); -} -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-pb/esm/src/index.js - - - - -const src_name = 'dag-pb'; -const code = 112; -function encode(node) { - validate(node); - const pbn = {}; - if (node.Links) { - pbn.Links = node.Links.map(l => { - const link = {}; - if (l.Hash) { - link.Hash = l.Hash.bytes; - } - if (l.Name !== undefined) { - link.Name = l.Name; - } - if (l.Tsize !== undefined) { - link.Tsize = l.Tsize; - } - return link; - }); - } - if (node.Data) { - pbn.Data = node.Data; - } - return encodeNode(pbn); -} -function decode(bytes) { - const pbn = decodeNode(bytes); - const node = {}; - if (pbn.Data) { - node.Data = pbn.Data; - } - if (pbn.Links) { - node.Links = pbn.Links.map(l => { - const link = {}; - try { - link.Hash = src_cid.CID.decode(l.Hash); - } catch (e) { - } - if (!link.Hash) { - throw new Error('Invalid Hash field found in link, expected CID'); - } - if (l.Name !== undefined) { - link.Name = l.Name; - } - if (l.Tsize !== undefined) { - link.Tsize = l.Tsize; - } - return link; - }); - } - return node; -} - -// EXTERNAL MODULE: ../node_modules/cborg/esm/cborg.js -var cborg = __webpack_require__(308); -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-cbor/esm/index.js - - -const CID_CBOR_TAG = 42; -function cidEncoder(obj) { - if (obj.asCID !== obj) { - return null; - } - const cid = src_cid.CID.asCID(obj); - if (!cid) { - return null; - } - const bytes = new Uint8Array(cid.bytes.byteLength + 1); - bytes.set(cid.bytes, 1); - return [ - new cborg/* Token */.WU(cborg/* Type.tag */.Dy.tag, CID_CBOR_TAG), - new cborg/* Token */.WU(cborg/* Type.bytes */.Dy.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 - } -}; -function cidDecoder(bytes) { - if (bytes[0] !== 0) { - throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00'); - } - return src_cid.CID.decode(bytes.subarray(1)); -} -const decodeOptions = { - allowIndefinite: false, - coerceUndefinedToNull: true, - allowNaN: false, - allowInfinity: false, - allowBigInt: true, - strict: true, - useMaps: false, - tags: [] -}; -decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; -const esm_name = 'dag-cbor'; -const esm_code = 113; -const esm_encode = node => cborg/* encode */.cv(node, encodeOptions); -const esm_decode = data => cborg/* decode */.Jx(data, decodeOptions); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/index.js -var src = __webpack_require__(7534); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bases/base64.js -var base64 = __webpack_require__(1453); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/token.js -var lib_token = __webpack_require__(1302); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/encode.js + 2 modules -var lib_encode = __webpack_require__(6456); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/common.js -var common = __webpack_require__(3002); -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/byte-utils.js -var byte_utils = __webpack_require__(1926); -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/json/encode.js - - - - -class JSONEncoder extends Array { - constructor() { - super(); - this.inRecursive = []; - } - prefix(buf) { - const recurs = this.inRecursive[this.inRecursive.length - 1]; - if (recurs) { - if (recurs.type === lib_token/* Type.array */.D.array) { - recurs.elements++; - if (recurs.elements !== 1) { - buf.push([44]); - } - } - if (recurs.type === lib_token/* Type.map */.D.map) { - recurs.elements++; - if (recurs.elements !== 1) { - if (recurs.elements % 2 === 1) { - buf.push([44]); - } else { - buf.push([58]); - } - } - } - } - } - [lib_token/* Type.uint.major */.D.uint.major](buf, token) { - this.prefix(buf); - const is = String(token.value); - const isa = []; - for (let i = 0; i < is.length; i++) { - isa[i] = is.charCodeAt(i); - } - buf.push(isa); - } - [lib_token/* Type.negint.major */.D.negint.major](buf, token) { - this[lib_token/* Type.uint.major */.D.uint.major](buf, token); - } - [lib_token/* Type.bytes.major */.D.bytes.major](_buf, _token) { - throw new Error(`${ common/* encodeErrPrefix */.OO } unsupported type: Uint8Array`); - } - [lib_token/* Type.string.major */.D.string.major](buf, token) { - this.prefix(buf); - const byts = (0,byte_utils/* fromString */.mL)(JSON.stringify(token.value)); - buf.push(byts.length > 32 ? (0,byte_utils/* asU8A */.Dz)(byts) : byts); - } - [lib_token/* Type.array.major */.D.array.major](buf, _token) { - this.prefix(buf); - this.inRecursive.push({ - type: lib_token/* Type.array */.D.array, - elements: 0 - }); - buf.push([91]); - } - [lib_token/* Type.map.major */.D.map.major](buf, _token) { - this.prefix(buf); - this.inRecursive.push({ - type: lib_token/* Type.map */.D.map, - elements: 0 - }); - buf.push([123]); - } - [lib_token/* Type.tag.major */.D.tag.major](_buf, _token) { - } - [lib_token/* Type.float.major */.D.float.major](buf, token) { - if (token.type.name === 'break') { - const recurs = this.inRecursive.pop(); - if (recurs) { - if (recurs.type === lib_token/* Type.array */.D.array) { - buf.push([93]); - } else if (recurs.type === lib_token/* Type.map */.D.map) { - buf.push([125]); - } else { - throw new Error('Unexpected recursive type; this should not happen!'); - } - return; - } - throw new Error('Unexpected break; this should not happen!'); - } - if (token.value === undefined) { - throw new Error(`${ common/* encodeErrPrefix */.OO } unsupported type: undefined`); - } - this.prefix(buf); - if (token.type.name === 'true') { - buf.push([ - 116, - 114, - 117, - 101 - ]); - return; - } else if (token.type.name === 'false') { - buf.push([ - 102, - 97, - 108, - 115, - 101 - ]); - return; - } else if (token.type.name === 'null') { - buf.push([ - 110, - 117, - 108, - 108 - ]); - return; - } - const is = String(token.value); - const isa = []; - let dp = false; - for (let i = 0; i < is.length; i++) { - isa[i] = is.charCodeAt(i); - if (!dp && (isa[i] === 46 || isa[i] === 101 || isa[i] === 69)) { - dp = true; - } - } - if (!dp) { - isa.push(46); - isa.push(48); - } - buf.push(isa); - } -} -function mapSorter(e1, e2) { - if (Array.isArray(e1[0]) || Array.isArray(e2[0])) { - throw new Error(`${ common/* encodeErrPrefix */.OO } complex map keys are not supported`); - } - const keyToken1 = e1[0]; - const keyToken2 = e2[0]; - if (keyToken1.type !== lib_token/* Type.string */.D.string || keyToken2.type !== lib_token/* Type.string */.D.string) { - throw new Error(`${ common/* encodeErrPrefix */.OO } non-string map keys are not supported`); - } - if (keyToken1 < keyToken2) { - return -1; - } - if (keyToken1 > keyToken2) { - return 1; - } - throw new Error(`${ common/* encodeErrPrefix */.OO } unexpected duplicate map keys, this is not supported`); -} -const defaultEncodeOptions = { - addBreakTokens: true, - mapSorter -}; -function encode_encode(data, options) { - options = Object.assign({}, defaultEncodeOptions, options); - return (0,lib_encode/* encodeCustom */.w$)(data, new JSONEncoder(), options); -} - -// EXTERNAL MODULE: ../node_modules/cborg/esm/lib/decode.js -var lib_decode = __webpack_require__(2972); -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/json/decode.js - - - - -class Tokenizer { - constructor(data, options = {}) { - this.pos = 0; - this.data = data; - this.options = options; - this.modeStack = ['value']; - this.lastToken = ''; - } - done() { - return this.pos >= this.data.length; - } - ch() { - return this.data[this.pos]; - } - currentMode() { - return this.modeStack[this.modeStack.length - 1]; - } - skipWhitespace() { - let c = this.ch(); - while (c === 32 || c === 9 || c === 13 || c === 10) { - c = this.data[++this.pos]; - } - } - expect(str) { - if (this.data.length - this.pos < str.length) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected end of input at position ${ this.pos }`); - } - for (let i = 0; i < str.length; i++) { - if (this.data[this.pos++] !== str[i]) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected token at position ${ this.pos }, expected to find '${ String.fromCharCode(...str) }'`); - } - } - } - parseNumber() { - const startPos = this.pos; - let negative = false; - let float = false; - const swallow = chars => { - while (!this.done()) { - const ch = this.ch(); - if (chars.includes(ch)) { - this.pos++; - } else { - break; - } - } - }; - if (this.ch() === 45) { - negative = true; - this.pos++; - } - if (this.ch() === 48) { - this.pos++; - if (this.ch() === 46) { - this.pos++; - float = true; - } else { - return new lib_token/* Token */.W(lib_token/* Type.uint */.D.uint, 0, this.pos - startPos); - } - } - swallow([ - 48, - 49, - 50, - 51, - 52, - 53, - 54, - 55, - 56, - 57 - ]); - if (negative && this.pos === startPos + 1) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected token at position ${ this.pos }`); - } - if (!this.done() && this.ch() === 46) { - if (float) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected token at position ${ this.pos }`); - } - float = true; - this.pos++; - swallow([ - 48, - 49, - 50, - 51, - 52, - 53, - 54, - 55, - 56, - 57 - ]); - } - if (!this.done() && (this.ch() === 101 || this.ch() === 69)) { - float = true; - this.pos++; - if (!this.done() && (this.ch() === 43 || this.ch() === 45)) { - this.pos++; - } - swallow([ - 48, - 49, - 50, - 51, - 52, - 53, - 54, - 55, - 56, - 57 - ]); - } - const numStr = String.fromCharCode.apply(null, this.data.subarray(startPos, this.pos)); - const num = parseFloat(numStr); - if (float) { - return new lib_token/* Token */.W(lib_token/* Type.float */.D.float, num, this.pos - startPos); - } - if (this.options.allowBigInt !== true || Number.isSafeInteger(num)) { - return new lib_token/* Token */.W(num >= 0 ? lib_token/* Type.uint */.D.uint : lib_token/* Type.negint */.D.negint, num, this.pos - startPos); - } - return new lib_token/* Token */.W(num >= 0 ? lib_token/* Type.uint */.D.uint : lib_token/* Type.negint */.D.negint, BigInt(numStr), this.pos - startPos); - } - parseString() { - if (this.ch() !== 34) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected character at position ${ this.pos }; this shouldn't happen`); - } - this.pos++; - for (let i = this.pos, l = 0; i < this.data.length && l < 65536; i++, l++) { - const ch = this.data[i]; - if (ch === 92 || ch < 32 || ch >= 128) { - break; - } - if (ch === 34) { - const str = String.fromCharCode.apply(null, this.data.subarray(this.pos, i)); - this.pos = i + 1; - return new lib_token/* Token */.W(lib_token/* Type.string */.D.string, str, l); - } - } - const startPos = this.pos; - const chars = []; - const readu4 = () => { - if (this.pos + 4 >= this.data.length) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected end of unicode escape sequence at position ${ this.pos }`); - } - let u4 = 0; - for (let i = 0; i < 4; i++) { - let ch = this.ch(); - if (ch >= 48 && ch <= 57) { - ch -= 48; - } else if (ch >= 97 && ch <= 102) { - ch = ch - 97 + 10; - } else if (ch >= 65 && ch <= 70) { - ch = ch - 65 + 10; - } else { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected unicode escape character at position ${ this.pos }`); - } - u4 = u4 * 16 + ch; - this.pos++; - } - return u4; - }; - const readUtf8Char = () => { - const firstByte = this.ch(); - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (this.pos + bytesPerSequence > this.data.length) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected unicode sequence at position ${ this.pos }`); - } - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = this.data[this.pos + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = this.data[this.pos + 1]; - thirdByte = this.data[this.pos + 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 = this.data[this.pos + 1]; - thirdByte = this.data[this.pos + 2]; - fourthByte = this.data[this.pos + 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; - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - chars.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - chars.push(codePoint); - this.pos += bytesPerSequence; - }; - while (!this.done()) { - const ch = this.ch(); - let ch1; - switch (ch) { - case 92: - this.pos++; - if (this.done()) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected string termination at position ${ this.pos }`); - } - ch1 = this.ch(); - this.pos++; - switch (ch1) { - case 34: - case 39: - case 92: - case 47: - chars.push(ch1); - break; - case 98: - chars.push(8); - break; - case 116: - chars.push(9); - break; - case 110: - chars.push(10); - break; - case 102: - chars.push(12); - break; - case 114: - chars.push(13); - break; - case 117: - chars.push(readu4()); - break; - default: - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected string escape character at position ${ this.pos }`); - } - break; - case 34: - this.pos++; - return new lib_token/* Token */.W(lib_token/* Type.string */.D.string, (0,byte_utils/* decodeCodePointsArray */.Pu)(chars), this.pos - startPos); - default: - if (ch < 32) { - throw new Error(`${ common/* decodeErrPrefix */.IR } invalid control character at position ${ this.pos }`); - } else if (ch < 128) { - chars.push(ch); - this.pos++; - } else { - readUtf8Char(); - } - } - } - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected end of string at position ${ this.pos }`); - } - parseValue() { - switch (this.ch()) { - case 123: - this.modeStack.push('obj-start'); - this.pos++; - return new lib_token/* Token */.W(lib_token/* Type.map */.D.map, Infinity, 1); - case 91: - this.modeStack.push('array-start'); - this.pos++; - return new lib_token/* Token */.W(lib_token/* Type.array */.D.array, Infinity, 1); - case 34: { - return this.parseString(); - } - case 110: - this.expect([ - 110, - 117, - 108, - 108 - ]); - return new lib_token/* Token */.W(lib_token/* Type.null */.D["null"], null, 4); - case 102: - this.expect([ - 102, - 97, - 108, - 115, - 101 - ]); - return new lib_token/* Token */.W(lib_token/* Type.false */.D["false"], false, 5); - case 116: - this.expect([ - 116, - 114, - 117, - 101 - ]); - return new lib_token/* Token */.W(lib_token/* Type.true */.D["true"], true, 4); - case 45: - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - return this.parseNumber(); - default: - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected character at position ${ this.pos }`); - } - } - next() { - this.skipWhitespace(); - switch (this.currentMode()) { - case 'value': - this.modeStack.pop(); - return this.parseValue(); - case 'array-value': { - this.modeStack.pop(); - if (this.ch() === 93) { - this.pos++; - this.skipWhitespace(); - return new lib_token/* Token */.W(lib_token/* Type.break */.D["break"], undefined, 1); - } - if (this.ch() !== 44) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected character at position ${ this.pos }, was expecting array delimiter but found '${ String.fromCharCode(this.ch()) }'`); - } - this.pos++; - this.modeStack.push('array-value'); - this.skipWhitespace(); - return this.parseValue(); - } - case 'array-start': { - this.modeStack.pop(); - if (this.ch() === 93) { - this.pos++; - this.skipWhitespace(); - return new lib_token/* Token */.W(lib_token/* Type.break */.D["break"], undefined, 1); - } - this.modeStack.push('array-value'); - this.skipWhitespace(); - return this.parseValue(); - } - case 'obj-key': - if (this.ch() === 125) { - this.modeStack.pop(); - this.pos++; - this.skipWhitespace(); - return new lib_token/* Token */.W(lib_token/* Type.break */.D["break"], undefined, 1); - } - if (this.ch() !== 44) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected character at position ${ this.pos }, was expecting object delimiter but found '${ String.fromCharCode(this.ch()) }'`); - } - this.pos++; - this.skipWhitespace(); - case 'obj-start': { - this.modeStack.pop(); - if (this.ch() === 125) { - this.pos++; - this.skipWhitespace(); - return new lib_token/* Token */.W(lib_token/* Type.break */.D["break"], undefined, 1); - } - const token = this.parseString(); - this.skipWhitespace(); - if (this.ch() !== 58) { - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected character at position ${ this.pos }, was expecting key/value delimiter ':' but found '${ String.fromCharCode(this.ch()) }'`); - } - this.pos++; - this.modeStack.push('obj-value'); - return token; - } - case 'obj-value': { - this.modeStack.pop(); - this.modeStack.push('obj-key'); - this.skipWhitespace(); - return this.parseValue(); - } - default: - throw new Error(`${ common/* decodeErrPrefix */.IR } unexpected parse state at position ${ this.pos }; this shouldn't happen`); - } - } -} -function decode_decode(data, options) { - options = Object.assign({ tokenizer: new Tokenizer(data, options) }, options); - return (0,lib_decode/* decode */.Jx)(data, options); -} - -;// CONCATENATED MODULE: ../node_modules/cborg/esm/lib/json/json.js - - - -;// CONCATENATED MODULE: ../node_modules/@ipld/dag-json/esm/index.js - - - - -function esm_cidEncoder(obj) { - if (obj.asCID !== obj) { - return null; - } - const cid = src.CID.asCID(obj); - if (!cid) { - return null; - } - const cidString = cid.toString(); - return [ - new cborg/* Token */.WU(cborg/* Type.map */.Dy.map, Infinity, 1), - new cborg/* Token */.WU(cborg/* Type.string */.Dy.string, '/', 1), - new cborg/* Token */.WU(cborg/* Type.string */.Dy.string, cidString, cidString.length), - new cborg/* Token */.WU(cborg/* Type.break */.Dy["break"], undefined, 1) - ]; -} -function bytesEncoder(bytes) { - const bytesString = base64.base64.encode(bytes).slice(1); - return [ - new cborg/* Token */.WU(cborg/* Type.map */.Dy.map, Infinity, 1), - new cborg/* Token */.WU(cborg/* Type.string */.Dy.string, '/', 1), - new cborg/* Token */.WU(cborg/* Type.map */.Dy.map, Infinity, 1), - new cborg/* Token */.WU(cborg/* Type.string */.Dy.string, 'bytes', 5), - new cborg/* Token */.WU(cborg/* Type.string */.Dy.string, bytesString, bytesString.length), - new cborg/* Token */.WU(cborg/* Type.break */.Dy["break"], undefined, 1), - new cborg/* Token */.WU(cborg/* Type.break */.Dy["break"], undefined, 1) - ]; -} -function esm_undefinedEncoder() { - throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded'); -} -function esm_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 esm_encodeOptions = { - typeEncoders: { - Object: esm_cidEncoder, - Uint8Array: bytesEncoder, - Buffer: bytesEncoder, - undefined: esm_undefinedEncoder, - number: esm_numberEncoder - } -}; -class DagJsonTokenizer extends Tokenizer { - constructor(data, options) { - super(data, options); - this.tokenBuffer = []; - } - done() { - return this.tokenBuffer.length === 0 && super.done(); - } - _next() { - if (this.tokenBuffer.length > 0) { - return this.tokenBuffer.pop(); - } - return super.next(); - } - next() { - const token = this._next(); - if (token.type === cborg/* Type.map */.Dy.map) { - const keyToken = this._next(); - if (keyToken.type === cborg/* Type.string */.Dy.string && keyToken.value === '/') { - const valueToken = this._next(); - if (valueToken.type === cborg/* Type.string */.Dy.string) { - const breakToken = this._next(); - if (breakToken.type !== cborg/* Type.break */.Dy["break"]) { - throw new Error('Invalid encoded CID form'); - } - this.tokenBuffer.push(valueToken); - return new cborg/* Token */.WU(cborg/* Type.tag */.Dy.tag, 42, 0); - } - if (valueToken.type === cborg/* Type.map */.Dy.map) { - const innerKeyToken = this._next(); - if (innerKeyToken.type === cborg/* Type.string */.Dy.string && innerKeyToken.value === 'bytes') { - const innerValueToken = this._next(); - if (innerValueToken.type === cborg/* Type.string */.Dy.string) { - for (let i = 0; i < 2; i++) { - const breakToken = this._next(); - if (breakToken.type !== cborg/* Type.break */.Dy["break"]) { - throw new Error('Invalid encoded Bytes form'); - } - } - const bytes = base64.base64.decode(`m${ innerValueToken.value }`); - return new cborg/* Token */.WU(cborg/* Type.bytes */.Dy.bytes, bytes, innerValueToken.value.length); - } - this.tokenBuffer.push(innerValueToken); - } - this.tokenBuffer.push(innerKeyToken); - } - this.tokenBuffer.push(valueToken); - } - this.tokenBuffer.push(keyToken); - } - return token; - } -} -const esm_decodeOptions = { - allowIndefinite: false, - allowUndefined: false, - allowNaN: false, - allowInfinity: false, - allowBigInt: true, - strict: true, - useMaps: false, - tags: [] -}; -esm_decodeOptions.tags[42] = src.CID.parse; -const dag_json_esm_name = 'dag-json'; -const dag_json_esm_code = 297; -const dag_json_esm_encode = node => encode_encode(node, esm_encodeOptions); -const dag_json_esm_decode = data => { - const options = Object.assign(esm_decodeOptions, { tokenizer: new DagJsonTokenizer(data, esm_decodeOptions) }); - return decode_decode(data, options); -}; -// EXTERNAL MODULE: ../node_modules/dag-jose/lib/index.js -var lib = __webpack_require__(3614); -var lib_namespaceObject = /*#__PURE__*/__webpack_require__.t(lib, 2); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/hashes/identity.js -var identity = __webpack_require__(7246); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/basics.js + 8 modules -var basics = __webpack_require__(9145); -// EXTERNAL MODULE: ../node_modules/multiaddr/src/index.js -var multiaddr_src = __webpack_require__(9038); -// EXTERNAL MODULE: ../node_modules/ipfs-utils/src/env.js -var env = __webpack_require__(1823); -;// CONCATENATED MODULE: ../node_modules/parse-duration/index.mjs -let durationRE = /(-?(?:\d+\.?\d*|\d*\.?\d+)(?:e[-+]?\d+)?)\s*([\p{L}]*)/uig - - -/** - * conversion ratios - */ - -parse.nanosecond = -parse.ns = 1 / 1e6 - -parse['µs'] = -parse['μs'] = -parse.us = -parse.microsecond = 1 / 1e3 - -parse.millisecond = -parse.ms = -parse[''] = 1 - -parse.second = -parse.sec = -parse.s = parse.ms * 1000 - -parse.minute = -parse.min = -parse.m = parse.s * 60 - -parse.hour = -parse.hr = -parse.h = parse.m * 60 - -parse.day = -parse.d = parse.h * 24 - -parse.week = -parse.wk = -parse.w = parse.d * 7 - -parse.month = -parse.b = -parse.d * (365.25 / 12) - -parse.year = -parse.yr = -parse.y = parse.d * 365.25 - -/** - * convert `str` to ms - * - * @param {String} str - * @param {String} format - * @return {Number} - */ - -function parse(str='', format='ms'){ - var result = null - // ignore commas/placeholders - str = (str+'').replace(/(\d)[,_](\d)/g, '$1$2') - str.replace(durationRE, function(_, n, units){ - units = unitRatio(units) - if (units) result = (result || 0) + parseFloat(n, 10) * units - }) - - return result && (result / (unitRatio(format) || 1)) -} - -function unitRatio(str) { - return parse[str] || parse[str.toLowerCase().replace(/s$/, '')] -} - -/* harmony default export */ const parse_duration = (parse); - -// EXTERNAL MODULE: ../node_modules/debug/src/browser.js -var browser = __webpack_require__(6292); -// EXTERNAL MODULE: ../node_modules/ipfs-utils/src/http.js -var http = __webpack_require__(2722); -// EXTERNAL MODULE: ../node_modules/merge-options/index.js -var merge_options = __webpack_require__(3224); -;// CONCATENATED MODULE: ../node_modules/merge-options/index.mjs -/** - * Thin ESM wrapper for CJS named exports. - * - * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1 - */ - - -/* harmony default export */ const node_modules_merge_options = (merge_options); - -// EXTERNAL MODULE: ../node_modules/multiaddr-to-uri/index.js -var multiaddr_to_uri = __webpack_require__(9546); -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/to-url-string.js - - -function toUrlString(url) { - try { - url = multiaddr_to_uri(new multiaddr_src.Multiaddr(url)); - } catch (err) { - } - url = url.toString(); - return url; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/agent.browser.js -/* harmony default export */ const agent_browser = (() => { -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/core.js - - - - - - - - -const log = browser('ipfs-http-client:lib:error-handler'); -const merge = node_modules_merge_options.bind({ ignoreUndefined: true }); -const DEFAULT_PROTOCOL = env.isBrowser || env.isWebWorker ? location.protocol : 'http'; -const DEFAULT_HOST = env.isBrowser || env.isWebWorker ? location.hostname : 'localhost'; -const DEFAULT_PORT = env.isBrowser || env.isWebWorker ? location.port : '5001'; -const normalizeOptions = (options = {}) => { - let url; - let opts = {}; - let agent; - if (typeof options === 'string' || multiaddr_src.Multiaddr.isMultiaddr(options)) { - url = new URL(toUrlString(options)); - } else if (options instanceof URL) { - url = options; - } else if (typeof options.url === 'string' || multiaddr_src.Multiaddr.isMultiaddr(options.url)) { - url = new URL(toUrlString(options.url)); - opts = options; - } else if (options.url instanceof URL) { - url = options.url; - opts = options; - } else { - opts = options || {}; - const protocol = (opts.protocol || DEFAULT_PROTOCOL).replace(':', ''); - const host = (opts.host || DEFAULT_HOST).split(':')[0]; - const port = opts.port || DEFAULT_PORT; - url = new URL(`${ protocol }://${ host }:${ port }`); - } - if (opts.apiPath) { - url.pathname = opts.apiPath; - } else if (url.pathname === '/' || url.pathname === undefined) { - url.pathname = 'api/v0'; - } - if (env.isNode) { - const Agent = agent_browser(url); - agent = opts.agent || new Agent({ - keepAlive: true, - maxSockets: 6 - }); - } - return { - ...opts, - host: url.host, - protocol: url.protocol.replace(':', ''), - port: Number(url.port), - apiPath: url.pathname, - url, - agent - }; -}; -const errorHandler = async response => { - let msg; - try { - if ((response.headers.get('Content-Type') || '').startsWith('application/json')) { - const data = await response.json(); - log(data); - msg = data.Message || data.message; - } else { - msg = await response.text(); - } - } catch (err) { - log('Failed to parse error response', err); - msg = err.message; - } - let error = new http.HTTPError(response); - if (msg) { - if (msg.includes('deadline has elapsed')) { - error = new http.TimeoutError(); - } - if (msg && msg.includes('context deadline exceeded')) { - error = new http.TimeoutError(); - } - } - if (msg && msg.includes('request timed out')) { - error = new http.TimeoutError(); - } - if (msg) { - error.message = msg; - } - throw error; -}; -const KEBAB_REGEX = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g; -const kebabCase = str => { - return str.replace(KEBAB_REGEX, function (match) { - return '-' + match.toLowerCase(); - }); -}; -const parseTimeout = value => { - return typeof value === 'string' ? parse_duration(value) : value; -}; -class Client extends http { - constructor(options = {}) { - const opts = normalizeOptions(options); - super({ - timeout: parseTimeout(opts.timeout || 0) || undefined, - headers: opts.headers, - base: `${ opts.url }`, - handleError: errorHandler, - transformSearchParams: search => { - const out = new URLSearchParams(); - for (const [key, value] of search) { - if (value !== 'undefined' && value !== 'null' && key !== 'signal') { - out.append(kebabCase(key), value); - } - if (key === 'timeout' && !isNaN(value)) { - out.append(kebabCase(key), value); - } - } - return out; - }, - agent: opts.agent - }); - delete this.get; - delete this.put; - delete this.delete; - delete this.options; - const fetch = this.fetch; - this.fetch = (resource, options = {}) => { - if (typeof resource === 'string' && !resource.startsWith('/')) { - resource = `${ opts.url }/${ resource }`; - } - return fetch.call(this, resource, merge(options, { method: 'POST' })); - }; - } -} -const HTTPError = http.HTTPError; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/configure.js - -const configure = fn => { - return options => { - return fn(new Client(options), options); - }; -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/mode-to-string.js -function modeToString(mode) { - if (mode == null) { - return undefined; - } - if (typeof mode === 'string') { - return mode; - } - return mode.toString(8).padStart(4, '0'); -} -// EXTERNAL MODULE: ../node_modules/err-code/index.js -var err_code = __webpack_require__(118); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/parse-mtime.js - -function parseMtime(input) { - if (input == null) { - return undefined; - } - let mtime; - if (input.secs != null) { - mtime = { - secs: input.secs, - nsecs: input.nsecs - }; - } - if (input.Seconds != null) { - mtime = { - secs: input.Seconds, - nsecs: input.FractionalNanoseconds - }; - } - if (Array.isArray(input)) { - mtime = { - secs: input[0], - nsecs: input[1] - }; - } - if (input instanceof Date) { - const ms = input.getTime(); - const secs = Math.floor(ms / 1000); - mtime = { - secs: secs, - nsecs: (ms - secs * 1000) * 1000 - }; - } - if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) { - return undefined; - } - if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) { - throw err_code(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS'); - } - return mtime; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/to-url-search-params.js - - -function toUrlSearchParams({arg, searchParams, hashAlg, mtime, mode, ...options} = {}) { - if (searchParams) { - options = { - ...options, - ...searchParams - }; - } - if (hashAlg) { - options.hash = hashAlg; - } - if (mtime != null) { - mtime = parseMtime(mtime); - options.mtime = mtime.secs; - options.mtimeNsecs = mtime.nsecs; - } - if (mode != null) { - options.mode = modeToString(mode); - } - if (options.timeout && !isNaN(options.timeout)) { - options.timeout = `${ options.timeout }ms`; - } - if (arg === undefined || arg === null) { - arg = []; - } else if (!Array.isArray(arg)) { - arg = [arg]; - } - const urlSearchParams = new URLSearchParams(options); - arg.forEach(arg => urlSearchParams.append('arg', arg)); - return urlSearchParams; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bitswap/wantlist.js - - - -const createWantlist = configure(api => { - async function wantlist(options = {}) { - const res = await (await api.post('bitswap/wantlist', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - })).json(); - return (res.Keys || []).map(k => src_cid.CID.parse(k['/'])); - } - return wantlist; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bitswap/wantlist-for-peer.js - - - -const createWantlistForPeer = configure(api => { - async function wantlistForPeer(peerId, options = {}) { - const res = await (await api.post('bitswap/wantlist', { - signal: options.signal, - searchParams: toUrlSearchParams({ - ...options, - peer: peerId.toString() - }), - headers: options.headers - })).json(); - return (res.Keys || []).map(k => src_cid.CID.parse(k['/'])); - } - return wantlistForPeer; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bitswap/stat.js - - - -const createStat = configure(api => { - async function stat(options = {}) { - const res = await api.post('bitswap/stat', { - searchParams: toUrlSearchParams(options), - signal: options.signal, - headers: options.headers - }); - return toCoreInterface(await res.json()); - } - return stat; -}); -function toCoreInterface(res) { - return { - provideBufLen: res.ProvideBufLen, - wantlist: (res.Wantlist || []).map(k => src_cid.CID.parse(k['/'])), - peers: res.Peers || [], - blocksReceived: BigInt(res.BlocksReceived), - dataReceived: BigInt(res.DataReceived), - blocksSent: BigInt(res.BlocksSent), - dataSent: BigInt(res.DataSent), - dupBlksReceived: BigInt(res.DupBlksReceived), - dupDataReceived: BigInt(res.DupDataReceived) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bitswap/unwant.js - - -const createUnwant = configure(api => { - async function unwant(cid, options = {}) { - const res = await api.post('bitswap/unwant', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cid.toString(), - ...options - }), - headers: options.headers - }); - return res.json(); - } - return unwant; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bitswap/index.js - - - - -function createBitswap(config) { - return { - wantlist: createWantlist(config), - wantlistForPeer: createWantlistForPeer(config), - unwant: createUnwant(config), - stat: createStat(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/block/get.js - - -const createGet = configure(api => { - async function get(cid, options = {}) { - const res = await api.post('block/get', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cid.toString(), - ...options - }), - headers: options.headers - }); - return new Uint8Array(await res.arrayBuffer()); - } - return get; -}); -// EXTERNAL MODULE: ../node_modules/it-peekable/index.js -var it_peekable = __webpack_require__(3506); -// EXTERNAL MODULE: ../node_modules/browser-readablestream-to-it/index.js -var browser_readablestream_to_it = __webpack_require__(2630); -// EXTERNAL MODULE: ../node_modules/it-all/index.js -var it_all = __webpack_require__(1251); -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/utils.js -function isBytes(obj) { - return ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer; -} -function isBlob(obj) { - return obj.constructor && (obj.constructor.name === 'Blob' || obj.constructor.name === 'File') && typeof obj.stream === 'function'; -} -function isFileObject(obj) { - return typeof obj === 'object' && (obj.path || obj.content); -} -const isReadableStream = value => value && typeof value.getReader === 'function'; -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-content.browser.js - - - - - -async function normaliseContent(input) { - if (isBytes(input)) { - return new Blob([input]); - } - if (typeof input === 'string' || input instanceof String) { - return new Blob([input.toString()]); - } - if (isBlob(input)) { - return input; - } - if (isReadableStream(input)) { - input = browser_readablestream_to_it(input); - } - if (Symbol.iterator in input || Symbol.asyncIterator in input) { - const peekable = it_peekable(input); - const {value, done} = await peekable.peek(); - if (done) { - return itToBlob(peekable); - } - peekable.push(value); - if (Number.isInteger(value)) { - return new Blob([Uint8Array.from(await it_all(peekable))]); - } - if (isBytes(value) || typeof value === 'string' || value instanceof String) { - return itToBlob(peekable); - } - } - throw err_code(new Error(`Unexpected input: ${ input }`), 'ERR_UNEXPECTED_INPUT'); -} -async function itToBlob(stream) { - const parts = []; - for await (const chunk of stream) { - parts.push(chunk); - } - return new Blob(parts); -} -// EXTERNAL MODULE: ../node_modules/it-map/index.js -var it_map = __webpack_require__(8731); -// EXTERNAL MODULE: ../node_modules/protobufjs/minimal.js -var minimal = __webpack_require__(3967); -;// CONCATENATED MODULE: ../node_modules/ipfs-unixfs/esm/src/unixfs.js - -const $Reader = minimal.Reader, $Writer = minimal.Writer, $util = minimal.util; -const $root = minimal.roots["ipfs-unixfs"] || (minimal.roots["ipfs-unixfs"] = {}); -const Data = $root.Data = (() => { - function Data(p) { - this.blocksizes = []; - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - Data.prototype.Type = 0; - Data.prototype.Data = $util.newBuffer([]); - Data.prototype.filesize = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Data.prototype.blocksizes = $util.emptyArray; - Data.prototype.hashType = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Data.prototype.fanout = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Data.prototype.mode = 0; - Data.prototype.mtime = null; - Data.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - w.uint32(8).int32(m.Type); - if (m.Data != null && Object.hasOwnProperty.call(m, 'Data')) - w.uint32(18).bytes(m.Data); - if (m.filesize != null && Object.hasOwnProperty.call(m, 'filesize')) - w.uint32(24).uint64(m.filesize); - if (m.blocksizes != null && m.blocksizes.length) { - for (var i = 0; i < m.blocksizes.length; ++i) - w.uint32(32).uint64(m.blocksizes[i]); - } - if (m.hashType != null && Object.hasOwnProperty.call(m, 'hashType')) - w.uint32(40).uint64(m.hashType); - if (m.fanout != null && Object.hasOwnProperty.call(m, 'fanout')) - w.uint32(48).uint64(m.fanout); - if (m.mode != null && Object.hasOwnProperty.call(m, 'mode')) - w.uint32(56).uint32(m.mode); - if (m.mtime != null && Object.hasOwnProperty.call(m, 'mtime')) - $root.UnixTime.encode(m.mtime, w.uint32(66).fork()).ldelim(); - return w; - }; - Data.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.Data(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.Type = r.int32(); - break; - case 2: - m.Data = r.bytes(); - break; - case 3: - m.filesize = r.uint64(); - break; - case 4: - if (!(m.blocksizes && m.blocksizes.length)) - m.blocksizes = []; - if ((t & 7) === 2) { - var c2 = r.uint32() + r.pos; - while (r.pos < c2) - m.blocksizes.push(r.uint64()); - } else - m.blocksizes.push(r.uint64()); - break; - case 5: - m.hashType = r.uint64(); - break; - case 6: - m.fanout = r.uint64(); - break; - case 7: - m.mode = r.uint32(); - break; - case 8: - m.mtime = $root.UnixTime.decode(r, r.uint32()); - break; - default: - r.skipType(t & 7); - break; - } - } - if (!m.hasOwnProperty('Type')) - throw $util.ProtocolError('missing required \'Type\'', { instance: m }); - return m; - }; - Data.fromObject = function fromObject(d) { - if (d instanceof $root.Data) - return d; - var m = new $root.Data(); - switch (d.Type) { - case 'Raw': - case 0: - m.Type = 0; - break; - case 'Directory': - case 1: - m.Type = 1; - break; - case 'File': - case 2: - m.Type = 2; - break; - case 'Metadata': - case 3: - m.Type = 3; - break; - case 'Symlink': - case 4: - m.Type = 4; - break; - case 'HAMTShard': - case 5: - m.Type = 5; - break; - } - if (d.Data != null) { - if (typeof d.Data === 'string') - $util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0); - else if (d.Data.length) - m.Data = d.Data; - } - if (d.filesize != null) { - if ($util.Long) - (m.filesize = $util.Long.fromValue(d.filesize)).unsigned = true; - else if (typeof d.filesize === 'string') - m.filesize = parseInt(d.filesize, 10); - else if (typeof d.filesize === 'number') - m.filesize = d.filesize; - else if (typeof d.filesize === 'object') - m.filesize = new $util.LongBits(d.filesize.low >>> 0, d.filesize.high >>> 0).toNumber(true); - } - if (d.blocksizes) { - if (!Array.isArray(d.blocksizes)) - throw TypeError('.Data.blocksizes: array expected'); - m.blocksizes = []; - for (var i = 0; i < d.blocksizes.length; ++i) { - if ($util.Long) - (m.blocksizes[i] = $util.Long.fromValue(d.blocksizes[i])).unsigned = true; - else if (typeof d.blocksizes[i] === 'string') - m.blocksizes[i] = parseInt(d.blocksizes[i], 10); - else if (typeof d.blocksizes[i] === 'number') - m.blocksizes[i] = d.blocksizes[i]; - else if (typeof d.blocksizes[i] === 'object') - m.blocksizes[i] = new $util.LongBits(d.blocksizes[i].low >>> 0, d.blocksizes[i].high >>> 0).toNumber(true); - } - } - if (d.hashType != null) { - if ($util.Long) - (m.hashType = $util.Long.fromValue(d.hashType)).unsigned = true; - else if (typeof d.hashType === 'string') - m.hashType = parseInt(d.hashType, 10); - else if (typeof d.hashType === 'number') - m.hashType = d.hashType; - else if (typeof d.hashType === 'object') - m.hashType = new $util.LongBits(d.hashType.low >>> 0, d.hashType.high >>> 0).toNumber(true); - } - if (d.fanout != null) { - if ($util.Long) - (m.fanout = $util.Long.fromValue(d.fanout)).unsigned = true; - else if (typeof d.fanout === 'string') - m.fanout = parseInt(d.fanout, 10); - else if (typeof d.fanout === 'number') - m.fanout = d.fanout; - else if (typeof d.fanout === 'object') - m.fanout = new $util.LongBits(d.fanout.low >>> 0, d.fanout.high >>> 0).toNumber(true); - } - if (d.mode != null) { - m.mode = d.mode >>> 0; - } - if (d.mtime != null) { - if (typeof d.mtime !== 'object') - throw TypeError('.Data.mtime: object expected'); - m.mtime = $root.UnixTime.fromObject(d.mtime); - } - return m; - }; - Data.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.arrays || o.defaults) { - d.blocksizes = []; - } - if (o.defaults) { - d.Type = o.enums === String ? 'Raw' : 0; - if (o.bytes === String) - d.Data = ''; - else { - d.Data = []; - if (o.bytes !== Array) - d.Data = $util.newBuffer(d.Data); - } - if ($util.Long) { - var n = new $util.Long(0, 0, true); - d.filesize = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n; - } else - d.filesize = o.longs === String ? '0' : 0; - if ($util.Long) { - var n = new $util.Long(0, 0, true); - d.hashType = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n; - } else - d.hashType = o.longs === String ? '0' : 0; - if ($util.Long) { - var n = new $util.Long(0, 0, true); - d.fanout = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n; - } else - d.fanout = o.longs === String ? '0' : 0; - d.mode = 0; - d.mtime = null; - } - if (m.Type != null && m.hasOwnProperty('Type')) { - d.Type = o.enums === String ? $root.Data.DataType[m.Type] : m.Type; - } - if (m.Data != null && m.hasOwnProperty('Data')) { - d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data; - } - if (m.filesize != null && m.hasOwnProperty('filesize')) { - if (typeof m.filesize === 'number') - d.filesize = o.longs === String ? String(m.filesize) : m.filesize; - else - d.filesize = o.longs === String ? $util.Long.prototype.toString.call(m.filesize) : o.longs === Number ? new $util.LongBits(m.filesize.low >>> 0, m.filesize.high >>> 0).toNumber(true) : m.filesize; - } - if (m.blocksizes && m.blocksizes.length) { - d.blocksizes = []; - for (var j = 0; j < m.blocksizes.length; ++j) { - if (typeof m.blocksizes[j] === 'number') - d.blocksizes[j] = o.longs === String ? String(m.blocksizes[j]) : m.blocksizes[j]; - else - d.blocksizes[j] = o.longs === String ? $util.Long.prototype.toString.call(m.blocksizes[j]) : o.longs === Number ? new $util.LongBits(m.blocksizes[j].low >>> 0, m.blocksizes[j].high >>> 0).toNumber(true) : m.blocksizes[j]; - } - } - if (m.hashType != null && m.hasOwnProperty('hashType')) { - if (typeof m.hashType === 'number') - d.hashType = o.longs === String ? String(m.hashType) : m.hashType; - else - d.hashType = o.longs === String ? $util.Long.prototype.toString.call(m.hashType) : o.longs === Number ? new $util.LongBits(m.hashType.low >>> 0, m.hashType.high >>> 0).toNumber(true) : m.hashType; - } - if (m.fanout != null && m.hasOwnProperty('fanout')) { - if (typeof m.fanout === 'number') - d.fanout = o.longs === String ? String(m.fanout) : m.fanout; - else - d.fanout = o.longs === String ? $util.Long.prototype.toString.call(m.fanout) : o.longs === Number ? new $util.LongBits(m.fanout.low >>> 0, m.fanout.high >>> 0).toNumber(true) : m.fanout; - } - if (m.mode != null && m.hasOwnProperty('mode')) { - d.mode = m.mode; - } - if (m.mtime != null && m.hasOwnProperty('mtime')) { - d.mtime = $root.UnixTime.toObject(m.mtime, o); - } - return d; - }; - Data.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, minimal.util.toJSONOptions); - }; - Data.DataType = function () { - const valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = 'Raw'] = 0; - values[valuesById[1] = 'Directory'] = 1; - values[valuesById[2] = 'File'] = 2; - values[valuesById[3] = 'Metadata'] = 3; - values[valuesById[4] = 'Symlink'] = 4; - values[valuesById[5] = 'HAMTShard'] = 5; - return values; - }(); - return Data; -})(); -const UnixTime = $root.UnixTime = (() => { - function UnixTime(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - UnixTime.prototype.Seconds = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - UnixTime.prototype.FractionalNanoseconds = 0; - UnixTime.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - w.uint32(8).int64(m.Seconds); - if (m.FractionalNanoseconds != null && Object.hasOwnProperty.call(m, 'FractionalNanoseconds')) - w.uint32(21).fixed32(m.FractionalNanoseconds); - return w; - }; - UnixTime.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.UnixTime(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.Seconds = r.int64(); - break; - case 2: - m.FractionalNanoseconds = r.fixed32(); - break; - default: - r.skipType(t & 7); - break; - } - } - if (!m.hasOwnProperty('Seconds')) - throw $util.ProtocolError('missing required \'Seconds\'', { instance: m }); - return m; - }; - UnixTime.fromObject = function fromObject(d) { - if (d instanceof $root.UnixTime) - return d; - var m = new $root.UnixTime(); - if (d.Seconds != null) { - if ($util.Long) - (m.Seconds = $util.Long.fromValue(d.Seconds)).unsigned = false; - else if (typeof d.Seconds === 'string') - m.Seconds = parseInt(d.Seconds, 10); - else if (typeof d.Seconds === 'number') - m.Seconds = d.Seconds; - else if (typeof d.Seconds === 'object') - m.Seconds = new $util.LongBits(d.Seconds.low >>> 0, d.Seconds.high >>> 0).toNumber(); - } - if (d.FractionalNanoseconds != null) { - m.FractionalNanoseconds = d.FractionalNanoseconds >>> 0; - } - return m; - }; - UnixTime.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - if ($util.Long) { - var n = new $util.Long(0, 0, false); - d.Seconds = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n; - } else - d.Seconds = o.longs === String ? '0' : 0; - d.FractionalNanoseconds = 0; - } - if (m.Seconds != null && m.hasOwnProperty('Seconds')) { - if (typeof m.Seconds === 'number') - d.Seconds = o.longs === String ? String(m.Seconds) : m.Seconds; - else - d.Seconds = o.longs === String ? $util.Long.prototype.toString.call(m.Seconds) : o.longs === Number ? new $util.LongBits(m.Seconds.low >>> 0, m.Seconds.high >>> 0).toNumber() : m.Seconds; - } - if (m.FractionalNanoseconds != null && m.hasOwnProperty('FractionalNanoseconds')) { - d.FractionalNanoseconds = m.FractionalNanoseconds; - } - return d; - }; - UnixTime.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, minimal.util.toJSONOptions); - }; - return UnixTime; -})(); -const Metadata = $root.Metadata = (() => { - function Metadata(p) { - if (p) - for (var ks = Object.keys(p), i = 0; i < ks.length; ++i) - if (p[ks[i]] != null) - this[ks[i]] = p[ks[i]]; - } - Metadata.prototype.MimeType = ''; - Metadata.encode = function encode(m, w) { - if (!w) - w = $Writer.create(); - if (m.MimeType != null && Object.hasOwnProperty.call(m, 'MimeType')) - w.uint32(10).string(m.MimeType); - return w; - }; - Metadata.decode = function decode(r, l) { - if (!(r instanceof $Reader)) - r = $Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, m = new $root.Metadata(); - while (r.pos < c) { - var t = r.uint32(); - switch (t >>> 3) { - case 1: - m.MimeType = r.string(); - break; - default: - r.skipType(t & 7); - break; - } - } - return m; - }; - Metadata.fromObject = function fromObject(d) { - if (d instanceof $root.Metadata) - return d; - var m = new $root.Metadata(); - if (d.MimeType != null) { - m.MimeType = String(d.MimeType); - } - return m; - }; - Metadata.toObject = function toObject(m, o) { - if (!o) - o = {}; - var d = {}; - if (o.defaults) { - d.MimeType = ''; - } - if (m.MimeType != null && m.hasOwnProperty('MimeType')) { - d.MimeType = m.MimeType; - } - return d; - }; - Metadata.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, minimal.util.toJSONOptions); - }; - return Metadata; -})(); - -;// CONCATENATED MODULE: ../node_modules/ipfs-unixfs/esm/src/index.js - - -const PBData = Data; -const types = (/* unused pure expression or super */ null && ([ - 'raw', - 'directory', - 'file', - 'metadata', - 'symlink', - 'hamt-sharded-directory' -])); -const dirTypes = (/* unused pure expression or super */ null && ([ - 'directory', - 'hamt-sharded-directory' -])); -const DEFAULT_FILE_MODE = parseInt('0644', 8); -const DEFAULT_DIRECTORY_MODE = parseInt('0755', 8); -function parseMode(mode) { - if (mode == null) { - return undefined; - } - if (typeof mode === 'number') { - return mode & 4095; - } - mode = mode.toString(); - if (mode.substring(0, 1) === '0') { - return parseInt(mode, 8) & 4095; - } - return parseInt(mode, 10) & 4095; -} -function src_parseMtime(input) { - if (input == null) { - return undefined; - } - let mtime; - if (input.secs != null) { - mtime = { - secs: input.secs, - nsecs: input.nsecs - }; - } - if (input.Seconds != null) { - mtime = { - secs: input.Seconds, - nsecs: input.FractionalNanoseconds - }; - } - if (Array.isArray(input)) { - mtime = { - secs: input[0], - nsecs: input[1] - }; - } - if (input instanceof Date) { - const ms = input.getTime(); - const secs = Math.floor(ms / 1000); - mtime = { - secs: secs, - nsecs: (ms - secs * 1000) * 1000 - }; - } - if (!Object.prototype.hasOwnProperty.call(mtime, 'secs')) { - return undefined; - } - if (mtime != null && mtime.nsecs != null && (mtime.nsecs < 0 || mtime.nsecs > 999999999)) { - throw err_code(new Error('mtime-nsecs must be within the range [0,999999999]'), 'ERR_INVALID_MTIME_NSECS'); - } - return mtime; -} -class UnixFS { - static unmarshal(marshaled) { - const message = PBData.decode(marshaled); - const decoded = PBData.toObject(message, { - defaults: false, - arrays: true, - longs: Number, - objects: false - }); - const data = new UnixFS({ - type: types[decoded.Type], - data: decoded.Data, - blockSizes: decoded.blocksizes, - mode: decoded.mode, - mtime: decoded.mtime ? { - secs: decoded.mtime.Seconds, - nsecs: decoded.mtime.FractionalNanoseconds - } : undefined - }); - data._originalMode = decoded.mode || 0; - return data; - } - constructor(options = { type: 'file' }) { - const {type, data, blockSizes, hashType, fanout, mtime, mode} = options; - if (type && !types.includes(type)) { - throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE'); - } - this.type = type || 'file'; - this.data = data; - this.hashType = hashType; - this.fanout = fanout; - this.blockSizes = blockSizes || []; - this._originalMode = 0; - this.mode = parseMode(mode); - if (mtime) { - this.mtime = src_parseMtime(mtime); - if (this.mtime && !this.mtime.nsecs) { - this.mtime.nsecs = 0; - } - } - } - set mode(mode) { - this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE; - const parsedMode = parseMode(mode); - if (parsedMode !== undefined) { - this._mode = parsedMode; - } - } - get mode() { - return this._mode; - } - isDirectory() { - return Boolean(this.type && dirTypes.includes(this.type)); - } - addBlockSize(size) { - this.blockSizes.push(size); - } - removeBlockSize(index) { - this.blockSizes.splice(index, 1); - } - fileSize() { - if (this.isDirectory()) { - return 0; - } - let sum = 0; - this.blockSizes.forEach(size => { - sum += size; - }); - if (this.data) { - sum += this.data.length; - } - return sum; - } - marshal() { - let type; - switch (this.type) { - case 'raw': - type = PBData.DataType.Raw; - break; - case 'directory': - type = PBData.DataType.Directory; - break; - case 'file': - type = PBData.DataType.File; - break; - case 'metadata': - type = PBData.DataType.Metadata; - break; - case 'symlink': - type = PBData.DataType.Symlink; - break; - case 'hamt-sharded-directory': - type = PBData.DataType.HAMTShard; - break; - default: - throw errcode(new Error('Type: ' + type + ' is not valid'), 'ERR_INVALID_TYPE'); - } - let data = this.data; - if (!this.data || !this.data.length) { - data = undefined; - } - let mode; - if (this.mode != null) { - mode = this._originalMode & 4294963200 | (parseMode(this.mode) || 0); - if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) { - mode = undefined; - } - if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) { - mode = undefined; - } - } - let mtime; - if (this.mtime != null) { - const parsed = src_parseMtime(this.mtime); - if (parsed) { - mtime = { - Seconds: parsed.secs, - FractionalNanoseconds: parsed.nsecs - }; - if (mtime.FractionalNanoseconds === 0) { - delete mtime.FractionalNanoseconds; - } - } - } - const pbData = { - Type: type, - Data: data, - filesize: this.isDirectory() ? undefined : this.fileSize(), - blocksizes: this.blockSizes, - hashType: this.hashType, - fanout: this.fanout, - mode, - mtime - }; - return PBData.encode(pbData).finish(); - } -} - -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-candidate-multiple.js - - - - - - -async function* normaliseCandidateMultiple(input, normaliseContent) { - if (typeof input === 'string' || input instanceof String || isBytes(input) || isBlob(input) || input._readableState) { - throw err_code(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT'); - } - if (isReadableStream(input)) { - input = browser_readablestream_to_it(input); - } - if (Symbol.iterator in input || Symbol.asyncIterator in input) { - const peekable = it_peekable(input); - const {value, done} = await peekable.peek(); - if (done) { - yield* []; - return; - } - peekable.push(value); - if (Number.isInteger(value)) { - throw err_code(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT'); - } - if (value._readableState) { - yield* it_map(peekable, value => toFileObject({ content: value }, normaliseContent)); - return; - } - if (isBytes(value)) { - yield toFileObject({ content: peekable }, normaliseContent); - return; - } - if (isFileObject(value) || value[Symbol.iterator] || value[Symbol.asyncIterator] || isReadableStream(value) || isBlob(value)) { - yield* it_map(peekable, value => toFileObject(value, normaliseContent)); - return; - } - } - if (isFileObject(input)) { - throw err_code(new Error('Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead'), 'ERR_UNEXPECTED_INPUT'); - } - throw err_code(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT'); -} -async function toFileObject(input, normaliseContent) { - const {path, mode, mtime, content} = input; - const file = { - path: path || '', - mode: parseMode(mode), - mtime: src_parseMtime(mtime) - }; - if (content) { - file.content = await normaliseContent(content); - } else if (!path) { - file.content = await normaliseContent(input); - } - return file; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-input-multiple.browser.js - - -function normaliseInput(input) { - return normaliseCandidateMultiple(input, normaliseContent, true); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/mode-to-string.js -function mode_to_string_modeToString(mode) { - if (mode == null) { - return undefined; - } - if (typeof mode === 'string') { - return mode; - } - return mode.toString(8).padStart(4, '0'); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/multipart-request.browser.js - - -async function multipartRequest(source, abortController, headers = {}) { - const parts = []; - const formData = new FormData(); - let index = 0; - let total = 0; - for await (const {content, path, mode, mtime} of normaliseInput(source)) { - let fileSuffix = ''; - const type = content ? 'file' : 'dir'; - if (index > 0) { - fileSuffix = `-${ index }`; - } - let fieldName = type + fileSuffix; - const qs = []; - if (mode !== null && mode !== undefined) { - qs.push(`mode=${ mode_to_string_modeToString(mode) }`); - } - if (mtime != null) { - const {secs, nsecs} = mtime; - qs.push(`mtime=${ secs }`); - if (nsecs != null) { - qs.push(`mtime-nsecs=${ nsecs }`); - } - } - if (qs.length) { - fieldName = `${ fieldName }?${ qs.join('&') }`; - } - if (content) { - formData.set(fieldName, content, path != null ? encodeURIComponent(path) : undefined); - const end = total + content.size; - parts.push({ - name: path, - start: total, - end - }); - total = end; - } else if (path != null) { - formData.set(fieldName, new File([''], encodeURIComponent(path), { type: 'application/x-directory' })); - } else { - throw new Error('path or content or both must be set'); - } - index++; - } - return { - total, - parts, - headers, - body: formData - }; -} -// EXTERNAL MODULE: ../node_modules/any-signal/index.js -var any_signal = __webpack_require__(1659); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/abort-signal.js - -function filter(signals) { - return signals.filter(Boolean); -} -function abortSignal(...signals) { - return (0,any_signal.anySignal)(filter(signals)); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/block/put.js - - - - - -const createPut = configure(api => { - async function put(data, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - let res; - try { - const response = await api.post('block/put', { - signal: signal, - searchParams: toUrlSearchParams(options), - ...await multipartRequest([data], controller, options.headers) - }); - res = await response.json(); - } catch (err) { - if (options.format === 'dag-pb') { - return put(data, { - ...options, - format: 'protobuf' - }); - } else if (options.format === 'dag-cbor') { - return put(data, { - ...options, - format: 'cbor' - }); - } - throw err; - } - return src_cid.CID.parse(res.Key); - } - return put; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/block/rm.js - - - -const createRm = configure(api => { - async function* rm(cid, options = {}) { - if (!Array.isArray(cid)) { - cid = [cid]; - } - const res = await api.post('block/rm', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cid.map(cid => cid.toString()), - 'stream-channels': true, - ...options - }), - headers: options.headers - }); - for await (const removed of res.ndjson()) { - yield rm_toCoreInterface(removed); - } - } - return rm; -}); -function rm_toCoreInterface(removed) { - const out = { cid: src_cid.CID.parse(removed.Hash) }; - if (removed.Error) { - out.error = new Error(removed.Error); - } - return out; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/block/stat.js - - - -const stat_createStat = configure(api => { - async function stat(cid, options = {}) { - const res = await api.post('block/stat', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cid.toString(), - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return { - cid: src_cid.CID.parse(data.Key), - size: data.Size - }; - } - return stat; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/block/index.js - - - - -function createBlock(config) { - return { - get: createGet(config), - put: createPut(config), - rm: createRm(config), - stat: stat_createStat(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/add.js - - - -const createAdd = configure(api => { - async function add(addr, options = {}) { - const res = await api.post('bootstrap/add', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: addr, - ...options - }), - headers: options.headers - }); - const {Peers} = await res.json(); - return { Peers: Peers.map(ma => new multiaddr_src.Multiaddr(ma)) }; - } - return add; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/clear.js - - - -const createClear = configure(api => { - async function clear(options = {}) { - const res = await api.post('bootstrap/rm', { - signal: options.signal, - searchParams: toUrlSearchParams({ - ...options, - all: true - }), - headers: options.headers - }); - const {Peers} = await res.json(); - return { Peers: Peers.map(ma => new multiaddr_src.Multiaddr(ma)) }; - } - return clear; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/list.js - - - -const createList = configure(api => { - async function list(options = {}) { - const res = await api.post('bootstrap/list', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const {Peers} = await res.json(); - return { Peers: Peers.map(ma => new multiaddr_src.Multiaddr(ma)) }; - } - return list; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/reset.js - - - -const createReset = configure(api => { - async function reset(options = {}) { - const res = await api.post('bootstrap/add', { - signal: options.signal, - searchParams: toUrlSearchParams({ - ...options, - default: true - }), - headers: options.headers - }); - const {Peers} = await res.json(); - return { Peers: Peers.map(ma => new multiaddr_src.Multiaddr(ma)) }; - } - return reset; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/rm.js - - - -const rm_createRm = configure(api => { - async function rm(addr, options = {}) { - const res = await api.post('bootstrap/rm', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: addr, - ...options - }), - headers: options.headers - }); - const {Peers} = await res.json(); - return { Peers: Peers.map(ma => new multiaddr_src.Multiaddr(ma)) }; - } - return rm; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/bootstrap/index.js - - - - - -function createBootstrap(config) { - return { - add: createAdd(config), - clear: createClear(config), - list: createList(config), - reset: createReset(config), - rm: rm_createRm(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/profiles/apply.js - - -const createApply = configure(api => { - async function apply(profile, options = {}) { - const res = await api.post('config/profile/apply', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: profile, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return { - original: data.OldCfg, - updated: data.NewCfg - }; - } - return apply; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/object-to-camel.js -function objectToCamel(obj) { - if (obj == null) { - return obj; - } - const caps = /^[A-Z]+$/; - const output = {}; - return Object.keys(obj).reduce((camelObj, k) => { - if (caps.test(k)) { - camelObj[k.toLowerCase()] = obj[k]; - } else if (caps.test(k[0])) { - camelObj[k[0].toLowerCase() + k.slice(1)] = obj[k]; - } else { - camelObj[k] = obj[k]; - } - return camelObj; - }, output); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/profiles/list.js - - - -const list_createList = configure(api => { - async function list(options = {}) { - const res = await api.post('config/profile/list', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const data = await res.json(); - return data.map(profile => objectToCamel(profile)); - } - return list; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/profiles/index.js - - -function createProfiles(config) { - return { - apply: createApply(config), - list: list_createList(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/get.js - - -const get_createGet = configure(api => { - const get = async (key, options = {}) => { - if (!key) { - throw new Error('key argument is required'); - } - const res = await api.post('config', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: key, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return data.Value; - }; - return get; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/get-all.js - - -const createGetAll = configure(api => { - const getAll = async (options = {}) => { - const res = await api.post('config/show', { - signal: options.signal, - searchParams: toUrlSearchParams({ ...options }), - headers: options.headers - }); - const data = await res.json(); - return data; - }; - return getAll; -}); -// EXTERNAL MODULE: ../node_modules/uint8arrays/esm/src/from-string.js -var from_string = __webpack_require__(4081); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/replace.js - - - - - -const createReplace = configure(api => { - const replace = async (config, options = {}) => { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('config/replace', { - signal, - searchParams: toUrlSearchParams(options), - ...await multipartRequest([(0,from_string.fromString)(JSON.stringify(config))], controller, options.headers) - }); - await res.text(); - }; - return replace; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/set.js - - -const createSet = configure(api => { - const set = async (key, value, options = {}) => { - if (typeof key !== 'string') { - throw new Error('Invalid key type'); - } - const params = { - ...options, - ...encodeParam(key, value) - }; - const res = await api.post('config', { - signal: options.signal, - searchParams: toUrlSearchParams(params), - headers: options.headers - }); - await res.text(); - }; - return set; -}); -const encodeParam = (key, value) => { - switch (typeof value) { - case 'boolean': - return { - arg: [ - key, - value.toString() - ], - bool: true - }; - case 'string': - return { - arg: [ - key, - value - ] - }; - default: - return { - arg: [ - key, - JSON.stringify(value) - ], - json: true - }; - } -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/config/index.js - - - - - -function createConfig(config) { - return { - getAll: createGetAll(config), - get: get_createGet(config), - set: createSet(config), - replace: createReplace(config), - profiles: createProfiles(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/export.js - - -const createExport = configure(api => { - async function* dagExport(root, options = {}) { - const res = await api.post('dag/export', { - signal: options.signal, - searchParams: toUrlSearchParams({ arg: root.toString() }), - headers: options.headers - }); - yield* res.iterator(); - } - return dagExport; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/resolve.js - - -async function* resolve(cid, path, codecs, getBlock, options) { - const load = async cid => { - const codec = await codecs.getCodec(cid.code); - const block = await getBlock(cid, options); - return codec.decode(block); - }; - const parts = path.split('/').filter(Boolean); - let value = await load(cid); - let lastCid = cid; - while (parts.length) { - const key = parts.shift(); - if (!key) { - throw err_code(new Error(`Could not resolve path "${ path }"`), 'ERR_INVALID_PATH'); - } - if (Object.prototype.hasOwnProperty.call(value, key)) { - value = value[key]; - yield { - value, - remainderPath: parts.join('/') - }; - } else { - throw err_code(new Error(`no link named "${ key }" under ${ lastCid }`), 'ERR_NO_LINK'); - } - const cid = src_cid.CID.asCID(value); - if (cid) { - lastCid = cid; - value = await load(value); - } - } - yield { - value, - remainderPath: '' - }; -} -// EXTERNAL MODULE: ../node_modules/it-first/index.js -var it_first = __webpack_require__(6843); -// EXTERNAL MODULE: ../node_modules/it-last/index.js -var it_last = __webpack_require__(1215); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/get.js - - - - - - -const dag_get_createGet = (codecs, options) => { - const fn = configure((api, opts) => { - const getBlock = createGet(opts); - const get = async (cid, options = {}) => { - if (options.path) { - const entry = options.localResolve ? await it_first(resolve(cid, options.path, codecs, getBlock, options)) : await it_last(resolve(cid, options.path, codecs, getBlock, options)); - const result = entry; - if (!result) { - throw err_code(new Error('Not found'), 'ERR_NOT_FOUND'); - } - return result; - } - const codec = await codecs.getCodec(cid.code); - const block = await getBlock(cid, options); - const node = codec.decode(block); - return { - value: node, - remainderPath: '' - }; - }; - return get; - }); - return fn(options); -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/import.js - - - - - -const createImport = configure(api => { - async function* dagImport(source, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const {headers, body} = await multipartRequest(source, controller, options.headers); - const res = await api.post('dag/import', { - signal, - headers, - body, - searchParams: toUrlSearchParams({ 'pin-roots': options.pinRoots }) - }); - for await (const {Root} of res.ndjson()) { - if (Root !== undefined) { - const { - Cid: {'/': Cid}, - PinErrorMsg - } = Root; - yield { - root: { - cid: src_cid.CID.parse(Cid), - pinErrorMsg: PinErrorMsg - } - }; - } - } - } - return dagImport; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/put.js - - - - - -const put_createPut = (codecs, options) => { - const fn = configure(api => { - const put = async (dagNode, options = {}) => { - const settings = { - storeCodec: 'dag-cbor', - hashAlg: 'sha2-256', - ...options - }; - let serialized; - if (settings.inputCodec) { - if (!(dagNode instanceof Uint8Array)) { - throw new Error('Can only inputCodec on raw bytes that can be decoded'); - } - serialized = dagNode; - } else { - const storeCodec = await codecs.getCodec(settings.storeCodec); - serialized = storeCodec.encode(dagNode); - settings.inputCodec = settings.storeCodec; - } - const controller = new AbortController(); - const signal = abortSignal(controller.signal, settings.signal); - const res = await api.post('dag/put', { - timeout: settings.timeout, - signal, - searchParams: toUrlSearchParams(settings), - ...await multipartRequest([serialized], controller, settings.headers) - }); - const data = await res.json(); - return src_cid.CID.parse(data.Cid['/']); - }; - return put; - }); - return fn(options); -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/resolve.js - - - -const createResolve = configure(api => { - const resolve = async (ipfsPath, options = {}) => { - const res = await api.post('dag/resolve', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ ipfsPath }${ options.path ? `/${ options.path }`.replace(/\/[/]+/g, '/') : '' }`, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return { - cid: src_cid.CID.parse(data.Cid['/']), - remainderPath: data.RemPath - }; - }; - return resolve; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dag/index.js - - - - - -function createDag(codecs, config) { - return { - export: createExport(config), - get: dag_get_createGet(codecs, config), - import: createImport(config), - put: put_createPut(codecs, config), - resolve: createResolve(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/response-types.js -const SendingQuery = 0; -const PeerResponse = 1; -const FinalPeer = 2; -const QueryError = 3; -const Provider = 4; -const Value = 5; -const AddingPeer = 6; -const DialingPeer = 7; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/map-event.js - - - -const mapEvent = event => { - if (event.Type === SendingQuery) { - return { - to: event.ID, - name: 'SENDING_QUERY', - type: event.Type - }; - } - if (event.Type === PeerResponse) { - return { - from: event.ID, - name: 'PEER_RESPONSE', - type: event.Type, - messageType: 0, - messageName: 'PUT_VALUE', - closer: (event.Responses || []).map(({ID, Addrs}) => ({ - id: ID, - multiaddrs: Addrs.map(addr => new multiaddr_src.Multiaddr(addr)) - })), - providers: (event.Responses || []).map(({ID, Addrs}) => ({ - id: ID, - multiaddrs: Addrs.map(addr => new multiaddr_src.Multiaddr(addr)) - })) - }; - } - if (event.Type === FinalPeer) { - let peer = { - id: event.ID, - multiaddrs: [] - }; - if (event.Responses && event.Responses.length) { - peer = { - id: event.Responses[0].ID, - multiaddrs: event.Responses[0].Addrs.map(addr => new multiaddr_src.Multiaddr(addr)) - }; - } - return { - from: event.ID, - name: 'FINAL_PEER', - type: event.Type, - peer - }; - } - if (event.Type === QueryError) { - return { - from: event.ID, - name: 'QUERY_ERROR', - type: event.Type, - error: new Error(event.Extra) - }; - } - if (event.Type === Provider) { - return { - from: event.ID, - name: 'PROVIDER', - type: event.Type, - providers: event.Responses.map(({ID, Addrs}) => ({ - id: ID, - multiaddrs: Addrs.map(addr => new multiaddr_src.Multiaddr(addr)) - })) - }; - } - if (event.Type === Value) { - return { - from: event.ID, - name: 'VALUE', - type: event.Type, - value: (0,from_string.fromString)(event.Extra, 'base64pad') - }; - } - if (event.Type === AddingPeer) { - const peers = event.Responses.map(({ID}) => ID); - if (!peers.length) { - throw new Error('No peer found'); - } - return { - name: 'ADDING_PEER', - type: event.Type, - peer: peers[0] - }; - } - if (event.Type === DialingPeer) { - return { - name: 'DIALING_PEER', - type: event.Type, - peer: event.ID - }; - } - throw new Error('Unknown DHT event type'); -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/find-peer.js - - - -const createFindPeer = configure(api => { - async function* findPeer(peerId, options = {}) { - const res = await api.post('dht/findpeer', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: peerId, - ...options - }), - headers: options.headers - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return findPeer; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/find-provs.js - - - -const createFindProvs = configure(api => { - async function* findProvs(cid, options = {}) { - const res = await api.post('dht/findprovs', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cid.toString(), - ...options - }), - headers: options.headers - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return findProvs; -}); -// EXTERNAL MODULE: ../node_modules/uint8arrays/esm/src/to-string.js -var to_string = __webpack_require__(5824); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/get.js - - - - -const dht_get_createGet = configure(api => { - async function* get(key, options = {}) { - const res = await api.post('dht/get', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: key instanceof Uint8Array ? (0,to_string.toString)(key) : key.toString(), - ...options - }), - headers: options.headers - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return get; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/provide.js - - - -const createProvide = configure(api => { - async function* provide(cids, options = { recursive: false }) { - const cidArr = Array.isArray(cids) ? cids : [cids]; - const res = await api.post('dht/provide', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: cidArr.map(cid => cid.toString()), - ...options - }), - headers: options.headers - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return provide; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/put.js - - - - - - -const dht_put_createPut = configure(api => { - async function* put(key, value, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('dht/put', { - signal, - searchParams: toUrlSearchParams({ - arg: key instanceof Uint8Array ? (0,to_string.toString)(key) : key.toString(), - ...options - }), - ...await multipartRequest([value], controller, options.headers) - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return put; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/query.js - - - -const createQuery = configure(api => { - async function* query(peerId, options = {}) { - const res = await api.post('dht/query', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: peerId.toString(), - ...options - }), - headers: options.headers - }); - for await (const event of res.ndjson()) { - yield mapEvent(event); - } - } - return query; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dht/index.js - - - - - - -function createDht(config) { - return { - findPeer: createFindPeer(config), - findProvs: createFindProvs(config), - get: dht_get_createGet(config), - provide: createProvide(config), - put: dht_put_createPut(config), - query: createQuery(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/diag/cmds.js - - -const createCmds = configure(api => { - async function cmds(options = {}) { - const res = await api.post('diag/cmds', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return res.json(); - } - return cmds; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/diag/net.js - - -const createNet = configure(api => { - async function net(options = {}) { - const res = await api.post('diag/net', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return res.json(); - } - return net; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/diag/sys.js - - -const createSys = configure(api => { - async function sys(options = {}) { - const res = await api.post('diag/sys', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return res.json(); - } - return sys; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/diag/index.js - - - -function createDiag(config) { - return { - cmds: createCmds(config), - net: createNet(config), - sys: createSys(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/chmod.js - - -const createChmod = configure(api => { - async function chmod(path, mode, options = {}) { - const res = await api.post('files/chmod', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - mode, - ...options - }), - headers: options.headers - }); - await res.text(); - } - return chmod; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/cp.js - - - -const createCp = configure(api => { - async function cp(sources, destination, options = {}) { - const sourceArr = Array.isArray(sources) ? sources : [sources]; - const res = await api.post('files/cp', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: sourceArr.concat(destination).map(src => src_cid.CID.asCID(src) ? `/ipfs/${ src }` : src), - ...options - }), - headers: options.headers - }); - await res.text(); - } - return cp; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/flush.js - - - -const createFlush = configure(api => { - async function flush(path, options = {}) { - if (!path || typeof path !== 'string') { - throw new Error('ipfs.files.flush requires a path'); - } - const res = await api.post('files/flush', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return src_cid.CID.parse(data.Cid); - } - return flush; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/object-to-camel-with-metadata.js - -function objectToCamelWithMetadata(entry) { - const file = objectToCamel(entry); - if (Object.prototype.hasOwnProperty.call(file, 'mode')) { - file.mode = parseInt(file.mode, 8); - } - if (Object.prototype.hasOwnProperty.call(file, 'mtime')) { - file.mtime = { - secs: file.mtime, - nsecs: file.mtimeNsecs || 0 - }; - delete file.mtimeNsecs; - } - return file; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/ls.js - - - - -const createLs = configure(api => { - async function* ls(path, options = {}) { - if (!path) { - throw new Error('ipfs.files.ls requires a path'); - } - const res = await api.post('files/ls', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: src_cid.CID.asCID(path) ? `/ipfs/${ path }` : path, - long: true, - ...options, - stream: true - }), - headers: options.headers - }); - for await (const result of res.ndjson()) { - if ('Entries' in result) { - for (const entry of result.Entries || []) { - yield ls_toCoreInterface(objectToCamelWithMetadata(entry)); - } - } else { - yield ls_toCoreInterface(objectToCamelWithMetadata(result)); - } - } - } - return ls; -}); -function ls_toCoreInterface(entry) { - if (entry.hash) { - entry.cid = src_cid.CID.parse(entry.hash); - } - delete entry.hash; - entry.type = entry.type === 1 ? 'directory' : 'file'; - return entry; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/mkdir.js - - -const createMkdir = configure(api => { - async function mkdir(path, options = {}) { - const res = await api.post('files/mkdir', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - await res.text(); - } - return mkdir; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/mv.js - - -const createMv = configure(api => { - async function mv(sources, destination, options = {}) { - if (!Array.isArray(sources)) { - sources = [sources]; - } - const res = await api.post('files/mv', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: sources.concat(destination), - ...options - }), - headers: options.headers - }); - await res.text(); - } - return mv; -}); -// EXTERNAL MODULE: ../node_modules/stream-to-it/source.js -var source = __webpack_require__(4372); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/read.js - - - -const createRead = configure(api => { - async function* read(path, options = {}) { - const res = await api.post('files/read', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - count: options.length, - ...options - }), - headers: options.headers - }); - yield* source(res.body); - } - return read; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/rm.js - - - -const files_rm_createRm = configure(api => { - async function rm(path, options = {}) { - const res = await api.post('files/rm', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - const body = await res.text(); - if (body !== '') { - const error = new http.HTTPError(res); - error.message = body; - throw error; - } - } - return rm; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/stat.js - - - - -const files_stat_createStat = configure(api => { - async function stat(path, options = {}) { - const res = await api.post('files/stat', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - data.WithLocality = data.WithLocality || false; - return stat_toCoreInterface(objectToCamelWithMetadata(data)); - } - return stat; -}); -function stat_toCoreInterface(entry) { - entry.cid = src_cid.CID.parse(entry.hash); - delete entry.hash; - return entry; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/touch.js - - -const createTouch = configure(api => { - async function touch(path, options = {}) { - const res = await api.post('files/touch', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - await res.text(); - } - return touch; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/write.js - - - - - - -const createWrite = configure(api => { - async function write(path, input, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('files/write', { - signal, - searchParams: toUrlSearchParams({ - arg: path, - streamChannels: true, - count: options.length, - ...options - }), - ...await multipartRequest([{ - content: input, - path: 'arg', - mode: modeToString(options.mode), - mtime: parseMtime(options.mtime) - }], controller, options.headers) - }); - await res.text(); - } - return write; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/files/index.js - - - - - - - - - - - -function createFiles(config) { - return { - chmod: createChmod(config), - cp: createCp(config), - flush: createFlush(config), - ls: createLs(config), - mkdir: createMkdir(config), - mv: createMv(config), - read: createRead(config), - rm: files_rm_createRm(config), - stat: files_stat_createStat(config), - touch: createTouch(config), - write: createWrite(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/export.js - - -const export_createExport = configure(api => { - const exportKey = async (name, password, options = {}) => { - throw err_code(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED'); - }; - return exportKey; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/gen.js - - - -const createGen = configure(api => { - async function gen(name, options = { - type: 'rsa', - size: 2048 - }) { - const res = await api.post('key/gen', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: name, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return objectToCamel(data); - } - return gen; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/import.js - - - -const import_createImport = configure(api => { - async function importKey(name, pem, password, options = {}) { - const res = await api.post('key/import', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: name, - pem, - password, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return objectToCamel(data); - } - return importKey; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/info.js - - -const createInfo = configure(api => { - const info = async (name, options = {}) => { - throw err_code(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED'); - }; - return info; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/list.js - - - -const key_list_createList = configure(api => { - async function list(options = {}) { - const res = await api.post('key/list', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const data = await res.json(); - return (data.Keys || []).map(k => objectToCamel(k)); - } - return list; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/rename.js - - - -const createRename = configure(api => { - async function rename(oldName, newName, options = {}) { - const res = await api.post('key/rename', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: [ - oldName, - newName - ], - ...options - }), - headers: options.headers - }); - return objectToCamel(await res.json()); - } - return rename; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/rm.js - - - -const key_rm_createRm = configure(api => { - async function rm(name, options = {}) { - const res = await api.post('key/rm', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: name, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return objectToCamel(data.Keys[0]); - } - return rm; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/key/index.js - - - - - - - -function createKey(config) { - return { - export: export_createExport(config), - gen: createGen(config), - import: import_createImport(config), - info: createInfo(config), - list: key_list_createList(config), - rename: createRename(config), - rm: key_rm_createRm(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/log/level.js - - - -const createLevel = configure(api => { - async function level(subsystem, level, options = {}) { - const res = await api.post('log/level', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: [ - subsystem, - level - ], - ...options - }), - headers: options.headers - }); - return objectToCamel(await res.json()); - } - return level; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/log/ls.js - - -const ls_createLs = configure(api => { - async function ls(options = {}) { - const res = await api.post('log/ls', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const data = await res.json(); - return data.Strings; - } - return ls; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/log/tail.js - - -const createTail = configure(api => { - async function* tail(options = {}) { - const res = await api.post('log/tail', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - yield* res.ndjson(); - } - return tail; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/log/index.js - - - -function createLog(config) { - return { - level: createLevel(config), - ls: ls_createLs(config), - tail: createTail(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/publish.js - - - -const createPublish = configure(api => { - async function publish(path, options = {}) { - const res = await api.post('name/publish', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ path }`, - ...options - }), - headers: options.headers - }); - return objectToCamel(await res.json()); - } - return publish; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/resolve.js - - -const resolve_createResolve = configure(api => { - async function* resolve(path, options = {}) { - const res = await api.post('name/resolve', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - stream: true, - ...options - }), - headers: options.headers - }); - for await (const result of res.ndjson()) { - yield result.Path; - } - } - return resolve; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/pubsub/cancel.js - - - -const createCancel = configure(api => { - async function cancel(name, options = {}) { - const res = await api.post('name/pubsub/cancel', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: name, - ...options - }), - headers: options.headers - }); - return objectToCamel(await res.json()); - } - return cancel; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/pubsub/state.js - - - -const createState = configure(api => { - async function state(options = {}) { - const res = await api.post('name/pubsub/state', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return objectToCamel(await res.json()); - } - return state; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/pubsub/subs.js - - -const createSubs = configure(api => { - async function subs(options = {}) { - const res = await api.post('name/pubsub/subs', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const data = await res.json(); - return data.Strings || []; - } - return subs; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/pubsub/index.js - - - -function createPubsub(config) { - return { - cancel: createCancel(config), - state: createState(config), - subs: createSubs(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/name/index.js - - - -function createName(config) { - return { - publish: createPublish(config), - resolve: resolve_createResolve(config), - pubsub: createPubsub(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/data.js - - - -const createData = configure(api => { - async function data(cid, options = {}) { - const res = await api.post('object/data', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ cid instanceof Uint8Array ? src_cid.CID.decode(cid) : cid }`, - ...options - }), - headers: options.headers - }); - const data = await res.arrayBuffer(); - return new Uint8Array(data, 0, data.byteLength); - } - return data; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/get.js - - - - -const object_get_createGet = configure(api => { - async function get(cid, options = {}) { - const res = await api.post('object/get', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ cid instanceof Uint8Array ? src_cid.CID.decode(cid) : cid }`, - dataEncoding: 'base64', - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return { - Data: (0,from_string.fromString)(data.Data, 'base64pad'), - Links: (data.Links || []).map(link => ({ - Name: link.Name, - Hash: src_cid.CID.parse(link.Hash), - Tsize: link.Size - })) - }; - } - return get; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/links.js - - - -const createLinks = configure(api => { - async function links(cid, options = {}) { - const res = await api.post('object/links', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ cid instanceof Uint8Array ? src_cid.CID.decode(cid) : cid }`, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return (data.Links || []).map(l => ({ - Name: l.Name, - Tsize: l.Size, - Hash: src_cid.CID.parse(l.Hash) - })); - } - return links; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/new.js - - - -const createNew = configure(api => { - async function newObject(options = {}) { - const res = await api.post('object/new', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: options.template, - ...options - }), - headers: options.headers - }); - const {Hash} = await res.json(); - return src_cid.CID.parse(Hash); - } - return newObject; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/put.js - - -const object_put_createPut = (codecs, options) => { - const fn = configure(api => { - const dagPut = put_createPut(codecs, options); - async function put(obj, options = {}) { - return dagPut(obj, { - ...options, - storeCodec: 'dag-pb', - hashAlg: 'sha2-256', - version: 1 - }); - } - return put; - }); - return fn(options); -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/stat.js - - - -const object_stat_createStat = configure(api => { - async function stat(cid, options = {}) { - const res = await api.post('object/stat', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ cid }`, - ...options - }), - headers: options.headers - }); - const output = await res.json(); - return { - ...output, - Hash: src_cid.CID.parse(output.Hash) - }; - } - return stat; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/patch/add-link.js - - - -const createAddLink = configure(api => { - async function addLink(cid, dLink, options = {}) { - const res = await api.post('object/patch/add-link', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: [ - `${ cid }`, - dLink.Name || dLink.name || '', - (dLink.Hash || dLink.cid || '').toString() || null - ], - ...options - }), - headers: options.headers - }); - const {Hash} = await res.json(); - return src_cid.CID.parse(Hash); - } - return addLink; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/patch/append-data.js - - - - - -const createAppendData = configure(api => { - async function appendData(cid, data, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('object/patch/append-data', { - signal, - searchParams: toUrlSearchParams({ - arg: `${ cid }`, - ...options - }), - ...await multipartRequest([data], controller, options.headers) - }); - const {Hash} = await res.json(); - return src_cid.CID.parse(Hash); - } - return appendData; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/patch/rm-link.js - - - -const createRmLink = configure(api => { - async function rmLink(cid, dLink, options = {}) { - const res = await api.post('object/patch/rm-link', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: [ - `${ cid }`, - dLink.Name || dLink.name || null - ], - ...options - }), - headers: options.headers - }); - const {Hash} = await res.json(); - return src_cid.CID.parse(Hash); - } - return rmLink; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/patch/set-data.js - - - - - -const createSetData = configure(api => { - async function setData(cid, data, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('object/patch/set-data', { - signal, - searchParams: toUrlSearchParams({ - arg: [`${ cid }`], - ...options - }), - ...await multipartRequest([data], controller, options.headers) - }); - const {Hash} = await res.json(); - return src_cid.CID.parse(Hash); - } - return setData; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/patch/index.js - - - - -function createPatch(config) { - return { - addLink: createAddLink(config), - appendData: createAppendData(config), - rmLink: createRmLink(config), - setData: createSetData(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/object/index.js - - - - - - - -function createObject(codecs, config) { - return { - data: createData(config), - get: object_get_createGet(config), - links: createLinks(config), - new: createNew(config), - put: object_put_createPut(codecs, config), - stat: object_stat_createStat(config), - patch: createPatch(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/pins/normalise-input.js - - -async function* normalise_input_normaliseInput(input) { - if (input === null || input === undefined) { - throw err_code(new Error(`Unexpected input: ${ input }`), 'ERR_UNEXPECTED_INPUT'); - } - const cid = src_cid.CID.asCID(input); - if (cid) { - yield toPin({ cid }); - return; - } - if (input instanceof String || typeof input === 'string') { - yield toPin({ path: input }); - return; - } - if (input.cid != null || input.path != null) { - return yield toPin(input); - } - if (Symbol.iterator in input) { - const iterator = input[Symbol.iterator](); - const first = iterator.next(); - if (first.done) - return iterator; - if (src_cid.CID.asCID(first.value) || first.value instanceof String || typeof first.value === 'string') { - yield toPin({ cid: first.value }); - for (const cid of iterator) { - yield toPin({ cid }); - } - return; - } - if (first.value.cid != null || first.value.path != null) { - yield toPin(first.value); - for (const obj of iterator) { - yield toPin(obj); - } - return; - } - throw err_code(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT'); - } - if (Symbol.asyncIterator in input) { - const iterator = input[Symbol.asyncIterator](); - const first = await iterator.next(); - if (first.done) - return iterator; - if (src_cid.CID.asCID(first.value) || first.value instanceof String || typeof first.value === 'string') { - yield toPin({ cid: first.value }); - for await (const cid of iterator) { - yield toPin({ cid }); - } - return; - } - if (first.value.cid != null || first.value.path != null) { - yield toPin(first.value); - for await (const obj of iterator) { - yield toPin(obj); - } - return; - } - throw err_code(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT'); - } - throw err_code(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT'); -} -function toPin(input) { - const path = input.cid || `${ input.path }`; - if (!path) { - throw err_code(new Error('Unexpected input: Please path either a CID or an IPFS path'), 'ERR_UNEXPECTED_INPUT'); - } - const pin = { - path, - recursive: input.recursive !== false - }; - if (input.metadata != null) { - pin.metadata = input.metadata; - } - return pin; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/add-all.js - - - - -const createAddAll = configure(api => { - async function* addAll(source, options = {}) { - for await (const {path, recursive, metadata} of normalise_input_normaliseInput(source)) { - const res = await api.post('pin/add', { - signal: options.signal, - searchParams: toUrlSearchParams({ - ...options, - arg: path, - recursive, - metadata: metadata ? JSON.stringify(metadata) : undefined, - stream: true - }), - headers: options.headers - }); - for await (const pin of res.ndjson()) { - if (pin.Pins) { - for (const cid of pin.Pins) { - yield src_cid.CID.parse(cid); - } - continue; - } - yield src_cid.CID.parse(pin); - } - } - } - return addAll; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/add.js - - - -function add_createAdd(config) { - const all = createAddAll(config); - return configure(() => { - async function add(path, options = {}) { - return it_last(all([{ - path, - ...options - }], options)); - } - return add; - })(config); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/ls.js - - - -function ls_toPin(type, cid, metadata) { - const pin = { - type, - cid: src_cid.CID.parse(cid) - }; - if (metadata) { - pin.metadata = metadata; - } - return pin; -} -const pin_ls_createLs = configure(api => { - async function* ls(options = {}) { - let paths = []; - if (options.paths) { - paths = Array.isArray(options.paths) ? options.paths : [options.paths]; - } - const res = await api.post('pin/ls', { - signal: options.signal, - searchParams: toUrlSearchParams({ - ...options, - arg: paths.map(path => `${ path }`), - stream: true - }), - headers: options.headers - }); - for await (const pin of res.ndjson()) { - if (pin.Keys) { - for (const cid of Object.keys(pin.Keys)) { - yield ls_toPin(pin.Keys[cid].Type, cid, pin.Keys[cid].Metadata); - } - return; - } - yield ls_toPin(pin.Type, pin.Cid, pin.Metadata); - } - } - return ls; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/rm-all.js - - - - -const createRmAll = configure(api => { - async function* rmAll(source, options = {}) { - for await (const {path, recursive} of normalise_input_normaliseInput(source)) { - const searchParams = new URLSearchParams(options.searchParams); - searchParams.append('arg', `${ path }`); - if (recursive != null) - searchParams.set('recursive', String(recursive)); - const res = await api.post('pin/rm', { - signal: options.signal, - headers: options.headers, - searchParams: toUrlSearchParams({ - ...options, - arg: `${ path }`, - recursive - }) - }); - for await (const pin of res.ndjson()) { - if (pin.Pins) { - yield* pin.Pins.map(cid => src_cid.CID.parse(cid)); - continue; - } - yield src_cid.CID.parse(pin); - } - } - } - return rmAll; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/rm.js - - - -const pin_rm_createRm = config => { - const all = createRmAll(config); - return configure(() => { - async function rm(path, options = {}) { - return it_last(all([{ - path, - ...options - }], options)); - } - return rm; - })(config); -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/utils.js - - -const decodePin = ({ - Name: name, - Status: status, - Cid: cid -}) => { - return { - cid: src_cid.CID.parse(cid), - name, - status - }; -}; -const encodeService = service => { - if (typeof service === 'string' && service !== '') { - return service; - } else { - throw new TypeError('service name must be passed'); - } -}; -const encodeCID = cid => { - if (src_cid.CID.asCID(cid)) { - return cid.toString(); - } else { - throw new TypeError(`CID instance expected instead of ${ typeof cid }`); - } -}; -const encodeQuery = ({service, cid, name, status, all}) => { - const query = toUrlSearchParams({ - service: encodeService(service), - name, - force: all ? true : undefined - }); - if (cid) { - for (const value of cid) { - query.append('cid', encodeCID(value)); - } - } - if (status) { - for (const value of status) { - query.append('status', value); - } - } - return query; -}; -const encodeAddParams = ({cid, service, background, name, origins}) => { - const params = toUrlSearchParams({ - arg: encodeCID(cid), - service: encodeService(service), - name, - background: background ? true : undefined - }); - if (origins) { - for (const origin of origins) { - params.append('origin', origin.toString()); - } - } - return params; -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/add.js - -function remote_add_createAdd(client) { - async function add(cid, {timeout, signal, headers, ...query}) { - const response = await client.post('pin/remote/add', { - timeout, - signal, - headers, - searchParams: encodeAddParams({ - cid, - ...query - }) - }); - return decodePin(await response.json()); - } - return add; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/ls.js - -function remote_ls_createLs(client) { - async function* ls({timeout, signal, headers, ...query}) { - const response = await client.post('pin/remote/ls', { - timeout, - signal, - headers, - searchParams: encodeQuery(query) - }); - for await (const pin of response.ndjson()) { - yield decodePin(pin); - } - } - return ls; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/rm.js - -function remote_rm_createRm(client) { - async function rm({timeout, signal, headers, ...query}) { - await client.post('pin/remote/rm', { - timeout, - signal, - headers, - searchParams: encodeQuery({ - ...query, - all: false - }) - }); - } - return rm; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/rm-all.js - -function rm_all_createRmAll(client) { - async function rmAll({timeout, signal, headers, ...query}) { - await client.post('pin/remote/rm', { - timeout, - signal, - headers, - searchParams: encodeQuery({ - ...query, - all: true - }) - }); - } - return rmAll; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/service/utils.js -function encodeEndpoint(url) { - const href = String(url); - if (href === 'undefined') { - throw Error('endpoint is required'); - } - return href[href.length - 1] === '/' ? href.slice(0, -1) : href; -} -function decodeRemoteService(json) { - return { - service: json.Service, - endpoint: new URL(json.ApiEndpoint), - ...json.Stat && { stat: decodeStat(json.Stat) } - }; -} -function decodeStat(json) { - switch (json.Status) { - case 'valid': { - const {Pinning, Pinned, Queued, Failed} = json.PinCount; - return { - status: 'valid', - pinCount: { - queued: Queued, - pinning: Pinning, - pinned: Pinned, - failed: Failed - } - }; - } - case 'invalid': { - return { status: 'invalid' }; - } - default: { - return { status: json.Status }; - } - } -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/service/add.js - - -function service_add_createAdd(client) { - async function add(name, options) { - const {endpoint, key, headers, timeout, signal} = options; - await client.post('pin/remote/service/add', { - timeout, - signal, - searchParams: toUrlSearchParams({ - arg: [ - name, - encodeEndpoint(endpoint), - key - ] - }), - headers - }); - } - return add; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/service/ls.js - - -function service_ls_createLs(client) { - async function ls(options = {}) { - const {stat, headers, timeout, signal} = options; - const response = await client.post('pin/remote/service/ls', { - timeout, - signal, - headers, - searchParams: stat === true ? toUrlSearchParams({ stat }) : undefined - }); - const {RemoteServices} = await response.json(); - return RemoteServices.map(decodeRemoteService); - } - return ls; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/service/rm.js - -function service_rm_createRm(client) { - async function rm(name, options = {}) { - await client.post('pin/remote/service/rm', { - signal: options.signal, - headers: options.headers, - searchParams: toUrlSearchParams({ arg: name }) - }); - } - return rm; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/service/index.js - - - - -function createService(config) { - const client = new Client(config); - return { - add: service_add_createAdd(client), - ls: service_ls_createLs(client), - rm: service_rm_createRm(client) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/remote/index.js - - - - - - -function createRemote(config) { - const client = new Client(config); - return { - add: remote_add_createAdd(client), - ls: remote_ls_createLs(client), - rm: remote_rm_createRm(client), - rmAll: rm_all_createRmAll(client), - service: createService(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pin/index.js - - - - - - -function createPin(config) { - return { - addAll: createAddAll(config), - add: add_createAdd(config), - ls: pin_ls_createLs(config), - rmAll: createRmAll(config), - rm: pin_rm_createRm(config), - remote: createRemote(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/lib/http-rpc-wire-format.js - - - -const rpcArrayToTextArray = strings => { - if (Array.isArray(strings)) { - return strings.map(rpcToText); - } - return strings; -}; -const rpcToText = mb => (0,to_string.toString)(rpcToBytes(mb)); -const rpcToBytes = mb => base64.base64url.decode(mb); -const textToUrlSafeRpc = text => base64.base64url.encode((0,from_string.fromString)(text)); - -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/ls.js - - - -const pubsub_ls_createLs = configure(api => { - async function ls(options = {}) { - const {Strings} = await (await api.post('pubsub/ls', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - })).json(); - return rpcArrayToTextArray(Strings) || []; - } - return ls; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/peers.js - - - -const createPeers = configure(api => { - async function peers(topic, options = {}) { - const res = await api.post('pubsub/peers', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: textToUrlSafeRpc(topic), - ...options - }), - headers: options.headers - }); - const {Strings} = await res.json(); - return Strings || []; - } - return peers; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/publish.js - - - - - -const publish_createPublish = configure(api => { - async function publish(topic, data, options = {}) { - const searchParams = toUrlSearchParams({ - arg: textToUrlSafeRpc(topic), - ...options - }); - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const res = await api.post('pubsub/pub', { - signal, - searchParams, - ...await multipartRequest([data], controller, options.headers) - }); - await res.text(); - } - return publish; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/subscribe.js - - - - -const subscribe_log = browser('ipfs-http-client:pubsub:subscribe'); -const createSubscribe = (options, subsTracker) => { - return configure(api => { - async function subscribe(topic, handler, options = {}) { - options.signal = subsTracker.subscribe(topic, handler, options.signal); - let done; - let fail; - const result = new Promise((resolve, reject) => { - done = resolve; - fail = reject; - }); - const ffWorkaround = setTimeout(() => done(), 1000); - api.post('pubsub/sub', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: textToUrlSafeRpc(topic), - ...options - }), - headers: options.headers - }).catch(err => { - subsTracker.unsubscribe(topic, handler); - fail(err); - }).then(response => { - clearTimeout(ffWorkaround); - if (!response) { - return; - } - readMessages(response, { - onMessage: handler, - onEnd: () => subsTracker.unsubscribe(topic, handler), - onError: options.onError - }); - done(); - }); - return result; - } - return subscribe; - })(options); -}; -async function readMessages(response, {onMessage, onEnd, onError}) { - onError = onError || subscribe_log; - try { - for await (const msg of response.ndjson()) { - try { - if (!msg.from) { - continue; - } - onMessage({ - from: msg.from, - data: rpcToBytes(msg.data), - seqno: rpcToBytes(msg.seqno), - topicIDs: rpcArrayToTextArray(msg.topicIDs) - }); - } catch (err) { - err.message = `Failed to parse pubsub message: ${ err.message }`; - onError(err, false, msg); - } - } - } catch (err) { - if (!isAbortError(err)) { - onError(err, true); - } - } finally { - onEnd(); - } -} -const isAbortError = error => { - switch (error.type) { - case 'aborted': - return true; - case 'abort': - return true; - default: - return error.name === 'AbortError'; - } -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/unsubscribe.js -const createUnsubscribe = (options, subsTracker) => { - async function unsubscribe(topic, handler) { - subsTracker.unsubscribe(topic, handler); - } - return unsubscribe; -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/subscription-tracker.js -class SubscriptionTracker { - constructor() { - this._subs = new Map(); - } - subscribe(topic, handler, signal) { - const topicSubs = this._subs.get(topic) || []; - if (topicSubs.find(s => s.handler === handler)) { - throw new Error(`Already subscribed to ${ topic } with this handler`); - } - const controller = new AbortController(); - this._subs.set(topic, [{ - handler, - controller - }].concat(topicSubs)); - if (signal) { - signal.addEventListener('abort', () => this.unsubscribe(topic, handler)); - } - return controller.signal; - } - unsubscribe(topic, handler) { - const subs = this._subs.get(topic) || []; - let unsubs; - if (handler) { - this._subs.set(topic, subs.filter(s => s.handler !== handler)); - unsubs = subs.filter(s => s.handler === handler); - } else { - this._subs.set(topic, []); - unsubs = subs; - } - if (!(this._subs.get(topic) || []).length) { - this._subs.delete(topic); - } - unsubs.forEach(s => s.controller.abort()); - } -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/pubsub/index.js - - - - - +exports.Parser = Parser; +exports["default"] = Parser; +//# sourceMappingURL=Parser.js.map -function pubsub_createPubsub(config) { - const subscriptionTracker = new SubscriptionTracker(); - return { - ls: pubsub_ls_createLs(config), - peers: createPeers(config), - publish: publish_createPublish(config), - subscribe: createSubscribe(config, subscriptionTracker), - unsubscribe: createUnsubscribe(config, subscriptionTracker) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/refs/local.js +/***/ }), +/***/ 241: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -const createLocal = configure(api => { - async function* refsLocal(options = {}) { - const res = await api.post('refs/local', { - signal: options.signal, - transform: objectToCamel, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - yield* res.ndjson(); - } - return refsLocal; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/refs/index.js +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findChildrenByType = void 0; +/** + * Finds all the direct childs of a specifyed type + */ +function findChildrenByType(token, type) { + return token.children ? token.children.filter(x => x.type == type) : []; +} +exports.findChildrenByType = findChildrenByType; +//# sourceMappingURL=SemanticHelpers.js.map +/***/ }), +/***/ 217: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TokenError = void 0; +class TokenError extends Error { + constructor(message, token) { + super(message); + this.message = message; + this.token = token; + if (token && token.errors) + token.errors.push(this); + else + throw this; + } + inspect() { + return 'SyntaxError: ' + this.message; + } +} +exports.TokenError = TokenError; +//# sourceMappingURL=TokenError.js.map -const createRefs = configure((api, opts) => { - const refs = async function* (args, options = {}) { - const argsArr = Array.isArray(args) ? args : [args]; - const res = await api.post('refs', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: argsArr.map(arg => `${ arg instanceof Uint8Array ? src_cid.CID.decode(arg) : arg }`), - ...options - }), - headers: options.headers, - transform: objectToCamel - }); - yield* res.ndjson(); - }; - return Object.assign(refs, { local: createLocal(opts) }); -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/repo/gc.js +/***/ }), +/***/ 425: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +"use strict"; -const createGc = configure(api => { - async function* gc(options = {}) { - const res = await api.post('repo/gc', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers, - transform: res => { - return { - err: res.Error ? new Error(res.Error) : null, - cid: (res.Key || {})['/'] ? src_cid.CID.parse(res.Key['/']) : null - }; - } - }); - yield* res.ndjson(); - } - return gc; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/repo/stat.js +Object.defineProperty(exports, "__esModule", ({ value: true })); +var Parser_1 = __webpack_require__(489); +Object.defineProperty(exports, "Parser", ({ enumerable: true, get: function () { return Parser_1.Parser; } })); +var TokenError_1 = __webpack_require__(217); +Object.defineProperty(exports, "TokenError", ({ enumerable: true, get: function () { return TokenError_1.TokenError; } })); +exports.Grammars = __webpack_require__(652); +//# sourceMappingURL=index.js.map +/***/ }), -const repo_stat_createStat = configure(api => { - async function stat(options = {}) { - const res = await api.post('repo/stat', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const data = await res.json(); - return { - numObjects: BigInt(data.NumObjects), - repoSize: BigInt(data.RepoSize), - repoPath: data.RepoPath, - version: data.Version, - storageMax: BigInt(data.StorageMax) - }; - } - return stat; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/repo/version.js +/***/ 338: +/***/ ((module, exports, __webpack_require__) => { +var __WEBPACK_AMD_DEFINE_RESULT__;/** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + */ +/*jslint bitwise: true */ +(function () { + 'use strict'; -const createVersion = configure(api => { - async function version(options = {}) { - const res = await (await api.post('repo/version', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - })).json(); - return res.Version; + 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; } - return version; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/repo/index.js - - - -function createRepo(config) { - return { - gc: createGc(config), - stat: repo_stat_createStat(config), - version: createVersion(config) - }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/stats/bw.js - - -const createBw = configure(api => { - async function* bw(options = {}) { - const res = await api.post('stats/bw', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers, - transform: stats => ({ - totalIn: BigInt(stats.TotalIn), - totalOut: BigInt(stats.TotalOut), - rateIn: parseFloat(stats.RateIn), - rateOut: parseFloat(stats.RateOut) - }) - }); - yield* res.ndjson(); + 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 = __webpack_require__.g; + } else if (WEB_WORKER) { + root = self; } - return bw; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/stats/index.js - - - -function createStats(config) { - return { - bitswap: createStat(config), - repo: repo_stat_createStat(config), - bw: createBw(config) + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && "object" === 'object' && module.exports; + var AMD = true && __webpack_require__.amdO; + 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 }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/addrs.js - - - -const createAddrs = configure(api => { - async function addrs(options = {}) { - const res = await api.post('swarm/addrs', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const {Addrs} = await res.json(); - return Object.keys(Addrs).map(id => ({ - id, - addrs: (Addrs[id] || []).map(a => new multiaddr_src.Multiaddr(a)) - })); - } - return addrs; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/connect.js - -const createConnect = configure(api => { - async function connect(addr, options = {}) { - const res = await api.post('swarm/connect', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: addr, - ...options - }), - headers: options.headers - }); - const {Strings} = await res.json(); - return Strings || []; + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; } - return connect; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/disconnect.js - -const createDisconnect = configure(api => { - async function disconnect(addr, options = {}) { - const res = await api.post('swarm/disconnect', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: addr, - ...options - }), - headers: options.headers - }); - const {Strings} = await res.json(); - return Strings || []; + 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; + }; } - return disconnect; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/local-addrs.js + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; -const createLocalAddrs = configure(api => { - async function localAddrs(options = {}) { - const res = await api.post('swarm/addrs/local', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const {Strings} = await res.json(); - return (Strings || []).map(a => new multiaddr_src.Multiaddr(a)); - } - return localAddrs; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/peers.js - - + var createCshakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits, n, s) { + return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); + }; + }; -const peers_createPeers = configure(api => { - async function peers(options = {}) { - const res = await api.post('swarm/peers', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - const {Peers} = await res.json(); - return (Peers || []).map(peer => { - return { - addr: new multiaddr_src.Multiaddr(peer.Addr), - peer: peer.Peer, - muxer: peer.Muxer, - latency: peer.Latency, - streams: peer.Streams, - direction: peer.Direction == null ? undefined : peer.Direction === 0 ? 'inbound' : 'outbound' - }; - }); - } - return peers; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/swarm/index.js + var createKmacOutputMethod = function (bits, padding, outputType) { + return function (key, message, outputBits, s) { + return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); + }; + }; + var createOutputMethods = function (method, createMethod, bits, padding) { + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createMethod(bits, padding, type); + } + return method; + }; + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits, padding); + }; + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits, padding); + }; + var createCshakeMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createCshakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits, n, s) { + if (!n && !s) { + return methods['shake' + bits].create(outputBits); + } else { + return new Keccak(bits, 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, bits, padding); + }; -function createSwarm(config) { - return { - addrs: createAddrs(config), - connect: createConnect(config), - disconnect: createDisconnect(config), - localAddrs: createLocalAddrs(config), - peers: peers_createPeers(config) + var createKmacMethod = function (bits, padding) { + var w = CSHAKE_BYTEPAD[bits]; + var method = createKmacOutputMethod(bits, padding, 'hex'); + method.create = function (key, outputBits, s) { + return new Kmac(bits, 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, bits, padding); }; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/add-all.js + var algorithms = [ + { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, + { name: 'sha3', padding: PADDING, bits: BITS, createMethod: 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(bits, 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 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } -const add_all_createAddAll = configure(api => { - async function* addAll(source, options = {}) { - const controller = new AbortController(); - const signal = abortSignal(controller.signal, options.signal); - const {headers, body, total, parts} = await multipartRequest(source, controller, options.headers); - const [progressFn, onUploadProgress] = typeof options.progress === 'function' ? createProgressHandler(total, parts, options.progress) : [ - undefined, - undefined - ]; - const res = await api.post('add', { - searchParams: toUrlSearchParams({ - 'stream-channels': true, - ...options, - progress: Boolean(progressFn) - }), - onUploadProgress, - signal, - headers, - body - }); - for await (let file of res.ndjson()) { - file = objectToCamel(file); - if (file.hash !== undefined) { - yield add_all_toCoreInterface(file); - } else if (progressFn) { - progressFn(file.bytes || 0, file.name); + 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; } - } - return addAll; -}); -const createProgressHandler = (total, parts, progress) => parts ? [ - undefined, - createOnUploadProgress(total, parts, progress) -] : [ - progress, - undefined -]; -const createOnUploadProgress = (size, parts, progress) => { - let index = 0; - const count = parts.length; - return ({loaded, total}) => { - const position = Math.floor(loaded / total * size); - while (index < count) { - const {start, end, name} = parts[index]; - if (position < end) { - progress(position - start, name); - break; + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; } else { - progress(end - start, name); - index += 1; + this.start = i; } } + return this; }; -}; -function add_all_toCoreInterface({name, hash, size, mode, mtime, mtimeNsecs}) { - const output = { - path: name, - cid: src_cid.CID.parse(hash), - size: parseInt(size) - }; - if (mode != null) { - output.mode = parseInt(mode, 8); - } - if (mtime != null) { - output.mtime = { - secs: mtime, - nsecs: mtimeNsecs || 0 - }; - } - return output; -} -// EXTERNAL MODULE: ../node_modules/blob-to-it/index.js -var blob_to_it = __webpack_require__(3133); -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-content.js - - - - - - - -async function* toAsyncIterable(thing) { - yield thing; -} -async function normalise_content_normaliseContent(input) { - if (isBytes(input)) { - return toAsyncIterable(toBytes(input)); - } - if (typeof input === 'string' || input instanceof String) { - return toAsyncIterable(toBytes(input.toString())); - } - if (isBlob(input)) { - return blob_to_it(input); - } - if (isReadableStream(input)) { - input = browser_readablestream_to_it(input); - } - if (Symbol.iterator in input || Symbol.asyncIterator in input) { - const peekable = it_peekable(input); - const {value, done} = await peekable.peek(); - if (done) { - return toAsyncIterable(new Uint8Array(0)); - } - peekable.push(value); - if (Number.isInteger(value)) { - return toAsyncIterable(Uint8Array.from(await it_all(peekable))); + 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 (isBytes(value) || typeof value === 'string' || value instanceof String) { - return it_map(peekable, toBytes); + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); } - } - throw err_code(new Error(`Unexpected input: ${ input }`), 'ERR_UNEXPECTED_INPUT'); -} -function toBytes(chunk) { - if (chunk instanceof Uint8Array) { - return chunk; - } - if (ArrayBuffer.isView(chunk)) { - return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - } - if (chunk instanceof ArrayBuffer) { - return new Uint8Array(chunk); - } - if (Array.isArray(chunk)) { - return Uint8Array.from(chunk); - } - return (0,from_string.fromString)(chunk.toString()); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-candidate-single.js - - - - + this.update(bytes); + return bytes.length; + }; -async function* normaliseCandidateSingle(input, normaliseContent) { - if (input === null || input === undefined) { - throw err_code(new Error(`Unexpected input: ${ input }`), 'ERR_UNEXPECTED_INPUT'); - } - if (typeof input === 'string' || input instanceof String) { - yield normalise_candidate_single_toFileObject(input.toString(), normaliseContent); - return; - } - if (isBytes(input) || isBlob(input)) { - yield normalise_candidate_single_toFileObject(input, normaliseContent); - return; - } - if (isReadableStream(input)) { - input = browser_readablestream_to_it(input); - } - if (Symbol.iterator in input || Symbol.asyncIterator in input) { - const peekable = it_peekable(input); - const {value, done} = await peekable.peek(); - if (done) { - yield { content: [] }; - return; + 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; } - peekable.push(value); - if (Number.isInteger(value) || isBytes(value) || typeof value === 'string' || value instanceof String) { - yield normalise_candidate_single_toFileObject(peekable, normaliseContent); - return; + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for (var i = 0; i < str.length; ++i) { + var code = str.charCodeAt(i); + if (code < 0x80) { + bytes += 1; + } else if (code < 0x800) { + bytes += 2; + } else if (code < 0xd800 || code >= 0xe000) { + bytes += 3; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); + bytes += 4; + } + } } - throw err_code(new Error('Unexpected input: multiple items passed - if you are using ipfs.add, please use ipfs.addAll instead'), 'ERR_UNEXPECTED_INPUT'); - } - if (isFileObject(input)) { - yield normalise_candidate_single_toFileObject(input, normaliseContent); - return; - } - throw err_code(new Error('Unexpected input: cannot convert "' + typeof input + '" into ImportCandidate'), 'ERR_UNEXPECTED_INPUT'); -} -async function normalise_candidate_single_toFileObject(input, normaliseContent) { - const {path, mode, mtime, content} = input; - const file = { - path: path || '', - mode: parseMode(mode), - mtime: src_parseMtime(mtime) + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; }; - if (content) { - file.content = await normaliseContent(content); - } else if (!path) { - file.content = await normaliseContent(input); - } - return file; -} -;// CONCATENATED MODULE: ../node_modules/ipfs-core-utils/esm/src/files/normalise-input-single.js - -function normalise_input_single_normaliseInput(input) { - return normaliseCandidateSingle(input, normalise_content_normaliseContent); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/add.js - - - - -function src_add_createAdd(options) { - const all = add_all_createAddAll(options); - return configure(() => { - async function add(input, options = {}) { - return await it_last(all(normalise_input_single_normaliseInput(input), options)); + Keccak.prototype.bytepad = function (strs, w) { + var bytes = this.encode(w); + for (var i = 0; i < strs.length; ++i) { + bytes += this.encodeString(strs[i]); } - return add; - })(options); -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/cat.js - - -const createCat = configure(api => { - async function* cat(path, options = {}) { - const res = await api.post('cat', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path.toString(), - ...options - }), - headers: options.headers - }); - yield* res.iterator(); - } - return cat; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/commands.js - - -const createCommands = configure(api => { - const commands = async (options = {}) => { - const res = await api.post('commands', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return res.json(); - }; - return commands; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/dns.js - - -const createDns = configure(api => { - const dns = async (domain, options = {}) => { - const res = await api.post('dns', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: domain, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - return data.Path; + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; }; - return dns; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/get-endpoint-config.js -const createGetEndpointConfig = configure(api => { - return () => { - const url = new URL(api.opts.base || ''); - return { - host: url.hostname, - port: url.port, - protocol: url.protocol, - pathname: url.pathname, - 'api-path': url.pathname - }; + Keccak.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); }; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/get.js - + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); -const src_get_createGet = configure(api => { - async function* get(path, options = {}) { - const opts = { - arg: `${ path instanceof Uint8Array ? src_cid.CID.decode(path) : path }`, - ...options - }; - if (opts.compressionLevel) { - opts['compression-level'] = opts.compressionLevel; - delete opts.compressionLevel; + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } } - const res = await api.post('get', { - signal: options.signal, - searchParams: toUrlSearchParams(opts), - headers: options.headers - }); - yield* res.iterator(); - } - return get; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/id.js - - - - -const createId = configure(api => { - async function id(options = {}) { - const res = await api.post('id', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: options.peerId ? options.peerId.toString() : undefined, - ...options - }), - headers: options.headers - }); - const data = await res.json(); - const output = { ...objectToCamel(data) }; - if (output.addresses) { - output.addresses = output.addresses.map(ma => new multiaddr_src.Multiaddr(ma)); + if (extraBytes) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } } - return output; - } - return id; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/is-online.js + return hex; + }; -const createIsOnline = options => { - const id = createId(options); - async function isOnline(options = {}) { - const res = await id(options); - return Boolean(res && res.addresses && res.addresses.length); - } - return isOnline; -}; -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/ls.js + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 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 (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); -const src_ls_createLs = configure((api, opts) => { - async function* ls(path, options = {}) { - const pathStr = `${ path instanceof Uint8Array ? src_cid.CID.decode(path) : path }`; - async function mapLink(link) { - let hash = link.Hash; - if (hash.includes('/')) { - const ipfsPath = hash.startsWith('/ipfs/') ? hash : `/ipfs/${ hash }`; - const stats = await files_stat_createStat(opts)(ipfsPath); - hash = stats.cid; - } else { - hash = src_cid.CID.parse(hash); - } - const entry = { - name: link.Name, - path: pathStr + (link.Name ? `/${ link.Name }` : ''), - size: link.Size, - cid: hash, - type: typeOf(link) - }; - if (link.Mode) { - entry.mode = parseInt(link.Mode, 8); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; } - if (link.Mtime !== undefined && link.Mtime !== null) { - entry.mtime = { secs: link.Mtime }; - if (link.MtimeNsecs !== undefined && link.MtimeNsecs !== null) { - entry.mtime.nsecs = link.MtimeNsecs; - } + if (j % blockCount === 0) { + f(s); } - return entry; } - const res = await api.post('ls', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: pathStr, - ...options - }), - headers: options.headers - }); - for await (let result of res.ndjson()) { - result = result.Objects; - if (!result) { - throw new Error('expected .Objects in results'); - } - result = result[0]; - if (!result) { - throw new Error('expected one array in results.Objects'); - } - const links = result.Links; - if (!Array.isArray(links)) { - throw new Error('expected one array in results.Objects[0].Links'); + if (extraBytes) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; } - if (!links.length) { - yield mapLink(result); - return; + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; } - yield* links.map(mapLink); } + return array; + }; + + function Kmac(bits, padding, outputBits) { + Keccak.call(this, bits, padding, outputBits); } - return ls; -}); -function typeOf(link) { - switch (link.Type) { - case 1: - case 5: - return 'dir'; - case 2: - return 'file'; - default: - return 'file'; - } -} -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/mount.js + 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]; + } + }; -const createMount = configure(api => { - async function mount(options = {}) { - const res = await api.post('dns', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return objectToCamel(await res.json()); + if (COMMON_JS) { + module.exports = methods; + } else { + for (i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + if (AMD) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return methods; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } } - return mount; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/ping.js - +})(); -const createPing = configure(api => { - async function* ping(peerId, options = {}) { - const res = await api.post('ping', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: `${ peerId }`, - ...options - }), - headers: options.headers, - transform: objectToCamel - }); - yield* res.ndjson(); - } - return ping; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/resolve.js +/***/ }), +/***/ 551: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { -const src_resolve_createResolve = configure(api => { - async function resolve(path, options = {}) { - const res = await api.post('resolve', { - signal: options.signal, - searchParams: toUrlSearchParams({ - arg: path, - ...options - }), - headers: options.headers - }); - const {Path} = await res.json(); - return Path; +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "fS": () => (/* binding */ equals), +/* harmony export */ "oQ": () => (/* binding */ coerce) +/* harmony export */ }); +/* unused harmony exports isBinary, fromHex, toHex, fromString, toString, empty */ +const empty = new Uint8Array(0); +const toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), ''); +const fromHex = hex => { + const hexes = hex.match(/../g); + return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty; +}; +const equals = (aa, bb) => { + if (aa === bb) + return true; + if (aa.byteLength !== bb.byteLength) { + return false; } - return resolve; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/start.js - - -const createStart = configure(api => { - const start = async (options = {}) => { - throw err_code(new Error('Not implemented'), 'ERR_NOT_IMPLEMENTED'); - }; - return start; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/stop.js - - -const createStop = configure(api => { - async function stop(options = {}) { - const res = await api.post('shutdown', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - await res.text(); + for (let ii = 0; ii < aa.byteLength; ii++) { + if (aa[ii] !== bb[ii]) { + return false; + } } - return stop; -}); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/version.js - - - -const version_createVersion = configure(api => { - async function version(options = {}) { - const res = await api.post('version', { - signal: options.signal, - searchParams: toUrlSearchParams(options), - headers: options.headers - }); - return { - ...objectToCamel(await res.json()), - 'ipfs-http-client': '1.0.0' - }; + return true; +}; +const 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); } - return version; -}); -// EXTERNAL MODULE: ipfs-utils/src/files/glob-source.js (ignored) -var glob_source_ignored_ = __webpack_require__(7868); -// EXTERNAL MODULE: ../node_modules/ipfs-utils/src/files/url-source.js -var url_source = __webpack_require__(6417); -;// CONCATENATED MODULE: ../node_modules/ipfs-http-client/esm/src/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -function create(options = {}) { - const id = { - name: identity.identity.name, - code: identity.identity.code, - encode: id => id, - decode: id => id - }; - const multibaseCodecs = Object.values(basics/* bases */.gh); - (options.ipld && options.ipld.bases ? options.ipld.bases : []).forEach(base => multibaseCodecs.push(base)); - const multibases = new Multibases({ - bases: multibaseCodecs, - loadBase: options.ipld && options.ipld.loadBase - }); - const blockCodecs = Object.values(basics/* codecs */.QB); - [ - src_namespaceObject, - esm_namespaceObject, - dag_json_esm_namespaceObject, - lib_namespaceObject, - id - ].concat(options.ipld && options.ipld.codecs || []).forEach(codec => blockCodecs.push(codec)); - const multicodecs = new Multicodecs({ - codecs: blockCodecs, - loadCodec: options.ipld && options.ipld.loadCodec - }); - const multihashHashers = Object.values(basics/* hashes */.kq); - (options.ipld && options.ipld.hashers ? options.ipld.hashers : []).forEach(hasher => multihashHashers.push(hasher)); - const multihashes = new Multihashes({ - hashers: multihashHashers, - loadHasher: options.ipld && options.ipld.loadHasher - }); - const client = { - add: src_add_createAdd(options), - addAll: add_all_createAddAll(options), - bitswap: createBitswap(options), - block: createBlock(options), - bootstrap: createBootstrap(options), - cat: createCat(options), - commands: createCommands(options), - config: createConfig(options), - dag: createDag(multicodecs, options), - dht: createDht(options), - diag: createDiag(options), - dns: createDns(options), - files: createFiles(options), - get: src_get_createGet(options), - getEndpointConfig: createGetEndpointConfig(options), - id: createId(options), - isOnline: createIsOnline(options), - key: createKey(options), - log: createLog(options), - ls: src_ls_createLs(options), - mount: createMount(options), - name: createName(options), - object: createObject(multicodecs, options), - pin: createPin(options), - ping: createPing(options), - pubsub: pubsub_createPubsub(options), - refs: createRefs(options), - repo: createRepo(options), - resolve: src_resolve_createResolve(options), - start: createStart(options), - stats: createStats(options), - stop: createStop(options), - swarm: createSwarm(options), - version: version_createVersion(options), - bases: multibases, - codecs: multicodecs, - hashers: multihashes - }; - return client; -} - - + throw new Error('Unknown type, must be binary type'); +}; +const isBinary = o => o instanceof ArrayBuffer || ArrayBuffer.isView(o); +const fromString = str => new TextEncoder().encode(str); +const toString = b => new TextDecoder().decode(b); -const globSource = glob_source_ignored_; /***/ }), -/***/ 9853: +/***/ 598: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { - "kU": () => (/* binding */ baseX), - "Dp": () => (/* binding */ from), - "ET": () => (/* binding */ rfc4648) + "CID": () => (/* binding */ CID) }); -// UNUSED EXPORTS: Codec, or - +// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/varint.js + 1 modules +var varint = __webpack_require__(209); +// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/hashes/digest.js +var hashes_digest = __webpack_require__(122); ;// CONCATENATED MODULE: ../node_modules/multiformats/esm/vendor/base-x.js function base(ALPHABET, name) { if (ALPHABET.length >= 255) { @@ -43496,7 +2390,7 @@ var src = base; var _brrp__multiformats_scope_baseX = src; /* harmony default export */ const base_x = (_brrp__multiformats_scope_baseX); // EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bytes.js -var bytes = __webpack_require__(9551); +var src_bytes = __webpack_require__(551); ;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base.js @@ -43582,7 +2476,7 @@ const baseX = ({prefix, name, alphabet}) => { prefix, name, encode, - decode: text => (0,bytes.coerce)(decode(text)) + decode: text => (0,src_bytes/* coerce */.oQ)(decode(text)) }); }; const decode = (string, alphabet, bitsPerChar, name) => { @@ -43639,427 +2533,87 @@ const encode = (data, alphabet, bitsPerChar) => { } return out; }; -const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => { - return from({ - prefix, - name, - encode(input) { - return encode(input, alphabet, bitsPerChar); - }, - decode(input) { - return decode(input, alphabet, bitsPerChar, name); - } - }); -}; - -/***/ }), - -/***/ 4052: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "base32": () => (/* binding */ base32), -/* harmony export */ "base32hex": () => (/* binding */ base32hex), -/* harmony export */ "base32hexpad": () => (/* binding */ base32hexpad), -/* harmony export */ "base32hexpadupper": () => (/* binding */ base32hexpadupper), -/* harmony export */ "base32hexupper": () => (/* binding */ base32hexupper), -/* harmony export */ "base32pad": () => (/* binding */ base32pad), -/* harmony export */ "base32padupper": () => (/* binding */ base32padupper), -/* harmony export */ "base32upper": () => (/* binding */ base32upper), -/* harmony export */ "base32z": () => (/* binding */ base32z) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9853); - -const base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'b', - name: 'base32', - alphabet: 'abcdefghijklmnopqrstuvwxyz234567', - bitsPerChar: 5 -}); -const base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'B', - name: 'base32upper', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', - bitsPerChar: 5 -}); -const base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'c', - name: 'base32pad', - alphabet: 'abcdefghijklmnopqrstuvwxyz234567=', - bitsPerChar: 5 -}); -const base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'C', - name: 'base32padupper', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=', - bitsPerChar: 5 -}); -const base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'v', - name: 'base32hex', - alphabet: '0123456789abcdefghijklmnopqrstuv', - bitsPerChar: 5 -}); -const base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'V', - name: 'base32hexupper', - alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV', - bitsPerChar: 5 -}); -const base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 't', - name: 'base32hexpad', - alphabet: '0123456789abcdefghijklmnopqrstuv=', - bitsPerChar: 5 -}); -const base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'T', - name: 'base32hexpadupper', - alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=', - bitsPerChar: 5 -}); -const base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'h', - name: 'base32z', - alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769', - bitsPerChar: 5 -}); - -/***/ }), - -/***/ 4749: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "base58btc": () => (/* binding */ base58btc), -/* harmony export */ "base58flickr": () => (/* binding */ base58flickr) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9853); - -const base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .baseX */ .kU)({ - name: 'base58btc', - prefix: 'z', - alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' -}); -const base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .baseX */ .kU)({ - name: 'base58flickr', - prefix: 'Z', - alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' -}); - -/***/ }), - -/***/ 1453: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "base64": () => (/* binding */ base64), -/* harmony export */ "base64pad": () => (/* binding */ base64pad), -/* harmony export */ "base64url": () => (/* binding */ base64url), -/* harmony export */ "base64urlpad": () => (/* binding */ base64urlpad) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9853); - -const base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'm', - name: 'base64', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', - bitsPerChar: 6 -}); -const base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'M', - name: 'base64pad', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - bitsPerChar: 6 -}); -const base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'u', - name: 'base64url', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', - bitsPerChar: 6 -}); -const base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__/* .rfc4648 */ .ET)({ - prefix: 'U', - name: 'base64urlpad', - alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=', - bitsPerChar: 6 -}); - -/***/ }), - -/***/ 9145: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "gh": () => (/* binding */ bases), - "QB": () => (/* binding */ codecs), - "kq": () => (/* binding */ hashes) -}); - -// UNUSED EXPORTS: CID, bytes, digest, hasher, varint - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/identity.js -var identity_namespaceObject = {}; -__webpack_require__.r(identity_namespaceObject); -__webpack_require__.d(identity_namespaceObject, { - "identity": () => (identity) -}); - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/base2.js -var base2_namespaceObject = {}; -__webpack_require__.r(base2_namespaceObject); -__webpack_require__.d(base2_namespaceObject, { - "base2": () => (base2) -}); - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/base8.js -var base8_namespaceObject = {}; -__webpack_require__.r(base8_namespaceObject); -__webpack_require__.d(base8_namespaceObject, { - "base8": () => (base8) -}); - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/base10.js -var base10_namespaceObject = {}; -__webpack_require__.r(base10_namespaceObject); -__webpack_require__.d(base10_namespaceObject, { - "base10": () => (base10) -}); - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/base16.js -var base16_namespaceObject = {}; -__webpack_require__.r(base16_namespaceObject); -__webpack_require__.d(base16_namespaceObject, { - "base16": () => (base16), - "base16upper": () => (base16upper) -}); +const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => { + return from({ + prefix, + name, + encode(input) { + return encode(input, alphabet, bitsPerChar); + }, + decode(input) { + return decode(input, alphabet, bitsPerChar, name); + } + }); +}; +;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base58.js -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/bases/base36.js -var base36_namespaceObject = {}; -__webpack_require__.r(base36_namespaceObject); -__webpack_require__.d(base36_namespaceObject, { - "base36": () => (base36), - "base36upper": () => (base36upper) +const base58btc = baseX({ + name: 'base58btc', + prefix: 'z', + alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' }); - -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/codecs/raw.js -var raw_namespaceObject = {}; -__webpack_require__.r(raw_namespaceObject); -__webpack_require__.d(raw_namespaceObject, { - "code": () => (code), - "decode": () => (decode), - "encode": () => (encode), - "name": () => (raw_name) +const base58flickr = baseX({ + name: 'base58flickr', + prefix: 'Z', + alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' }); +;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base32.js -// NAMESPACE OBJECT: ../node_modules/multiformats/esm/src/codecs/json.js -var json_namespaceObject = {}; -__webpack_require__.r(json_namespaceObject); -__webpack_require__.d(json_namespaceObject, { - "code": () => (json_code), - "decode": () => (json_decode), - "encode": () => (json_encode), - "name": () => (json_name) +const base32 = rfc4648({ + prefix: 'b', + name: 'base32', + alphabet: 'abcdefghijklmnopqrstuvwxyz234567', + bitsPerChar: 5 }); - -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bases/base.js + 1 modules -var base = __webpack_require__(9853); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bytes.js -var bytes = __webpack_require__(9551); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/identity.js - - -const identity = (0,base/* from */.Dp)({ - prefix: '\0', - name: 'identity', - encode: buf => (0,bytes.toString)(buf), - decode: str => (0,bytes.fromString)(str) +const base32upper = rfc4648({ + prefix: 'B', + name: 'base32upper', + alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', + bitsPerChar: 5 }); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base2.js - -const base2 = (0,base/* rfc4648 */.ET)({ - prefix: '0', - name: 'base2', - alphabet: '01', - bitsPerChar: 1 +const base32pad = rfc4648({ + prefix: 'c', + name: 'base32pad', + alphabet: 'abcdefghijklmnopqrstuvwxyz234567=', + bitsPerChar: 5 }); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base8.js - -const base8 = (0,base/* rfc4648 */.ET)({ - prefix: '7', - name: 'base8', - alphabet: '01234567', - bitsPerChar: 3 +const base32padupper = rfc4648({ + prefix: 'C', + name: 'base32padupper', + alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=', + bitsPerChar: 5 }); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base10.js - -const base10 = (0,base/* baseX */.kU)({ - prefix: '9', - name: 'base10', - alphabet: '0123456789' +const base32hex = rfc4648({ + prefix: 'v', + name: 'base32hex', + alphabet: '0123456789abcdefghijklmnopqrstuv', + bitsPerChar: 5 }); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base16.js - -const base16 = (0,base/* rfc4648 */.ET)({ - prefix: 'f', - name: 'base16', - alphabet: '0123456789abcdef', - bitsPerChar: 4 +const base32hexupper = rfc4648({ + prefix: 'V', + name: 'base32hexupper', + alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV', + bitsPerChar: 5 }); -const base16upper = (0,base/* rfc4648 */.ET)({ - prefix: 'F', - name: 'base16upper', - alphabet: '0123456789ABCDEF', - bitsPerChar: 4 +const base32hexpad = rfc4648({ + prefix: 't', + name: 'base32hexpad', + alphabet: '0123456789abcdefghijklmnopqrstuv=', + bitsPerChar: 5 }); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bases/base32.js -var base32 = __webpack_require__(4052); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/bases/base36.js - -const base36 = (0,base/* baseX */.kU)({ - prefix: 'k', - name: 'base36', - alphabet: '0123456789abcdefghijklmnopqrstuvwxyz' +const base32hexpadupper = rfc4648({ + prefix: 'T', + name: 'base32hexpadupper', + alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=', + bitsPerChar: 5 }); -const base36upper = (0,base/* baseX */.kU)({ - prefix: 'K', - name: 'base36upper', - alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +const base32z = rfc4648({ + prefix: 'h', + name: 'base32z', + alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769', + bitsPerChar: 5 }); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bases/base58.js -var base58 = __webpack_require__(4749); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/bases/base64.js -var base64 = __webpack_require__(1453); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/hashes/sha2-browser.js -var sha2_browser = __webpack_require__(2671); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/hashes/identity.js -var hashes_identity = __webpack_require__(7246); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/codecs/raw.js - -const raw_name = 'raw'; -const code = 85; -const encode = node => (0,bytes.coerce)(node); -const decode = data => (0,bytes.coerce)(data); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/codecs/json.js -const textEncoder = new TextEncoder(); -const textDecoder = new TextDecoder(); -const json_name = 'json'; -const json_code = 512; -const json_encode = node => textEncoder.encode(JSON.stringify(node)); -const json_decode = data => JSON.parse(textDecoder.decode(data)); -// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/index.js -var src = __webpack_require__(7534); -;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/basics.js - - - - - - - - - - - - - - -const bases = { - ...identity_namespaceObject, - ...base2_namespaceObject, - ...base8_namespaceObject, - ...base10_namespaceObject, - ...base16_namespaceObject, - ...base32, - ...base36_namespaceObject, - ...base58, - ...base64 -}; -const hashes = { - ...sha2_browser, - ...hashes_identity -}; -const codecs = { - raw: raw_namespaceObject, - json: json_namespaceObject -}; - - -/***/ }), - -/***/ 9551: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "coerce": () => (/* binding */ coerce), -/* harmony export */ "empty": () => (/* binding */ empty), -/* harmony export */ "equals": () => (/* binding */ equals), -/* harmony export */ "fromHex": () => (/* binding */ fromHex), -/* harmony export */ "fromString": () => (/* binding */ fromString), -/* harmony export */ "isBinary": () => (/* binding */ isBinary), -/* harmony export */ "toHex": () => (/* binding */ toHex), -/* harmony export */ "toString": () => (/* binding */ toString) -/* harmony export */ }); -const empty = new Uint8Array(0); -const toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), ''); -const fromHex = hex => { - const hexes = hex.match(/../g); - return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty; -}; -const equals = (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 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'); -}; -const isBinary = o => o instanceof ArrayBuffer || ArrayBuffer.isView(o); -const fromString = str => new TextEncoder().encode(str); -const toString = b => new TextDecoder().decode(b); - - -/***/ }), - -/***/ 3036: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CID": () => (/* binding */ CID) -/* harmony export */ }); -/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3209); -/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9122); -/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4749); -/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4052); -/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9551); +;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/cid.js @@ -44076,14 +2630,14 @@ class CID { this.asCID = this; this._baseCache = new Map(); Object.defineProperties(this, { - byteOffset: hidden, - byteLength: hidden, + byteOffset: cid_hidden, + byteLength: cid_hidden, code: readonly, version: readonly, multihash: readonly, bytes: readonly, - _baseCache: hidden, - asCID: hidden + _baseCache: cid_hidden, + asCID: cid_hidden }); } toV0() { @@ -44107,7 +2661,7 @@ class CID { switch (this.version) { case 0: { const {code, digest} = this.multihash; - const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, digest); + const multihash = hashes_digest/* create */.Ue(code, digest); return CID.createV1(this.code, multihash); } case 1: { @@ -44119,15 +2673,15 @@ class CID { } } equals(other) { - return other && this.code === other.code && this.version === other.version && _hashes_digest_js__WEBPACK_IMPORTED_MODULE_1__.equals(this.multihash, other.multihash); + return other && this.code === other.code && this.version === other.version && hashes_digest/* equals */.fS(this.multihash, other.multihash); } toString(base) { const {bytes, version, _baseCache} = this; switch (version) { case 0: - return toStringV0(bytes, _baseCache, base || _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder); + return toStringV0(bytes, _baseCache, base || base58btc.encoder); default: - return toStringV1(bytes, _baseCache, base || _bases_base32_js__WEBPACK_IMPORTED_MODULE_3__.base32.encoder); + return toStringV1(bytes, _baseCache, base || base32.encoder); } } toJSON() { @@ -44170,7 +2724,7 @@ class CID { return new CID(version, code, multihash, bytes || encodeCID(version, code, multihash.bytes)); } else if (value != null && value[cidSymbol] === true) { const {version, multihash, code} = value; - const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_1__.decode(multihash); + const digest = hashes_digest/* decode */.Jx(multihash); return CID.create(version, code, digest); } else { return null; @@ -44213,12 +2767,12 @@ class CID { static decodeFirst(bytes) { const specs = CID.inspectBytes(bytes); const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_4__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + const multihashBytes = (0,src_bytes/* coerce */.oQ)(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 = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_1__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const digest = new hashes_digest/* Digest */.zZ(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); const cid = specs.version === 0 ? CID.createV0(digest) : CID.createV1(specs.codec, digest); return [ cid, @@ -44228,7 +2782,7 @@ class CID { static inspectBytes(initialBytes) { let offset = 0; const next = () => { - const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_0__.decode(initialBytes.subarray(offset)); + const [i, length] = varint/* decode */.Jx(initialBytes.subarray(offset)); offset += length; return i; }; @@ -44267,23 +2821,23 @@ class CID { const parseCIDtoBytes = (source, base) => { switch (source[0]) { case 'Q': { - const decoder = base || _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc; + const decoder = base || base58btc; return [ - _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, - decoder.decode(`${ _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix }${ source }`) + base58btc.prefix, + decoder.decode(`${ base58btc.prefix }${ source }`) ]; } - case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: { - const decoder = base || _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc; + case base58btc.prefix: { + const decoder = base || base58btc; return [ - _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, + base58btc.prefix, decoder.decode(source) ]; } - case _bases_base32_js__WEBPACK_IMPORTED_MODULE_3__.base32.prefix: { - const decoder = base || _bases_base32_js__WEBPACK_IMPORTED_MODULE_3__.base32; + case base32.prefix: { + const decoder = base || base32; return [ - _bases_base32_js__WEBPACK_IMPORTED_MODULE_3__.base32.prefix, + base32.prefix, decoder.decode(source) ]; } @@ -44300,7 +2854,7 @@ const parseCIDtoBytes = (source, base) => { }; const toStringV0 = (bytes, cache, base) => { const {prefix} = base; - if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) { + if (prefix !== base58btc.prefix) { throw Error(`Cannot string encode V0 in ${ base.name } encoding`); } const cid = cache.get(prefix); @@ -44326,11 +2880,11 @@ const toStringV1 = (bytes, cache, base) => { const DAG_PB_CODE = 112; const SHA_256_CODE = 18; const encodeCID = (version, code, multihash) => { - const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_0__.encodingLength(version); - const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_0__.encodingLength(code); + const codeOffset = varint/* encodingLength */.P$(version); + const hashOffset = codeOffset + varint/* encodingLength */.P$(code); const bytes = new Uint8Array(hashOffset + multihash.byteLength); - _varint_js__WEBPACK_IMPORTED_MODULE_0__.encodeTo(version, bytes, 0); - _varint_js__WEBPACK_IMPORTED_MODULE_0__.encodeTo(code, bytes, codeOffset); + varint/* encodeTo */.mL(version, bytes, 0); + varint/* encodeTo */.mL(code, bytes, codeOffset); bytes.set(multihash, hashOffset); return bytes; }; @@ -44340,7 +2894,7 @@ const readonly = { configurable: false, enumerable: true }; -const hidden = { +const cid_hidden = { writable: false, enumerable: false, configurable: false @@ -44371,35 +2925,34 @@ if (cid) { /***/ }), -/***/ 9122: +/***/ 122: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Digest": () => (/* binding */ Digest), -/* harmony export */ "create": () => (/* binding */ create), -/* harmony export */ "decode": () => (/* binding */ decode), -/* harmony export */ "equals": () => (/* binding */ equals) +/* harmony export */ "Jx": () => (/* binding */ decode), +/* harmony export */ "Ue": () => (/* binding */ create), +/* harmony export */ "fS": () => (/* binding */ equals), +/* harmony export */ "zZ": () => (/* binding */ Digest) /* harmony export */ }); -/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9551); -/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3209); +/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(551); +/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(209); const create = (code, digest) => { const size = digest.byteLength; - const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code); - const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size); + const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodingLength */ .P$(code); + const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodingLength */ .P$(size); const bytes = new Uint8Array(digestOffset + size); - _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0); - _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset); + _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeTo */ .mL(code, bytes, 0); + _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .encodeTo */ .mL(size, bytes, sizeOffset); bytes.set(digest, digestOffset); return new Digest(code, size, digest, bytes); }; const decode = multihash => { - const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash); - const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes); - const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset)); + const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__/* .coerce */ .oQ)(multihash); + const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .decode */ .Jx(bytes); + const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__/* .decode */ .Jx(bytes.subarray(sizeOffset)); const digest = bytes.subarray(sizeOffset + digestOffset); if (digest.byteLength !== size) { throw new Error('Incorrect length'); @@ -44410,7 +2963,7 @@ const equals = (a, b) => { if (a === b) { return true; } else { - return a.code === b.code && a.size === b.size && (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, b.bytes); + return a.code === b.code && a.size === b.size && (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__/* .equals */ .fS)(a.bytes, b.bytes); } }; class Digest { @@ -44424,16 +2977,22 @@ class Digest { /***/ }), -/***/ 4986: +/***/ 865: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; +// ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Hasher": () => (/* binding */ Hasher), -/* harmony export */ "from": () => (/* binding */ from) -/* harmony export */ }); -/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9122); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "sha256": () => (/* binding */ sha256), + "sha512": () => (/* binding */ sha512) +}); + +// EXTERNAL MODULE: ../node_modules/multiformats/esm/src/hashes/digest.js +var hashes_digest = __webpack_require__(122); +;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/hashes/hasher.js const from = ({name, code, encode}) => new Hasher(name, code, encode); class Hasher { @@ -44445,58 +3004,21 @@ class Hasher { digest(input) { if (input instanceof Uint8Array) { const result = this.encode(input); - return result instanceof Uint8Array ? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result) : result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest)); + return result instanceof Uint8Array ? hashes_digest/* create */.Ue(this.code, result) : result.then(digest => hashes_digest/* create */.Ue(this.code, digest)); } else { throw Error('Unknown type, must be binary type'); } } } - -/***/ }), - -/***/ 7246: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "identity": () => (/* binding */ identity) -/* harmony export */ }); -/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9551); -/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9122); - - -const code = 0; -const name = 'identity'; -const encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce; -const digest = input => _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input)); -const identity = { - code, - name, - encode, - digest -}; - -/***/ }), - -/***/ 2671: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "sha256": () => (/* binding */ sha256), -/* harmony export */ "sha512": () => (/* binding */ sha512) -/* harmony export */ }); -/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4986); +;// CONCATENATED MODULE: ../node_modules/multiformats/esm/src/hashes/sha2-browser.js const sha = name => async data => new Uint8Array(await crypto.subtle.digest(name, data)); -const sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({ +const sha256 = from({ name: 'sha2-256', code: 18, encode: sha('SHA-256') }); -const sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({ +const sha512 = from({ name: 'sha2-512', code: 19, encode: sha('SHA-512') @@ -44504,44 +3026,16 @@ const sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({ /***/ }), -/***/ 7534: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CID": () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_0__.CID), -/* harmony export */ "bytes": () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_2__), -/* harmony export */ "digest": () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__), -/* harmony export */ "hasher": () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__), -/* harmony export */ "varint": () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_1__) -/* harmony export */ }); -/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3036); -/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3209); -/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9551); -/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4986); -/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9122); - - - - - - - -/***/ }), - -/***/ 3209: +/***/ 209: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { - "decode": () => (/* binding */ varint_decode), - "encodeTo": () => (/* binding */ encodeTo), - "encodingLength": () => (/* binding */ encodingLength) + "Jx": () => (/* binding */ varint_decode), + "mL": () => (/* binding */ encodeTo), + "P$": () => (/* binding */ encodingLength) }); ;// CONCATENATED MODULE: ../node_modules/multiformats/esm/vendor/varint.js @@ -44615,149 +3109,6 @@ const encodingLength = int => { return vendor_varint.encodingLength(int); }; -/***/ }), - -/***/ 6729: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "concat": () => (/* binding */ concat) -/* harmony export */ }); -function concat(arrays, length) { - if (!length) { - length = arrays.reduce((acc, curr) => acc + curr.length, 0); - } - const output = new Uint8Array(length); - let offset = 0; - for (const arr of arrays) { - output.set(arr, offset); - offset += arr.length; - } - return output; -} - -/***/ }), - -/***/ 5732: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "equals": () => (/* binding */ equals) -/* harmony export */ }); -function equals(a, b) { - if (a === b) { - return true; - } - if (a.byteLength !== b.byteLength) { - return false; - } - for (let i = 0; i < a.byteLength; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} - -/***/ }), - -/***/ 4081: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "fromString": () => (/* binding */ fromString) -/* harmony export */ }); -/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1785); - -function fromString(string, encoding = 'utf8') { - const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z[encoding]; - if (!base) { - throw new Error(`Unsupported encoding "${ encoding }"`); - } - return base.decoder.decode(`${ base.prefix }${ string }`); -} - -/***/ }), - -/***/ 5824: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "toString": () => (/* binding */ toString) -/* harmony export */ }); -/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1785); - -function toString(array, encoding = 'utf8') { - const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z[encoding]; - if (!base) { - throw new Error(`Unsupported encoding "${ encoding }"`); - } - return base.encoder.encode(array).substring(1); -} - -/***/ }), - -/***/ 1785: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9145); - -function createCodec(name, prefix, encode, decode) { - return { - name, - prefix, - encoder: { - name, - prefix, - encode - }, - decoder: { decode } - }; -} -const string = createCodec('utf8', 'u', buf => { - const decoder = new TextDecoder('utf8'); - return 'u' + decoder.decode(buf); -}, str => { - const encoder = new TextEncoder(); - return encoder.encode(str.substring(1)); -}); -const ascii = createCodec('ascii', 'a', buf => { - let string = 'a'; - for (let i = 0; i < buf.length; i++) { - string += String.fromCharCode(buf[i]); - } - return string; -}, str => { - str = str.substring(1); - const buf = new Uint8Array(str.length); - for (let i = 0; i < str.length; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -}); -const BASES = { - utf8: string, - 'utf-8': string, - hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__/* .bases.base16 */ .gh.base16, - latin1: ascii, - ascii: ascii, - binary: ascii, - ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__/* .bases */ .gh -}; -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES); - /***/ }) }]); \ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 55f75ac..bcc1a7f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -5,36 +5,66 @@ dmap - + + + +

dmap

+

+ This page is designed to be saved (as in "File > Save") and be usable even if DNS or this web host go offline or are compromised. +

+

+ You can also add it to ipfs, which is an easy way to monitor changes: +

+
+    wget -r dmap.sh && ipfs add dmap.sh -r --pin --cid-version=1
+
+

+ Your local ETH thin client and IPFS client are fundamental to securing your software supply chain. +

+

+ Do not depend on this domain name to resolve to the correct dmap interface. +

+

+ Make sure you are bootstrapped and can get oriented even if DNS goes offline. +

+ +

+The dmap address is 0x90949c9937A11BA943C7A72C3FA073a37E3FdD96 . +

+ +

configure

- - + +
+ + +
+
+ +

resolve a dpath

+ +
+ - - +
-
+

 
-
-
 
 
 
diff --git a/docs/main.js b/docs/main.js
index ffd7b1d..72ae726 100644
--- a/docs/main.js
+++ b/docs/main.js
@@ -1,10 +1,10 @@
-import { ethers } from 'ethers'
-import { CID } from 'multiformats/cid'
-import { sha256 } from 'multiformats/hashes/sha2'
+const { CID } = require('multiformats/cid')
+const { sha256 } = require ('multiformats/hashes/sha2')
+
 const dmap = require('../dmap.js')
-const dmapAddress = dmap.address
-const dmapArtifact = dmap.artifact
-const IPFS = require('ipfs-http-client')
+
+const fail =s=> { throw new Error(s) }
+const need =(b,s)=> b || fail(s)
 
 const gateways = ['https://ipfs.fleek.co/ipfs/',
                   'https://gateway.pinata.cloud/ipfs/',
@@ -12,6 +12,43 @@ const gateways = ['https://ipfs.fleek.co/ipfs/',
                   'https://storry.tv/ipfs/',
                   'https://ipfs.io/ipfs/',
                   'https://hub.textile.io/ipfs/']
+const infuraURL = 'https://mainnet.infura.io/v3/c0a739d64257448f855847c6e3d173e1'
+const prefLenIndex = 30
+
+module.exports = utils = {}
+
+utils.prepareCID = (cidStr, lock) => {
+    const cid = CID.parse(cidStr)
+    need(cid.multihash.size <= 32, `Hash exceeds 256 bits`)
+    const prefixLen = cid.byteLength - cid.multihash.size
+    const meta = new Uint8Array(32).fill(0)
+    const data = new Uint8Array(32).fill(0)
+
+    data.set(cid.bytes.slice(-cid.multihash.size), 32 - cid.multihash.size)
+    meta.set(cid.bytes.slice(0, prefixLen))
+    if (lock) meta[31] |= dmap.FLAG_LOCK
+    meta[prefLenIndex] = prefixLen
+    return [meta, data]
+}
+
+utils.unpackCID = (metaStr, dataStr) => {
+    const meta = dmap._hexToArrayBuffer(metaStr)
+    const data = dmap._hexToArrayBuffer(dataStr)
+    const prefixLen = meta[prefLenIndex]
+    const specs = CID.inspectBytes(meta.slice(0, prefixLen))
+    const hashLen = specs.digestSize
+    const cidBytes = new Uint8Array(prefixLen + hashLen)
+
+    cidBytes.set(meta.slice(0, prefixLen), 0)
+    cidBytes.set(data.slice(32 - hashLen), prefixLen)
+    const cid = CID.decode(cidBytes)
+    return cid.toString()
+}
+
+utils.readCID = async (contract, path) => {
+    const packed = await dmap.walk(contract, path)
+    return utils.unpackCID(packed.meta, packed.data)
+}
 
 const resolveCID = async (cid, targetDigest, nodeAddress) => {
     const verify = async bytes => {
@@ -19,11 +56,14 @@ const resolveCID = async (cid, targetDigest, nodeAddress) => {
         const resultDigest = JSON.stringify(hash.digest)
         return targetDigest === resultDigest
     }
-    const node = IPFS.create(nodeAddress)
-    const catResponse = await node.cat(cid)
+
+    const url = nodeAddress + '/api/v0/cat?arg=' + cid
+    const response = await fetch(url, { method: 'POST' })
+    const catResponse = response.body.getReader();
+
     // initially handle only single chunk verification and sha256
     try {
-        const chunk = await catResponse.next()
+        const chunk = await catResponse.read()
         if(await verify(chunk.value)) {
             return chunk.value
         }
@@ -43,43 +83,104 @@ const resolveCID = async (cid, targetDigest, nodeAddress) => {
     throw 'unable to resolve cid'
 }
 
+const makeRPC = async (url, method, params) => {
+    let result = null
+    try {
+        const response = await fetch(url, {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify({
+                "jsonrpc": "2.0",
+                "method": method,
+                "params": params,
+                "id": 0
+            }),
+        });
+        ({result} = await response.json())
+    }
+    catch (err) {}
+    return result
+}
+
+const RPCGetStorage = async (url, address, slot) => {
+    const block = await makeRPC(url, "eth_blockNumber", [])
+    return await makeRPC(url, "eth_getStorageAt", [address, slot, block])
+}
+
+const windowGetStorage = async (address, slot) => {
+    const block  = await window.ethereum.request({ method: 'eth_blockNumber',  params: [] });
+    return await window.ethereum.request({ method: 'eth_getStorageAt', params: [address, slot, block] });
+}
+
+const getFacade = async (customURL) => {
+    let storageFunction = null, description = ''
+
+    if (await makeRPC(customURL, "eth_chainId", []) == '0x1') {
+        storageFunction = RPCGetStorage.bind(null, customURL)
+        description = 'custom node'
+    } else if (typeof window.ethereum !== 'undefined' &&
+               await window.ethereum.request({ method: 'eth_chainId',  params: [] }) == '0x1') {
+        storageFunction = windowGetStorage
+        description = 'window.ethereum'
+    } else if (await makeRPC(infuraURL, "eth_chainId", []) == '0x1') {
+        storageFunction = RPCGetStorage.bind(null, infuraURL)
+        description = 'infura'
+    } else {
+        throw 'no ethereum connection'
+    }
+
+    return [{ provider: { getStorageAt:storageFunction },
+              address: dmap.address
+            }, description]
+}
+
 window.onload = async() => {
     const $ = document.querySelector.bind(document);
     const line =s=> { $('#result').textContent += s + '\n' }
 
     $('#btnGet').addEventListener('click', async () =>  {
-        const dpath = $('#dpath').value;
-        line(`WALK ${dpath}`)
-        const provider = new ethers.providers.Web3Provider(window.ethereum)
-        const dmapContract = new ethers.Contract(
-            dmapAddress,
-            dmapArtifact.abi,
-            provider
-        );
+        let dpath = $('#dpath').value;
+        if (dpath.length && dpath[0] != ':') {
+            dpath = ':' + dpath
+        }
+        const [dmapFacade, description] = await getFacade($('#ethNode').value)
+
+        line(`(using ${description} for eth connection) \n`)
+        line(`WALK ${dpath} \n`)
 
         let walkResult
         try {
-            walkResult = await dmap.walk(dmapContract, dpath)
-            line(`meta: ${walkResult.meta}`)
-            line(`data: ${walkResult.data}`)
+            walkResult = await dmap.walk2(dmapFacade, dpath)
+            for (const step of walkResult) {
+                line(`step`)
+                line(`  meta: ${step[0]}`)
+                line(`  data: ${step[1]}`)
+            }
         }
         catch (error) {
+            line('')
             line(`FAIL: ${error}`)
             return
         }
+        line('')
+        const last = walkResult.pop()
+        console.log(last)
+        walkResult = { meta: last[0], data: last[1] }
 
         try {
             // display ipfs content from a CID if we can, otherwise display as text
-            const cid = dmap.unpackCID(walkResult.meta, walkResult.data)
+            const cid = utils.unpackCID(walkResult.meta, walkResult.data)
             line(`ipfs: ${cid}`)
             const targetDigest = JSON.stringify(CID.parse(cid).multihash.digest)
-            const resolved = await resolveCID(cid, targetDigest, $('#localNode').value)
+            const resolved = await resolveCID(cid, targetDigest, $('#ipfsNode').value)
             let utf8decoder = new TextDecoder()
             line(utf8decoder.decode(resolved))
         }
         catch(e){
             let utf8decoder = new TextDecoder()
-            const bytes = Buffer.from(walkResult.data.slice(2), 'hex')
+            const bytes = dmap._hexToArrayBuffer(walkResult.data)
             for (var i = 0; i < bytes.length; i++) {
                 if (bytes[bytes.length -1 - i] !== 0) {
                     break
diff --git a/docs/main.unmin.js b/docs/main.unmin.js
index db360a6..56b8161 100644
--- a/docs/main.unmin.js
+++ b/docs/main.unmin.js
@@ -1,34 +1,26 @@
 /******/ (() => { // webpackBootstrap
 /******/ 	var __webpack_modules__ = ({
 
-/***/ 2971:
+/***/ 971:
 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
 
-/* provided dependency */ var Buffer = __webpack_require__(816)["Buffer"];
-const ebnf = __webpack_require__(1425)
-const ethers = __webpack_require__(5341)
-const multiformats = __webpack_require__(7534)
+const kek = __webpack_require__(338)
+const ebnf = __webpack_require__(425)
 
-const pack = __webpack_require__(1471)
-const artifact = __webpack_require__(6960)
+const pack = __webpack_require__(789)
+const artifact = __webpack_require__(791)
 
-const abi    = artifact.abi
-const dmap_i = new ethers.utils.Interface(abi)
 const dmap_address = pack.objects.dmap.address
 
 const fail =s=> { throw new Error(s) }
 const need =(b,s)=> b || fail(s)
 
-const coder = ethers.utils.defaultAbiCoder
-const keccak256 = ethers.utils.keccak256
-const prefLenIndex = 2
-
 module.exports = lib = {}
 
 lib.address = dmap_address
 lib.artifact = artifact
 
-lib.FLAG_LOCK = 1 << 7
+lib.FLAG_LOCK = 1
 lib.grammar = `
 dpath ::= (step)* EOF
 step  ::= (rune) (name)
@@ -50,8 +42,8 @@ lib.parse =s=> {
 }
 
 lib.get = async (dmap, slot) => {
-    const nextslot = ethers.utils.hexZeroPad(
-        ethers.BigNumber.from(slot).add(1).toHexString(), 32
+    const nextslot = hexZeroPad(
+        hexlify(BigInt(slot) + BigInt(1)), 32
     )
     let meta, data
     await Promise.all(
@@ -60,28 +52,24 @@ lib.get = async (dmap, slot) => {
             dmap.provider.getStorageAt(dmap.address, nextslot)
         ]
     ).then(res => [meta, data] = res)
-    const resdata = dmap_i.encodeFunctionResult("get", [meta, data])
-    const res = dmap_i.decodeFunctionResult("get", resdata)
-    return res
+    return [meta, data]
 }
 
 lib.getByZoneAndName = async (dmap, zone, name) => {
-    const slot = keccak256(coder.encode(["address", "bytes32"], [zone, name]))
+    const slot = keccak256(encodeZoneAndName(zone, name));
     return lib.get(dmap, slot)
 }
 
 lib.set = async (dmap, name, meta, data) => {
-    const calldata = dmap_i.encodeFunctionData("set", [name, meta, data])
+    const calldata = encodeFunctionCallBytes32Args("set(bytes32,bytes32,bytes32)", [name, meta, data])
     return dmap.signer.sendTransaction({to: dmap.address, data: calldata})
 }
 
-const slotabi = ["function slot(bytes32 s) external view returns (bytes32)"]
-const slot_i = new ethers.utils.Interface(slotabi)
+// const slotabi = ["function slot(bytes32 s) external view returns (bytes32)"]
+// const slot_i = new ethers.utils.Interface(slotabi)
 lib.slot = async (dmap, slot) => {
     const val = await dmap.provider.getStorageAt(dmap.address, slot)
-    const resdata = slot_i.encodeFunctionResult("slot", [val])
-    const res = slot_i.decodeFunctionResult("slot", resdata)
-    return res[0]
+    return val
 }
 
 
@@ -94,11 +82,11 @@ lib.walk = async (dmap, path) => {
         if (zone === '0x' + '00'.repeat(20)) {
             fail(`zero register`)
         }
-        const fullname = '0x' + Buffer.from(step.name).toString('hex') + '00'.repeat(32-step.name.length);
+        const fullname = '0x' + lib._strToHex(step.name) + '00'.repeat(32-step.name.length);
         [meta, data] = await lib.getByZoneAndName(dmap, zone, fullname)
         if (step.locked) {
             need(ctx.locked, `Encountered ':' in unlocked subpath`)
-            need((Buffer.from(meta.slice(2), 'hex')[0] & lib.FLAG_LOCK) !== 0, `Entry is not locked`)
+            need((lib._hexToArrayBuffer(meta)[31] & lib.FLAG_LOCK) !== 0, `Entry is not locked`)
             ctx.locked = true
         }
         ctx.locked = step.locked
@@ -106,58 +94,152 @@ lib.walk = async (dmap, path) => {
     return {meta, data}
 }
 
-lib.prepareCID = (cidStr, lock) => {
-    const cid = multiformats.CID.parse(cidStr)
-    need(cid.multihash.size <= 32, `Hash exceeds 256 bits`)
-    const prefixLen = cid.byteLength - cid.multihash.size
-    const meta = new Uint8Array(32).fill(0)
-    const data = new Uint8Array(32).fill(0)
+lib.walk2 = async (dmap, path) => {
+    if ( path.length > 0 && ![':', '.'].includes(path.charAt(0))) path = ':' + path
+    let [meta, data] = await lib.get(dmap, '0x' + '00'.repeat(32))
+    let ctx = {locked: path.charAt(0) === ':'}
+    const trace = [[meta,data]]
+    for (const step of lib.parse(path)) {
+        zone = data.slice(0, 21 * 2)
+        if (zone === '0x' + '00'.repeat(20)) {
+            fail(`zero register`)
+        }
+        const fullname = '0x' + lib._strToHex(step.name) + '00'.repeat(32-step.name.length);
+        [meta, data] = await lib.getByZoneAndName(dmap, zone, fullname)
+        trace.push([meta,data])
+        if (step.locked) {
+            need(ctx.locked, `Encountered ':' in unlocked subpath`)
+            need((lib._hexToArrayBuffer(meta)[31] & lib.FLAG_LOCK) !== 0, `Entry is not locked`)
+            ctx.locked = true
+        }
+        ctx.locked = step.locked
+    }
+    return trace
+}
 
-    data.set(cid.bytes.slice(-cid.multihash.size), 32 - cid.multihash.size)
-    meta.set(cid.bytes.slice(0, prefixLen), 32 - prefixLen)
-    if (lock) meta[0] |= lib.FLAG_LOCK
-    meta[prefLenIndex] = prefixLen
-    return [meta, data]
+lib._hexToArrayBuffer = hex => {
+    const bytes = []
+    for (let c = 2; c < hex.length; c += 2)
+        bytes.push(parseInt(hex.slice(c, c + 2), 16))
+    return new Uint8Array(bytes)
 }
 
-lib.unpackCID = (metaStr, dataStr) => {
-    const meta = Buffer.from(metaStr.slice(2), 'hex')
-    const data = Buffer.from(dataStr.slice(2), 'hex')
-    const prefixLen = meta[prefLenIndex]
-    const specs = multiformats.CID.inspectBytes(meta.slice(-prefixLen))
-    const hashLen = specs.digestSize
-    const cidBytes = new Uint8Array(prefixLen + hashLen)
+lib._strToHex = str => {
+    let codes =  str.split('').map(c => c.charCodeAt(0))
+    return codes.map(c => c.toString(16)).join('')
+}
 
-    cidBytes.set(meta.slice(-prefixLen), 0)
-    cidBytes.set(data.slice(32 - hashLen), prefixLen)
-    const cid = multiformats.CID.decode(cidBytes)
-    return cid.toString()
+// GLOBAL TODO: !DMFXYZ! error and bounds checking for inputs
+const HexCharacters = "0123456789abcdef";
+
+function hexZeroPad(value, length) {
+    if (typeof(value) !== "string") {
+        value = hexlify(value);
+    }
+
+    if (value.length > 2 * length + 2) {
+        throw "Value too big"
+    }
+
+    while (value.length < 2 * length + 2) {
+        value = "0x0" + value.substring(2);
+    }
+
+    return value;
 }
 
-lib.readCID = async (dmap, path) => {
-    const packed = await lib.walk(dmap, path)
-    return lib.unpackCID(packed.meta, packed.data)
+function hexlify(value) {
+
+    if (typeof(value) === "number") {
+        let hex = "";
+        while (value) {
+            hex = HexCharacters[value & 0xf] + hex;
+            value = Math.floor(value / 16); // can bitshift instead
+        }
+
+        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 (typeof(value) === 'string') {
+        return lib._strToHex(value);
+    }
 }
 
+// Assumes value is a hex encoded string for now, or already a byte array
+function keccak256(value) {
 
-/***/ }),
+    if (typeof(value) == "string") {
+        return "0x" + kek.keccak256(new Uint8Array(_toBytes(value)));
+    }
+    // add back in prefix and return as unsigned 1byte int array
+    return "0x" + kek.keccak256(value);
+}
 
-/***/ 2220:
-/***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => {
+function encodeZoneAndName(zone, name) {
+    // zone should be an address, start by zero-padding 12 bytes
+    let params = '0x' + '00'.repeat(12);
+    if (zone.length == 0) {
+        params = params + '00'.repeat(20);
+    } else {
+        params = params + zone.slice(2); // assume has leading 0x, prob shouldn't do this
+    }
+    if (name.length == 0 || name == null) {
+        params = params + '00'.repeat(32);
+    } else if (typeof(name) == 'object') {
+        params = params + name.toString('hex');
+    } else {
+        // if already a hex string, just drop the 0x
+        params = params + name.slice(2);
+    }
+    return params;
+}
 
-"use strict";
-/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9450);
-/* harmony import */ var ethers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3726);
-/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3036);
-/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2671);
-/* provided dependency */ var Buffer = __webpack_require__(816)["Buffer"];
+function encodeFunctionCallBytes32Args(signature, args) {
+    // calculate function selector as first 4 bytes of hashed signature
+    // keccak256 returns a string, so we take the first 10 characters
+    let data = keccak256(signature).slice(0, 10)
+    for (arg of args) {
+        typeof arg == 'object' ? data += arg.toString('hex') : data += arg.slice(2)
+    }
+    return data;
 
+}
 
+function _toBytes(value) {
+    if (typeof(value) == 'string') {
+        return lib._hexToArrayBuffer(value)
+    }
+    return value
+}
+
+
+/***/ }),
 
-const dmap = __webpack_require__(2971)
-const dmapAddress = dmap.address
-const dmapArtifact = dmap.artifact
-const IPFS = __webpack_require__(2708)
+/***/ 220:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+const { CID } = __webpack_require__(598)
+const { sha256 } = __webpack_require__ (865)
+
+const dmap = __webpack_require__(971)
+
+const fail =s=> { throw new Error(s) }
+const need =(b,s)=> b || fail(s)
 
 const gateways = ['https://ipfs.fleek.co/ipfs/',
                   'https://gateway.pinata.cloud/ipfs/',
@@ -165,18 +247,58 @@ const gateways = ['https://ipfs.fleek.co/ipfs/',
                   'https://storry.tv/ipfs/',
                   'https://ipfs.io/ipfs/',
                   'https://hub.textile.io/ipfs/']
+const infuraURL = 'https://mainnet.infura.io/v3/c0a739d64257448f855847c6e3d173e1'
+const prefLenIndex = 30
+
+module.exports = utils = {}
+
+utils.prepareCID = (cidStr, lock) => {
+    const cid = CID.parse(cidStr)
+    need(cid.multihash.size <= 32, `Hash exceeds 256 bits`)
+    const prefixLen = cid.byteLength - cid.multihash.size
+    const meta = new Uint8Array(32).fill(0)
+    const data = new Uint8Array(32).fill(0)
+
+    data.set(cid.bytes.slice(-cid.multihash.size), 32 - cid.multihash.size)
+    meta.set(cid.bytes.slice(0, prefixLen))
+    if (lock) meta[31] |= dmap.FLAG_LOCK
+    meta[prefLenIndex] = prefixLen
+    return [meta, data]
+}
+
+utils.unpackCID = (metaStr, dataStr) => {
+    const meta = dmap._hexToArrayBuffer(metaStr)
+    const data = dmap._hexToArrayBuffer(dataStr)
+    const prefixLen = meta[prefLenIndex]
+    const specs = CID.inspectBytes(meta.slice(0, prefixLen))
+    const hashLen = specs.digestSize
+    const cidBytes = new Uint8Array(prefixLen + hashLen)
+
+    cidBytes.set(meta.slice(0, prefixLen), 0)
+    cidBytes.set(data.slice(32 - hashLen), prefixLen)
+    const cid = CID.decode(cidBytes)
+    return cid.toString()
+}
+
+utils.readCID = async (contract, path) => {
+    const packed = await dmap.walk(contract, path)
+    return utils.unpackCID(packed.meta, packed.data)
+}
 
 const resolveCID = async (cid, targetDigest, nodeAddress) => {
     const verify = async bytes => {
-        const hash = await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_1__.sha256.digest(bytes)
+        const hash = await sha256.digest(bytes)
         const resultDigest = JSON.stringify(hash.digest)
         return targetDigest === resultDigest
     }
-    const node = IPFS.create(nodeAddress)
-    const catResponse = await node.cat(cid)
+
+    const url = nodeAddress + '/api/v0/cat?arg=' + cid
+    const response = await fetch(url, { method: 'POST' })
+    const catResponse = response.body.getReader();
+
     // initially handle only single chunk verification and sha256
     try {
-        const chunk = await catResponse.next()
+        const chunk = await catResponse.read()
         if(await verify(chunk.value)) {
             return chunk.value
         }
@@ -196,43 +318,104 @@ const resolveCID = async (cid, targetDigest, nodeAddress) => {
     throw 'unable to resolve cid'
 }
 
+const makeRPC = async (url, method, params) => {
+    let result = null
+    try {
+        const response = await fetch(url, {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify({
+                "jsonrpc": "2.0",
+                "method": method,
+                "params": params,
+                "id": 0
+            }),
+        });
+        ({result} = await response.json())
+    }
+    catch (err) {}
+    return result
+}
+
+const RPCGetStorage = async (url, address, slot) => {
+    const block = await makeRPC(url, "eth_blockNumber", [])
+    return await makeRPC(url, "eth_getStorageAt", [address, slot, block])
+}
+
+const windowGetStorage = async (address, slot) => {
+    const block  = await window.ethereum.request({ method: 'eth_blockNumber',  params: [] });
+    return await window.ethereum.request({ method: 'eth_getStorageAt', params: [address, slot, block] });
+}
+
+const getFacade = async (customURL) => {
+    let storageFunction = null, description = ''
+
+    if (await makeRPC(customURL, "eth_chainId", []) == '0x1') {
+        storageFunction = RPCGetStorage.bind(null, customURL)
+        description = 'custom node'
+    } else if (typeof window.ethereum !== 'undefined' &&
+               await window.ethereum.request({ method: 'eth_chainId',  params: [] }) == '0x1') {
+        storageFunction = windowGetStorage
+        description = 'window.ethereum'
+    } else if (await makeRPC(infuraURL, "eth_chainId", []) == '0x1') {
+        storageFunction = RPCGetStorage.bind(null, infuraURL)
+        description = 'infura'
+    } else {
+        throw 'no ethereum connection'
+    }
+
+    return [{ provider: { getStorageAt:storageFunction },
+              address: dmap.address
+            }, description]
+}
+
 window.onload = async() => {
     const $ = document.querySelector.bind(document);
     const line =s=> { $('#result').textContent += s + '\n' }
 
     $('#btnGet').addEventListener('click', async () =>  {
-        const dpath = $('#dpath').value;
-        line(`WALK ${dpath}`)
-        const provider = new ethers__WEBPACK_IMPORTED_MODULE_2__/* .Web3Provider */ .Q(window.ethereum)
-        const dmapContract = new ethers__WEBPACK_IMPORTED_MODULE_3__/* .Contract */ .CH(
-            dmapAddress,
-            dmapArtifact.abi,
-            provider
-        );
+        let dpath = $('#dpath').value;
+        if (dpath.length && dpath[0] != ':') {
+            dpath = ':' + dpath
+        }
+        const [dmapFacade, description] = await getFacade($('#ethNode').value)
+
+        line(`(using ${description} for eth connection) \n`)
+        line(`WALK ${dpath} \n`)
 
         let walkResult
         try {
-            walkResult = await dmap.walk(dmapContract, dpath)
-            line(`meta: ${walkResult.meta}`)
-            line(`data: ${walkResult.data}`)
+            walkResult = await dmap.walk2(dmapFacade, dpath)
+            for (const step of walkResult) {
+                line(`step`)
+                line(`  meta: ${step[0]}`)
+                line(`  data: ${step[1]}`)
+            }
         }
         catch (error) {
+            line('')
             line(`FAIL: ${error}`)
             return
         }
+        line('')
+        const last = walkResult.pop()
+        console.log(last)
+        walkResult = { meta: last[0], data: last[1] }
 
         try {
             // display ipfs content from a CID if we can, otherwise display as text
-            const cid = dmap.unpackCID(walkResult.meta, walkResult.data)
+            const cid = utils.unpackCID(walkResult.meta, walkResult.data)
             line(`ipfs: ${cid}`)
-            const targetDigest = JSON.stringify(multiformats_cid__WEBPACK_IMPORTED_MODULE_0__.CID.parse(cid).multihash.digest)
-            const resolved = await resolveCID(cid, targetDigest, $('#localNode').value)
+            const targetDigest = JSON.stringify(CID.parse(cid).multihash.digest)
+            const resolved = await resolveCID(cid, targetDigest, $('#ipfsNode').value)
             let utf8decoder = new TextDecoder()
             line(utf8decoder.decode(resolved))
         }
         catch(e){
             let utf8decoder = new TextDecoder()
-            const bytes = Buffer.from(walkResult.data.slice(2), 'hex')
+            const bytes = dmap._hexToArrayBuffer(walkResult.data)
             for (var i = 0; i < bytes.length; i++) {
                 if (bytes[bytes.length -1 - i] !== 0) {
                     break
@@ -251,40 +434,19 @@ window.onload = async() => {
 
 /***/ }),
 
-/***/ 5545:
-/***/ (() => {
-
-/* (ignored) */
-
-/***/ }),
-
-/***/ 7868:
-/***/ (() => {
-
-/* (ignored) */
-
-/***/ }),
-
-/***/ 3034:
-/***/ (() => {
-
-/* (ignored) */
-
-/***/ }),
-
-/***/ 6960:
+/***/ 789:
 /***/ ((module) => {
 
 "use strict";
-module.exports = JSON.parse('{"_format":"hh-sol-artifact-1","contractName":"Dmap","sourceName":"core/dmap.sol","abi":[{"inputs":[],"name":"LOCK","type":"error"},{"anonymous":true,"inputs":[{"indexed":true,"internalType":"address","name":"zone","type":"address"},{"indexed":true,"internalType":"bytes32","name":"name","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"meta","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"data","type":"bytes32"}],"name":"Set","type":"event"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"get","outputs":[{"internalType":"bytes32","name":"meta","type":"bytes32"},{"internalType":"bytes32","name":"data","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"name","type":"bytes32"},{"internalType":"bytes32","name":"meta","type":"bytes32"},{"internalType":"bytes32","name":"data","type":"bytes32"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"}],"bytecode":"0x608060405234801561001057600080fd5b5060405161016738038061016783398101604081905261002f91610042565b600160ff1b60005560601b600155610072565b60006020828403121561005457600080fd5b81516001600160a01b038116811461006b57600080fd5b9392505050565b60e7806100806000396000f3fe608060405236602403602257600435546000526004356001015460205260406000f35b6004356024356044353360005282602052604060002081838533600080a481600182015580547f8000000000000000000000000000000000000000000000000000000000000000163660641817607757828155005b505050503660640360ac577fa4f0d7d00000000000000000000000000000000000000000000000000000000060005260046000fd5b600080fdfea2646970667358221220f1dd384635737b10f38bc53d8e50b1a499c75d139ab94907b42e7797a5e1f30c64736f6c634300080d0033","deployedBytecode":"0x608060405236602403602257600435546000526004356001015460205260406000f35b6004356024356044353360005282602052604060002081838533600080a481600182015580547f8000000000000000000000000000000000000000000000000000000000000000163660641817607757828155005b505050503660640360ac577fa4f0d7d00000000000000000000000000000000000000000000000000000000060005260046000fd5b600080fdfea2646970667358221220f1dd384635737b10f38bc53d8e50b1a499c75d139ab94907b42e7797a5e1f30c64736f6c634300080d0033","linkReferences":{},"deployedLinkReferences":{}}');
+module.exports = JSON.parse('{"format":"dpack-1","network":"ethereum","types":{"Dmap":{"typename":"Dmap","artifact":{"/":"bafkreifpsbpx33jchsau6z63zvik3fnpxhaxgyzbtco6tpyq34wp2raggy"}}},"objects":{"dmap":{"objectname":"dmap","typename":"Dmap","address":"0x90949c9937A11BA943C7A72C3FA073a37E3FdD96","artifact":{"/":"bafkreifpsbpx33jchsau6z63zvik3fnpxhaxgyzbtco6tpyq34wp2raggy"}}}}');
 
 /***/ }),
 
-/***/ 1471:
+/***/ 791:
 /***/ ((module) => {
 
 "use strict";
-module.exports = JSON.parse('{"format":"dpack-1","network":"goerli","types":{"Dmap":{"typename":"Dmap","artifact":{"/":"bafkreig6eylwv3ycrp5spwrtevdtllq4rkub44g6gy5c27lpc7hgy33uqi"}},"RootZone":{"typename":"RootZone","artifact":{"/":"bafkreihichgzifyxns7fmhywfugsaad2jbx2buubgcq7ofyg6n6iofp65y"}},"FreeZone":{"typename":"FreeZone","artifact":{"/":"bafkreic7kytcoyczzwc3bqi33wh7n7lejkxbrdruq2lpk2feowd2wf22je"}}},"objects":{"dmap":{"objectname":"dmap","typename":"Dmap","address":"0x6dAa8F4b23D220Ce08a4CFDb040eE705E643e449","artifact":{"/":"bafkreig6eylwv3ycrp5spwrtevdtllq4rkub44g6gy5c27lpc7hgy33uqi"}},"rootzone":{"objectname":"rootzone","typename":"RootZone","address":"0xEDa48aCC95daFF28f6f56e325d0b8A11802cAD66","artifact":{"/":"bafkreihichgzifyxns7fmhywfugsaad2jbx2buubgcq7ofyg6n6iofp65y"}},"freezone":{"objectname":"freezone","typename":"FreeZone","address":"0xb40832863d5D67d1F4e9d1192a17BAE8aC6a8081","artifact":{"/":"bafkreic7kytcoyczzwc3bqi33wh7n7lejkxbrdruq2lpk2feowd2wf22je"}}}}');
+module.exports = JSON.parse('{"_format":"hh-sol-artifact-1","contractName":"Dmap","sourceName":"core/dmap.sol","abi":[{"inputs":[],"name":"LOCKED","type":"error"},{"anonymous":true,"inputs":[{"indexed":true,"internalType":"address","name":"zone","type":"address"},{"indexed":true,"internalType":"bytes32","name":"name","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"meta","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"data","type":"bytes32"}],"name":"Set","type":"event"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"get","outputs":[{"internalType":"bytes32","name":"meta","type":"bytes32"},{"internalType":"bytes32","name":"data","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"name","type":"bytes32"},{"internalType":"bytes32","name":"meta","type":"bytes32"},{"internalType":"bytes32","name":"data","type":"bytes32"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"}],"bytecode":"0x608060405234801561001057600080fd5b5060405161012e38038061012e83398101604081905261002f91610041565b60016000558060601b60015550610071565b60006020828403121561005357600080fd5b81516001600160a01b038116811461006a57600080fd5b9392505050565b60af8061007f6000396000f3fe608060405236602403602257600435546000526004356001015460205260406000f35b6004356024356044353360005282602052604060002081838533600080a481600182015580546001163660641817605857828155005b505050503660640360745763a1422f6960e01b60005260046000fd5b600080fdfea2646970667358221220475e238f09c07b2df011287cd0b887d9e0864657776ab6a3484c43f79237fefa64736f6c634300080d0033","deployedBytecode":"0x608060405236602403602257600435546000526004356001015460205260406000f35b6004356024356044353360005282602052604060002081838533600080a481600182015580546001163660641817605857828155005b505050503660640360745763a1422f6960e01b60005260046000fd5b600080fdfea2646970667358221220475e238f09c07b2df011287cd0b887d9e0864657776ab6a3484c43f79237fefa64736f6c634300080d0033","linkReferences":{},"deployedLinkReferences":{}}');
 
 /***/ })
 
@@ -302,16 +464,13 @@ module.exports = JSON.parse('{"format":"dpack-1","network":"goerli","types":{"Dm
 /******/ 		}
 /******/ 		// Create a new module (and put it into the cache)
 /******/ 		var module = __webpack_module_cache__[moduleId] = {
-/******/ 			id: moduleId,
-/******/ 			loaded: false,
+/******/ 			// no module.id needed
+/******/ 			// no module.loaded needed
 /******/ 			exports: {}
 /******/ 		};
 /******/ 	
 /******/ 		// Execute the module function
-/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-/******/ 	
-/******/ 		// Flag the module as loaded
-/******/ 		module.loaded = true;
+/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
 /******/ 	
 /******/ 		// Return the exports of the module
 /******/ 		return module.exports;
@@ -358,48 +517,6 @@ module.exports = JSON.parse('{"format":"dpack-1","network":"goerli","types":{"Dm
 /******/ 		};
 /******/ 	})();
 /******/ 	
-/******/ 	/* webpack/runtime/compat get default export */
-/******/ 	(() => {
-/******/ 		// getDefaultExport function for compatibility with non-harmony modules
-/******/ 		__webpack_require__.n = (module) => {
-/******/ 			var getter = module && module.__esModule ?
-/******/ 				() => (module['default']) :
-/******/ 				() => (module);
-/******/ 			__webpack_require__.d(getter, { a: getter });
-/******/ 			return getter;
-/******/ 		};
-/******/ 	})();
-/******/ 	
-/******/ 	/* webpack/runtime/create fake namespace object */
-/******/ 	(() => {
-/******/ 		var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
-/******/ 		var leafPrototypes;
-/******/ 		// create a fake namespace object
-/******/ 		// mode & 1: value is a module id, require it
-/******/ 		// mode & 2: merge all properties of value into the ns
-/******/ 		// mode & 4: return value when already ns object
-/******/ 		// mode & 16: return value when it's Promise-like
-/******/ 		// mode & 8|1: behave like require
-/******/ 		__webpack_require__.t = function(value, mode) {
-/******/ 			if(mode & 1) value = this(value);
-/******/ 			if(mode & 8) return value;
-/******/ 			if(typeof value === 'object' && value) {
-/******/ 				if((mode & 4) && value.__esModule) return value;
-/******/ 				if((mode & 16) && typeof value.then === 'function') return value;
-/******/ 			}
-/******/ 			var ns = Object.create(null);
-/******/ 			__webpack_require__.r(ns);
-/******/ 			var def = {};
-/******/ 			leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
-/******/ 			for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
-/******/ 				Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
-/******/ 			}
-/******/ 			def['default'] = () => (value);
-/******/ 			__webpack_require__.d(ns, def);
-/******/ 			return ns;
-/******/ 		};
-/******/ 	})();
-/******/ 	
 /******/ 	/* webpack/runtime/define property getters */
 /******/ 	(() => {
 /******/ 		// define getter functions for harmony exports
@@ -440,15 +557,6 @@ module.exports = JSON.parse('{"format":"dpack-1","network":"goerli","types":{"Dm
 /******/ 		};
 /******/ 	})();
 /******/ 	
-/******/ 	/* webpack/runtime/node module decorator */
-/******/ 	(() => {
-/******/ 		__webpack_require__.nmd = (module) => {
-/******/ 			module.paths = [];
-/******/ 			if (!module.children) module.children = [];
-/******/ 			return module;
-/******/ 		};
-/******/ 	})();
-/******/ 	
 /******/ 	/* webpack/runtime/jsonp chunk loading */
 /******/ 	(() => {
 /******/ 		// no baseURI
@@ -507,7 +615,7 @@ module.exports = JSON.parse('{"format":"dpack-1","network":"goerli","types":{"Dm
 /******/ 	// startup
 /******/ 	// Load entry module and return exports
 /******/ 	// This entry module depends on other loaded chunks and execution need to be delayed
-/******/ 	var __webpack_exports__ = __webpack_require__.O(undefined, [697], () => (__webpack_require__(2220)))
+/******/ 	var __webpack_exports__ = __webpack_require__.O(undefined, [697], () => (__webpack_require__(220)))
 /******/ 	__webpack_exports__ = __webpack_require__.O(__webpack_exports__);
 /******/ 	
 /******/ })()
diff --git a/docs/old-readme.md b/docs/old-readme.md
deleted file mode 100644
index 6cd9bd7..0000000
--- a/docs/old-readme.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# dmap
-
-- `dmap` is a key-value store
-- It supports user-defined registries, but all values are stored in one contract
-- + Traversal proofs do not need to spin up an EVM or execute arbitrary logic
-- `dpath` is a path format with a concept of 'verify immutable'
-- + example: `:stone:rock.backdoored.subreg`
-- + `:stone:rock` will always resolve to the same value, but from there `.backdoored.subreg` could change
-- Values have flags
-- + dmap defines one core flag: `locked`
-- + the `locked` flag lets you to verify that an entry is immutable without having to audit external logic
-- + The 255 'user' flags are open to interpretation by other protocols
-- + The 1st user flag is `dir`, used to define hierarchal resolution
-
-If you are concerned about web3 decentralization, you should do the following right now:
-
-- Sync an ETH light client to your actual physical computer.
-- Spin up an ETH2 validator on a server that you physically control, if you can afford to. Pool on rocketpool if you can't.
-- Store critical values for your dapp in dmap. Consider storing a [dpack](https://github.com/dapphub/dpack) CID.
-- + A create-only registry at `:free:yourapp*` is a good stopgap solution.
-- Write your own `dmap` client that talks directly to your ETH node.
-- + Make sure your client verifies state trie proofs.
-- Remove dependency on DNS for resolution and SSL for authentication
-- + You need to verify merkle proofs for ETH values
-- + You need to verify CIDs for IPFS values
diff --git a/docs/webpack.config.js b/docs/webpack.config.js
index 9fe77f0..d27761c 100644
--- a/docs/webpack.config.js
+++ b/docs/webpack.config.js
@@ -10,11 +10,6 @@ module.exports = {
         path: path.resolve(__dirname),
         filename: '[name].unmin.js',
     },
-    plugins: [
-        new webpack.ProvidePlugin({
-            Buffer: ['buffer', 'Buffer'],
-        })
-    ],
     optimization: {
         minimize: false,
         splitChunks: {
diff --git a/hardhat.config.js b/hardhat.config.js
index becf376..53df787 100644
--- a/hardhat.config.js
+++ b/hardhat.config.js
@@ -1,6 +1,6 @@
 require('@nomiclabs/hardhat-ethers')
 
-require('./dmap-mock-deploy.js')
+require('./mock-deploy.js')
 
 /**
  * @type import('hardhat/config').HardhatUserConfig
diff --git a/dmap-mock-deploy.js b/mock-deploy.js
similarity index 97%
rename from dmap-mock-deploy.js
rename to mock-deploy.js
index d08d10b..41f2bc8 100644
--- a/dmap-mock-deploy.js
+++ b/mock-deploy.js
@@ -67,7 +67,7 @@ task('dmap-mock-deploy', async (args, hh)=> {
 
     const show =(o)=> JSON.stringify(o, null, 2)
 
-    fs.writeFileSync(packdir + `Dmap.json`, show(dmap_type))
+    fs.writeFileSync(packdir + `MockDmap.json`, show(dmap_type))
     fs.writeFileSync(packdir + `RootZone.json`, show(root_type))
     fs.writeFileSync(packdir + `FreeZone.json`, show(free_type))
 
diff --git a/pack/dmap_core_ethereum.dpack.json b/pack/dmap.json
similarity index 100%
rename from pack/dmap_core_ethereum.dpack.json
rename to pack/dmap.json
diff --git a/pack/Dmap.json b/pack/ipfs/Dmap.json
similarity index 100%
rename from pack/Dmap.json
rename to pack/ipfs/Dmap.json
diff --git a/pack/FreeZone.json b/pack/ipfs/FreeZone.json
similarity index 100%
rename from pack/FreeZone.json
rename to pack/ipfs/FreeZone.json
diff --git a/pack/RootZone.json b/pack/ipfs/RootZone.json
similarity index 100%
rename from pack/RootZone.json
rename to pack/ipfs/RootZone.json
diff --git a/pack/dmap_full_ethereum.dpack.json b/pack/root-and-free.json
similarity index 100%
rename from pack/dmap_full_ethereum.dpack.json
rename to pack/root-and-free.json
diff --git a/package.json b/package.json
index 35fb36d..eee6a38 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,6 @@
     "@nomiclabs/hardhat-ethers": "^2.0.5",
     "@types/mocha": "^9.0.0",
     "hardhat": "^2.8.3",
-    "ipfs-http-client": "^56.0.2",
     "minihat": "^0.0.5",
     "web3-utils": "^1.7.1",
     "webpack": "^5.70.0",
@@ -19,6 +18,7 @@
   },
   "dependencies": {
     "ebnf": "^1.9.0",
+    "js-sha3": "^0.8.0",
     "tapzero": "^0.6.1"
   }
 }
diff --git a/readme.txt b/readme.txt
new file mode 100644
index 0000000..3f06f84
--- /dev/null
+++ b/readme.txt
@@ -0,0 +1,7 @@
+This is the state of the dmap repo shortly after deployment.
+Here is the dmap address: 0x90949c9937A11BA943C7A72C3FA073a37E3FdD96
+
+We are keeping this repo here for reference but development is now
+fragmented across many repos. There is no 'official' dmap project repo,
+dmap is defined by one simple object that treats every caller identically.
+
diff --git a/test/free-test.js b/test/free-test.js
index 359f273..230e691 100644
--- a/test/free-test.js
+++ b/test/free-test.js
@@ -7,7 +7,8 @@ const coder = ethers.utils.defaultAbiCoder
 const keccak256 = ethers.utils.keccak256
 const { b32, fail, revert, send, snapshot, want, mine } = require('minihat')
 const { bounds } = require('./bounds')
-const lib = require('../dmap.js')
+global.window = {}
+const utils = require('../docs/main')
 const {expectEvent, check_gas, testlib} = require("./utils/helpers");
 const constants = ethers.constants
 
@@ -132,31 +133,29 @@ describe('freezone', ()=>{
         await fail('LOCKED()', freezone.set, name, lock, data1)
     })
 
-    /*
     it('store CID variants', async ()=>{
         const cids = [cidDefault, cidSHA3, cidV0, cidBlake2b160]
         for (const [index, cid] of cids.entries()) {
             const name = b32(index.toString())
             await send(freezone.take, name)
-            const [meta, data] = lib.prepareCID(cid, false)
+            const [meta, data] = utils.prepareCID(cid, false)
             await send(freezone.set, name, meta, data)
 
-            const[lock_meta, lock_data] = lib.prepareCID(cid, true)
+            const[lock_meta, lock_data] = utils.prepareCID(cid, true)
             await send(freezone.set, name, lock_meta, lock_data)
             await fail('LOCK', freezone.set, name, lock_meta, lock_data)
 
             const slot = keccak256(coder.encode(["address", "bytes32"], [freezone.address, name]))
             const [read_meta, read_data] = await testlib.get(dmap, slot)
-            const res_cid = lib.unpackCID(read_meta, read_data)
-            const helper_cid = await lib.readCID(dmap, 'free:' + index.toString())
+            const res_cid = utils.unpackCID(read_meta, read_data)
+            const helper_cid = await utils.readCID(dmap, 'free:' + index.toString())
             want(cid).eq(res_cid)
             want(cid).eq(helper_cid)
         }
     })
-     */
 
     it('store 512 CID', async ()=>{
-        assert.throws(() => { lib.prepareCID(cid512, false) }, /Hash exceeds 256 bits/);
+        assert.throws(() => { utils.prepareCID(cid512, false) }, /Hash exceeds 256 bits/);
     })
 
     describe('Give event', () => {
diff --git a/test/utils/helpers.js b/test/utils/helpers.js
index e15f3f6..6d330f0 100644
--- a/test/utils/helpers.js
+++ b/test/utils/helpers.js
@@ -67,16 +67,16 @@ const check_entry = async (dmap, usr, key, _meta, _data) => {
     const meta = typeof(_meta) == 'string' ? _meta : '0x'+_meta.toString('hex')
     const data = typeof(_data) == 'string' ? _data : '0x'+_data.toString('hex')
     const resZoneName = await lib.getByZoneAndName(dmap, usr, key)
-    want(resZoneName.meta).to.eql(meta)
-    want(resZoneName.data).to.eql(data)
+    want(resZoneName[0]).to.eql(meta)
+    want(resZoneName[1]).to.eql(data)
     want(resZoneName).to.eql([meta, data])
 
     const coder = ethers.utils.defaultAbiCoder
     const keccak256 = ethers.utils.keccak256
     const slot = keccak256(coder.encode(["address", "bytes32"], [usr, key]))
     const resGet = await testlib.get(dmap, slot)
-    want(resGet.meta).to.eql(meta)
-    want(resGet.data).to.eql(data)
+    want(resGet[0]).to.eql(meta)
+    want(resGet[1]).to.eql(data)
     want(resGet).to.eql([meta, data])
 
     const nextslot = ethers.utils.hexZeroPad(