diff --git a/patches/@nimiq+ledger-api+3.1.1.patch b/patches/@nimiq+ledger-api+3.1.1.patch index 1ebc84c7..b6da8e1f 100644 --- a/patches/@nimiq+ledger-api+3.1.1.patch +++ b/patches/@nimiq+ledger-api+3.1.1.patch @@ -10,7 +10,7 @@ index b05f20b..b609e35 100644 + // TODO either automatically adapt the version, based on @nimiq/core's package.json (here in the patch, or in the + // the Ledger API itself), or ideally make the dependency an external one in the Ledger API, and try to inject it + // in vue.config.js. -+ ? '/nimiq/v2.0.5/web/' ++ ? '/nimiq/v2.0.5-history-fix/web/' // In other cases load @nimiq/core-web@next from jsdelivr. Load from cdn to avoid bundling a copy of core if it's // not needed. This way, we also don't need to handle the wasm file in the rollup config. : 'https://cdn.jsdelivr.net/npm/@nimiq/core@next/web/'; @@ -81,7 +81,7 @@ index 5b18143..6a45b5f 100644 + // TODO either automatically adapt the version, based on @nimiq/core's package.json (here in the patch, or in the + // the Ledger API itself), or ideally make the dependency an external one in the Ledger API, and try to inject it + // in vue.config.js. -+ ? '/nimiq/v2.0.5/web/' ++ ? '/nimiq/v2.0.5-history-fix/web/' // In other cases load @nimiq/core-web@next from jsdelivr. Load from cdn to avoid bundling a copy of core if it's // not needed. This way, we also don't need to handle the wasm file in the rollup config. : 'https://cdn.jsdelivr.net/npm/@nimiq/core@next/web/'; diff --git a/public/nimiq/2.0.5-history-fix/launcher/browser/.gitkeep b/public/nimiq/2.0.5-history-fix/launcher/browser/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/public/nimiq/2.0.5-history-fix/launcher/browser/client-proxy.mjs b/public/nimiq/2.0.5-history-fix/launcher/browser/client-proxy.mjs new file mode 100644 index 00000000..3ca495ad --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/launcher/browser/client-proxy.mjs @@ -0,0 +1,63 @@ +// launcher/client-proxy.ts +function clientFactory(workerFactory, comlinkWrapper) { + return { + async create(config) { + const worker = workerFactory(); + await new Promise((resolve) => { + const readyListener = (event) => { + removeEventListener(worker, "message", readyListener); + if (getEventData(event) === "NIMIQ_ONLOAD") resolve(); + }; + addEventListener(worker, "message", readyListener); + }); + console.debug("Client WASM worker loaded"); + const client = comlinkWrapper(worker); + if (typeof window !== "undefined") { + window.addEventListener("offline", () => worker.postMessage("offline")); + window.addEventListener("online", () => worker.postMessage("online")); + } + if (typeof document !== "undefined") { + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") { + worker.postMessage("visible"); + } + }); + } + console.debug("Sending NIMIQ_INIT message to client worker"); + worker.postMessage({ + type: "NIMIQ_INIT", + config + }); + await new Promise((resolve, reject) => { + addEventListener(worker, "message", (event) => { + const eventData = getEventData(event); + if (!("ok" in eventData)) return; + if (eventData.ok === true) resolve(); + if (eventData.ok === false && "error" in eventData && typeof eventData.error === "string") { + const error = new Error(eventData.error); + if ("stack" in eventData && typeof eventData.stack === "string") { + error.stack = eventData.stack; + } + reject(error); + } + }); + }); + console.debug("Have client worker remote"); + return client; + } + }; +} +function addEventListener(worker, type, listener) { + const method = "addListener" in worker ? "addListener" : "addEventListener"; + worker[method](type, listener); +} +function removeEventListener(worker, type, listener) { + const method = "removeListener" in worker ? "removeListener" : "removeEventListener"; + worker[method](type, listener); +} +function getEventData(event) { + return typeof event === "object" && "data" in event ? event.data : event; +} +export { + clientFactory +}; diff --git a/public/nimiq/2.0.5-history-fix/launcher/browser/cryptoutils-worker-proxy.mjs b/public/nimiq/2.0.5-history-fix/launcher/browser/cryptoutils-worker-proxy.mjs new file mode 100644 index 00000000..ffcb9820 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/launcher/browser/cryptoutils-worker-proxy.mjs @@ -0,0 +1,38 @@ +// launcher/cryptoutils-worker-proxy.ts +var remote; +function cryptoUtilsWorkerFactory(workerFactory, comlinkWrapper) { + const proxy = {}; + ["otpKdf"].forEach((method) => { + proxy[method] = async function() { + remote = remote || await startWorker(workerFactory, comlinkWrapper); + return remote[method](...arguments); + }; + }); + return proxy; +} +async function startWorker(workerFactory, comlinkWrapper) { + const worker = workerFactory(); + await new Promise((resolve) => { + const readyListener = (event) => { + removeEventListener(worker, "message", readyListener); + if (getEventData(event) === "NIMIQ_ONLOAD") resolve(); + }; + addEventListener(worker, "message", readyListener); + }); + console.debug("Have crypto worker remote"); + return comlinkWrapper(worker); +} +function addEventListener(worker, type, listener) { + const method = "addListener" in worker ? "addListener" : "addEventListener"; + worker[method](type, listener); +} +function removeEventListener(worker, type, listener) { + const method = "removeListener" in worker ? "removeListener" : "removeEventListener"; + worker[method](type, listener); +} +function getEventData(event) { + return typeof event === "object" && "data" in event ? event.data : event; +} +export { + cryptoUtilsWorkerFactory +}; diff --git a/public/nimiq/2.0.5-history-fix/launcher/browser/transfer-handlers.mjs b/public/nimiq/2.0.5-history-fix/launcher/browser/transfer-handlers.mjs new file mode 100644 index 00000000..4d2b4516 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/launcher/browser/transfer-handlers.mjs @@ -0,0 +1,27 @@ +// launcher/transfer-handlers.ts +function setupMainThreadTransferHandlers(Comlink, classes) { + Comlink.transferHandlers.set("function", { + canHandle: (obj) => typeof obj === "function", + serialize(obj) { + return Comlink.transferHandlers.get("proxy").serialize(obj); + } + // deserialize(plain) {}, // Cannot receive functions from worker + }); + function canBeSerialized(obj) { + return obj instanceof classes.Address || obj instanceof classes.Transaction; + } + Comlink.transferHandlers.set("plain", { + canHandle: (obj) => canBeSerialized(obj) || Array.isArray(obj) && obj.some((item) => canBeSerialized(item)), + serialize(obj) { + if (Array.isArray(obj)) { + return [obj.map((item) => canBeSerialized(item) ? item.serialize() : item), []]; + } else { + return [obj.serialize(), []]; + } + } + // deserialize(plain) {}, // Cannot receive class instances from worker + }); +} +export { + setupMainThreadTransferHandlers +}; diff --git a/public/nimiq/2.0.5-history-fix/lib/web/index.mjs b/public/nimiq/2.0.5-history-fix/lib/web/index.mjs new file mode 100644 index 00000000..3f57ca13 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/lib/web/index.mjs @@ -0,0 +1,1156 @@ +// lib/ArrayUtils.ts +var ArrayUtils = class { + static subarray(uintarr, begin = 0, end = uintarr.byteLength) { + function clamp(v, min, max) { + return v < min ? min : v > max ? max : v; + } + begin = clamp(begin, 0, uintarr.byteLength); + end = clamp(end, 0, uintarr.byteLength); + let len = end - begin; + if (len < 0) len = 0; + return new Uint8Array(uintarr.buffer, uintarr.byteOffset + begin, len); + } +}; + +// lib/NumberUtils.ts +var NumberUtils = class _NumberUtils { + static UINT8_MAX = 255; + static UINT16_MAX = 65535; + static UINT32_MAX = 4294967295; + static UINT64_MAX = Number.MAX_SAFE_INTEGER; + static isInteger(val) { + return Number.isInteger(val); + } + static isUint8(val) { + return _NumberUtils.isInteger(val) && val >= 0 && val <= _NumberUtils.UINT8_MAX; + } + static isUint16(val) { + return _NumberUtils.isInteger(val) && val >= 0 && val <= _NumberUtils.UINT16_MAX; + } + static isUint32(val) { + return _NumberUtils.isInteger(val) && val >= 0 && val <= _NumberUtils.UINT32_MAX; + } + static isUint64(val) { + return _NumberUtils.isInteger(val) && val >= 0 && val <= _NumberUtils.UINT64_MAX; + } +}; + +// lib/StringUtils.ts +var StringUtils = class _StringUtils { + static isWellFormed(str) { + return typeof str.isWellFormed === "function" ? str.isWellFormed() : _StringUtils._isWellFormedUnicode(str); + } + static isHex(str) { + return /^[0-9A-Fa-f]*$/.test(str); + } + static isHexBytes(str, length) { + if (!_StringUtils.isHex(str)) return false; + if (str.length % 2 !== 0) return false; + if (typeof length === "number" && str.length / 2 !== length) return false; + return true; + } + /** + * Copied from: + * https://github.com/ljharb/es-abstract/blob/main/2024/IsStringWellFormedUnicode.js + */ + static _isWellFormedUnicode(string) { + var len = string.length; + var k = 0; + while (k < len) { + var cp = _StringUtils._codePointAt(string, k); + if (cp["[[IsUnpairedSurrogate]]"]) { + return false; + } + k += cp["[[CodeUnitCount]]"]; + } + return true; + } + /** + * Copied from: + * https://github.com/ljharb/es-abstract/blob/main/2024/CodePointAt.js + */ + static _codePointAt(string, position) { + var size = string.length; + if (position < 0 || position >= size) { + throw new Error("Assertion failed: `position` must be >= 0, and < the length of `string`"); + } + var first = string.charCodeAt(position); + var cp = string.charAt(position); + var firstIsLeading = _StringUtils._isLeadingSurrogate(first); + var firstIsTrailing = _StringUtils._isTrailingSurrogate(first); + if (!firstIsLeading && !firstIsTrailing) { + return { + "[[CodePoint]]": cp, + "[[CodeUnitCount]]": 1, + "[[IsUnpairedSurrogate]]": false + }; + } + if (firstIsTrailing || position + 1 === size) { + return { + "[[CodePoint]]": cp, + "[[CodeUnitCount]]": 1, + "[[IsUnpairedSurrogate]]": true + }; + } + var second = string.charCodeAt(position + 1); + if (!_StringUtils._isTrailingSurrogate(second)) { + return { + "[[CodePoint]]": cp, + "[[CodeUnitCount]]": 1, + "[[IsUnpairedSurrogate]]": true + }; + } + return { + "[[CodePoint]]": _StringUtils._utf16SurrogatePairToCodePoint(first, second), + "[[CodeUnitCount]]": 2, + "[[IsUnpairedSurrogate]]": false + }; + } + /** + * Copied from: + * https://github.com/ljharb/es-abstract/blob/main/helpers/isLeadingSurrogate.js + */ + static _isLeadingSurrogate(charCode) { + return charCode >= 55296 && charCode <= 56319; + } + /** + * Copied from: + * https://github.com/ljharb/es-abstract/blob/main/helpers/isTrailingSurrogate.js + */ + static _isTrailingSurrogate(charCode) { + return charCode >= 56320 && charCode <= 57343; + } + /** + * Copied from: + * https://github.com/ljharb/es-abstract/blob/main/2024/UTF16SurrogatePairToCodePoint.js + */ + static _utf16SurrogatePairToCodePoint(lead, trail) { + if (!_StringUtils._isLeadingSurrogate(lead) || !_StringUtils._isTrailingSurrogate(trail)) { + throw new Error( + "Assertion failed: `lead` must be a leading surrogate char code, and `trail` must be a trailing surrogate char code" + ); + } + return String.fromCharCode(lead) + String.fromCharCode(trail); + } +}; + +// lib/SerialBuffer.ts +var SerialBuffer = class _SerialBuffer extends Uint8Array { + _view; + _readPos; + _writePos; + static EMPTY = new _SerialBuffer(0); + constructor(bufferOrArrayOrLength) { + super(bufferOrArrayOrLength); + this._view = new DataView(this.buffer); + this._readPos = 0; + this._writePos = 0; + } + subarray(start, end) { + return ArrayUtils.subarray(this, start, end); + } + get readPos() { + return this._readPos; + } + set readPos(value) { + if (value < 0 || value > this.byteLength) throw `Invalid readPos ${value}`; + this._readPos = value; + } + get writePos() { + return this._writePos; + } + set writePos(value) { + if (value < 0 || value > this.byteLength) throw `Invalid writePos ${value}`; + this._writePos = value; + } + /** + * Resets the read and write position of the buffer to zero. + */ + reset() { + this._readPos = 0; + this._writePos = 0; + } + read(length) { + const value = this.subarray(this._readPos, this._readPos + length); + this._readPos += length; + return new Uint8Array(value); + } + write(array) { + this.set(array, this._writePos); + this._writePos += array.byteLength; + } + readUint8() { + return this._view.getUint8(this._readPos++); + } + writeUint8(value) { + this._view.setUint8(this._writePos++, value); + } + readUint16() { + const value = this._view.getUint16(this._readPos); + this._readPos += 2; + return value; + } + writeUint16(value) { + this._view.setUint16(this._writePos, value); + this._writePos += 2; + } + readUint32() { + const value = this._view.getUint32(this._readPos); + this._readPos += 4; + return value; + } + writeUint32(value) { + this._view.setUint32(this._writePos, value); + this._writePos += 4; + } + readUint64() { + const value = this._view.getUint32(this._readPos) * Math.pow(2, 32) + this._view.getUint32(this._readPos + 4); + if (!NumberUtils.isUint64(value)) throw new Error("Malformed value"); + this._readPos += 8; + return value; + } + writeUint64(value) { + if (!NumberUtils.isUint64(value)) throw new Error("Malformed value"); + this._view.setUint32(this._writePos, Math.floor(value / Math.pow(2, 32))); + this._view.setUint32(this._writePos + 4, value); + this._writePos += 8; + } + // Copied from: https://github.com/chrisdickinson/varint/blob/master/decode.js + readVarUint() { + let res = 0; + let shift = 0; + let b; + do { + if (shift > 49) { + throw new RangeError("Could not decode varint"); + } + b = this.readUint8(); + res += shift < 28 ? (b & VARINT_REST) << shift : (b & VARINT_REST) * Math.pow(2, shift); + shift += 7; + } while (b >= VARINT_MSB); + return res; + } + // Copied from: https://github.com/chrisdickinson/varint/blob/master/encode.js + writeVarUint(value) { + if (Number.MAX_SAFE_INTEGER && value > Number.MAX_SAFE_INTEGER) { + throw new RangeError("Could not encode varint"); + } + while (value >= VARINT_INT) { + this.writeUint8(value & 255 | VARINT_MSB); + value /= 128; + } + while (value & VARINT_MSBALL) { + this.writeUint8(value & 255 | VARINT_MSB); + value >>>= 7; + } + this.writeUint8(value | 0); + } + // Copied from: https://github.com/chrisdickinson/varint/blob/master/length.js + static varUintSize(value) { + if (value < Math.pow(2, 7)) return 1; + if (value < Math.pow(2, 14)) return 2; + if (value < Math.pow(2, 21)) return 3; + if (value < Math.pow(2, 28)) return 4; + if (value < Math.pow(2, 35)) return 5; + if (value < Math.pow(2, 42)) return 6; + if (value < Math.pow(2, 49)) return 7; + if (value < Math.pow(2, 56)) return 8; + if (value < Math.pow(2, 93)) return 9; + return 10; + } + readFloat64() { + const value = this._view.getFloat64(this._readPos); + this._readPos += 8; + return value; + } + writeFloat64(value) { + this._view.setFloat64(this._writePos, value); + this._writePos += 8; + } + readString(length) { + const bytes = this.read(length); + return BufferUtils.toUtf8(bytes); + } + writeString(value, length) { + if (!StringUtils.isWellFormed(value) || value.length !== length) throw new Error("Malformed value/length"); + const bytes = BufferUtils.fromUtf8(value); + this.write(bytes); + } + readPaddedString(length) { + const bytes = this.read(length); + let i = 0; + while (i < length && bytes[i] !== 0) i++; + const view = new Uint8Array(bytes.buffer, bytes.byteOffset, i); + return BufferUtils.toUtf8(view); + } + writePaddedString(value, length) { + if (!StringUtils.isWellFormed(value) || value.length > length) throw new Error("Malformed value/length"); + const bytes = BufferUtils.fromUtf8(value); + this.write(bytes); + const padding = length - bytes.byteLength; + this.write(new Uint8Array(padding)); + } + readVarLengthString() { + const length = this.readVarUint(); + if (this._readPos + length > this.length) throw new Error("Malformed length"); + const bytes = this.read(length); + return BufferUtils.toUtf8(bytes); + } + writeVarLengthString(value) { + if (!StringUtils.isWellFormed(value)) throw new Error("Malformed value"); + const bytes = BufferUtils.fromUtf8(value); + this.writeVarUint(bytes.byteLength); + this.write(bytes); + } + static varLengthStringSize(value) { + if (!StringUtils.isWellFormed(value)) throw new Error("Malformed value"); + const bytes = BufferUtils.fromUtf8(value); + return _SerialBuffer.varUintSize(bytes.byteLength) + bytes.byteLength; + } +}; +var VARINT_MSB = 128; +var VARINT_REST = 127; +var VARINT_MSBALL = ~VARINT_REST; +var VARINT_INT = Math.pow(2, 31); + +// lib/BufferUtils.ts +var BufferUtils = class _BufferUtils { + static BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + static BASE32_ALPHABET = { + RFC4648: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", + RFC4648_HEX: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", + NIMIQ: "0123456789ABCDEFGHJKLMNPQRSTUVXY" + }; + static HEX_ALPHABET = "0123456789abcdef"; + static _BASE64_LOOKUP = []; + static _ISO_8859_15_DECODER; + static _UTF8_DECODER; + static _UTF8_ENCODER; + static _codePointTextDecoder(buffer) { + if (typeof TextDecoder === "undefined") throw new Error("TextDecoder not supported"); + if (_BufferUtils._ISO_8859_15_DECODER === null) throw new Error("TextDecoder does not support iso-8859-15"); + if (_BufferUtils._ISO_8859_15_DECODER === void 0) { + try { + _BufferUtils._ISO_8859_15_DECODER = new TextDecoder("iso-8859-15"); + } catch (e) { + _BufferUtils._ISO_8859_15_DECODER = null; + throw new Error("TextDecoder does not support iso-8859-15"); + } + } + const uint8View = _BufferUtils._toUint8View(buffer); + return _BufferUtils._ISO_8859_15_DECODER.decode(uint8View).replace(/\u20ac/g, "\xA4").replace(/\u0160/g, "\xA6").replace(/\u0161/g, "\xA8").replace(/\u017d/g, "\xB4").replace(/\u017e/g, "\xB8").replace(/\u0152/g, "\xBC").replace(/\u0153/g, "\xBD").replace(/\u0178/g, "\xBE"); + } + static _tripletToBase64(num) { + return _BufferUtils._BASE64_LOOKUP[num >> 18 & 63] + _BufferUtils._BASE64_LOOKUP[num >> 12 & 63] + _BufferUtils._BASE64_LOOKUP[num >> 6 & 63] + _BufferUtils._BASE64_LOOKUP[num & 63]; + } + static _base64encodeChunk(u8, start, end) { + let tmp; + const output = []; + for (let i = start; i < end; i += 3) { + tmp = (u8[i] << 16 & 16711680) + (u8[i + 1] << 8 & 65280) + (u8[i + 2] & 255); + output.push(_BufferUtils._tripletToBase64(tmp)); + } + return output.join(""); + } + static _base64fromByteArray(u8) { + let tmp; + const len = u8.length; + const extraBytes = len % 3; + let output = ""; + const parts = []; + const maxChunkLength = 16383; + for (let i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push( + _BufferUtils._base64encodeChunk(u8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength) + ); + } + if (extraBytes === 1) { + tmp = u8[len - 1]; + output += _BufferUtils._BASE64_LOOKUP[tmp >> 2]; + output += _BufferUtils._BASE64_LOOKUP[tmp << 4 & 63]; + output += "=="; + } else if (extraBytes === 2) { + tmp = (u8[len - 2] << 8) + u8[len - 1]; + output += _BufferUtils._BASE64_LOOKUP[tmp >> 10]; + output += _BufferUtils._BASE64_LOOKUP[tmp >> 4 & 63]; + output += _BufferUtils._BASE64_LOOKUP[tmp << 2 & 63]; + output += "="; + } + parts.push(output); + return parts.join(""); + } + static toBase64(buffer) { + if (typeof Buffer !== "undefined") { + return Buffer.from(buffer).toString("base64"); + } + if (typeof TextDecoder !== "undefined" && _BufferUtils._ISO_8859_15_DECODER !== null) { + try { + return btoa(_BufferUtils._codePointTextDecoder(buffer)); + } catch (e) { + } + } + return _BufferUtils._base64fromByteArray(_BufferUtils._toUint8View(buffer)); + } + static fromBase64(base64, length) { + let arr; + if (typeof Buffer !== "undefined") { + arr = Buffer.from(base64, "base64"); + } else { + arr = new Uint8Array(atob(base64).split("").map((c) => c.charCodeAt(0))); + } + if (length !== void 0 && arr.length !== length) { + throw new Error("Decoded length does not match expected length"); + } + return new SerialBuffer(arr); + } + static toBase64Url(buffer) { + return _BufferUtils.toBase64(buffer).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); + } + static fromBase64Url(base64, length) { + return _BufferUtils.fromBase64(base64.replace(/_/g, "/").replace(/-/g, "+").replace(/\./g, "="), length); + } + static toBase32(buf, alphabet = _BufferUtils.BASE32_ALPHABET.NIMIQ) { + let shift = 3, carry = 0, byte, symbol, i, res = ""; + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + symbol = carry | byte >> shift; + res += alphabet[symbol & 31]; + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + res += alphabet[symbol & 31]; + } + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + if (shift !== 3) { + res += alphabet[carry & 31]; + } + while (res.length % 8 !== 0 && alphabet.length === 33) { + res += alphabet[32]; + } + return res; + } + static fromBase32(base32, alphabet = _BufferUtils.BASE32_ALPHABET.NIMIQ) { + const charmap = {}; + alphabet.toUpperCase().split("").forEach((c, i) => { + if (!(c in charmap)) charmap[c] = i; + }); + let symbol, shift = 8, carry = 0, buf = []; + base32.toUpperCase().split("").forEach((char) => { + if (alphabet.length === 33 && char === alphabet[32]) return; + symbol = charmap[char] & 255; + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | symbol >> -shift); + shift += 8; + carry = symbol << shift & 255; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + if (shift !== 8 && carry !== 0) { + buf.push(carry); + } + return new Uint8Array(buf); + } + static toHex(buffer) { + let hex = ""; + for (let i = 0; i < buffer.length; i++) { + const code = buffer[i]; + hex += _BufferUtils.HEX_ALPHABET[code >>> 4]; + hex += _BufferUtils.HEX_ALPHABET[code & 15]; + } + return hex; + } + static fromHex(hex, length) { + hex = hex.trim(); + if (!StringUtils.isHexBytes(hex, length)) throw new Error("String is not a hex string (of matching length)"); + return new SerialBuffer(new Uint8Array((hex.match(/.{2}/g) || []).map((byte) => parseInt(byte, 16)))); + } + static _utf8TextEncoder(str) { + if (typeof TextEncoder === "undefined") throw new Error("TextEncoder not supported"); + if (_BufferUtils._UTF8_ENCODER === null) throw new Error("TextEncoder does not support utf8"); + if (_BufferUtils._UTF8_ENCODER === void 0) { + try { + _BufferUtils._UTF8_ENCODER = new TextEncoder(); + } catch (e) { + _BufferUtils._UTF8_ENCODER = null; + throw new Error("TextEncoder does not support utf8"); + } + } + return _BufferUtils._UTF8_ENCODER.encode(str); + } + static fromUtf8(str) { + return _BufferUtils._utf8TextEncoder(str); + } + static _utf8TextDecoder(buf, options) { + if (typeof TextDecoder === "undefined") throw new Error("TextDecoder not supported"); + if (_BufferUtils._UTF8_DECODER === null) throw new Error("TextDecoder does not support utf8"); + if (_BufferUtils._UTF8_DECODER === void 0) { + try { + _BufferUtils._UTF8_DECODER = new TextDecoder("utf-8", options); + } catch (e) { + _BufferUtils._UTF8_DECODER = null; + throw new Error("TextDecoder does not support utf8"); + } + } + return _BufferUtils._UTF8_DECODER.decode(buf); + } + static toUtf8(buf) { + return _BufferUtils._utf8TextDecoder(buf); + } + static fromAny(o, length) { + if (o === "") return SerialBuffer.EMPTY; + if (!o) throw new Error("Invalid buffer format"); + if (o instanceof Uint8Array) return new SerialBuffer(o); + try { + return _BufferUtils.fromHex(o, length); + } catch (e) { + } + try { + return _BufferUtils.fromBase64(o, length); + } catch (e) { + } + throw new Error("Invalid buffer format"); + } + static equals(a, b) { + const viewA = _BufferUtils._toUint8View(a); + const viewB = _BufferUtils._toUint8View(b); + if (viewA.length !== viewB.length) return false; + for (let i = 0; i < viewA.length; i++) { + if (viewA[i] !== viewB[i]) return false; + } + return true; + } + /** + * Returns -1 if a is smaller than b, 1 if a is larger than b, 0 if a equals b. + * Shorter arrays are always considered smaller than longer ones. + */ + static compare(a, b) { + if (a.length < b.length) return -1; + if (a.length > b.length) return 1; + for (let i = 0; i < a.length; i++) { + if (a[i] < b[i]) return -1; + if (a[i] > b[i]) return 1; + } + return 0; + } + static xor(a, b) { + const res = new Uint8Array(a.byteLength); + for (let i = 0; i < a.byteLength; ++i) { + res[i] = a[i] ^ b[i]; + } + return res; + } + static _toUint8View(arrayLike) { + if (arrayLike instanceof Uint8Array) { + return arrayLike; + } else if (arrayLike instanceof ArrayBuffer) { + return new Uint8Array(arrayLike); + } else if (arrayLike.buffer instanceof ArrayBuffer) { + return new Uint8Array(arrayLike.buffer); + } else { + throw new Error("TypedArray or ArrayBuffer required"); + } + } +}; +for (let i = 0, len = BufferUtils.BASE64_ALPHABET.length; i < len; ++i) { + BufferUtils._BASE64_LOOKUP[i] = BufferUtils.BASE64_ALPHABET[i]; +} + +// lib/Entropy.ts +import { CryptoUtils as CryptoUtils4 } from "../../web/index.js"; + +// lib/ExtendedPrivateKey.ts +import { CryptoUtils, PrivateKey, PublicKey } from "../../web/index.js"; + +// lib/Serializable.ts +var Serializable = class _Serializable { + /** + * Checks for equality with another Serializable. + */ + equals(o) { + return o instanceof _Serializable && BufferUtils.equals(this.serialize(), o.serialize()); + } + /** + * Compares this object to another object. + * + * Returns a negative number if `this` is smaller than o, a positive number if `this` is larger than o, and zero if equal. + */ + compare(o) { + return BufferUtils.compare(this.serialize(), o.serialize()); + } + /** + * Formats the object into a hex string. + */ + toString() { + return this.toHex(); + } + /** + * Formats the object into a base64 string. + */ + toBase64() { + return BufferUtils.toBase64(this.serialize()); + } + /** + * Formats the object into a hex string. + */ + toHex() { + return BufferUtils.toHex(this.serialize()); + } +}; + +// lib/ExtendedPrivateKey.ts +var ExtendedPrivateKey = class _ExtendedPrivateKey extends Serializable { + static CHAIN_CODE_SIZE = 32; + _key; + _chainCode; + /** + * Creates an ExtendedPrivateKey from a private key and chain code. + */ + constructor(key, chainCode) { + super(); + if (!(key instanceof PrivateKey)) throw new Error("ExtendedPrivateKey: Invalid key"); + if (!(chainCode instanceof Uint8Array)) throw new Error("ExtendedPrivateKey: Invalid chainCode"); + if (chainCode.length !== _ExtendedPrivateKey.CHAIN_CODE_SIZE) { + throw new Error("ExtendedPrivateKey: Invalid chainCode length"); + } + this._key = key; + this._chainCode = chainCode; + } + /** + * Generates the master ExtendedPrivateKey from a seed. + */ + static generateMasterKey(seed) { + const bCurve = BufferUtils.fromUtf8("ed25519 seed"); + const hash = CryptoUtils.computeHmacSha512(bCurve, seed); + return new _ExtendedPrivateKey(new PrivateKey(hash.slice(0, 32)), hash.slice(32)); + } + /** + * Derives a child ExtendedPrivateKey from the current key at the provided index. + */ + derive(index) { + if (index < 2147483648) index += 2147483648; + const data = new SerialBuffer(1 + PrivateKey.SIZE + 4); + data.writeUint8(0); + data.write(this._key.serialize()); + data.writeUint32(index); + const hash = CryptoUtils.computeHmacSha512(this._chainCode, data); + return new _ExtendedPrivateKey(new PrivateKey(hash.slice(0, 32)), hash.slice(32)); + } + /** + * Tests if a HD derivation path is valid. + */ + static isValidPath(path) { + if (path.match(/^m(\/[0-9]+')*$/) === null) return false; + const segments = path.split("/"); + for (let i = 1; i < segments.length; i++) { + if (!NumberUtils.isUint32(parseInt(segments[i]))) return false; + } + return true; + } + /** + * Derives a child ExtendedPrivateKey from the current key at the provided path. + */ + derivePath(path) { + if (!_ExtendedPrivateKey.isValidPath(path)) throw new Error("Invalid path"); + let extendedKey = this; + const segments = path.split("/"); + for (let i = 1; i < segments.length; i++) { + const index = parseInt(segments[i]); + extendedKey = extendedKey.derive(index); + } + return extendedKey; + } + /** + * Derives an ExtendedPrivateKey from a seed and a derivation path. + */ + static derivePathFromSeed(path, seed) { + let extendedKey = _ExtendedPrivateKey.generateMasterKey(seed); + return extendedKey.derivePath(path); + } + /** + * Deserializes an ExtendedPrivateKey from a byte array. + */ + static deserialize(buf) { + const privateKey = PrivateKey.deserialize(buf); + const chainCode = buf.read(_ExtendedPrivateKey.CHAIN_CODE_SIZE); + return new _ExtendedPrivateKey(privateKey, chainCode); + } + /** + * Deserializes an ExtendedPrivateKey from a hex string. + */ + static fromHex(hex) { + return _ExtendedPrivateKey.deserialize(BufferUtils.fromHex(hex)); + } + /** + * Serializes the ExtendedPrivateKey to a byte array. + */ + serialize(buf) { + buf = buf || new SerialBuffer(this.serializedSize); + buf.write(this._key.serialize()); + buf.write(this._chainCode); + return buf; + } + /** + * Returns the serialized size of this ExtendedPrivateKey. + */ + get serializedSize() { + return this._key.serializedSize + _ExtendedPrivateKey.CHAIN_CODE_SIZE; + } + /** + * Checks for equality with another ExtendedPrivateKey. + */ + equals(o) { + return o instanceof _ExtendedPrivateKey && super.equals(o); + } + /** + * Returns the private key of this ExtendedPrivateKey. + */ + get privateKey() { + return this._key; + } + /** + * Returns the chain code of this ExtendedPrivateKey. + */ + get chainCode() { + return this._chainCode; + } + /** + * Returns the address related to this ExtendedPrivateKey. + */ + toAddress() { + return PublicKey.derive(this._key).toAddress(); + } +}; + +// lib/MnemonicUtils.ts +import { CryptoUtils as CryptoUtils2, Hash } from "../../web/index.js"; + +// lib/CRC8.ts +var CRC8 = class _CRC8 { + static _table = null; + // Adapted from https://github.com/mode80/crc8js + static _createTable() { + const table = []; + for (let i = 0; i < 256; ++i) { + let curr = i; + for (let j = 0; j < 8; ++j) { + if ((curr & 128) !== 0) { + curr = (curr << 1 ^ 151) % 256; + } else { + curr = (curr << 1) % 256; + } + } + table[i] = curr; + } + return table; + } + static compute(buf) { + if (!_CRC8._table) _CRC8._table = _CRC8._createTable(); + let c = 0; + for (let i = 0; i < buf.length; i++) { + c = _CRC8._table[(c ^ buf[i]) % 256]; + } + return c; + } +}; + +// lib/MnemonicUtils.ts +var MnemonicUtils = class _MnemonicUtils { + // Adapted from https://github.com/bitcoinjs/bip39, see license below. + /** + * The English wordlist. + */ + static ENGLISH_WORDLIST; + /** + * The default English wordlist. + */ + static DEFAULT_WORDLIST; + /** + * Converts an Entropy to a mnemonic. + */ + static entropyToMnemonic(entropy, wordlist) { + wordlist = wordlist || _MnemonicUtils.DEFAULT_WORDLIST; + const normalized = _MnemonicUtils._normalizeEntropy(entropy); + const entropyBits = _MnemonicUtils._entropyToBits(normalized); + const checksumBits = _MnemonicUtils._sha256Checksum(normalized); + const bits = entropyBits + checksumBits; + return _MnemonicUtils._bitsToMnemonic(bits, wordlist); + } + /** + * Converts a mnemonic to an Entropy. + */ + static mnemonicToEntropy(mnemonic, wordlist) { + if (!Array.isArray(mnemonic)) mnemonic = mnemonic.trim().split(/\s+/g); + wordlist = wordlist || _MnemonicUtils.DEFAULT_WORDLIST; + const bits = _MnemonicUtils._mnemonicToBits(mnemonic, wordlist); + return new Entropy(_MnemonicUtils._bitsToEntropy(bits, false)); + } + /** + * Converts a mnemonic to a seed. + * + * Optionally takes a password to use for the seed derivation. + */ + static mnemonicToSeed(mnemonic, password) { + if (Array.isArray(mnemonic)) mnemonic = mnemonic.join(" "); + const mnemonicBuffer = BufferUtils.fromUtf8(mnemonic); + const saltBuffer = BufferUtils.fromUtf8(_MnemonicUtils._salt(password)); + return new SerialBuffer(CryptoUtils2.computePBKDF2sha512(mnemonicBuffer, saltBuffer, 2048, 64)); + } + /** + * Converts a mnemonic to an extended private key. + * + * Optionally takes a password to use for the seed derivation. + */ + static mnemonicToExtendedPrivateKey(mnemonic, password) { + const seed = _MnemonicUtils.mnemonicToSeed(mnemonic, password); + return ExtendedPrivateKey.generateMasterKey(seed); + } + /** + * Tests if a mnemonic can be both for a legacy Nimiq wallet and a BIP39 wallet. + */ + static isCollidingChecksum(entropy) { + const normalizedEntropy = _MnemonicUtils._normalizeEntropy(entropy); + return _MnemonicUtils._crcChecksum(normalizedEntropy) === _MnemonicUtils._sha256Checksum(normalizedEntropy); + } + /** + * Gets the type of a mnemonic. + * + * Return values: + * - `0 = MnemonicType.LEGACY`: the mnemonic is for a legacy Nimiq wallet. + * - `1 = MnemonicType.BIP39`: the mnemonic is for a BIP39 wallet. + * - `-1 = MnemonicType.UNKNOWN`: the mnemonic can be for both. + * + * Throws if the menmonic is invalid. + */ + static getMnemonicType(mnemonic, wordlist) { + if (!Array.isArray(mnemonic)) mnemonic = mnemonic.trim().split(/\s+/g); + wordlist = wordlist || _MnemonicUtils.DEFAULT_WORDLIST; + const bits = _MnemonicUtils._mnemonicToBits(mnemonic, wordlist); + let isBIP39 = true; + try { + _MnemonicUtils._bitsToEntropy(bits, false); + } catch (e) { + isBIP39 = false; + } + let isLegacy = true; + try { + _MnemonicUtils._bitsToEntropy(bits, true); + } catch (e) { + isLegacy = false; + } + if (isBIP39 && isLegacy) return _MnemonicUtils.MnemonicType.UNKNOWN; + if (!isBIP39 && !isLegacy) throw new Error("Invalid checksum"); + return isBIP39 ? _MnemonicUtils.MnemonicType.BIP39 : _MnemonicUtils.MnemonicType.LEGACY; + } + static _crcChecksum(entropy) { + const ENT = entropy.length * 8; + const CS = ENT / 32; + const hash = CRC8.compute(entropy); + return _MnemonicUtils._toBinary([hash]).slice(0, CS); + } + static _sha256Checksum(entropy) { + const ENT = entropy.length * 8; + const CS = ENT / 32; + const hash = Hash.computeSha256(entropy); + return _MnemonicUtils._toBinary(hash).slice(0, CS); + } + static _entropyToBits(entropy) { + if (entropy.length < 16) throw new Error("Invalid key, length < 16"); + if (entropy.length > 32) throw new Error("Invalid key, length > 32"); + if (entropy.length % 4 !== 0) throw new Error("Invalid key, length % 4 != 0"); + return _MnemonicUtils._toBinary(entropy); + } + static _normalizeEntropy(entropy) { + let normalized; + if (typeof entropy === "string") normalized = BufferUtils.fromHex(entropy); + else if (entropy instanceof Entropy) normalized = entropy.serialize(); + else if (entropy instanceof ArrayBuffer) normalized = new Uint8Array(entropy); + else normalized = entropy; + return normalized; + } + static _bitsToMnemonic(bits, wordlist) { + const chunks = bits.match(/(.{11})/g); + if (!chunks) throw new Error("Invalid bits, less than 11 characters"); + const words = chunks.map((chunk) => { + const index = _MnemonicUtils._fromBinary(chunk); + return wordlist[index]; + }); + return words; + } + static _mnemonicToBits(mnemonic, wordlist) { + const words = mnemonic; + if (words.length < 12) throw new Error("Invalid mnemonic, less than 12 words"); + if (words.length > 24) throw new Error("Invalid mnemonic, more than 24 words"); + if (words.length % 3 !== 0) throw new Error("Invalid mnemonic, words % 3 != 0"); + const bits = words.map(function(word) { + const index = wordlist.indexOf(word.toLowerCase()); + if (index === -1) throw new Error(`Invalid mnemonic, word >${word}< is not in wordlist`); + return index.toString(2).padStart(11, "0"); + }).join(""); + return bits; + } + static _bitsToEntropy(bits, legacy = false) { + const dividerIndex = bits.length - (bits.length % 8 || 8); + const entropyBits = bits.slice(0, dividerIndex); + const checksumBits = bits.slice(dividerIndex); + const chunks = entropyBits.match(/(.{8})/g); + if (!chunks) throw new Error("Invalid entropyBits, less than 8 characters"); + const entropyBytes = chunks.map(_MnemonicUtils._fromBinary); + if (entropyBytes.length < 16) throw new Error("Invalid generated key, length < 16"); + if (entropyBytes.length > 32) throw new Error("Invalid generated key, length > 32"); + if (entropyBytes.length % 4 !== 0) throw new Error("Invalid generated key, length % 4 != 0"); + const entropy = new Uint8Array(entropyBytes); + const checksum = legacy ? _MnemonicUtils._crcChecksum(entropy) : _MnemonicUtils._sha256Checksum(entropy); + if (checksum !== checksumBits) throw new Error("Invalid checksum"); + return entropy; + } + static _salt(password) { + return `mnemonic${password || ""}`; + } + static _fromBinary(bin) { + return parseInt(bin, 2); + } + static _toBinary(buffer) { + let bin = ""; + for (let i = 0; i < buffer.length; i++) { + const code = buffer[i]; + bin += code.toString(2).padStart(8, "0"); + } + return bin; + } +}; +MnemonicUtils.ENGLISH_WORDLIST = /* dprint-ignore */ +["abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown", "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban", "urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual", "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave", "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife", "wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo"]; +MnemonicUtils.DEFAULT_WORDLIST = MnemonicUtils.ENGLISH_WORDLIST; +((MnemonicUtils2) => { + let MnemonicType; + ((MnemonicType2) => { + MnemonicType2[MnemonicType2["UNKNOWN"] = -1] = "UNKNOWN"; + MnemonicType2[MnemonicType2["LEGACY"] = 0] = "LEGACY"; + MnemonicType2[MnemonicType2["BIP39"] = 1] = "BIP39"; + })(MnemonicType = MnemonicUtils2.MnemonicType || (MnemonicUtils2.MnemonicType = {})); +})(MnemonicUtils || (MnemonicUtils = {})); +Object.freeze(MnemonicUtils); + +// lib/Secret.ts +import { CryptoUtils as CryptoUtils3, Hash as Hash2, PrivateKey as PrivateKey2 } from "../../web/index.js"; +var Secret = class _Secret extends Serializable { + _type; + _purposeId; + static SIZE = 32; + static ENCRYPTION_SALT_SIZE = 16; + static ENCRYPTION_KDF_ROUNDS = 256; + static ENCRYPTION_CHECKSUM_SIZE = 4; + static ENCRYPTION_CHECKSUM_SIZE_V3 = 2; + constructor(type, purposeId) { + super(); + this._type = type; + this._purposeId = purposeId; + } + /** + * Decrypts a Secret from an encrypted byte array and its password. + */ + static async fromEncrypted(buf, key) { + const version = buf.readUint8(); + const roundsLog = buf.readUint8(); + if (roundsLog > 32) throw new Error("Rounds out-of-bounds"); + const rounds = Math.pow(2, roundsLog); + switch (version) { + case 3: + return _Secret._decryptV3(buf, key, rounds); + default: + throw new Error("Unsupported version"); + } + } + static async exportEncrypted(secret, key) { + const salt = CryptoUtils3.getRandomValues(_Secret.ENCRYPTION_SALT_SIZE); + const data = new SerialBuffer( + /*purposeId*/ + 4 + _Secret.SIZE + ); + if (secret instanceof PrivateKey2) { + data.writeUint32(PrivateKey2.PURPOSE_ID); + } else if (secret instanceof Entropy) { + data.writeUint32(Entropy.PURPOSE_ID); + } else { + throw new Error("Unsupported secret type"); + } + data.write(secret.serialize()); + const checksum = Hash2.computeBlake2b(data).subarray(0, _Secret.ENCRYPTION_CHECKSUM_SIZE_V3); + const plaintext = new SerialBuffer(checksum.byteLength + data.byteLength); + plaintext.write(checksum); + plaintext.write(data); + const ciphertext = await CryptoUtils3.otpKdf(plaintext, key, salt, _Secret.ENCRYPTION_KDF_ROUNDS); + const buf = new SerialBuffer( + /*version*/ + 1 + /*kdf rounds*/ + 1 + salt.byteLength + ciphertext.byteLength + ); + buf.writeUint8(3); + buf.writeUint8(Math.log2(_Secret.ENCRYPTION_KDF_ROUNDS)); + buf.write(salt); + buf.write(ciphertext); + return buf; + } + /** + * Encrypts the Secret with a password. + */ + async exportEncrypted(key) { + return _Secret.exportEncrypted(this, key); + } + /** + * Returns the serialized size of this object when encrypted. + */ + get encryptedSize() { + return ( + /*version*/ + 1 + /*kdf rounds*/ + 1 + _Secret.ENCRYPTION_SALT_SIZE + _Secret.ENCRYPTION_CHECKSUM_SIZE_V3 + /*purposeId*/ + 4 + _Secret.SIZE + ); + } + // private static async _decryptV1(buf: SerialBuffer, key: Uint8Array, rounds: number): Promise { + // const ciphertext = buf.read(Secret.SIZE); + // const salt = buf.read(Secret.ENCRYPTION_SALT_SIZE); + // const check = buf.read(Secret.ENCRYPTION_CHECKSUM_SIZE); + // const plaintext = await CryptoUtils.otpKdfLegacy(ciphertext, key, salt, rounds); + // const privateKey = new PrivateKey(plaintext); + // const publicKey = PublicKey.derive(privateKey); + // const checksum = publicKey.hash().subarray(0, Secret.ENCRYPTION_CHECKSUM_SIZE); + // if (!BufferUtils.equals(check, checksum)) { + // throw new Error('Invalid key'); + // } + // return privateKey; + // } + // private static async _decryptV2(buf: SerialBuffer, key: Uint8Array, rounds: number): Promise { + // const ciphertext = buf.read(Secret.SIZE); + // const salt = buf.read(Secret.ENCRYPTION_SALT_SIZE); + // const check = buf.read(Secret.ENCRYPTION_CHECKSUM_SIZE); + // const plaintext = await CryptoUtils.otpKdfLegacy(ciphertext, key, salt, rounds); + // const checksum = Hash.computeBlake2b(plaintext).subarray(0, Secret.ENCRYPTION_CHECKSUM_SIZE); + // if (!BufferUtils.equals(check, checksum)) { + // throw new Error('Invalid key'); + // } + // return new PrivateKey(plaintext); + // } + static async _decryptV3(buf, key, rounds) { + const salt = buf.read(_Secret.ENCRYPTION_SALT_SIZE); + const ciphertext = buf.read(_Secret.ENCRYPTION_CHECKSUM_SIZE_V3 + /*purposeId*/ + 4 + _Secret.SIZE); + const plaintext = await CryptoUtils3.otpKdf(ciphertext, key, salt, rounds); + const check = plaintext.subarray(0, _Secret.ENCRYPTION_CHECKSUM_SIZE_V3); + const payload = plaintext.subarray(_Secret.ENCRYPTION_CHECKSUM_SIZE_V3); + const checksum = Hash2.computeBlake2b(payload).subarray(0, _Secret.ENCRYPTION_CHECKSUM_SIZE_V3); + if (!BufferUtils.equals(check, checksum)) { + throw new Error("Invalid key"); + } + const purposeId = payload[0] << 24 | payload[1] << 16 | payload[2] << 8 | payload[3]; + const secret = payload.subarray(4); + switch (purposeId) { + case PrivateKey2.PURPOSE_ID: + return new PrivateKey2(secret); + case Entropy.PURPOSE_ID: + default: + return new Entropy(secret); + } + } +}; +((Secret2) => { + let Type; + ((Type2) => { + Type2[Type2["PRIVATE_KEY"] = 1] = "PRIVATE_KEY"; + Type2[Type2["ENTROPY"] = 2] = "ENTROPY"; + })(Type = Secret2.Type || (Secret2.Type = {})); +})(Secret || (Secret = {})); + +// lib/Entropy.ts +var Entropy = class _Entropy extends Secret { + static SIZE = Secret.SIZE; + static PURPOSE_ID = 1107296258; + _obj; + /** + * Creates a new Entropy from a byte array. + */ + constructor(arg) { + super(Secret.Type.ENTROPY, _Entropy.PURPOSE_ID); + if (!(arg instanceof Uint8Array)) throw new Error("Primitive: Invalid type"); + if (arg.length !== _Entropy.SIZE) throw new Error("Primitive: Invalid length"); + this._obj = arg; + } + /** + * Generates a new Entropy object from secure randomness. + */ + static generate() { + const entropy = CryptoUtils4.getRandomValues(_Entropy.SIZE); + return new _Entropy(entropy); + } + /** + * Derives an ExtendedPrivateKey from the Entropy. + */ + toExtendedPrivateKey(password, wordlist) { + return MnemonicUtils.mnemonicToExtendedPrivateKey(this.toMnemonic(wordlist), password); + } + /** + * Converts the Entropy into a mnemonic. + */ + toMnemonic(wordlist) { + return MnemonicUtils.entropyToMnemonic(this, wordlist); + } + /** + * Deserializes an Entropy object from a byte array. + */ + static deserialize(buf) { + return new _Entropy(buf.read(_Entropy.SIZE)); + } + /** + * Deserializes an Entropy object from a hex string. + */ + static fromHex(hex) { + return _Entropy.deserialize(BufferUtils.fromHex(hex)); + } + /** + * Serializes the Entropy to a byte array. + */ + serialize(buf) { + buf = buf || new SerialBuffer(this.serializedSize); + buf.write(this._obj); + return buf; + } + /** + * Returns the serialized size of this Entropy. + */ + get serializedSize() { + return _Entropy.SIZE; + } + /** + * Overwrites this Entropy's bytes with a replacement in-memory + */ + overwrite(entropy) { + this._obj.set(entropy._obj); + } + /** + * Checks for equality with another Entropy. + */ + equals(o) { + return o instanceof _Entropy && super.equals(o); + } +}; +export { + ArrayUtils, + BufferUtils, + Entropy, + ExtendedPrivateKey, + MnemonicUtils, + NumberUtils, + Secret, + SerialBuffer, + StringUtils +}; diff --git a/public/nimiq/2.0.5-history-fix/web/comlink.min.js b/public/nimiq/2.0.5-history-fix/web/comlink.min.js new file mode 100644 index 00000000..8aa02e87 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/comlink.min.js @@ -0,0 +1,7 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Comlink={})}(this,(function(e){"use strict"; +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */const t=Symbol("Comlink.proxy"),n=Symbol("Comlink.endpoint"),r=Symbol("Comlink.releaseProxy"),a=Symbol("Comlink.finalizer"),s=Symbol("Comlink.thrown"),o=e=>"object"==typeof e&&null!==e||"function"==typeof e,i=new Map([["proxy",{canHandle:e=>o(e)&&e[t],serialize(e){const{port1:t,port2:n}=new MessageChannel;return c(e,t),[n,[n]]},deserialize:e=>(e.start(),l(e))}],["throw",{canHandle:e=>o(e)&&s in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function c(e,t=globalThis,n=["*"]){t.addEventListener("message",(function r(o){if(!o||!o.data)return;if(!function(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}(n,o.origin))return void console.warn(`Invalid origin '${o.origin}' for comlink proxy`);const{id:i,type:l,path:p}=Object.assign({path:[]},o.data),f=(o.data.argumentList||[]).map(w);let d;try{const t=p.slice(0,-1).reduce(((e,t)=>e[t]),e),n=p.reduce(((e,t)=>e[t]),e);switch(l){case"GET":d=n;break;case"SET":t[p.slice(-1)[0]]=w(o.data.value),d=!0;break;case"APPLY":d=n.apply(t,f);break;case"CONSTRUCT":d=b(new n(...f));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;c(e,n),d=E(t,[t])}break;case"RELEASE":d=void 0;break;default:return}}catch(e){d={value:e,[s]:0}}Promise.resolve(d).catch((e=>({value:e,[s]:0}))).then((n=>{const[s,o]=v(n);t.postMessage(Object.assign(Object.assign({},s),{id:i}),o),"RELEASE"===l&&(t.removeEventListener("message",r),u(t),a in e&&"function"==typeof e[a]&&e[a]())})).catch((e=>{const[n,r]=v({value:new TypeError("Unserializable return value"),[s]:0});t.postMessage(Object.assign(Object.assign({},n),{id:i}),r)}))})),t.start&&t.start()}function u(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function l(e,t){return m(e,[],t)}function p(e){if(e)throw new Error("Proxy has been released and is not useable")}function f(e){return k(e,{type:"RELEASE"}).then((()=>{u(e)}))}const d=new WeakMap,g="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(d.get(e)||0)-1;d.set(e,t),0===t&&f(e)}));function m(e,t=[],a=function(){}){let s=!1;const o=new Proxy(a,{get(n,a){if(p(s),a===r)return()=>{!function(e){g&&g.unregister(e)}(o),f(e),s=!0};if("then"===a){if(0===t.length)return{then:()=>o};const n=k(e,{type:"GET",path:t.map((e=>e.toString()))}).then(w);return n.then.bind(n)}return m(e,[...t,a])},set(n,r,a){p(s);const[o,i]=v(a);return k(e,{type:"SET",path:[...t,r].map((e=>e.toString())),value:o},i).then(w)},apply(r,a,o){p(s);const i=t[t.length-1];if(i===n)return k(e,{type:"ENDPOINT"}).then(w);if("bind"===i)return m(e,t.slice(0,-1));const[c,u]=y(o);return k(e,{type:"APPLY",path:t.map((e=>e.toString())),argumentList:c},u).then(w)},construct(n,r){p(s);const[a,o]=y(r);return k(e,{type:"CONSTRUCT",path:t.map((e=>e.toString())),argumentList:a},o).then(w)}});return function(e,t){const n=(d.get(t)||0)+1;d.set(t,n),g&&g.register(e,t,e)}(o,e),o}function y(e){const t=e.map(v);return[t.map((e=>e[0])),(n=t.map((e=>e[1])),Array.prototype.concat.apply([],n))];var n}const h=new WeakMap;function E(e,t){return h.set(e,t),e}function b(e){return Object.assign(e,{[t]:!0})}function v(e){for(const[t,n]of i)if(n.canHandle(e)){const[r,a]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},a]}return[{type:"RAW",value:e},h.get(e)||[]]}function w(e){switch(e.type){case"HANDLER":return i.get(e.name).deserialize(e.value);case"RAW":return e.value}}function k(e,t,n){return new Promise((r=>{const a=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");e.addEventListener("message",(function t(n){n.data&&n.data.id&&n.data.id===a&&(e.removeEventListener("message",t),r(n.data))})),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),n)}))}e.createEndpoint=n,e.expose=c,e.finalizer=a,e.proxy=b,e.proxyMarker=t,e.releaseProxy=r,e.transfer=E,e.transferHandlers=i,e.windowEndpoint=function(e,t=globalThis,n="*"){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}},e.wrap=l})); +//# sourceMappingURL=comlink.min.js.map diff --git a/public/nimiq/2.0.5-history-fix/web/comlink.min.js.map b/public/nimiq/2.0.5-history-fix/web/comlink.min.js.map new file mode 100644 index 00000000..c6f4f26e --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/comlink.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"comlink.min.js","sources":["../../src/comlink.ts"],"sourcesContent":[null],"names":["proxyMarker","Symbol","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","transferHandlers","Map","canHandle","serialize","obj","port1","port2","MessageChannel","expose","deserialize","port","start","wrap","value","serialized","Error","isError","message","name","stack","Object","assign","ep","globalThis","allowedOrigins","addEventListener","callback","ev","data","origin","allowedOrigin","RegExp","test","isAllowedOrigin","console","warn","id","type","path","argumentList","map","fromWireValue","returnValue","parent","slice","reduce","prop","rawValue","apply","proxy","transfer","undefined","Promise","resolve","catch","then","wireValue","transferables","toWireValue","postMessage","removeEventListener","closeEndPoint","error","TypeError","endpoint","constructor","isMessagePort","close","target","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","WeakMap","proxyFinalizers","FinalizationRegistry","newCount","get","set","isProxyReleased","Proxy","_target","unregister","unregisterProxy","length","r","p","toString","bind","_thisArg","rawArgumentList","last","processArguments","construct","register","registerProxy","processed","v","arr","Array","prototype","concat","transferCache","transfers","handler","serializedValue","msg","fill","Math","floor","random","Number","MAX_SAFE_INTEGER","join","l","w","context","targetOrigin"],"mappings":";;;;;aAiBaA,EAAcC,OAAO,iBACrBC,EAAiBD,OAAO,oBACxBE,EAAeF,OAAO,wBACtBG,EAAYH,OAAO,qBAE1BI,EAAcJ,OAAO,kBAuJrBK,EAAYC,GACA,iBAARA,GAA4B,OAARA,GAAgC,mBAARA,EA+FzCC,EAAmB,IAAIC,IAGlC,CACA,CAAC,QAjEgE,CACjEC,UAAYH,GACVD,EAASC,IAASA,EAAoBP,GACxCW,UAAUC,GACR,MAAMC,MAAEA,EAAKC,MAAEA,GAAU,IAAIC,eAE7B,OADAC,EAAOJ,EAAKC,GACL,CAACC,EAAO,CAACA,GACjB,EACDG,YAAYC,IACVA,EAAKC,QACEC,EAAKF,MAwDd,CAAC,QAtCC,CACFR,UAAYW,GACVf,EAASe,IAAUhB,KAAegB,EACpCV,WAAUU,MAAEA,IACV,IAAIC,EAaJ,OAXEA,EADED,aAAiBE,MACN,CACXC,SAAS,EACTH,MAAO,CACLI,QAASJ,EAAMI,QACfC,KAAML,EAAMK,KACZC,MAAON,EAAMM,QAIJ,CAAEH,SAAS,EAAOH,SAE1B,CAACC,EAAY,GACrB,EACDL,YAAYK,GACV,GAAIA,EAAWE,QACb,MAAMI,OAAOC,OACX,IAAIN,MAAMD,EAAWD,MAAMI,SAC3BH,EAAWD,OAGf,MAAMC,EAAWD,KAClB,MA6BG,SAAUL,EACdJ,EACAkB,EAAeC,WACfC,EAAsC,CAAC,MAEvCF,EAAGG,iBAAiB,WAAW,SAASC,EAASC,GAC/C,IAAKA,IAAOA,EAAGC,KACb,OAEF,IAxBJ,SACEJ,EACAK,GAEA,IAAK,MAAMC,KAAiBN,EAAgB,CAC1C,GAAIK,IAAWC,GAAmC,MAAlBA,EAC9B,OAAO,EAET,GAAIA,aAAyBC,QAAUD,EAAcE,KAAKH,GACxD,OAAO,CAEV,CACD,OAAO,CACT,CAWSI,CAAgBT,EAAgBG,EAAGE,QAEtC,YADAK,QAAQC,KAAK,mBAAmBR,EAAGE,6BAGrC,MAAMO,GAAEA,EAAEC,KAAEA,EAAIC,KAAEA,GAAMlB,OAAAC,OAAA,CACtBiB,KAAM,IACFX,EAAGC,MAEHW,GAAgBZ,EAAGC,KAAKW,cAAgB,IAAIC,IAAIC,GACtD,IAAIC,EACJ,IACE,MAAMC,EAASL,EAAKM,MAAM,GAAI,GAAGC,QAAO,CAACzC,EAAK0C,IAAS1C,EAAI0C,IAAO1C,GAC5D2C,EAAWT,EAAKO,QAAO,CAACzC,EAAK0C,IAAS1C,EAAI0C,IAAO1C,GACvD,OAAQiC,GACN,IAAA,MAEIK,EAAcK,EAEhB,MACF,IAAA,MAEIJ,EAAOL,EAAKM,OAAO,GAAG,IAAMH,EAAcd,EAAGC,KAAKf,OAClD6B,GAAc,EAEhB,MACF,IAAA,QAEIA,EAAcK,EAASC,MAAML,EAAQJ,GAEvC,MACF,IAAA,YAGIG,EAAcO,EADA,IAAIF,KAAYR,IAGhC,MACF,IAAA,WACE,CACE,MAAMlC,MAAEA,EAAKC,MAAEA,GAAU,IAAIC,eAC7BC,EAAOJ,EAAKE,GACZoC,EAAcQ,EAAS7C,EAAO,CAACA,GAChC,CACD,MACF,IAAA,UAEIqC,OAAcS,EAEhB,MACF,QACE,OAIL,CAFC,MAAOtC,GACP6B,EAAc,CAAE7B,QAAOhB,CAACA,GAAc,EACvC,CACDuD,QAAQC,QAAQX,GACbY,OAAOzC,IACC,CAAEA,QAAOhB,CAACA,GAAc,MAEhC0D,MAAMb,IACL,MAAOc,EAAWC,GAAiBC,EAAYhB,GAC/CpB,EAAGqC,YAAiBvC,OAAAC,OAAAD,OAAAC,OAAA,GAAAmC,IAAWpB,OAAMqB,eACjCpB,IAEFf,EAAGsC,oBAAoB,UAAWlC,GAClCmC,EAAcvC,GACV1B,KAAaQ,GAAiC,mBAAnBA,EAAIR,IACjCQ,EAAIR,KAEP,IAEF0D,OAAOQ,IAEN,MAAON,EAAWC,GAAiBC,EAAY,CAC7C7C,MAAO,IAAIkD,UAAU,+BACrBlE,CAACA,GAAc,IAEjByB,EAAGqC,YAAiBvC,OAAAC,OAAAD,OAAAC,OAAA,GAAAmC,IAAWpB,OAAMqB,EAAc,GAEzD,IACInC,EAAGX,OACLW,EAAGX,OAEP,CAMA,SAASkD,EAAcG,IAJvB,SAAuBA,GACrB,MAAqC,gBAA9BA,EAASC,YAAY/C,IAC9B,EAGMgD,CAAcF,IAAWA,EAASG,OACxC,CAEgB,SAAAvD,EAAQU,EAAc8C,GACpC,OAAOC,EAAe/C,EAAI,GAAI8C,EAChC,CAEA,SAASE,EAAqBC,GAC5B,GAAIA,EACF,MAAM,IAAIxD,MAAM,6CAEpB,CAEA,SAASyD,EAAgBlD,GACvB,OAAOmD,EAAuBnD,EAAI,CAChCe,KAAyB,YACxBkB,MAAK,KACNM,EAAcvC,EAAG,GAErB,CAaA,MAAMoD,EAAe,IAAIC,QACnBC,EACJ,yBAA0BrD,YAC1B,IAAIsD,sBAAsBvD,IACxB,MAAMwD,GAAYJ,EAAaK,IAAIzD,IAAO,GAAK,EAC/CoD,EAAaM,IAAI1D,EAAIwD,GACJ,IAAbA,GACFN,EAAgBlD,EACjB,IAiBL,SAAS+C,EACP/C,EACAgB,EAAqC,GACrC8B,EAAiB,WAAA,GAEjB,IAAIa,GAAkB,EACtB,MAAMhC,EAAQ,IAAIiC,MAAMd,EAAQ,CAC9BW,IAAII,EAASrC,GAEX,GADAwB,EAAqBW,GACjBnC,IAASnD,EACX,MAAO,MAhBf,SAAyBsD,GACnB2B,GACFA,EAAgBQ,WAAWnC,EAE/B,CAaUoC,CAAgBpC,GAChBuB,EAAgBlD,GAChB2D,GAAkB,CAAI,EAG1B,GAAa,SAATnC,EAAiB,CACnB,GAAoB,IAAhBR,EAAKgD,OACP,MAAO,CAAE/B,KAAM,IAAMN,GAEvB,MAAMsC,EAAId,EAAuBnD,EAAI,CACnCe,KAAqB,MACrBC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,eACvBlC,KAAKd,GACR,OAAO8C,EAAEhC,KAAKmC,KAAKH,EACpB,CACD,OAAOlB,EAAY/C,EAAI,IAAIgB,EAAMQ,GAClC,EACDkC,IAAIG,EAASrC,EAAMC,GACjBuB,EAAqBW,GAGrB,MAAOpE,EAAO4C,GAAiBC,EAAYX,GAC3C,OAAO0B,EACLnD,EACA,CACEe,KAAqB,MACrBC,KAAM,IAAIA,EAAMQ,GAAMN,KAAKgD,GAAMA,EAAEC,aACnC5E,SAEF4C,GACAF,KAAKd,EACR,EACDO,MAAMmC,EAASQ,EAAUC,GACvBtB,EAAqBW,GACrB,MAAMY,EAAOvD,EAAKA,EAAKgD,OAAS,GAChC,GAAKO,IAAiBnG,EACpB,OAAO+E,EAAuBnD,EAAI,CAChCe,KAA0B,aACzBkB,KAAKd,GAGV,GAAa,SAAToD,EACF,OAAOxB,EAAY/C,EAAIgB,EAAKM,MAAM,GAAI,IAExC,MAAOL,EAAckB,GAAiBqC,EAAiBF,GACvD,OAAOnB,EACLnD,EACA,CACEe,KAAuB,QACvBC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,aACxBlD,gBAEFkB,GACAF,KAAKd,EACR,EACDsD,UAAUZ,EAASS,GACjBtB,EAAqBW,GACrB,MAAO1C,EAAckB,GAAiBqC,EAAiBF,GACvD,OAAOnB,EACLnD,EACA,CACEe,KAA2B,YAC3BC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,aACxBlD,gBAEFkB,GACAF,KAAKd,EACR,IAGH,OA/FF,SAAuBQ,EAAe3B,GACpC,MAAMwD,GAAYJ,EAAaK,IAAIzD,IAAO,GAAK,EAC/CoD,EAAaM,IAAI1D,EAAIwD,GACjBF,GACFA,EAAgBoB,SAAS/C,EAAO3B,EAAI2B,EAExC,CAwFEgD,CAAchD,EAAO3B,GACd2B,CACT,CAMA,SAAS6C,EAAiBvD,GACxB,MAAM2D,EAAY3D,EAAaC,IAAIkB,GACnC,MAAO,CAACwC,EAAU1D,KAAK2D,GAAMA,EAAE,MANdC,EAM0BF,EAAU1D,KAAK2D,GAAMA,EAAE,KAL3DE,MAAMC,UAAUC,OAAOvD,MAAM,GAAIoD,KAD1C,IAAmBA,CAOnB,CAEA,MAAMI,EAAgB,IAAI7B,QACV,SAAAzB,EAAY9C,EAAQqG,GAElC,OADAD,EAAcxB,IAAI5E,EAAKqG,GAChBrG,CACT,CAEM,SAAU6C,EAAoB7C,GAClC,OAAOgB,OAAOC,OAAOjB,EAAK,CAAEZ,CAACA,IAAc,GAC7C,CAeA,SAASkE,EAAY7C,GACnB,IAAK,MAAOK,EAAMwF,KAAY1G,EAC5B,GAAI0G,EAAQxG,UAAUW,GAAQ,CAC5B,MAAO8F,EAAiBlD,GAAiBiD,EAAQvG,UAAUU,GAC3D,MAAO,CACL,CACEwB,KAA2B,UAC3BnB,OACAL,MAAO8F,GAETlD,EAEH,CAEH,MAAO,CACL,CACEpB,KAAuB,MACvBxB,SAEF2F,EAAczB,IAAIlE,IAAU,GAEhC,CAEA,SAAS4B,EAAc5B,GACrB,OAAQA,EAAMwB,MACZ,IAAA,UACE,OAAOrC,EAAiB+E,IAAIlE,EAAMK,MAAOT,YAAYI,EAAMA,OAC7D,IAAA,MACE,OAAOA,EAAMA,MAEnB,CAEA,SAAS4D,EACPnD,EACAsF,EACAH,GAEA,OAAO,IAAIrD,SAASC,IAClB,MAAMjB,EAgBD,IAAIiE,MAAM,GACdQ,KAAK,GACLrE,KAAI,IAAMsE,KAAKC,MAAMD,KAAKE,SAAWC,OAAOC,kBAAkBzB,SAAS,MACvE0B,KAAK,KAlBN7F,EAAGG,iBAAiB,WAAW,SAAS2F,EAAEzF,GACnCA,EAAGC,MAASD,EAAGC,KAAKQ,IAAMT,EAAGC,KAAKQ,KAAOA,IAG9Cd,EAAGsC,oBAAoB,UAAWwD,GAClC/D,EAAQ1B,EAAGC,MACb,IACIN,EAAGX,OACLW,EAAGX,QAELW,EAAGqC,YAAcvC,OAAAC,OAAA,CAAAe,MAAOwE,GAAOH,EAAU,GAE7C,2IAhEM,SACJY,EACAC,EAAuB/F,WACvBgG,EAAe,KAEf,MAAO,CACL5D,YAAa,CAACiD,EAAUnD,IACtB4D,EAAE1D,YAAYiD,EAAKW,EAAc9D,GACnChC,iBAAkB6F,EAAQ7F,iBAAiBiE,KAAK4B,GAChD1D,oBAAqB0D,EAAQ1D,oBAAoB8B,KAAK4B,GAE1D"} \ No newline at end of file diff --git a/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs b/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs new file mode 100644 index 00000000..cd008f0a --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs @@ -0,0 +1,7 @@ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const e=Symbol("Comlink.proxy"),t=Symbol("Comlink.endpoint"),n=Symbol("Comlink.releaseProxy"),r=Symbol("Comlink.finalizer"),a=Symbol("Comlink.thrown"),s=e=>"object"==typeof e&&null!==e||"function"==typeof e,o=new Map([["proxy",{canHandle:t=>s(t)&&t[e],serialize(e){const{port1:t,port2:n}=new MessageChannel;return i(e,t),[n,[n]]},deserialize:e=>(e.start(),u(e))}],["throw",{canHandle:e=>s(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}}]]);function i(e,t=globalThis,n=["*"]){t.addEventListener("message",(function s(o){if(!o||!o.data)return;if(!function(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}(n,o.origin))return void console.warn(`Invalid origin '${o.origin}' for comlink proxy`);const{id:u,type:l,path:p}=Object.assign({path:[]},o.data),g=(o.data.argumentList||[]).map(w);let f;try{const t=p.slice(0,-1).reduce(((e,t)=>e[t]),e),n=p.reduce(((e,t)=>e[t]),e);switch(l){case"GET":f=n;break;case"SET":t[p.slice(-1)[0]]=w(o.data.value),f=!0;break;case"APPLY":f=n.apply(t,g);break;case"CONSTRUCT":f=y(new n(...g));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;i(e,n),f=E(t,[t])}break;case"RELEASE":f=void 0;break;default:return}}catch(e){f={value:e,[a]:0}}Promise.resolve(f).catch((e=>({value:e,[a]:0}))).then((n=>{const[a,o]=b(n);t.postMessage(Object.assign(Object.assign({},a),{id:u}),o),"RELEASE"===l&&(t.removeEventListener("message",s),c(t),r in e&&"function"==typeof e[r]&&e[r]())})).catch((e=>{const[n,r]=b({value:new TypeError("Unserializable return value"),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:u}),r)}))})),t.start&&t.start()}function c(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function u(e,t){return m(e,[],t)}function l(e){if(e)throw new Error("Proxy has been released and is not useable")}function p(e){return L(e,{type:"RELEASE"}).then((()=>{c(e)}))}const g=new WeakMap,f="FinalizationRegistry"in globalThis&&new FinalizationRegistry((e=>{const t=(g.get(e)||0)-1;g.set(e,t),0===t&&p(e)}));function m(e,r=[],a=function(){}){let s=!1;const o=new Proxy(a,{get(t,a){if(l(s),a===n)return()=>{!function(e){f&&f.unregister(e)}(o),p(e),s=!0};if("then"===a){if(0===r.length)return{then:()=>o};const t=L(e,{type:"GET",path:r.map((e=>e.toString()))}).then(w);return t.then.bind(t)}return m(e,[...r,a])},set(t,n,a){l(s);const[o,i]=b(a);return L(e,{type:"SET",path:[...r,n].map((e=>e.toString())),value:o},i).then(w)},apply(n,a,o){l(s);const i=r[r.length-1];if(i===t)return L(e,{type:"ENDPOINT"}).then(w);if("bind"===i)return m(e,r.slice(0,-1));const[c,u]=d(o);return L(e,{type:"APPLY",path:r.map((e=>e.toString())),argumentList:c},u).then(w)},construct(t,n){l(s);const[a,o]=d(n);return L(e,{type:"CONSTRUCT",path:r.map((e=>e.toString())),argumentList:a},o).then(w)}});return function(e,t){const n=(g.get(t)||0)+1;g.set(t,n),f&&f.register(e,t,e)}(o,e),o}function d(e){const t=e.map(b);return[t.map((e=>e[0])),(n=t.map((e=>e[1])),Array.prototype.concat.apply([],n))];var n}const h=new WeakMap;function E(e,t){return h.set(e,t),e}function y(t){return Object.assign(t,{[e]:!0})}function v(e,t=globalThis,n="*"){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function b(e){for(const[t,n]of o)if(n.canHandle(e)){const[r,a]=n.serialize(e);return[{type:"HANDLER",name:t,value:r},a]}return[{type:"RAW",value:e},h.get(e)||[]]}function w(e){switch(e.type){case"HANDLER":return o.get(e.name).deserialize(e.value);case"RAW":return e.value}}function L(e,t,n){return new Promise((r=>{const a=new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-");e.addEventListener("message",(function t(n){n.data&&n.data.id&&n.data.id===a&&(e.removeEventListener("message",t),r(n.data))})),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),n)}))}export{t as createEndpoint,i as expose,r as finalizer,y as proxy,e as proxyMarker,n as releaseProxy,E as transfer,o as transferHandlers,v as windowEndpoint,u as wrap}; +//# sourceMappingURL=comlink.min.mjs.map diff --git a/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs.map b/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs.map new file mode 100644 index 00000000..0c7ba803 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/comlink.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"comlink.min.mjs","sources":["../../src/comlink.ts"],"sourcesContent":[null],"names":["proxyMarker","Symbol","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","transferHandlers","Map","canHandle","serialize","obj","port1","port2","MessageChannel","expose","deserialize","port","start","wrap","value","serialized","Error","isError","message","name","stack","Object","assign","ep","globalThis","allowedOrigins","addEventListener","callback","ev","data","origin","allowedOrigin","RegExp","test","isAllowedOrigin","console","warn","id","type","path","argumentList","map","fromWireValue","returnValue","parent","slice","reduce","prop","rawValue","apply","proxy","transfer","undefined","Promise","resolve","catch","then","wireValue","transferables","toWireValue","postMessage","removeEventListener","closeEndPoint","error","TypeError","endpoint","constructor","isMessagePort","close","target","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","WeakMap","proxyFinalizers","FinalizationRegistry","newCount","get","set","isProxyReleased","Proxy","_target","unregister","unregisterProxy","length","r","p","toString","bind","_thisArg","rawArgumentList","last","processArguments","construct","register","registerProxy","processed","v","arr","Array","prototype","concat","transferCache","transfers","windowEndpoint","w","context","targetOrigin","msg","handler","serializedValue","fill","Math","floor","random","Number","MAX_SAFE_INTEGER","join","l"],"mappings":";;;;;MAiBaA,EAAcC,OAAO,iBACrBC,EAAiBD,OAAO,oBACxBE,EAAeF,OAAO,wBACtBG,EAAYH,OAAO,qBAE1BI,EAAcJ,OAAO,kBAuJrBK,EAAYC,GACA,iBAARA,GAA4B,OAARA,GAAgC,mBAARA,EA+FzCC,EAAmB,IAAIC,IAGlC,CACA,CAAC,QAjEgE,CACjEC,UAAYH,GACVD,EAASC,IAASA,EAAoBP,GACxCW,UAAUC,GACR,MAAMC,MAAEA,EAAKC,MAAEA,GAAU,IAAIC,eAE7B,OADAC,EAAOJ,EAAKC,GACL,CAACC,EAAO,CAACA,GACjB,EACDG,YAAYC,IACVA,EAAKC,QACEC,EAAKF,MAwDd,CAAC,QAtCC,CACFR,UAAYW,GACVf,EAASe,IAAUhB,KAAegB,EACpCV,WAAUU,MAAEA,IACV,IAAIC,EAaJ,OAXEA,EADED,aAAiBE,MACN,CACXC,SAAS,EACTH,MAAO,CACLI,QAASJ,EAAMI,QACfC,KAAML,EAAMK,KACZC,MAAON,EAAMM,QAIJ,CAAEH,SAAS,EAAOH,SAE1B,CAACC,EAAY,GACrB,EACDL,YAAYK,GACV,GAAIA,EAAWE,QACb,MAAMI,OAAOC,OACX,IAAIN,MAAMD,EAAWD,MAAMI,SAC3BH,EAAWD,OAGf,MAAMC,EAAWD,KAClB,MA6BG,SAAUL,EACdJ,EACAkB,EAAeC,WACfC,EAAsC,CAAC,MAEvCF,EAAGG,iBAAiB,WAAW,SAASC,EAASC,GAC/C,IAAKA,IAAOA,EAAGC,KACb,OAEF,IAxBJ,SACEJ,EACAK,GAEA,IAAK,MAAMC,KAAiBN,EAAgB,CAC1C,GAAIK,IAAWC,GAAmC,MAAlBA,EAC9B,OAAO,EAET,GAAIA,aAAyBC,QAAUD,EAAcE,KAAKH,GACxD,OAAO,CAEV,CACD,OAAO,CACT,CAWSI,CAAgBT,EAAgBG,EAAGE,QAEtC,YADAK,QAAQC,KAAK,mBAAmBR,EAAGE,6BAGrC,MAAMO,GAAEA,EAAEC,KAAEA,EAAIC,KAAEA,GAAMlB,OAAAC,OAAA,CACtBiB,KAAM,IACFX,EAAGC,MAEHW,GAAgBZ,EAAGC,KAAKW,cAAgB,IAAIC,IAAIC,GACtD,IAAIC,EACJ,IACE,MAAMC,EAASL,EAAKM,MAAM,GAAI,GAAGC,QAAO,CAACzC,EAAK0C,IAAS1C,EAAI0C,IAAO1C,GAC5D2C,EAAWT,EAAKO,QAAO,CAACzC,EAAK0C,IAAS1C,EAAI0C,IAAO1C,GACvD,OAAQiC,GACN,IAAA,MAEIK,EAAcK,EAEhB,MACF,IAAA,MAEIJ,EAAOL,EAAKM,OAAO,GAAG,IAAMH,EAAcd,EAAGC,KAAKf,OAClD6B,GAAc,EAEhB,MACF,IAAA,QAEIA,EAAcK,EAASC,MAAML,EAAQJ,GAEvC,MACF,IAAA,YAGIG,EAAcO,EADA,IAAIF,KAAYR,IAGhC,MACF,IAAA,WACE,CACE,MAAMlC,MAAEA,EAAKC,MAAEA,GAAU,IAAIC,eAC7BC,EAAOJ,EAAKE,GACZoC,EAAcQ,EAAS7C,EAAO,CAACA,GAChC,CACD,MACF,IAAA,UAEIqC,OAAcS,EAEhB,MACF,QACE,OAIL,CAFC,MAAOtC,GACP6B,EAAc,CAAE7B,QAAOhB,CAACA,GAAc,EACvC,CACDuD,QAAQC,QAAQX,GACbY,OAAOzC,IACC,CAAEA,QAAOhB,CAACA,GAAc,MAEhC0D,MAAMb,IACL,MAAOc,EAAWC,GAAiBC,EAAYhB,GAC/CpB,EAAGqC,YAAiBvC,OAAAC,OAAAD,OAAAC,OAAA,GAAAmC,IAAWpB,OAAMqB,eACjCpB,IAEFf,EAAGsC,oBAAoB,UAAWlC,GAClCmC,EAAcvC,GACV1B,KAAaQ,GAAiC,mBAAnBA,EAAIR,IACjCQ,EAAIR,KAEP,IAEF0D,OAAOQ,IAEN,MAAON,EAAWC,GAAiBC,EAAY,CAC7C7C,MAAO,IAAIkD,UAAU,+BACrBlE,CAACA,GAAc,IAEjByB,EAAGqC,YAAiBvC,OAAAC,OAAAD,OAAAC,OAAA,GAAAmC,IAAWpB,OAAMqB,EAAc,GAEzD,IACInC,EAAGX,OACLW,EAAGX,OAEP,CAMA,SAASkD,EAAcG,IAJvB,SAAuBA,GACrB,MAAqC,gBAA9BA,EAASC,YAAY/C,IAC9B,EAGMgD,CAAcF,IAAWA,EAASG,OACxC,CAEgB,SAAAvD,EAAQU,EAAc8C,GACpC,OAAOC,EAAe/C,EAAI,GAAI8C,EAChC,CAEA,SAASE,EAAqBC,GAC5B,GAAIA,EACF,MAAM,IAAIxD,MAAM,6CAEpB,CAEA,SAASyD,EAAgBlD,GACvB,OAAOmD,EAAuBnD,EAAI,CAChCe,KAAyB,YACxBkB,MAAK,KACNM,EAAcvC,EAAG,GAErB,CAaA,MAAMoD,EAAe,IAAIC,QACnBC,EACJ,yBAA0BrD,YAC1B,IAAIsD,sBAAsBvD,IACxB,MAAMwD,GAAYJ,EAAaK,IAAIzD,IAAO,GAAK,EAC/CoD,EAAaM,IAAI1D,EAAIwD,GACJ,IAAbA,GACFN,EAAgBlD,EACjB,IAiBL,SAAS+C,EACP/C,EACAgB,EAAqC,GACrC8B,EAAiB,WAAA,GAEjB,IAAIa,GAAkB,EACtB,MAAMhC,EAAQ,IAAIiC,MAAMd,EAAQ,CAC9BW,IAAII,EAASrC,GAEX,GADAwB,EAAqBW,GACjBnC,IAASnD,EACX,MAAO,MAhBf,SAAyBsD,GACnB2B,GACFA,EAAgBQ,WAAWnC,EAE/B,CAaUoC,CAAgBpC,GAChBuB,EAAgBlD,GAChB2D,GAAkB,CAAI,EAG1B,GAAa,SAATnC,EAAiB,CACnB,GAAoB,IAAhBR,EAAKgD,OACP,MAAO,CAAE/B,KAAM,IAAMN,GAEvB,MAAMsC,EAAId,EAAuBnD,EAAI,CACnCe,KAAqB,MACrBC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,eACvBlC,KAAKd,GACR,OAAO8C,EAAEhC,KAAKmC,KAAKH,EACpB,CACD,OAAOlB,EAAY/C,EAAI,IAAIgB,EAAMQ,GAClC,EACDkC,IAAIG,EAASrC,EAAMC,GACjBuB,EAAqBW,GAGrB,MAAOpE,EAAO4C,GAAiBC,EAAYX,GAC3C,OAAO0B,EACLnD,EACA,CACEe,KAAqB,MACrBC,KAAM,IAAIA,EAAMQ,GAAMN,KAAKgD,GAAMA,EAAEC,aACnC5E,SAEF4C,GACAF,KAAKd,EACR,EACDO,MAAMmC,EAASQ,EAAUC,GACvBtB,EAAqBW,GACrB,MAAMY,EAAOvD,EAAKA,EAAKgD,OAAS,GAChC,GAAKO,IAAiBnG,EACpB,OAAO+E,EAAuBnD,EAAI,CAChCe,KAA0B,aACzBkB,KAAKd,GAGV,GAAa,SAAToD,EACF,OAAOxB,EAAY/C,EAAIgB,EAAKM,MAAM,GAAI,IAExC,MAAOL,EAAckB,GAAiBqC,EAAiBF,GACvD,OAAOnB,EACLnD,EACA,CACEe,KAAuB,QACvBC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,aACxBlD,gBAEFkB,GACAF,KAAKd,EACR,EACDsD,UAAUZ,EAASS,GACjBtB,EAAqBW,GACrB,MAAO1C,EAAckB,GAAiBqC,EAAiBF,GACvD,OAAOnB,EACLnD,EACA,CACEe,KAA2B,YAC3BC,KAAMA,EAAKE,KAAKgD,GAAMA,EAAEC,aACxBlD,gBAEFkB,GACAF,KAAKd,EACR,IAGH,OA/FF,SAAuBQ,EAAe3B,GACpC,MAAMwD,GAAYJ,EAAaK,IAAIzD,IAAO,GAAK,EAC/CoD,EAAaM,IAAI1D,EAAIwD,GACjBF,GACFA,EAAgBoB,SAAS/C,EAAO3B,EAAI2B,EAExC,CAwFEgD,CAAchD,EAAO3B,GACd2B,CACT,CAMA,SAAS6C,EAAiBvD,GACxB,MAAM2D,EAAY3D,EAAaC,IAAIkB,GACnC,MAAO,CAACwC,EAAU1D,KAAK2D,GAAMA,EAAE,MANdC,EAM0BF,EAAU1D,KAAK2D,GAAMA,EAAE,KAL3DE,MAAMC,UAAUC,OAAOvD,MAAM,GAAIoD,KAD1C,IAAmBA,CAOnB,CAEA,MAAMI,EAAgB,IAAI7B,QACV,SAAAzB,EAAY9C,EAAQqG,GAElC,OADAD,EAAcxB,IAAI5E,EAAKqG,GAChBrG,CACT,CAEM,SAAU6C,EAAoB7C,GAClC,OAAOgB,OAAOC,OAAOjB,EAAK,CAAEZ,CAACA,IAAc,GAC7C,CAEM,SAAUkH,EACdC,EACAC,EAAuBrF,WACvBsF,EAAe,KAEf,MAAO,CACLlD,YAAa,CAACmD,EAAUrD,IACtBkD,EAAEhD,YAAYmD,EAAKD,EAAcpD,GACnChC,iBAAkBmF,EAAQnF,iBAAiBiE,KAAKkB,GAChDhD,oBAAqBgD,EAAQhD,oBAAoB8B,KAAKkB,GAE1D,CAEA,SAASlD,EAAY7C,GACnB,IAAK,MAAOK,EAAM6F,KAAY/G,EAC5B,GAAI+G,EAAQ7G,UAAUW,GAAQ,CAC5B,MAAOmG,EAAiBvD,GAAiBsD,EAAQ5G,UAAUU,GAC3D,MAAO,CACL,CACEwB,KAA2B,UAC3BnB,OACAL,MAAOmG,GAETvD,EAEH,CAEH,MAAO,CACL,CACEpB,KAAuB,MACvBxB,SAEF2F,EAAczB,IAAIlE,IAAU,GAEhC,CAEA,SAAS4B,EAAc5B,GACrB,OAAQA,EAAMwB,MACZ,IAAA,UACE,OAAOrC,EAAiB+E,IAAIlE,EAAMK,MAAOT,YAAYI,EAAMA,OAC7D,IAAA,MACE,OAAOA,EAAMA,MAEnB,CAEA,SAAS4D,EACPnD,EACAwF,EACAL,GAEA,OAAO,IAAIrD,SAASC,IAClB,MAAMjB,EAgBD,IAAIiE,MAAM,GACdY,KAAK,GACLzE,KAAI,IAAM0E,KAAKC,MAAMD,KAAKE,SAAWC,OAAOC,kBAAkB7B,SAAS,MACvE8B,KAAK,KAlBNjG,EAAGG,iBAAiB,WAAW,SAAS+F,EAAE7F,GACnCA,EAAGC,MAASD,EAAGC,KAAKQ,IAAMT,EAAGC,KAAKQ,KAAOA,IAG9Cd,EAAGsC,oBAAoB,UAAW4D,GAClCnE,EAAQ1B,EAAGC,MACb,IACIN,EAAGX,OACLW,EAAGX,QAELW,EAAGqC,YAAcvC,OAAAC,OAAA,CAAAe,MAAO0E,GAAOL,EAAU,GAE7C"} \ No newline at end of file diff --git a/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index.js b/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index.js new file mode 100644 index 00000000..e5a9bc31 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index.js @@ -0,0 +1,354 @@ +let wasm_bindgen; +(function() { + const __exports = {}; + let script_src; + if (typeof document !== 'undefined' && document.currentScript !== null) { + script_src = new URL(document.currentScript.src, location.href).toString(); + } + let wasm = undefined; + + function addToExternrefTable0(obj) { + const idx = wasm.__externref_table_alloc(); + wasm.__wbindgen_export_2.set(idx, obj); + return idx; + } + + function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + const idx = addToExternrefTable0(e); + wasm.__wbindgen_exn_store(idx); + } + } + + const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); + + if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; + + let cachedUint8ArrayMemory0 = null; + + function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; + } + + function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); + } + + const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(state => { + wasm.__wbindgen_export_3.get(state.dtor)(state.a, state.b) + }); + + function makeMutClosure(arg0, arg1, dtor, f) { + const state = { a: arg0, b: arg1, cnt: 1, dtor }; + const real = (...args) => { + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + const a = state.a; + state.a = 0; + try { + return f(a, state.b, ...args); + } finally { + if (--state.cnt === 0) { + wasm.__wbindgen_export_3.get(state.dtor)(a, state.b); + CLOSURE_DTORS.unregister(state); + } else { + state.a = a; + } + } + }; + real.original = state; + CLOSURE_DTORS.register(real, state, state); + return real; + } + + let WASM_VECTOR_LEN = 0; + + function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8ArrayMemory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; + } + function __wbg_adapter_20(arg0, arg1, arg2) { + wasm.closure12_externref_shim(arg0, arg1, arg2); + } + + function __wbg_adapter_32(arg0, arg1, arg2, arg3) { + wasm.closure22_externref_shim(arg0, arg1, arg2, arg3); + } + + const CryptoUtilsFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_cryptoutils_free(ptr >>> 0, 1)); + + class CryptoUtils { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + CryptoUtilsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_cryptoutils_free(ptr, 0); + } + /** + * Encrypts a message with an [OTP] [KDF] and the given parameters. + * The KDF uses Argon2d for hashing. + * + * [OTP]: https://en.wikipedia.org/wiki/One-time_pad + * [KDF]: https://en.wikipedia.org/wiki/Key_derivation_function + * @param {Uint8Array} message + * @param {Uint8Array} key + * @param {Uint8Array} salt + * @param {number} iterations + * @returns {Promise} + */ + static otpKdf(message, key, salt, iterations) { + const ptr0 = passArray8ToWasm0(message, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(key, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ptr2 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); + const len2 = WASM_VECTOR_LEN; + const ret = wasm.cryptoutils_otpKdf(ptr0, len0, ptr1, len1, ptr2, len2, iterations); + return ret; + } + } + __exports.CryptoUtils = CryptoUtils; + + async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } + } + + function __wbg_get_imports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_buffer_6e1d53ff183194fc = function(arg0) { + const ret = arg0.buffer; + return ret; + }; + imports.wbg.__wbg_call_0411c0c3c424db9a = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.call(arg1, arg2); + return ret; + }, arguments) }; + imports.wbg.__wbg_call_3114932863209ca6 = function() { return handleError(function (arg0, arg1) { + const ret = arg0.call(arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_globalThis_1e2ac1d6eee845b3 = function() { return handleError(function () { + const ret = globalThis.globalThis; + return ret; + }, arguments) }; + imports.wbg.__wbg_global_f25a574ae080367c = function() { return handleError(function () { + const ret = global.global; + return ret; + }, arguments) }; + imports.wbg.__wbg_new_1e8ca58d170d6ad0 = function(arg0, arg1) { + try { + var state0 = {a: arg0, b: arg1}; + var cb0 = (arg0, arg1) => { + const a = state0.a; + state0.a = 0; + try { + return __wbg_adapter_32(a, state0.b, arg0, arg1); + } finally { + state0.a = a; + } + }; + const ret = new Promise(cb0); + return ret; + } finally { + state0.a = state0.b = 0; + } + }; + imports.wbg.__wbg_new_23362fa370a0a372 = function(arg0) { + const ret = new Uint8Array(arg0); + return ret; + }; + imports.wbg.__wbg_newnoargs_19a249f4eceaaac3 = function(arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbg_newwithbyteoffsetandlength_ee8def7000b7b2be = function(arg0, arg1, arg2) { + const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0); + return ret; + }; + imports.wbg.__wbg_queueMicrotask_3d422e1ba49c2500 = function(arg0) { + const ret = arg0.queueMicrotask; + return ret; + }; + imports.wbg.__wbg_queueMicrotask_f301663ccadbb7d0 = function(arg0) { + queueMicrotask(arg0); + }; + imports.wbg.__wbg_resolve_6a311e8bb26423ab = function(arg0) { + const ret = Promise.resolve(arg0); + return ret; + }; + imports.wbg.__wbg_self_ac4343e4047b83cc = function() { return handleError(function () { + const ret = self.self; + return ret; + }, arguments) }; + imports.wbg.__wbg_then_5c6469c1e1da9e59 = function(arg0, arg1) { + const ret = arg0.then(arg1); + return ret; + }; + imports.wbg.__wbg_window_1a23defd102c72f4 = function() { return handleError(function () { + const ret = window.window; + return ret; + }, arguments) }; + imports.wbg.__wbindgen_cb_drop = function(arg0) { + const obj = arg0.original; + if (obj.cnt-- == 1) { + obj.a = 0; + return true; + } + const ret = false; + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper60 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 13, __wbg_adapter_20); + return ret; + }; + imports.wbg.__wbindgen_error_new = function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbindgen_init_externref_table = function() { + const table = wasm.__wbindgen_export_2; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + ; + }; + imports.wbg.__wbindgen_is_function = function(arg0) { + const ret = typeof(arg0) === 'function'; + return ret; + }; + imports.wbg.__wbindgen_is_undefined = function(arg0) { + const ret = arg0 === undefined; + return ret; + }; + imports.wbg.__wbindgen_memory = function() { + const ret = wasm.memory; + return ret; + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + + return imports; + } + + function __wbg_init_memory(imports, memory) { + + } + + function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + __wbg_init.__wbindgen_wasm_module = module; + cachedUint8ArrayMemory0 = null; + + + wasm.__wbindgen_start(); + return wasm; + } + + function initSync(module) { + if (wasm !== undefined) return wasm; + + + if (typeof module !== 'undefined') { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({module} = module) + } else { + console.warn('using deprecated parameters for `initSync()`; pass a single object instead') + } + } + + const imports = __wbg_get_imports(); + + __wbg_init_memory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return __wbg_finalize_init(instance, module); + } + + async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + + if (typeof module_or_path !== 'undefined') { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({module_or_path} = module_or_path) + } else { + console.warn('using deprecated parameters for the initialization function; pass a single object instead') + } + } + + if (typeof module_or_path === 'undefined' && typeof script_src !== 'undefined') { + module_or_path = script_src.replace(/\.js$/, '_bg.wasm'); + } + const imports = __wbg_get_imports(); + + if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { + module_or_path = fetch(module_or_path); + } + + __wbg_init_memory(imports); + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); + } + + wasm_bindgen = Object.assign(__wbg_init, { initSync }, __exports); + +})(); diff --git a/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index_bg.wasm b/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index_bg.wasm new file mode 100644 index 00000000..103c6b9b Binary files /dev/null and b/public/nimiq/2.0.5-history-fix/web/crypto-wasm/index_bg.wasm differ diff --git a/public/nimiq/2.0.5-history-fix/web/crypto.js b/public/nimiq/2.0.5-history-fix/web/crypto.js new file mode 100644 index 00000000..c93452a1 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/crypto.js @@ -0,0 +1,20 @@ +// The worker has its own scope and no direct access to functions/objects of the +// global scope. We import the generated JS file to make `wasm_bindgen` +// available which we need to initialize our WASM code. +importScripts( + './comlink.min.js', + './crypto-wasm/index.js', +); + +const { CryptoUtils } = wasm_bindgen; + +(async function init() { + console.log('Initializing crypto WASM worker'); + + // Load the wasm file by awaiting the Promise returned by `wasm_bindgen`. + await wasm_bindgen('./crypto-wasm/index_bg.wasm'); + + Comlink.expose(CryptoUtils); + + self.postMessage('NIMIQ_ONLOAD'); +})(); diff --git a/public/nimiq/2.0.5-history-fix/web/index.js b/public/nimiq/2.0.5-history-fix/web/index.js new file mode 100644 index 00000000..fc790458 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/index.js @@ -0,0 +1,31 @@ +import * as Comlink from './comlink.min.mjs'; +import init, { Address, CryptoUtils, Transaction } from './main-wasm/index.js'; +import { clientFactory } from '../launcher/browser/client-proxy.mjs'; +import { cryptoUtilsWorkerFactory } from '../launcher/browser/cryptoutils-worker-proxy.mjs'; +import { setupMainThreadTransferHandlers } from '../launcher/browser/transfer-handlers.mjs'; + +setupMainThreadTransferHandlers(Comlink, { + Address, + Transaction, +}); + +const Client = clientFactory( + () => new Worker(new URL('./worker.js', import.meta.url)), + worker => Comlink.wrap(worker), +); + +const CryptoUtilsWorker = cryptoUtilsWorkerFactory( + () => new Worker(new URL('./crypto.js', import.meta.url)), + worker => Comlink.wrap(worker), +); +for (const propName in CryptoUtilsWorker) { + const prop = CryptoUtilsWorker[propName]; + if (typeof prop === 'function') { + CryptoUtils[propName] = prop; + } +} + +export * from './main-wasm/index.js'; +export { Client }; +export * from '../lib/web/index.mjs'; +export default init; diff --git a/public/nimiq/2.0.5-history-fix/web/main-wasm/index.js b/public/nimiq/2.0.5-history-fix/web/main-wasm/index.js new file mode 100644 index 00000000..776b4d95 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/main-wasm/index.js @@ -0,0 +1,4085 @@ +let wasm; + +let WASM_VECTOR_LEN = 0; + +let cachedUint8ArrayMemory0 = null; + +function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; +} + +const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachedDataViewMemory0 = null; + +function getDataViewMemory0() { + if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; +} + +function addToExternrefTable0(obj) { + const idx = wasm.__externref_table_alloc(); + wasm.__wbindgen_export_4.set(idx, obj); + return idx; +} + +function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + const idx = addToExternrefTable0(e); + wasm.__wbindgen_exn_store(idx); + } +} + +const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); + +if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; + +function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); +} + +function isLikeNone(x) { + return x === undefined || x === null; +} + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches && builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +function _assertClass(instance, klass) { + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } +} + +function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8ArrayMemory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; +} + +function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_export_4.get(idx); + wasm.__externref_table_dealloc(idx); + return value; +} + +function getArrayU8FromWasm0(ptr, len) { + ptr = ptr >>> 0; + return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); +} + +function passArrayJsValueToWasm0(array, malloc) { + const ptr = malloc(array.length * 4, 4) >>> 0; + const mem = getDataViewMemory0(); + for (let i = 0; i < array.length; i++) { + mem.setUint32(ptr + 4 * i, addToExternrefTable0(array[i]), true); + } + WASM_VECTOR_LEN = array.length; + return ptr; +} +/** + * @enum {0 | 1 | 2 | 3} + */ +export const AccountType = Object.freeze({ + Basic: 0, "0": "Basic", + Vesting: 1, "1": "Vesting", + HTLC: 2, "2": "HTLC", + Staking: 3, "3": "Staking", +}); +/** + * A transaction flag signals a special purpose of the transaction. `ContractCreation` must be set + * to create new vesting contracts or HTLCs. `Signaling` must be set to interact with the staking + * contract for non-value transactions. All other transactions' flag is set to `None`. + * @enum {0 | 1 | 2} + */ +export const TransactionFlag = Object.freeze({ + None: 0, "0": "None", + ContractCreation: 1, "1": "ContractCreation", + Signaling: 2, "2": "Signaling", +}); +/** + * @enum {0 | 1} + */ +export const TransactionFormat = Object.freeze({ + Basic: 0, "0": "Basic", + Extended: 1, "1": "Extended", +}); + +const AddressFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_address_free(ptr >>> 0, 1)); +/** + * An object representing a Nimiq address. + * Offers methods to parse and format addresses from and to strings. + */ +export class Address { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Address.prototype); + obj.__wbg_ptr = ptr; + AddressFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + AddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_address_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.address___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + AddressFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Deserializes an address from a byte array. + * @param {Uint8Array} bytes + * @returns {Address} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Parses an address from an {@link Address} instance, a hex string representation, or a byte array. + * + * Throws when an address cannot be parsed from the argument. + * @param {Address | string | Uint8Array} addr + * @returns {Address} + */ + static fromAny(addr) { + const ret = wasm.address_fromAny(addr); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Parses an address from a string representation, either user-friendly or hex format. + * + * Throws when an address cannot be parsed from the string. + * @param {string} str + * @returns {Address} + */ + static fromString(str) { + const ptr0 = passStringToWasm0(str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_fromString(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Parses an address from its user-friendly string representation. + * + * Throws when an address cannot be parsed from the string. + * @param {string} str + * @returns {Address} + */ + static fromUserFriendlyAddress(str) { + const ptr0 = passStringToWasm0(str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_fromUserFriendlyAddress(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Formats the address into a plain string format. + * @returns {string} + */ + toPlain() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.address_toPlain(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Formats the address into user-friendly IBAN format. + * @returns {string} + */ + toUserFriendlyAddress() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.address_toUserFriendlyAddress(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Formats the address into hex format. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.address_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Returns the byte representation of the address. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.address_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Returns if this address is equal to the other address. + * @param {Address} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, Address); + const ret = wasm.address_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } + /** + * Compares this address to the other address. + * + * Returns -1 if this address is smaller than the other address, 0 if they are equal, + * and 1 if this address is larger than the other address. + * @param {Address} other + * @returns {number} + */ + compare(other) { + _assertClass(other, Address); + const ret = wasm.address_compare(this.__wbg_ptr, other.__wbg_ptr); + return ret; + } +} + +const BLSKeyPairFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_blskeypair_free(ptr >>> 0, 1)); +/** + * A BLS keypair + * It is used by validators to vote during Tendermint rounds. + * This is just a wrapper around our internal BLS structs + */ +export class BLSKeyPair { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(BLSKeyPair.prototype); + obj.__wbg_ptr = ptr; + BLSKeyPairFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + BLSKeyPairFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_blskeypair_free(ptr, 0); + } + /** + * Generates a new keypair from secure randomness. + * @returns {BLSKeyPair} + */ + static generate() { + const ret = wasm.blskeypair_generate(); + return BLSKeyPair.__wrap(ret); + } + /** + * Derives a keypair from an existing private key. + * @param {BLSSecretKey} private_key + * @returns {BLSKeyPair} + */ + static derive(private_key) { + _assertClass(private_key, BLSSecretKey); + const ret = wasm.blskeypair_derive(private_key.__wbg_ptr); + return BLSKeyPair.__wrap(ret); + } + /** + * Deserializes a keypair from a byte array. + * @param {Uint8Array} bytes + * @returns {BLSKeyPair} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blskeypair_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return BLSKeyPair.__wrap(ret[0]); + } + /** + * @param {BLSSecretKey} secret_key + * @param {BLSPublicKey} public_key + */ + constructor(secret_key, public_key) { + _assertClass(secret_key, BLSSecretKey); + _assertClass(public_key, BLSPublicKey); + const ret = wasm.blskeypair_new(secret_key.__wbg_ptr, public_key.__wbg_ptr); + this.__wbg_ptr = ret >>> 0; + BLSKeyPairFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.blskeypair_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Gets the keypair's secret key. + * @returns {BLSSecretKey} + */ + get secretKey() { + const ret = wasm.blskeypair_secretKey(this.__wbg_ptr); + return BLSSecretKey.__wrap(ret); + } + /** + * Gets the keypair's public key. + * @returns {BLSPublicKey} + */ + get publicKey() { + const ret = wasm.blskeypair_publicKey(this.__wbg_ptr); + return BLSPublicKey.__wrap(ret); + } + /** + * Formats the keypair into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.blskeypair_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const BLSPublicKeyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_blspublickey_free(ptr >>> 0, 1)); +/** + * The public part of the BLS keypair. + * This is specified in the staking contract to verify votes from Validators. + */ +export class BLSPublicKey { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(BLSPublicKey.prototype); + obj.__wbg_ptr = ptr; + BLSPublicKeyFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + BLSPublicKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_blspublickey_free(ptr, 0); + } + /** + * Derives a public key from an existing private key. + * @param {BLSSecretKey} secret_key + * @returns {BLSPublicKey} + */ + static derive(secret_key) { + _assertClass(secret_key, BLSSecretKey); + const ret = wasm.blspublickey_derive(secret_key.__wbg_ptr); + return BLSPublicKey.__wrap(ret); + } + /** + * Deserializes a public key from a byte array. + * @param {Uint8Array} bytes + * @returns {BLSPublicKey} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blspublickey_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return BLSPublicKey.__wrap(ret[0]); + } + /** + * Creates a new public key from a byte array. + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blspublickey_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + BLSPublicKeyFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the public key to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.blspublickey_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses a public key from its hex representation. + * @param {string} hex + * @returns {BLSPublicKey} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blspublickey_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return BLSPublicKey.__wrap(ret[0]); + } + /** + * Formats the public key into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.blspublickey_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const BLSSecretKeyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_blssecretkey_free(ptr >>> 0, 1)); +/** + * The secret part of the BLS keypair. + * This is specified in the config file, and is used by Validators to vote. + */ +export class BLSSecretKey { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(BLSSecretKey.prototype); + obj.__wbg_ptr = ptr; + BLSSecretKeyFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + BLSSecretKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_blssecretkey_free(ptr, 0); + } + /** + * Generates a new private key from secure randomness. + * @returns {BLSSecretKey} + */ + static generate() { + const ret = wasm.blssecretkey_generate(); + return BLSSecretKey.__wrap(ret); + } + /** + * Deserializes a private key from a byte array. + * @param {Uint8Array} bytes + * @returns {BLSSecretKey} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blssecretkey_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return BLSSecretKey.__wrap(ret[0]); + } + /** + * Creates a new private key from a byte array. + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blssecretkey_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + BLSSecretKeyFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the private key to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.blssecretkey_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses a private key from its hex representation. + * @param {string} hex + * @returns {BLSSecretKey} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.blssecretkey_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return BLSSecretKey.__wrap(ret[0]); + } + /** + * Formats the private key into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.blssecretkey_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const ClientConfigurationFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_clientconfiguration_free(ptr >>> 0, 1)); +/** + * Use this to provide initialization-time configuration to the Client. + * This is a simplified version of the configuration that is used for regular nodes, + * since not all configuration knobs are available when running inside a browser. + */ +export class ClientConfiguration { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + ClientConfigurationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_clientconfiguration_free(ptr, 0); + } + /** + * Creates a default client configuration that can be used to change the client's configuration. + * + * Use its `instantiateClient()` method to launch the client and connect to the network. + */ + constructor() { + const ret = wasm.clientconfiguration_new(); + this.__wbg_ptr = ret >>> 0; + ClientConfigurationFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Sets the network ID the client should use. Input is case-insensitive. + * + * Possible values are `'MainAlbatross' | 'TestAlbatross' | 'DevAlbatross'`. + * Default is `'MainAlbatross'`. + * @param {string} network + */ + network(network) { + const ptr0 = passStringToWasm0(network, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.clientconfiguration_network(this.__wbg_ptr, ptr0, len0); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } + } + /** + * Sets the list of seed nodes that are used to connect to the Nimiq Albatross network. + * + * Each array entry must be a proper Multiaddr format string. + * @param {any[]} seeds + */ + seedNodes(seeds) { + const ptr0 = passArrayJsValueToWasm0(seeds, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.clientconfiguration_seedNodes(this.__wbg_ptr, ptr0, len0); + } + /** + * Sets the log level that is used when logging to the console. + * + * Possible values are `'trace' | 'debug' | 'info' | 'warn' | 'error'`. + * Default is `'info'`. + * @param {string} log_level + */ + logLevel(log_level) { + const ptr0 = passStringToWasm0(log_level, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + wasm.clientconfiguration_logLevel(this.__wbg_ptr, ptr0, len0); + } + /** + * Sets whether the client should only connect to secure WebSocket connections. + * Default is `true`. + * @param {boolean} only_secure_ws_connections + */ + onlySecureWsConnections(only_secure_ws_connections) { + wasm.clientconfiguration_onlySecureWsConnections(this.__wbg_ptr, only_secure_ws_connections); + } + /** + * Sets the desired number of peers the client should try to connect to. + * Default is `12`. + * @param {number} desired_peer_count + */ + desiredPeerCount(desired_peer_count) { + wasm.clientconfiguration_desiredPeerCount(this.__wbg_ptr, desired_peer_count); + } + /** + * Sets the maximum number of peers the client should connect to. + * Default is `50`. + * @param {number} peer_count_max + */ + peerCountMax(peer_count_max) { + wasm.clientconfiguration_peerCountMax(this.__wbg_ptr, peer_count_max); + } + /** + * Sets the maximum number of peers the client should connect to per IP address. + * Default is `10`. + * @param {number} peer_count_per_ip_max + */ + peerCountPerIpMax(peer_count_per_ip_max) { + wasm.clientconfiguration_peerCountPerIpMax(this.__wbg_ptr, peer_count_per_ip_max); + } + /** + * Sets the maximum number of peers the client should connect to per subnet. + * Default is `10`. + * @param {number} peer_count_per_subnet_max + */ + peerCountPerSubnetMax(peer_count_per_subnet_max) { + wasm.clientconfiguration_peerCountPerSubnetMax(this.__wbg_ptr, peer_count_per_subnet_max); + } + /** + * Returns a plain configuration object to be passed to `Client.create`. + * @returns {PlainClientConfiguration} + */ + build() { + const ret = wasm.clientconfiguration_build(this.__wbg_ptr); + return ret; + } +} + +const CryptoUtilsFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_cryptoutils_free(ptr >>> 0, 1)); + +export class CryptoUtils { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + CryptoUtilsFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_cryptoutils_free(ptr, 0); + } + /** + * Generates a secure random byte array of the given length. + * @param {number} length + * @returns {Uint8Array} + */ + static getRandomValues(length) { + const ret = wasm.cryptoutils_getRandomValues(length); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Computes a 64-byte [HMAC]-SHA512 hash from the input key and data. + * + * [HMAC]: https://en.wikipedia.org/wiki/HMAC + * @param {Uint8Array} key + * @param {Uint8Array} data + * @returns {Uint8Array} + */ + static computeHmacSha512(key, data) { + const ptr0 = passArray8ToWasm0(key, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.cryptoutils_computeHmacSha512(ptr0, len0, ptr1, len1); + var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v3; + } + /** + * Computes a [PBKDF2]-over-SHA512 key from the password with the given parameters. + * + * [PBKDF2]: https://en.wikipedia.org/wiki/PBKDF2 + * @param {Uint8Array} password + * @param {Uint8Array} salt + * @param {number} iterations + * @param {number} derived_key_length + * @returns {Uint8Array} + */ + static computePBKDF2sha512(password, salt, iterations, derived_key_length) { + const ptr0 = passArray8ToWasm0(password, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.cryptoutils_computePBKDF2sha512(ptr0, len0, ptr1, len1, iterations, derived_key_length); + if (ret[3]) { + throw takeFromExternrefTable0(ret[2]); + } + var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v3; + } +} + +const ES256PublicKeyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_es256publickey_free(ptr >>> 0, 1)); +/** + * The non-secret (public) part of an ES256 asymmetric key pair that is typically used to digitally verify or encrypt data. + */ +export class ES256PublicKey { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(ES256PublicKey.prototype); + obj.__wbg_ptr = ptr; + ES256PublicKeyFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + ES256PublicKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_es256publickey_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.es256publickey___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Verifies that a signature is valid for this public key and the provided data. + * @param {ES256Signature} signature + * @param {Uint8Array} data + * @returns {boolean} + */ + verify(signature, data) { + _assertClass(signature, ES256Signature); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_verify(this.__wbg_ptr, signature.__wbg_ptr, ptr0, len0); + return ret !== 0; + } + /** + * Deserializes a public key from a byte array. + * + * Throws when the byte array contains less than 33 bytes. + * @param {Uint8Array} bytes + * @returns {ES256PublicKey} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256PublicKey.__wrap(ret[0]); + } + /** + * Deserializes a public key from its SPKI representation. + * @param {Uint8Array} spki_bytes + * @returns {ES256PublicKey} + */ + static fromSpki(spki_bytes) { + const ptr0 = passArray8ToWasm0(spki_bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_fromSpki(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256PublicKey.__wrap(ret[0]); + } + /** + * Deserializes a public key from its raw representation. + * @param {Uint8Array} raw_bytes + * @returns {ES256PublicKey} + */ + static fromRaw(raw_bytes) { + const ptr0 = passArray8ToWasm0(raw_bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_fromRaw(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256PublicKey.__wrap(ret[0]); + } + /** + * Creates a new public key from a byte array. + * + * Compatible with the `-7` COSE algorithm identifier. + * + * ## Example + * + * ```javascript + * // Create/register a credential with the Webauthn API: + * const cred = await navigator.credentials.create({ + * publicKey: { + * pubKeyCredParams: [{ + * type: "public-key", + * alg: -7, // ES256 = ECDSA over P-256 with SHA-256 + * }], + * // ... + * }, + * }); + * + * // Then create an instance of ES256PublicKey from the credential response: + * const publicKey = new Nimiq.ES256PublicKey(new Uint8Array(cred.response.getPublicKey())); + * ``` + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + ES256PublicKeyFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the public key to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.es256publickey_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses a public key from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 33 bytes. + * @param {string} hex + * @returns {ES256PublicKey} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256publickey_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256PublicKey.__wrap(ret[0]); + } + /** + * Formats the public key into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.es256publickey_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Gets the public key's address. + * @returns {Address} + */ + toAddress() { + const ret = wasm.es256publickey_toAddress(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * Returns if this public key is equal to the other public key. + * @param {ES256PublicKey} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, ES256PublicKey); + const ret = wasm.es256publickey_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } + /** + * Compares this public key to the other public key. + * + * Returns -1 if this public key is smaller than the other public key, 0 if they are equal, + * and 1 if this public key is larger than the other public key. + * @param {ES256PublicKey} other + * @returns {number} + */ + compare(other) { + _assertClass(other, ES256PublicKey); + const ret = wasm.es256publickey_compare(this.__wbg_ptr, other.__wbg_ptr); + return ret; + } +} + +const ES256SignatureFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_es256signature_free(ptr >>> 0, 1)); +/** + * An ES256 Signature represents a cryptographic proof that an ES256 private key signed some data. + * It can be verified with the private key's public key. + */ +export class ES256Signature { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(ES256Signature.prototype); + obj.__wbg_ptr = ptr; + ES256SignatureFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + ES256SignatureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_es256signature_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.es256signature___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Deserializes an ES256 signature from a byte array. + * + * Throws when the byte array contains less than 64 bytes. + * @param {Uint8Array} bytes + * @returns {ES256Signature} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256signature_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256Signature.__wrap(ret[0]); + } + /** + * Serializes the signature to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.es256signature_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses an ES256 signature from its ASN.1 representation. + * @param {Uint8Array} bytes + * @returns {ES256Signature} + */ + static fromAsn1(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256signature_fromAsn1(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256Signature.__wrap(ret[0]); + } + /** + * Parses an ES256 signature from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 64 bytes. + * @param {string} hex + * @returns {ES256Signature} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.es256signature_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return ES256Signature.__wrap(ret[0]); + } + /** + * Formats the signature into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.es256signature_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const HashFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_hash_free(ptr >>> 0, 1)); + +export class Hash { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + HashFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_hash_free(ptr, 0); + } + /** + * Computes a 32-byte [Blake2b] hash from the input data. + * + * Blake2b is used for example to compute a public key's address. + * + * [Blake2b]: https://en.wikipedia.org/wiki/BLAKE_(hash_function) + * @param {Uint8Array} data + * @returns {Uint8Array} + */ + static computeBlake2b(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash_computeBlake2b(ptr0, len0); + var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v2; + } + /** + * Computes a 32-byte [SHA256] hash from the input data. + * + * [SHA256]: https://en.wikipedia.org/wiki/SHA-2 + * @param {Uint8Array} data + * @returns {Uint8Array} + */ + static computeSha256(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash_computeSha256(ptr0, len0); + var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v2; + } + /** + * Computes a 64-byte [SHA512] hash from the input data. + * + * [SHA512]: https://en.wikipedia.org/wiki/SHA-2 + * @param {Uint8Array} data + * @returns {Uint8Array} + */ + static computeSha512(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hash_computeSha512(ptr0, len0); + var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v2; + } + /** + * Computes an [Argon2d] hash with some Nimiq-specific parameters. + * + * `iterations` specifies the number of iterations done in the hash + * function. It can be used to control the hash computation time. + * Increasing this will make it harder for an attacker to brute-force the + * password. + * + * `derived_key_length` specifies the number of bytes that are output. + * + * [Argon2d]: https://en.wikipedia.org/wiki/Argon2 + * @param {Uint8Array} password + * @param {Uint8Array} salt + * @param {number} iterations + * @param {number} derived_key_length + * @returns {Uint8Array} + */ + static computeNimiqArgon2d(password, salt, iterations, derived_key_length) { + const ptr0 = passArray8ToWasm0(password, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.hash_computeNimiqArgon2d(ptr0, len0, ptr1, len1, iterations, derived_key_length); + if (ret[3]) { + throw takeFromExternrefTable0(ret[2]); + } + var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v3; + } + /** + * Computes an [Argon2id] hash with some Nimiq-specific parameters. + * + * `iterations` specifies the number of iterations done in the hash + * function. It can be used to control the hash computation time. + * Increasing this will make it harder for an attacker to brute-force the + * password. + * + * `derived_key_length` specifies the number of bytes that are output. + * + * [Argon2id]: https://en.wikipedia.org/wiki/Argon2 + * @param {Uint8Array} password + * @param {Uint8Array} salt + * @param {number} iterations + * @param {number} derived_key_length + * @returns {Uint8Array} + */ + static computeNimiqArgon2id(password, salt, iterations, derived_key_length) { + const ptr0 = passArray8ToWasm0(password, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(salt, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.hash_computeNimiqArgon2id(ptr0, len0, ptr1, len1, iterations, derived_key_length); + if (ret[3]) { + throw takeFromExternrefTable0(ret[2]); + } + var v3 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v3; + } +} + +const HashedTimeLockedContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_hashedtimelockedcontract_free(ptr >>> 0, 1)); +/** + * Utility class providing methods to parse Hashed Time Locked Contract transaction data and proofs. + */ +export class HashedTimeLockedContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + HashedTimeLockedContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_hashedtimelockedcontract_free(ptr, 0); + } + /** + * Parses the data of a Hashed Time Locked Contract creation transaction into a plain object. + * @param {Uint8Array} data + * @returns {PlainTransactionRecipientData} + */ + static dataToPlain(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hashedtimelockedcontract_dataToPlain(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Parses the proof of a Hashed Time Locked Contract settlement transaction into a plain object. + * @param {Uint8Array} proof + * @returns {PlainTransactionProof} + */ + static proofToPlain(proof) { + const ptr0 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.hashedtimelockedcontract_proofToPlain(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } +} + +const KeyPairFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_keypair_free(ptr >>> 0, 1)); +/** + * A keypair represents a private key and its respective public key. + * It is used for signing data, usually transactions. + */ +export class KeyPair { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(KeyPair.prototype); + obj.__wbg_ptr = ptr; + KeyPairFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + KeyPairFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_keypair_free(ptr, 0); + } + /** + * Generates a new keypair from secure randomness. + * @returns {KeyPair} + */ + static generate() { + const ret = wasm.keypair_generate(); + return KeyPair.__wrap(ret); + } + /** + * Derives a keypair from an existing private key. + * @param {PrivateKey} private_key + * @returns {KeyPair} + */ + static derive(private_key) { + _assertClass(private_key, PrivateKey); + const ret = wasm.keypair_derive(private_key.__wbg_ptr); + return KeyPair.__wrap(ret); + } + /** + * Parses a keypair from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 64 bytes. + * @param {string} hex + * @returns {KeyPair} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.keypair_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return KeyPair.__wrap(ret[0]); + } + /** + * Deserializes a keypair from a byte array. + * + * Throws when the byte array contains less than 64 bytes. + * @param {Uint8Array} bytes + * @returns {KeyPair} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.keypair_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return KeyPair.__wrap(ret[0]); + } + /** + * @param {PrivateKey} private_key + * @param {PublicKey} public_key + */ + constructor(private_key, public_key) { + _assertClass(private_key, PrivateKey); + _assertClass(public_key, PublicKey); + const ret = wasm.keypair_new(private_key.__wbg_ptr, public_key.__wbg_ptr); + this.__wbg_ptr = ret >>> 0; + KeyPairFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the keypair to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.keypair_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Signs arbitrary data, returns a signature object. + * @param {Uint8Array} data + * @returns {Signature} + */ + sign(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.keypair_sign(this.__wbg_ptr, ptr0, len0); + return Signature.__wrap(ret); + } + /** + * Signs a transaction and sets the signature proof on the transaction object. + * @param {Transaction} transaction + */ + signTransaction(transaction) { + _assertClass(transaction, Transaction); + const ret = wasm.keypair_signTransaction(this.__wbg_ptr, transaction.__wbg_ptr); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } + } + /** + * Gets the keypair's private key. + * @returns {PrivateKey} + */ + get privateKey() { + const ret = wasm.keypair_privateKey(this.__wbg_ptr); + return PrivateKey.__wrap(ret); + } + /** + * Gets the keypair's public key. + * @returns {PublicKey} + */ + get publicKey() { + const ret = wasm.keypair_publicKey(this.__wbg_ptr); + return PublicKey.__wrap(ret); + } + /** + * Gets the keypair's address. + * @returns {Address} + */ + toAddress() { + const ret = wasm.keypair_toAddress(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * Formats the keypair into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.keypair_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const MerkleTreeFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_merkletree_free(ptr >>> 0, 1)); +/** + * The Merkle tree is a data structure that allows for efficient verification of the membership of an element in a set. + */ +export class MerkleTree { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + MerkleTreeFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_merkletree_free(ptr, 0); + } + /** + * Computes the root of a Merkle tree from a list of Uint8Arrays. + * @param {(Uint8Array)[]} values + * @returns {Uint8Array} + */ + static computeRoot(values) { + const ptr0 = passArrayJsValueToWasm0(values, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.merkletree_computeRoot(ptr0, len0); + var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v2; + } +} + +const PolicyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_policy_free(ptr >>> 0, 1)); + +export class Policy { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + PolicyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_policy_free(ptr, 0); + } + /** + * Number of batches a transaction is valid with Albatross consensus. + * @returns {number} + */ + static get TRANSACTION_VALIDITY_WINDOW() { + const ret = wasm.policy_transaction_validity_window(); + return ret >>> 0; + } + /** + * Number of blocks a transaction is valid with Albatross consensus. + * @returns {number} + */ + static get TRANSACTION_VALIDITY_WINDOW_BLOCKS() { + const ret = wasm.policy_transaction_validity_window_blocks(); + return ret >>> 0; + } + /** + * How many batches constitute an epoch + * @returns {number} + */ + static get BATCHES_PER_EPOCH() { + const ret = wasm.policy_batches_per_epoch(); + return ret; + } + /** + * Length of a batch including the macro block + * @returns {number} + */ + static get BLOCKS_PER_BATCH() { + const ret = wasm.policy_blocks_per_batch(); + return ret >>> 0; + } + /** + * Length of an epoch including the election block + * @returns {number} + */ + static get BLOCKS_PER_EPOCH() { + const ret = wasm.policy_blocks_per_epoch(); + return ret >>> 0; + } + /** + * Genesis block number + * @returns {number} + */ + static get GENESIS_BLOCK_NUMBER() { + const ret = wasm.policy_genesis_block_number(); + return ret >>> 0; + } + /** + * Maximum size of accounts trie chunks. + * @returns {number} + */ + static get STATE_CHUNKS_MAX_SIZE() { + const ret = wasm.policy_state_chunks_max_size(); + return ret >>> 0; + } + /** + * Returns the epoch number at a given block number (height). + * @param {number} block_number + * @returns {number} + */ + static epochAt(block_number) { + const ret = wasm.policy_epochAt(block_number); + return ret >>> 0; + } + /** + * Returns the epoch index at a given block number. The epoch index is the number of a block relative + * to the epoch it is in. For example, the first block of any epoch always has an epoch index of 0. + * @param {number} block_number + * @returns {number} + */ + static epochIndexAt(block_number) { + const ret = wasm.policy_epochIndexAt(block_number); + return ret >>> 0; + } + /** + * Returns the batch number at a given `block_number` (height) + * @param {number} block_number + * @returns {number} + */ + static batchAt(block_number) { + const ret = wasm.policy_batchAt(block_number); + return ret >>> 0; + } + /** + * Returns the batch index at a given block number. The batch index is the number of a block relative + * to the batch it is in. For example, the first block of any batch always has an batch index of 0. + * @param {number} block_number + * @returns {number} + */ + static batchIndexAt(block_number) { + const ret = wasm.policy_batchIndexAt(block_number); + return ret >>> 0; + } + /** + * Returns the number (height) of the next election macro block after a given block number (height). + * @param {number} block_number + * @returns {number} + */ + static electionBlockAfter(block_number) { + const ret = wasm.policy_electionBlockAfter(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the preceding election macro block before a given block number (height). + * If the given block number is an election macro block, it returns the election macro block before it. + * @param {number} block_number + * @returns {number} + */ + static electionBlockBefore(block_number) { + const ret = wasm.policy_electionBlockBefore(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the last election macro block at a given block number (height). + * If the given block number is an election macro block, then it returns that block number. + * @param {number} block_number + * @returns {number} + */ + static lastElectionBlock(block_number) { + const ret = wasm.policy_lastElectionBlock(block_number); + return ret >>> 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is an election macro block. + * @param {number} block_number + * @returns {boolean} + */ + static isElectionBlockAt(block_number) { + const ret = wasm.policy_isElectionBlockAt(block_number); + return ret !== 0; + } + /** + * Returns the block number (height) of the next macro block after a given block number (height). + * If the given block number is a macro block, it returns the macro block after it. + * @param {number} block_number + * @returns {number} + */ + static macroBlockAfter(block_number) { + const ret = wasm.policy_macroBlockAfter(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the preceding macro block before a given block number (height). + * If the given block number is a macro block, it returns the macro block before it. + * @param {number} block_number + * @returns {number} + */ + static macroBlockBefore(block_number) { + const ret = wasm.policy_macroBlockBefore(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the last macro block at a given block number (height). + * If the given block number is a macro block, then it returns that block number. + * @param {number} block_number + * @returns {number} + */ + static lastMacroBlock(block_number) { + const ret = wasm.policy_lastMacroBlock(block_number); + return ret >>> 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is a macro block. + * @param {number} block_number + * @returns {boolean} + */ + static isMacroBlockAt(block_number) { + const ret = wasm.policy_isMacroBlockAt(block_number); + return ret !== 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is a micro block. + * @param {number} block_number + * @returns {boolean} + */ + static isMicroBlockAt(block_number) { + const ret = wasm.policy_isMicroBlockAt(block_number); + return ret !== 0; + } + /** + * Returns the block number of the first block of the given epoch (which is always a micro block). + * If the index is out of bounds, None is returned + * @param {number} epoch + * @returns {number | undefined} + */ + static firstBlockOf(epoch) { + const ret = wasm.policy_firstBlockOf(epoch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the first block of the given batch (which is always a micro block). + * If the index is out of bounds, None is returned + * @param {number} batch + * @returns {number | undefined} + */ + static firstBlockOfBatch(batch) { + const ret = wasm.policy_firstBlockOfBatch(batch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the election macro block of the given epoch (which is always the last block). + * If the index is out of bounds, None is returned + * @param {number} epoch + * @returns {number | undefined} + */ + static electionBlockOf(epoch) { + const ret = wasm.policy_electionBlockOf(epoch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the macro block (checkpoint or election) of the given batch (which + * is always the last block). + * If the index is out of bounds, None is returned + * @param {number} batch + * @returns {number | undefined} + */ + static macroBlockOf(batch) { + const ret = wasm.policy_macroBlockOf(batch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns a boolean expressing if the batch at a given block number (height) is the first batch + * of the epoch. + * @param {number} block_number + * @returns {boolean} + */ + static firstBatchOfEpoch(block_number) { + const ret = wasm.policy_firstBatchOfEpoch(block_number); + return ret !== 0; + } + /** + * Returns the block height for the last block of the reporting window of a given block number. + * Note: This window is meant for reporting malicious behaviour (aka `jailable` behaviour). + * @param {number} block_number + * @returns {number} + */ + static lastBlockOfReportingWindow(block_number) { + const ret = wasm.policy_lastBlockOfReportingWindow(block_number); + return ret >>> 0; + } + /** + * Returns the first block after the reporting window of a given block number has ended. + * @param {number} block_number + * @returns {number} + */ + static blockAfterReportingWindow(block_number) { + const ret = wasm.policy_blockAfterReportingWindow(block_number); + return ret >>> 0; + } + /** + * Returns the first block after the jail period of a given block number has ended. + * @param {number} block_number + * @returns {number} + */ + static blockAfterJail(block_number) { + const ret = wasm.policy_blockAfterJail(block_number); + return ret >>> 0; + } + /** + * Returns the supply at a given time (as Unix time) in Lunas (1 NIM = 100,000 Lunas). It is + * calculated using the following formula: + * ```text + * supply(t) = total_supply - (total_supply - genesis_supply) * supply_decay^t + * ``` + * Where t is the time in milliseconds since the PoS genesis block and `genesis_supply` is the supply at + * the genesis of the Nimiq 2.0 chain. + * @param {bigint} genesis_supply + * @param {bigint} genesis_time + * @param {bigint} current_time + * @returns {bigint} + */ + static supplyAt(genesis_supply, genesis_time, current_time) { + const ret = wasm.policy_supplyAt(genesis_supply, genesis_time, current_time); + return BigInt.asUintN(64, ret); + } + /** + * Returns the percentage reduction that should be applied to the rewards due to a delayed batch. + * This function returns a float in the range [0, 1] + * I.e 1 means that the full rewards should be given, whereas 0.5 means that half of the rewards should be given + * The input to this function is the batch delay, in milliseconds + * The function is: [(1 - MINIMUM_REWARDS_PERCENTAGE) * BLOCKS_DELAY_DECAY ^ (t^2)] + MINIMUM_REWARDS_PERCENTAGE + * @param {bigint} delay + * @returns {number} + */ + static batchDelayPenalty(delay) { + const ret = wasm.policy_batchDelayPenalty(delay); + return ret; + } + /** + * This is the address for the staking contract. + * @returns {string} + */ + static get STAKING_CONTRACT_ADDRESS() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.policy_wasm_staking_contract_address(); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * This is the address for the coinbase. Note that this is not a real account, it is just the + * address we use to denote that some coins originated from a coinbase event. + * @returns {string} + */ + static get COINBASE_ADDRESS() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.policy_wasm_coinbase_address(); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * The maximum allowed size, in bytes, for a micro block body. + * @returns {number} + */ + static get MAX_SIZE_MICRO_BODY() { + const ret = wasm.policy_wasm_max_size_micro_body(); + return ret >>> 0; + } + /** + * The current version number of the protocol. Changing this always results in a hard fork. + * @returns {number} + */ + static get VERSION() { + const ret = wasm.policy_wasm_min_epochs_stored(); + return ret; + } + /** + * Number of available validator slots. Note that a single validator may own several validator slots. + * @returns {number} + */ + static get SLOTS() { + const ret = wasm.policy_wasm_slots(); + return ret; + } + /** + * Calculates 2f+1 slots which is the minimum number of slots necessary to produce a macro block, + * a skip block and other actions. + * It is also the minimum number of slots necessary to be guaranteed to have a majority of honest + * slots. That's because from a total of 3f+1 slots at most f will be malicious. If in a group of + * 2f+1 slots we have f malicious ones (which is the worst case scenario), that still leaves us + * with f+1 honest slots. Which is more than the f slots that are not in this group (which must all + * be honest). + * It is calculated as `ceil(SLOTS*2/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the + * ceiling division. + * @returns {number} + */ + static get TWO_F_PLUS_ONE() { + const ret = wasm.policy_wasm_two_f_plus_one(); + return ret; + } + /** + * Calculates f+1 slots which is the minimum number of slots necessary to be guaranteed to have at + * least one honest slots. That's because from a total of 3f+1 slots at most f will be malicious. + * It is calculated as `ceil(SLOTS/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the + * ceiling division. + * @returns {number} + */ + static get F_PLUS_ONE() { + const ret = wasm.policy_wasm_f_plus_one(); + return ret; + } + /** + * The minimum timeout in milliseconds for a validator to produce a block (4s) + * @returns {bigint} + */ + static get MIN_PRODUCER_TIMEOUT() { + const ret = wasm.policy_wasm_min_block_producer_timeout(); + return BigInt.asUintN(64, ret); + } + /** + * The optimal time in milliseconds between blocks (1s) + * @returns {bigint} + */ + static get BLOCK_SEPARATION_TIME() { + const ret = wasm.policy_wasm_block_separation_time(); + return BigInt.asUintN(64, ret); + } + /** + * Minimum number of epochs that the ChainStore will store fully + * @returns {number} + */ + static get MIN_EPOCHS_STORED() { + const ret = wasm.policy_wasm_min_epochs_stored(); + return ret >>> 0; + } + /** + * The maximum drift, in milliseconds, that is allowed between any block's timestamp and the node's + * system time. We only care about drifting to the future. + * @returns {bigint} + */ + static get TIMESTAMP_MAX_DRIFT() { + const ret = wasm.policy_wasm_timestamp_max_drift(); + return BigInt.asUintN(64, ret); + } + /** + * The minimum rewards percentage that we allow + * @returns {number} + */ + static get MINIMUM_REWARDS_PERCENTAGE() { + const ret = wasm.policy_wasm_minimum_rewards_percentage(); + return ret; + } + /** + * The deposit necessary to create a validator in Lunas (1 NIM = 100,000 Lunas). + * A validator is someone who actually participates in block production. They are akin to miners + * in proof-of-work. + * @returns {bigint} + */ + static get VALIDATOR_DEPOSIT() { + const ret = wasm.policy_wasm_validator_deposit(); + return BigInt.asUintN(64, ret); + } + /** + * The number of epochs a validator is put in jail for. The jailing only happens for severe offenses. + * @returns {number} + */ + static get JAIL_EPOCHS() { + const ret = wasm.policy_wasm_jail_epochs(); + return ret >>> 0; + } + /** + * Total supply in units. + * @returns {bigint} + */ + static get TOTAL_SUPPLY() { + const ret = wasm.policy_wasm_total_supply(); + return BigInt.asUintN(64, ret); + } + /** + * The maximum size of the BLS public key cache. + * @returns {number} + */ + static get BLS_CACHE_MAX_CAPACITY() { + const ret = wasm.policy_wasm_bls_cache_max_capacity(); + return ret >>> 0; + } + /** + * Maximum size of history chunks. + * 25 MB. + * @returns {bigint} + */ + static get HISTORY_CHUNKS_MAX_SIZE() { + const ret = wasm.policy_wasm_history_chunks_max_size(); + return BigInt.asUintN(64, ret); + } +} + +const PrivateKeyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_privatekey_free(ptr >>> 0, 1)); +/** + * The secret (private) part of an asymmetric key pair that is typically used to digitally sign or decrypt data. + */ +export class PrivateKey { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(PrivateKey.prototype); + obj.__wbg_ptr = ptr; + PrivateKeyFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + PrivateKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_privatekey_free(ptr, 0); + } + /** + * @returns {number} + */ + static get PURPOSE_ID() { + const ret = wasm.privatekey_purpose_id(); + return ret >>> 0; + } + /** + * @returns {number} + */ + static get SIZE() { + const ret = wasm.privatekey_size(); + return ret >>> 0; + } + /** + * @returns {number} + */ + get serializedSize() { + const ret = wasm.privatekey_serialized_size(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Generates a new private key from secure randomness. + * @returns {PrivateKey} + */ + static generate() { + const ret = wasm.privatekey_generate(); + return PrivateKey.__wrap(ret); + } + /** + * Deserializes a private key from a byte array. + * + * Throws when the byte array contains less than 32 bytes. + * @param {Uint8Array} bytes + * @returns {PrivateKey} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.privatekey_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PrivateKey.__wrap(ret[0]); + } + /** + * Creates a new private key from a byte array. + * + * Throws when the byte array is not exactly 32 bytes long. + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.privatekey_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + PrivateKeyFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the private key to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.privatekey_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses a private key from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 32 bytes. + * @param {string} hex + * @returns {PrivateKey} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.privatekey_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PrivateKey.__wrap(ret[0]); + } + /** + * Formats the private key into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.privatekey_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Returns if this private key is equal to the other private key. + * @param {PrivateKey} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, PrivateKey); + const ret = wasm.privatekey_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } +} + +const PublicKeyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_publickey_free(ptr >>> 0, 1)); +/** + * The non-secret (public) part of an asymmetric key pair that is typically used to digitally verify or encrypt data. + */ +export class PublicKey { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(PublicKey.prototype); + obj.__wbg_ptr = ptr; + PublicKeyFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + PublicKeyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_publickey_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.publickey___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * @returns {number} + */ + static get SIZE() { + const ret = wasm.privatekey_size(); + return ret >>> 0; + } + /** + * @returns {number} + */ + get serializedSize() { + const ret = wasm.publickey_serialized_size(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Derives a public key from an existing private key. + * @param {PrivateKey} private_key + * @returns {PublicKey} + */ + static derive(private_key) { + _assertClass(private_key, PrivateKey); + const ret = wasm.publickey_derive(private_key.__wbg_ptr); + return PublicKey.__wrap(ret); + } + /** + * Parses a public key from a {@link PublicKey} instance, a hex string representation, or a byte array. + * + * Throws when an PublicKey cannot be parsed from the argument. + * @param {PublicKey | string | Uint8Array} addr + * @returns {PublicKey} + */ + static fromAny(addr) { + const ret = wasm.publickey_fromAny(addr); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PublicKey.__wrap(ret[0]); + } + /** + * Verifies that a signature is valid for this public key and the provided data. + * @param {Signature} signature + * @param {Uint8Array} data + * @returns {boolean} + */ + verify(signature, data) { + _assertClass(signature, Signature); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_verify(this.__wbg_ptr, signature.__wbg_ptr, ptr0, len0); + return ret !== 0; + } + /** + * Deserializes a public key from a byte array. + * + * Throws when the byte array contains less than 32 bytes. + * @param {Uint8Array} bytes + * @returns {PublicKey} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PublicKey.__wrap(ret[0]); + } + /** + * Deserializes a public key from its SPKI representation. + * @param {Uint8Array} spki_bytes + * @returns {PublicKey} + */ + static fromSpki(spki_bytes) { + const ptr0 = passArray8ToWasm0(spki_bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_fromSpki(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PublicKey.__wrap(ret[0]); + } + /** + * Deserializes a public key from its raw representation. + * @param {Uint8Array} raw_bytes + * @returns {PublicKey} + */ + static fromRaw(raw_bytes) { + const ptr0 = passArray8ToWasm0(raw_bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_fromRaw(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PublicKey.__wrap(ret[0]); + } + /** + * Creates a new public key from a byte array. + * + * Throws when the byte array is not exactly 32 bytes long. + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + PublicKeyFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Serializes the public key to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.publickey_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Parses a public key from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 32 bytes. + * @param {string} hex + * @returns {PublicKey} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.publickey_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return PublicKey.__wrap(ret[0]); + } + /** + * Formats the public key into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.publickey_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Gets the public key's address. + * @returns {Address} + */ + toAddress() { + const ret = wasm.publickey_toAddress(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * Returns if this public key is equal to the other public key. + * @param {PublicKey} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, PublicKey); + const ret = wasm.publickey_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } + /** + * Compares this public key to the other public key. + * + * Returns -1 if this public key is smaller than the other public key, 0 if they are equal, + * and 1 if this public key is larger than the other public key. + * @param {PublicKey} other + * @returns {number} + */ + compare(other) { + _assertClass(other, PublicKey); + const ret = wasm.publickey_compare(this.__wbg_ptr, other.__wbg_ptr); + return ret; + } +} + +const SignatureFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_signature_free(ptr >>> 0, 1)); +/** + * An Ed25519 Signature represents a cryptographic proof that a private key signed some data. + * It can be verified with the private key's public key. + */ +export class Signature { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Signature.prototype); + obj.__wbg_ptr = ptr; + SignatureFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + SignatureFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_signature_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.signature___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Deserializes an Ed25519 signature from a byte array. + * + * Throws when the byte array contains less than 64 bytes. + * @param {Uint8Array} bytes + * @returns {Signature} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signature_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Signature.__wrap(ret[0]); + } + /** + * Serializes the signature to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.signature_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Create a signature from a private key and its public key over byte data. + * @param {PrivateKey} private_key + * @param {PublicKey} public_key + * @param {Uint8Array} data + * @returns {Signature} + */ + static create(private_key, public_key, data) { + _assertClass(private_key, PrivateKey); + _assertClass(public_key, PublicKey); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signature_create(private_key.__wbg_ptr, public_key.__wbg_ptr, ptr0, len0); + return Signature.__wrap(ret); + } + /** + * Parses an Ed25519 signature from its ASN.1 representation. + * @param {Uint8Array} bytes + * @returns {Signature} + */ + static fromAsn1(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signature_fromAsn1(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Signature.__wrap(ret[0]); + } + /** + * Parses an Ed25519 signature from its hex representation. + * + * Throws when the string is not valid hex format or when it represents less than 64 bytes. + * @param {string} hex + * @returns {Signature} + */ + static fromHex(hex) { + const ptr0 = passStringToWasm0(hex, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signature_fromHex(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Signature.__wrap(ret[0]); + } + /** + * Formats the signature into a hex string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.signature_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } +} + +const SignatureProofFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_signatureproof_free(ptr >>> 0, 1)); +/** + * A signature proof represents a signature together with its public key and the public key's merkle path. + * It is used as the proof for transactions. + */ +export class SignatureProof { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(SignatureProof.prototype); + obj.__wbg_ptr = ptr; + SignatureProofFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + SignatureProofFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_signatureproof_free(ptr, 0); + } + /** + * @returns {number} + */ + static get SINGLE_SIG_SIZE() { + const ret = wasm.signatureproof_single_sig_size(); + return ret >>> 0; + } + /** + * @returns {number} + */ + static get ES256_SINGLE_SIG_SIZE() { + const ret = wasm.signatureproof_es256_single_sig_size(); + return ret >>> 0; + } + /** + * Creates a Ed25519/Schnorr signature proof for a single-sig signature. + * @param {PublicKey} public_key + * @param {Signature} signature + * @returns {SignatureProof} + */ + static singleSig(public_key, signature) { + _assertClass(public_key, PublicKey); + _assertClass(signature, Signature); + const ret = wasm.signatureproof_singleSig(public_key.__wbg_ptr, signature.__wbg_ptr); + return SignatureProof.__wrap(ret); + } + /** + * Creates a Ed25519/Schnorr signature proof for a multi-sig signature. + * The public keys can also include ES256 keys. + * @param {PublicKey} signer_key + * @param {(PublicKey | ES256PublicKey)[]} public_keys + * @param {Signature} signature + * @returns {SignatureProof} + */ + static multiSig(signer_key, public_keys, signature) { + _assertClass(signer_key, PublicKey); + _assertClass(signature, Signature); + const ret = wasm.signatureproof_multiSig(signer_key.__wbg_ptr, public_keys, signature.__wbg_ptr); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return SignatureProof.__wrap(ret[0]); + } + /** + * Creates a Webauthn signature proof for a single-sig signature. + * @param {PublicKey | ES256PublicKey} public_key + * @param {Signature | ES256Signature} signature + * @param {Uint8Array} authenticator_data + * @param {Uint8Array} client_data_json + * @returns {SignatureProof} + */ + static webauthnSingleSig(public_key, signature, authenticator_data, client_data_json) { + const ptr0 = passArray8ToWasm0(authenticator_data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(client_data_json, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.signatureproof_webauthnSingleSig(public_key, signature, ptr0, len0, ptr1, len1); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return SignatureProof.__wrap(ret[0]); + } + /** + * Creates a Webauthn signature proof for a multi-sig signature. + * @param {PublicKey | ES256PublicKey} signer_key + * @param {(PublicKey | ES256PublicKey)[]} public_keys + * @param {Signature | ES256Signature} signature + * @param {Uint8Array} authenticator_data + * @param {Uint8Array} client_data_json + * @returns {SignatureProof} + */ + static webauthnMultiSig(signer_key, public_keys, signature, authenticator_data, client_data_json) { + const ptr0 = passArray8ToWasm0(authenticator_data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ptr1 = passArray8ToWasm0(client_data_json, wasm.__wbindgen_malloc); + const len1 = WASM_VECTOR_LEN; + const ret = wasm.signatureproof_webauthnMultiSig(signer_key, public_keys, signature, ptr0, len0, ptr1, len1); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return SignatureProof.__wrap(ret[0]); + } + /** + * Verifies the signature proof against the provided data. + * @param {Uint8Array} data + * @returns {boolean} + */ + verify(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signatureproof_verify(this.__wbg_ptr, ptr0, len0); + return ret !== 0; + } + /** + * Checks if the signature proof is signed by the provided address. + * @param {Address} sender + * @returns {boolean} + */ + isSignedBy(sender) { + _assertClass(sender, Address); + const ret = wasm.signatureproof_isSignedBy(this.__wbg_ptr, sender.__wbg_ptr); + return ret !== 0; + } + /** + * The embedded signature. + * @returns {Signature | ES256Signature} + */ + get signature() { + const ret = wasm.signatureproof_signature(this.__wbg_ptr); + return ret; + } + /** + * The embedded public key. + * @returns {PublicKey | ES256PublicKey} + */ + get publicKey() { + const ret = wasm.signatureproof_publicKey(this.__wbg_ptr); + return ret; + } + /** + * Serializes the proof to a byte array, e.g. for assigning it to a `transaction.proof` field. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.signatureproof_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Creates a JSON-compatible plain object representing the signature proof. + * @returns {PlainTransactionProof} + */ + toPlain() { + const ret = wasm.signatureproof_toPlain(this.__wbg_ptr); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Deserializes a signature proof from a byte array. + * @param {Uint8Array} bytes + * @returns {SignatureProof} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signatureproof_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return SignatureProof.__wrap(ret[0]); + } +} + +const StakingContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_stakingcontract_free(ptr >>> 0, 1)); +/** + * Utility class providing methods to parse Staking Contract transaction data and proofs. + */ +export class StakingContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + StakingContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakingcontract_free(ptr, 0); + } + /** + * Parses the data of a Staking Contract incoming transaction into a plain object. + * @param {Uint8Array} data + * @returns {PlainTransactionRecipientData} + */ + static dataToPlain(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.stakingcontract_dataToPlain(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Parses the proof of a Staking Contract outgoing transaction into a plain object. + * @param {Uint8Array} proof + * @returns {PlainTransactionProof} + */ + static proofToPlain(proof) { + const ptr0 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.stakingcontract_proofToPlain(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } +} + +const TransactionFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_transaction_free(ptr >>> 0, 1)); +/** + * Transactions describe a transfer of value, usually from the sender to the recipient. + * However, transactions can also have no value, when they are used to _signal_ a change in the staking contract. + * + * Transactions can be used to create contracts, such as vesting contracts and HTLCs. + * + * Transactions require a valid signature proof over their serialized content. + * Furthermore, transactions are only valid for 2 hours after their validity-start block height. + */ +export class Transaction { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Transaction.prototype); + obj.__wbg_ptr = ptr; + TransactionFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + TransactionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transaction_free(ptr, 0); + } + /** + * @returns {string} + */ + __getClassname() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.transaction___getClassname(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Creates a new unsigned transaction that transfers `value` amount of luna (NIM's smallest unit) + * from the sender to the recipient, where both sender and recipient can be any account type, + * and custom extra data can be added to the transaction. + * + * ### Basic transactions + * If both the sender and recipient types are omitted or `0` and both data and flags are empty, + * a smaller basic transaction is created. + * + * ### Extended transactions + * If no flags are given, but sender type is not basic (`0`) or data is set, an extended + * transaction is created. + * + * ### Contract creation transactions + * To create a new vesting or HTLC contract, set `flags` to `0b1` and specify the contract + * type as the `recipient_type`: `1` for vesting, `2` for HTLC. The `data` bytes must have + * the correct format of contract creation data for the respective contract type. + * + * ### Signaling transactions + * To interact with the staking contract, signaling transaction are often used to not + * transfer any value, but to simply _signal_ a state change instead, such as changing one's + * delegation from one validator to another. To create such a transaction, set `flags` to ` + * 0b10` and populate the `data` bytes accordingly. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when an account type is unknown, the numbers given for value and fee do not fit + * within a u64 or the networkId is unknown. Also throws when no data or recipient type is + * given for contract creation transactions, or no data is given for signaling transactions. + * @param {Address} sender + * @param {number | undefined} sender_type + * @param {Uint8Array | undefined} sender_data + * @param {Address} recipient + * @param {number | undefined} recipient_type + * @param {Uint8Array | undefined} recipient_data + * @param {bigint} value + * @param {bigint} fee + * @param {number | undefined} flags + * @param {number} validity_start_height + * @param {number} network_id + */ + constructor(sender, sender_type, sender_data, recipient, recipient_type, recipient_data, value, fee, flags, validity_start_height, network_id) { + _assertClass(sender, Address); + var ptr0 = isLikeNone(sender_data) ? 0 : passArray8ToWasm0(sender_data, wasm.__wbindgen_malloc); + var len0 = WASM_VECTOR_LEN; + _assertClass(recipient, Address); + var ptr1 = isLikeNone(recipient_data) ? 0 : passArray8ToWasm0(recipient_data, wasm.__wbindgen_malloc); + var len1 = WASM_VECTOR_LEN; + const ret = wasm.transaction_new(sender.__wbg_ptr, isLikeNone(sender_type) ? 0xFFFFFF : sender_type, ptr0, len0, recipient.__wbg_ptr, isLikeNone(recipient_type) ? 0xFFFFFF : recipient_type, ptr1, len1, value, fee, isLikeNone(flags) ? 0xFFFFFF : flags, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + TransactionFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Signs the transaction with the provided key pair. Automatically determines the format + * of the signature proof required for the transaction. + * + * ### Limitations + * - HTLC redemption is not supported and will throw. + * - For transaction to the staking contract, both signatures are made with the same keypair, + * so it is not possible to interact with a staker that is different from the sender address + * or using a different cold or signing key for validator transactions. + * @param {KeyPair} key_pair + */ + sign(key_pair) { + _assertClass(key_pair, KeyPair); + const ret = wasm.transaction_sign(this.__wbg_ptr, key_pair.__wbg_ptr); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } + } + /** + * Computes the transaction's hash, which is used as its unique identifier on the blockchain. + * @returns {string} + */ + hash() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.transaction_hash(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Verifies that a transaction has valid properties and a valid signature proof. + * Optionally checks if the transaction is valid on the provided network. + * + * **Throws with any transaction validity error.** Returns without exception if the transaction is valid. + * + * Throws when the given networkId is unknown. + * @param {number | undefined} [network_id] + */ + verify(network_id) { + const ret = wasm.transaction_verify(this.__wbg_ptr, isLikeNone(network_id) ? 0xFFFFFF : network_id); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } + } + /** + * Tests if the transaction is valid at the specified block height. + * @param {number} block_height + * @returns {boolean} + */ + isValidAt(block_height) { + const ret = wasm.transaction_isValidAt(this.__wbg_ptr, block_height); + return ret !== 0; + } + /** + * Returns the address of the contract that is created with this transaction. + * @returns {Address} + */ + getContractCreationAddress() { + const ret = wasm.transaction_getContractCreationAddress(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * Serializes the transaction's content to be used for creating its signature. + * @returns {Uint8Array} + */ + serializeContent() { + const ret = wasm.transaction_serializeContent(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Serializes the transaction to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.transaction_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * The transaction's {@link TransactionFormat}. + * @returns {TransactionFormat} + */ + get format() { + const ret = wasm.transaction_format(this.__wbg_ptr); + return ret; + } + /** + * The transaction's sender address. + * @returns {Address} + */ + get sender() { + const ret = wasm.transaction_sender(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * The transaction's sender {@link AccountType}. + * @returns {AccountType} + */ + get senderType() { + const ret = wasm.transaction_senderType(this.__wbg_ptr); + return ret; + } + /** + * The transaction's recipient address. + * @returns {Address} + */ + get recipient() { + const ret = wasm.transaction_recipient(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * The transaction's recipient {@link AccountType}. + * @returns {AccountType} + */ + get recipientType() { + const ret = wasm.transaction_recipientType(this.__wbg_ptr); + return ret; + } + /** + * The transaction's value in luna (NIM's smallest unit). + * @returns {bigint} + */ + get value() { + const ret = wasm.transaction_value(this.__wbg_ptr); + return BigInt.asUintN(64, ret); + } + /** + * The transaction's fee in luna (NIM's smallest unit). + * @returns {bigint} + */ + get fee() { + const ret = wasm.transaction_fee(this.__wbg_ptr); + return BigInt.asUintN(64, ret); + } + /** + * The transaction's fee per byte in luna (NIM's smallest unit). + * @returns {number} + */ + get feePerByte() { + const ret = wasm.transaction_feePerByte(this.__wbg_ptr); + return ret; + } + /** + * The transaction's validity-start height. The transaction is valid for 2 hours after this block height. + * @returns {number} + */ + get validityStartHeight() { + const ret = wasm.transaction_validityStartHeight(this.__wbg_ptr); + return ret >>> 0; + } + /** + * The transaction's network ID. + * @returns {number} + */ + get networkId() { + const ret = wasm.transaction_networkId(this.__wbg_ptr); + return ret; + } + /** + * The transaction's flags: `0b1` = contract creation, `0b10` = signaling. + * @returns {TransactionFlag} + */ + get flags() { + const ret = wasm.transaction_flags(this.__wbg_ptr); + return ret; + } + /** + * The transaction's data as a byte array. + * @returns {Uint8Array} + */ + get data() { + const ret = wasm.transaction_data(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Set the transaction's data + * @param {Uint8Array} data + */ + set data(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_set_data(this.__wbg_ptr, ptr0, len0); + } + /** + * The transaction's sender data as a byte array. + * @returns {Uint8Array} + */ + get senderData() { + const ret = wasm.transaction_senderData(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * The transaction's signature proof as a byte array. + * @returns {Uint8Array} + */ + get proof() { + const ret = wasm.transaction_proof(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Set the transaction's signature proof. + * @param {Uint8Array} proof + */ + set proof(proof) { + const ptr0 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_set_proof(this.__wbg_ptr, ptr0, len0); + } + /** + * The transaction's byte size. + * @returns {number} + */ + get serializedSize() { + const ret = wasm.transaction_serializedSize(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Serializes the transaction into a HEX string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.transaction_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Creates a JSON-compatible plain object representing the transaction. + * @param {number | undefined} [genesis_number] + * @param {bigint | undefined} [genesis_timestamp] + * @returns {PlainTransaction} + */ + toPlain(genesis_number, genesis_timestamp) { + const ret = wasm.transaction_toPlain(this.__wbg_ptr, isLikeNone(genesis_number) ? 0x100000001 : (genesis_number) >>> 0, !isLikeNone(genesis_timestamp), isLikeNone(genesis_timestamp) ? BigInt(0) : genesis_timestamp); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Deserializes a transaction from a byte array. + * @param {Uint8Array} bytes + * @returns {Transaction} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.transaction_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Parses a transaction from a {@link Transaction} instance, a plain object, a hex string + * representation, or a byte array. + * + * Throws when a transaction cannot be parsed from the argument. + * @param {Transaction | PlainTransaction | string | Uint8Array} tx + * @returns {Transaction} + */ + static fromAny(tx) { + const ret = wasm.transaction_fromAny(tx); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Parses a transaction from a plain object. + * + * Throws when a transaction cannot be parsed from the argument. + * @param {PlainTransaction} plain + * @returns {Transaction} + */ + static fromPlain(plain) { + const ret = wasm.transaction_fromPlain(plain); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } +} + +const TransactionBuilderFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_transactionbuilder_free(ptr >>> 0, 1)); +/** + * The TransactionBuilder class provides helper methods to easily create standard types of transactions. + * It can only be instantiated from a Client with `client.transactionBuilder()`. + */ +export class TransactionBuilder { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + TransactionBuilderFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transactionbuilder_free(ptr, 0); + } + /** + * Creates a basic transaction that transfers `value` amount of luna (NIM's smallest unit) from the + * sender to the recipient. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for value and fee do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {Address} recipient + * @param {bigint} value + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newBasic(sender, recipient, value, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(recipient, Address); + const ret = wasm.transactionbuilder_newBasic(sender.__wbg_ptr, recipient.__wbg_ptr, value, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Creates a basic transaction that transfers `value` amount of luna (NIM's smallest unit) from the + * sender to the recipient. It can include arbitrary `data`, up to 64 bytes. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for value and fee do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {Address} recipient + * @param {Uint8Array} data + * @param {bigint} value + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newBasicWithData(sender, recipient, data, value, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(recipient, Address); + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.transactionbuilder_newBasicWithData(sender.__wbg_ptr, recipient.__wbg_ptr, ptr0, len0, value, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Creates a new staker in the staking contract and transfers `value` amount of luna (NIM's smallest unit) + * from the sender account to this new staker. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for value and fee do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {Address} delegation + * @param {bigint} value + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newCreateStaker(sender, delegation, value, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(delegation, Address); + const ret = wasm.transactionbuilder_newCreateStaker(sender.__wbg_ptr, delegation.__wbg_ptr, value, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Adds stake to a staker in the staking contract and transfers `value` amount of luna (NIM's smallest unit) + * from the sender account to this staker. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for value and fee do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {Address} staker_address + * @param {bigint} value + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newAddStake(sender, staker_address, value, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(staker_address, Address); + const ret = wasm.transactionbuilder_newAddStake(sender.__wbg_ptr, staker_address.__wbg_ptr, value, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Updates a staker in the staking contract to stake for a different validator. This is a + * signaling transaction and as such does not transfer any value. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the number given for fee does not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {Address} new_delegation + * @param {boolean} reactivate_all_stake + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newUpdateStaker(sender, new_delegation, reactivate_all_stake, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(new_delegation, Address); + const ret = wasm.transactionbuilder_newUpdateStaker(sender.__wbg_ptr, new_delegation.__wbg_ptr, reactivate_all_stake, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Sets the active stake balance of the staker. This is a + * signaling transaction and as such does not transfer any value. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for fee and `new_active_balance` do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {bigint} new_active_balance + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newSetActiveStake(sender, new_active_balance, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + const ret = wasm.transactionbuilder_newSetActiveStake(sender.__wbg_ptr, new_active_balance, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Retires a portion of the inactive stake balance of the staker. This is a + * signaling transaction and as such does not transfer any value. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for fee and `retire_stake` do not fit within a u64 or the networkId is unknown. + * @param {Address} sender + * @param {bigint} retire_stake + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newRetireStake(sender, retire_stake, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + const ret = wasm.transactionbuilder_newRetireStake(sender.__wbg_ptr, retire_stake, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Removes stake from the staking contract and transfers `value` amount of luna (NIM's smallest unit) + * from the staker to the recipient. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the numbers given for value and fee do not fit within a u64 or the networkId is unknown. + * @param {Address} recipient + * @param {bigint} value + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newRemoveStake(recipient, value, fee, validity_start_height, network_id) { + _assertClass(recipient, Address); + const ret = wasm.transactionbuilder_newRemoveStake(recipient.__wbg_ptr, value, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Registers a new validator in the staking contract. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the fee does not fit within a u64 or the `networkId` is unknown. + * @param {Address} sender + * @param {Address} reward_address + * @param {PublicKey} signing_key + * @param {BLSKeyPair} voting_key_pair + * @param {string | undefined} signal_data + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newCreateValidator(sender, reward_address, signing_key, voting_key_pair, signal_data, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(reward_address, Address); + _assertClass(signing_key, PublicKey); + _assertClass(voting_key_pair, BLSKeyPair); + var ptr0 = isLikeNone(signal_data) ? 0 : passStringToWasm0(signal_data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + const ret = wasm.transactionbuilder_newCreateValidator(sender.__wbg_ptr, reward_address.__wbg_ptr, signing_key.__wbg_ptr, voting_key_pair.__wbg_ptr, ptr0, len0, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Updates parameters of a validator in the staking contract. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the fee does not fit within a u64 or the `networkId` is unknown. + * @param {Address} sender + * @param {Address | undefined} reward_address + * @param {PublicKey | undefined} signing_key + * @param {BLSKeyPair | undefined} voting_key_pair + * @param {string | undefined} signal_data + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newUpdateValidator(sender, reward_address, signing_key, voting_key_pair, signal_data, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + let ptr0 = 0; + if (!isLikeNone(reward_address)) { + _assertClass(reward_address, Address); + ptr0 = reward_address.__destroy_into_raw(); + } + let ptr1 = 0; + if (!isLikeNone(signing_key)) { + _assertClass(signing_key, PublicKey); + ptr1 = signing_key.__destroy_into_raw(); + } + let ptr2 = 0; + if (!isLikeNone(voting_key_pair)) { + _assertClass(voting_key_pair, BLSKeyPair); + ptr2 = voting_key_pair.__destroy_into_raw(); + } + var ptr3 = isLikeNone(signal_data) ? 0 : passStringToWasm0(signal_data, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len3 = WASM_VECTOR_LEN; + const ret = wasm.transactionbuilder_newUpdateValidator(sender.__wbg_ptr, ptr0, ptr1, ptr2, ptr3, len3, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Deactivates a validator in the staking contract. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the fee does not fit within a u64 or the `networkId` is unknown. + * @param {Address} sender + * @param {Address} validator + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newDeactivateValidator(sender, validator, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + _assertClass(validator, Address); + const ret = wasm.transactionbuilder_newDeactivateValidator(sender.__wbg_ptr, validator.__wbg_ptr, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Deleted a validator the staking contract. The deposit is returned to the Sender + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the fee does not fit within a u64 or the `networkId` is unknown. + * @param {Address} sender + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newDeleteValidator(sender, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + const ret = wasm.transactionbuilder_newDeleteValidator(sender.__wbg_ptr, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Retires a validator in the staking contract. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when the fee does not fit within a u64 or the `networkId` is unknown. + * @param {Address} sender + * @param {bigint | undefined} fee + * @param {number} validity_start_height + * @param {number} network_id + * @returns {Transaction} + */ + static newRetireValidator(sender, fee, validity_start_height, network_id) { + _assertClass(sender, Address); + const ret = wasm.transactionbuilder_newRetireValidator(sender.__wbg_ptr, !isLikeNone(fee), isLikeNone(fee) ? BigInt(0) : fee, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } +} + +const VestingContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_vestingcontract_free(ptr >>> 0, 1)); +/** + * Utility class providing methods to parse Vesting Contract transaction data and proofs. + */ +export class VestingContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + VestingContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vestingcontract_free(ptr, 0); + } + /** + * Parses the data of a Vesting Contract creation transaction into a plain object. + * @param {Uint8Array} data + * @param {bigint} tx_value + * @returns {PlainTransactionRecipientData} + */ + static dataToPlain(data, tx_value) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.vestingcontract_dataToPlain(ptr0, len0, tx_value); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Parses the proof of a Vesting Contract claiming transaction into a plain object. + * @param {Uint8Array} proof + * @returns {PlainTransactionProof} + */ + static proofToPlain(proof) { + const ptr0 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.vestingcontract_proofToPlain(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } +} + +async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } +} + +function __wbg_get_imports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) { + const ret = String(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbg_apply_793fa4b678a475e7 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = Reflect.apply(arg0, arg1, arg2); + return ret; + }, arguments) }; + imports.wbg.__wbg_buffer_6e1d53ff183194fc = function(arg0) { + const ret = arg0.buffer; + return ret; + }; + imports.wbg.__wbg_call_0411c0c3c424db9a = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.call(arg1, arg2); + return ret; + }, arguments) }; + imports.wbg.__wbg_call_3114932863209ca6 = function() { return handleError(function (arg0, arg1) { + const ret = arg0.call(arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_crypto_ed58b8e10a292839 = function(arg0) { + const ret = arg0.crypto; + return ret; + }; + imports.wbg.__wbg_done_adfd3f40364def50 = function(arg0) { + const ret = arg0.done; + return ret; + }; + imports.wbg.__wbg_entries_ce82e236f8300a53 = function(arg0) { + const ret = Object.entries(arg0); + return ret; + }; + imports.wbg.__wbg_es256publickey_new = function(arg0) { + const ret = ES256PublicKey.__wrap(arg0); + return ret; + }; + imports.wbg.__wbg_es256signature_new = function(arg0) { + const ret = ES256Signature.__wrap(arg0); + return ret; + }; + imports.wbg.__wbg_getRandomValues_bcb4912f16000dc4 = function() { return handleError(function (arg0, arg1) { + arg0.getRandomValues(arg1); + }, arguments) }; + imports.wbg.__wbg_get_68aa371864aa301a = function(arg0, arg1) { + const ret = arg0[arg1 >>> 0]; + return ret; + }; + imports.wbg.__wbg_get_92a4780a3beb5fe9 = function() { return handleError(function (arg0, arg1) { + const ret = Reflect.get(arg0, arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) { + const ret = arg0[arg1]; + return ret; + }; + imports.wbg.__wbg_globalThis_1e2ac1d6eee845b3 = function() { return handleError(function () { + const ret = globalThis.globalThis; + return ret; + }, arguments) }; + imports.wbg.__wbg_global_f25a574ae080367c = function() { return handleError(function () { + const ret = global.global; + return ret; + }, arguments) }; + imports.wbg.__wbg_instanceof_ArrayBuffer_435fcead703e2827 = function(arg0) { + let result; + try { + result = arg0 instanceof ArrayBuffer; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Map_77fd223783fe0068 = function(arg0) { + let result; + try { + result = arg0 instanceof Map; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Uint8Array_9b67296cab48238f = function(arg0) { + let result; + try { + result = arg0 instanceof Uint8Array; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_isArray_fcd559a3bcfde1e9 = function(arg0) { + const ret = Array.isArray(arg0); + return ret; + }; + imports.wbg.__wbg_isSafeInteger_4de146aa53f6e470 = function(arg0) { + const ret = Number.isSafeInteger(arg0); + return ret; + }; + imports.wbg.__wbg_iterator_7a20c20ce22add0f = function() { + const ret = Symbol.iterator; + return ret; + }; + imports.wbg.__wbg_length_2e63ba34c4121df5 = function(arg0) { + const ret = arg0.length; + return ret; + }; + imports.wbg.__wbg_length_e74df4881604f1d9 = function(arg0) { + const ret = arg0.length; + return ret; + }; + imports.wbg.__wbg_msCrypto_0a36e2ec3a343d26 = function(arg0) { + const ret = arg0.msCrypto; + return ret; + }; + imports.wbg.__wbg_new_076cac58bb698dd4 = function() { + const ret = new Object(); + return ret; + }; + imports.wbg.__wbg_new_0c28e72025e00594 = function() { + const ret = new Array(); + return ret; + }; + imports.wbg.__wbg_new_23362fa370a0a372 = function(arg0) { + const ret = new Uint8Array(arg0); + return ret; + }; + imports.wbg.__wbg_newnoargs_19a249f4eceaaac3 = function(arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbg_newwithbyteoffsetandlength_ee8def7000b7b2be = function(arg0, arg1, arg2) { + const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0); + return ret; + }; + imports.wbg.__wbg_newwithlength_91de49dea5643c87 = function(arg0) { + const ret = new Uint8Array(arg0 >>> 0); + return ret; + }; + imports.wbg.__wbg_next_c591766a7286b02a = function() { return handleError(function (arg0) { + const ret = arg0.next(); + return ret; + }, arguments) }; + imports.wbg.__wbg_next_f387ecc56a94ba00 = function(arg0) { + const ret = arg0.next; + return ret; + }; + imports.wbg.__wbg_node_02999533c4ea02e3 = function(arg0) { + const ret = arg0.node; + return ret; + }; + imports.wbg.__wbg_process_5c1d670bc53614b8 = function(arg0) { + const ret = arg0.process; + return ret; + }; + imports.wbg.__wbg_publickey_new = function(arg0) { + const ret = PublicKey.__wrap(arg0); + return ret; + }; + imports.wbg.__wbg_randomFillSync_ab2cfe79ebbf2740 = function() { return handleError(function (arg0, arg1) { + arg0.randomFillSync(arg1); + }, arguments) }; + imports.wbg.__wbg_require_79b1e9274cde3c87 = function() { return handleError(function () { + const ret = module.require; + return ret; + }, arguments) }; + imports.wbg.__wbg_self_ac4343e4047b83cc = function() { return handleError(function () { + const ret = self.self; + return ret; + }, arguments) }; + imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) { + arg0[arg1] = arg2; + }; + imports.wbg.__wbg_set_7b70226104a82921 = function(arg0, arg1, arg2) { + arg0.set(arg1, arg2 >>> 0); + }; + imports.wbg.__wbg_set_a1fb6291729caffb = function(arg0, arg1, arg2) { + arg0[arg1 >>> 0] = arg2; + }; + imports.wbg.__wbg_signature_new = function(arg0) { + const ret = Signature.__wrap(arg0); + return ret; + }; + imports.wbg.__wbg_subarray_b4e9772c34a7f5ba = function(arg0, arg1, arg2) { + const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0); + return ret; + }; + imports.wbg.__wbg_value_30db1d77772f3236 = function(arg0) { + const ret = arg0.value; + return ret; + }; + imports.wbg.__wbg_versions_c71aa1626a93e0a1 = function(arg0) { + const ret = arg0.versions; + return ret; + }; + imports.wbg.__wbg_window_1a23defd102c72f4 = function() { return handleError(function () { + const ret = window.window; + return ret; + }, arguments) }; + imports.wbg.__wbindgen_as_number = function(arg0) { + const ret = +arg0; + return ret; + }; + imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) { + const ret = arg0; + return ret; + }; + imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) { + const ret = BigInt.asUintN(64, arg0); + return ret; + }; + imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) { + const v = arg1; + const ret = typeof(v) === 'bigint' ? v : undefined; + getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_boolean_get = function(arg0) { + const v = arg0; + const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2; + return ret; + }; + imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { + const ret = debugString(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_error_new = function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbindgen_in = function(arg0, arg1) { + const ret = arg0 in arg1; + return ret; + }; + imports.wbg.__wbindgen_init_externref_table = function() { + const table = wasm.__wbindgen_export_4; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + ; + }; + imports.wbg.__wbindgen_is_bigint = function(arg0) { + const ret = typeof(arg0) === 'bigint'; + return ret; + }; + imports.wbg.__wbindgen_is_function = function(arg0) { + const ret = typeof(arg0) === 'function'; + return ret; + }; + imports.wbg.__wbindgen_is_object = function(arg0) { + const val = arg0; + const ret = typeof(val) === 'object' && val !== null; + return ret; + }; + imports.wbg.__wbindgen_is_string = function(arg0) { + const ret = typeof(arg0) === 'string'; + return ret; + }; + imports.wbg.__wbindgen_is_undefined = function(arg0) { + const ret = arg0 === undefined; + return ret; + }; + imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) { + const ret = arg0 === arg1; + return ret; + }; + imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) { + const ret = arg0 == arg1; + return ret; + }; + imports.wbg.__wbindgen_memory = function() { + const ret = wasm.memory; + return ret; + }; + imports.wbg.__wbindgen_number_get = function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'number' ? obj : undefined; + getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_number_new = function(arg0) { + const ret = arg0; + return ret; + }; + imports.wbg.__wbindgen_string_get = function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'string' ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return ret; + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + + return imports; +} + +function __wbg_init_memory(imports, memory) { + +} + +function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + __wbg_init.__wbindgen_wasm_module = module; + cachedDataViewMemory0 = null; + cachedUint8ArrayMemory0 = null; + + + wasm.__wbindgen_start(); + return wasm; +} + +function initSync(module) { + if (wasm !== undefined) return wasm; + + + if (typeof module !== 'undefined') { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({module} = module) + } else { + console.warn('using deprecated parameters for `initSync()`; pass a single object instead') + } + } + + const imports = __wbg_get_imports(); + + __wbg_init_memory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return __wbg_finalize_init(instance, module); +} + +async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + + if (typeof module_or_path !== 'undefined') { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({module_or_path} = module_or_path) + } else { + console.warn('using deprecated parameters for the initialization function; pass a single object instead') + } + } + + if (typeof module_or_path === 'undefined') { + module_or_path = new URL('index_bg.wasm', import.meta.url); + } + const imports = __wbg_get_imports(); + + if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { + module_or_path = fetch(module_or_path); + } + + __wbg_init_memory(imports); + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); +} + +export { initSync }; +export default __wbg_init; diff --git a/public/nimiq/2.0.5-history-fix/web/main-wasm/index_bg.wasm b/public/nimiq/2.0.5-history-fix/web/main-wasm/index_bg.wasm new file mode 100644 index 00000000..3d97ba43 Binary files /dev/null and b/public/nimiq/2.0.5-history-fix/web/main-wasm/index_bg.wasm differ diff --git a/public/nimiq/2.0.5-history-fix/web/worker-wasm/index.js b/public/nimiq/2.0.5-history-fix/web/worker-wasm/index.js new file mode 100644 index 00000000..85a6f281 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/worker-wasm/index.js @@ -0,0 +1,2378 @@ +let wasm_bindgen; +(function() { + const __exports = {}; + let script_src; + if (typeof document !== 'undefined' && document.currentScript !== null) { + script_src = new URL(document.currentScript.src, location.href).toString(); + } + let wasm = undefined; + + let WASM_VECTOR_LEN = 0; + + let cachedUint8ArrayMemory0 = null; + + function getUint8ArrayMemory0() { + if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { + cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8ArrayMemory0; + } + + const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); + + const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); + } + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; + }); + + function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8ArrayMemory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; + const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; + } + + WASM_VECTOR_LEN = offset; + return ptr; + } + + let cachedDataViewMemory0 = null; + + function getDataViewMemory0() { + if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { + cachedDataViewMemory0 = new DataView(wasm.memory.buffer); + } + return cachedDataViewMemory0; + } + + const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); + + if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; + + function getStringFromWasm0(ptr, len) { + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); + } + + function addToExternrefTable0(obj) { + const idx = wasm.__externref_table_alloc(); + wasm.__wbindgen_export_4.set(idx, obj); + return idx; + } + + function handleError(f, args) { + try { + return f.apply(this, args); + } catch (e) { + const idx = addToExternrefTable0(e); + wasm.__wbindgen_exn_store(idx); + } + } + + function getArrayU8FromWasm0(ptr, len) { + ptr = ptr >>> 0; + return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); + } + + function isLikeNone(x) { + return x === undefined || x === null; + } + + const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(state => { + wasm.__wbindgen_export_5.get(state.dtor)(state.a, state.b) + }); + + function makeMutClosure(arg0, arg1, dtor, f) { + const state = { a: arg0, b: arg1, cnt: 1, dtor }; + const real = (...args) => { + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + const a = state.a; + state.a = 0; + try { + return f(a, state.b, ...args); + } finally { + if (--state.cnt === 0) { + wasm.__wbindgen_export_5.get(state.dtor)(a, state.b); + CLOSURE_DTORS.unregister(state); + } else { + state.a = a; + } + } + }; + real.original = state; + CLOSURE_DTORS.register(real, state, state); + return real; + } + + function makeClosure(arg0, arg1, dtor, f) { + const state = { a: arg0, b: arg1, cnt: 1, dtor }; + const real = (...args) => { + // First up with a closure we increment the internal reference + // count. This ensures that the Rust closure environment won't + // be deallocated while we're invoking it. + state.cnt++; + try { + return f(state.a, state.b, ...args); + } finally { + if (--state.cnt === 0) { + wasm.__wbindgen_export_5.get(state.dtor)(state.a, state.b); + state.a = 0; + CLOSURE_DTORS.unregister(state); + } + } + }; + real.original = state; + CLOSURE_DTORS.register(real, state, state); + return real; + } + + function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches && builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; + } + + function passArray8ToWasm0(arg, malloc) { + const ptr = malloc(arg.length * 1, 1) >>> 0; + getUint8ArrayMemory0().set(arg, ptr / 1); + WASM_VECTOR_LEN = arg.length; + return ptr; + } + + function takeFromExternrefTable0(idx) { + const value = wasm.__wbindgen_export_4.get(idx); + wasm.__externref_table_dealloc(idx); + return value; + } + + function _assertClass(instance, klass) { + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } + } + function __wbg_adapter_52(arg0, arg1, arg2) { + wasm.closure649_externref_shim(arg0, arg1, arg2); + } + + function __wbg_adapter_55(arg0, arg1, arg2) { + wasm.closure1713_externref_shim(arg0, arg1, arg2); + } + + function __wbg_adapter_62(arg0, arg1) { + wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd7899ddf60e50ca1(arg0, arg1); + } + + function __wbg_adapter_65(arg0, arg1) { + wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h27e2e55155cec891(arg0, arg1); + } + + function __wbg_adapter_68(arg0, arg1, arg2) { + wasm.closure2644_externref_shim(arg0, arg1, arg2); + } + + function __wbg_adapter_324(arg0, arg1, arg2, arg3) { + wasm.closure2846_externref_shim(arg0, arg1, arg2, arg3); + } + + /** + * @enum {0 | 1 | 2 | 3} + */ + __exports.AccountType = Object.freeze({ + Basic: 0, "0": "Basic", + Vesting: 1, "1": "Vesting", + HTLC: 2, "2": "HTLC", + Staking: 3, "3": "Staking", + }); + /** + * A transaction flag signals a special purpose of the transaction. `ContractCreation` must be set + * to create new vesting contracts or HTLCs. `Signaling` must be set to interact with the staking + * contract for non-value transactions. All other transactions' flag is set to `None`. + * @enum {0 | 1 | 2} + */ + __exports.TransactionFlag = Object.freeze({ + None: 0, "0": "None", + ContractCreation: 1, "1": "ContractCreation", + Signaling: 2, "2": "Signaling", + }); + /** + * @enum {0 | 1} + */ + __exports.TransactionFormat = Object.freeze({ + Basic: 0, "0": "Basic", + Extended: 1, "1": "Extended", + }); + + const __wbindgen_enum_BinaryType = ["blob", "arraybuffer"]; + + const AddressFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_address_free(ptr >>> 0, 1)); + /** + * An object representing a Nimiq address. + * Offers methods to parse and format addresses from and to strings. + */ + class Address { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Address.prototype); + obj.__wbg_ptr = ptr; + AddressFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + AddressFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_address_free(ptr, 0); + } + /** + * @param {Uint8Array} bytes + */ + constructor(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_new(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + AddressFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Deserializes an address from a byte array. + * @param {Uint8Array} bytes + * @returns {Address} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Parses an address from an {@link Address} instance, a hex string representation, or a byte array. + * + * Throws when an address cannot be parsed from the argument. + * @param {string | Uint8Array} addr + * @returns {Address} + */ + static fromAny(addr) { + const ret = wasm.address_fromAny(addr); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Parses an address from a string representation, either user-friendly or hex format. + * + * Throws when an address cannot be parsed from the string. + * @param {string} str + * @returns {Address} + */ + static fromString(str) { + const ptr0 = passStringToWasm0(str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.address_fromString(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Address.__wrap(ret[0]); + } + /** + * Formats the address into a plain string format. + * @returns {string} + */ + toPlain() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.address_toPlain(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + } + __exports.Address = Address; + + const ClientFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_client_free(ptr >>> 0, 1)); + /** + * Nimiq Albatross client that runs in browsers via WASM and is exposed to Javascript. + * + * ### Usage: + * + * ```js + * import init, * as Nimiq from "./pkg/nimiq_web_client.js"; + * + * init().then(async () => { + * const config = new Nimiq.ClientConfiguration(); + * const client = await config.instantiateClient(); + * // ... + * }); + * ``` + */ + class Client { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Client.prototype); + obj.__wbg_ptr = ptr; + ClientFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + ClientFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_client_free(ptr, 0); + } + /** + * Creates a new Client that automatically starts connecting to the network. + * @param {PlainClientConfiguration} config + * @returns {Promise} + */ + static create(config) { + const ret = wasm.client_create(config); + return ret; + } + /** + * Adds an event listener for consensus-change events, such as when consensus is established or lost. + * @param {(state: ConsensusState) => any} listener + * @returns {Promise} + */ + addConsensusChangedListener(listener) { + const ret = wasm.client_addConsensusChangedListener(this.__wbg_ptr, listener); + return ret; + } + /** + * Adds an event listener for new blocks added to the blockchain. + * @param {(hash: string, reason: string, reverted_blocks: string[], adopted_blocks: string[]) => any} listener + * @returns {Promise} + */ + addHeadChangedListener(listener) { + const ret = wasm.client_addHeadChangedListener(this.__wbg_ptr, listener); + return ret; + } + /** + * Adds an event listener for peer-change events, such as when a new peer joins, or a peer leaves. + * @param {(peer_id: string, reason: 'joined' | 'left', peer_count: number, peer_info?: PlainPeerInfo) => any} listener + * @returns {Promise} + */ + addPeerChangedListener(listener) { + const ret = wasm.client_addPeerChangedListener(this.__wbg_ptr, listener); + return ret; + } + /** + * Adds an event listener for transactions to and from the provided addresses. + * + * The listener is called for transactions when they are _included_ in the blockchain. + * @param {(transaction: PlainTransactionDetails) => any} listener + * @param {(string | Uint8Array)[]} addresses + * @returns {Promise} + */ + addTransactionListener(listener, addresses) { + const ret = wasm.client_addTransactionListener(this.__wbg_ptr, listener, addresses); + return ret; + } + /** + * Removes an event listener by its handle. + * @param {number} handle + * @returns {Promise} + */ + removeListener(handle) { + const ret = wasm.client_removeListener(this.__wbg_ptr, handle); + return ret; + } + /** + * Returns the network ID that the client is connecting to. + * @returns {Promise} + */ + getNetworkId() { + const ret = wasm.client_getNetworkId(this.__wbg_ptr); + return ret; + } + /** + * Returns if the client currently has consensus with the network. + * @returns {Promise} + */ + isConsensusEstablished() { + const ret = wasm.client_isConsensusEstablished(this.__wbg_ptr); + return ret; + } + /** + * Returns a promise that resolves when the client has established consensus with the network. + * @returns {Promise} + */ + waitForConsensusEstablished() { + const ret = wasm.client_waitForConsensusEstablished(this.__wbg_ptr); + return ret; + } + /** + * Returns the block hash of the current blockchain head. + * @returns {Promise} + */ + getHeadHash() { + const ret = wasm.client_getHeadHash(this.__wbg_ptr); + return ret; + } + /** + * Returns the block number of the current blockchain head. + * @returns {Promise} + */ + getHeadHeight() { + const ret = wasm.client_getHeadHeight(this.__wbg_ptr); + return ret; + } + /** + * Returns the current blockchain head block. + * Note that the web client is a light client and does not have block bodies, i.e. no transactions. + * @returns {Promise} + */ + getHeadBlock() { + const ret = wasm.client_getHeadBlock(this.__wbg_ptr); + return ret; + } + /** + * Returns the current address books peers. + * Each peer will have one address and currently no guarantee for the usefulness of that address can be given. + * + * The resulting Array may be empty if there is no peers in the address book. + * @returns {Promise} + */ + getAddressBook() { + const ret = wasm.client_getAddressBook(this.__wbg_ptr); + return ret; + } + /** + * Fetches a block by its hash. + * + * Throws if the client does not have the block. + * + * Fetching blocks from the network is not yet available. + * @param {string} hash + * @returns {Promise} + */ + getBlock(hash) { + const ptr0 = passStringToWasm0(hash, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.client_getBlock(this.__wbg_ptr, ptr0, len0); + return ret; + } + /** + * Fetches a block by its height (block number). + * + * Throws if the client does not have the block. + * + * Fetching blocks from the network is not yet available. + * @param {number} height + * @returns {Promise} + */ + getBlockAt(height) { + const ret = wasm.client_getBlockAt(this.__wbg_ptr, height); + return ret; + } + /** + * Fetches the account for the provided address from the network. + * + * Throws if the address cannot be parsed and on network errors. + * @param {string | Uint8Array} address + * @returns {Promise} + */ + getAccount(address) { + const ret = wasm.client_getAccount(this.__wbg_ptr, address); + return ret; + } + /** + * Fetches the accounts for the provided addresses from the network. + * + * Throws if an address cannot be parsed and on network errors. + * @param {(string | Uint8Array)[]} addresses + * @returns {Promise} + */ + getAccounts(addresses) { + const ret = wasm.client_getAccounts(this.__wbg_ptr, addresses); + return ret; + } + /** + * Fetches the staker for the provided address from the network. + * + * Throws if the address cannot be parsed and on network errors. + * @param {string | Uint8Array} address + * @returns {Promise} + */ + getStaker(address) { + const ret = wasm.client_getStaker(this.__wbg_ptr, address); + return ret; + } + /** + * Fetches the stakers for the provided addresses from the network. + * + * Throws if an address cannot be parsed and on network errors. + * @param {(string | Uint8Array)[]} addresses + * @returns {Promise<(PlainStaker | undefined)[]>} + */ + getStakers(addresses) { + const ret = wasm.client_getStakers(this.__wbg_ptr, addresses); + return ret; + } + /** + * Fetches the validator for the provided address from the network. + * + * Throws if the address cannot be parsed and on network errors. + * @param {string | Uint8Array} address + * @returns {Promise} + */ + getValidator(address) { + const ret = wasm.client_getValidator(this.__wbg_ptr, address); + return ret; + } + /** + * Fetches the validators for the provided addresses from the network. + * + * Throws if an address cannot be parsed and on network errors. + * @param {(string | Uint8Array)[]} addresses + * @returns {Promise<(PlainValidator | undefined)[]>} + */ + getValidators(addresses) { + const ret = wasm.client_getValidators(this.__wbg_ptr, addresses); + return ret; + } + /** + * Sends a transaction to the network and returns {@link PlainTransactionDetails}. + * + * Throws in case of network errors. + * @param {PlainTransaction | string | Uint8Array} transaction + * @returns {Promise} + */ + sendTransaction(transaction) { + const ret = wasm.client_sendTransaction(this.__wbg_ptr, transaction); + return ret; + } + /** + * Fetches the transaction details for the given transaction hash. + * @param {string} hash + * @returns {Promise} + */ + getTransaction(hash) { + const ptr0 = passStringToWasm0(hash, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.client_getTransaction(this.__wbg_ptr, ptr0, len0); + return ret; + } + /** + * This function is used to query the network for transaction receipts from and to a + * specific address, that have been included in the chain. + * + * The obtained receipts are _not_ verified before being returned. + * + * Up to a `limit` number of transaction receipts are returned from newest to oldest. + * It starts at the `start_at` transaction and goes backwards. If this hash does not exist + * or does not belong to the address, an empty list is returned. + * If the network does not have at least `min_peers` to query, then an error is returned. + * @param {string | Uint8Array} address + * @param {number | undefined} [limit] + * @param {string | undefined} [start_at] + * @param {number | undefined} [min_peers] + * @returns {Promise} + */ + getTransactionReceiptsByAddress(address, limit, start_at, min_peers) { + var ptr0 = isLikeNone(start_at) ? 0 : passStringToWasm0(start_at, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + const ret = wasm.client_getTransactionReceiptsByAddress(this.__wbg_ptr, address, isLikeNone(limit) ? 0xFFFFFF : limit, ptr0, len0, isLikeNone(min_peers) ? 0x100000001 : (min_peers) >>> 0); + return ret; + } + /** + * This function is used to query the network for transactions from and to a specific + * address, that have been included in the chain. + * + * The obtained transactions are verified before being returned. + * + * If you already have transactions belonging to this address, you can provide some of that + * information to reduce the amount of network requests made: + * - Provide the `since_block_height` parameter to exclude any history from before + * that block height. You should be completely certain about its state. This should not be + * the last known block height, but an earlier block height that could not have been forked + * from (e.g. the last known election or checkpoint block). + * - Provide a list of `known_transaction_details` to have them verified and/or broadcasted + * again. + * - Provide a `start_at` parameter to start the query at a specific transaction hash + * (which will not be included). This hash must exist and the corresponding transaction + * must involve this address for the query to work correctly. + * + * Up to a `limit` number of transactions are returned from newest to oldest. + * If the network does not have at least `min_peers` to query, an error is returned. + * @param {string | Uint8Array} address + * @param {number | undefined} [since_block_height] + * @param {PlainTransactionDetails[] | undefined} [known_transaction_details] + * @param {string | undefined} [start_at] + * @param {number | undefined} [limit] + * @param {number | undefined} [min_peers] + * @returns {Promise} + */ + getTransactionsByAddress(address, since_block_height, known_transaction_details, start_at, limit, min_peers) { + var ptr0 = isLikeNone(start_at) ? 0 : passStringToWasm0(start_at, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + const ret = wasm.client_getTransactionsByAddress(this.__wbg_ptr, address, isLikeNone(since_block_height) ? 0x100000001 : (since_block_height) >>> 0, isLikeNone(known_transaction_details) ? 0 : addToExternrefTable0(known_transaction_details), ptr0, len0, isLikeNone(limit) ? 0xFFFFFF : limit, isLikeNone(min_peers) ? 0x100000001 : (min_peers) >>> 0); + return ret; + } + /** + * This function is used to tell the network to disconnect from every connected + * peer and stop trying to connect to other peers. + * + * **Important**: this function returns when the signal to disconnect was sent, + * before all peers actually disconnect. This means that in order to ensure the + * network is disconnected, wait for all peers to disappear after calling. + * @returns {Promise} + */ + disconnectNetwork() { + const ret = wasm.client_disconnectNetwork(this.__wbg_ptr); + return ret; + } + /** + * This function is used to tell the network to (re)start connecting to peers. + * This is could be used to tell the network to restart connection operations after + * disconnect network is called. + * @returns {Promise} + */ + connectNetwork() { + const ret = wasm.client_connectNetwork(this.__wbg_ptr); + return ret; + } + } + __exports.Client = Client; + + const ClientConfigurationFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_clientconfiguration_free(ptr >>> 0, 1)); + /** + * Use this to provide initialization-time configuration to the Client. + * This is a simplified version of the configuration that is used for regular nodes, + * since not all configuration knobs are available when running inside a browser. + */ + class ClientConfiguration { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + ClientConfigurationFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_clientconfiguration_free(ptr, 0); + } + } + __exports.ClientConfiguration = ClientConfiguration; + + const HashedTimeLockedContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_hashedtimelockedcontract_free(ptr >>> 0, 1)); + /** + * Utility class providing methods to parse Hashed Time Locked Contract transaction data and proofs. + */ + class HashedTimeLockedContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + HashedTimeLockedContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_hashedtimelockedcontract_free(ptr, 0); + } + } + __exports.HashedTimeLockedContract = HashedTimeLockedContract; + + const PolicyFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_policy_free(ptr >>> 0, 1)); + + class Policy { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + PolicyFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_policy_free(ptr, 0); + } + /** + * Number of batches a transaction is valid with Albatross consensus. + * @returns {number} + */ + static get TRANSACTION_VALIDITY_WINDOW() { + const ret = wasm.policy_transaction_validity_window(); + return ret >>> 0; + } + /** + * Number of blocks a transaction is valid with Albatross consensus. + * @returns {number} + */ + static get TRANSACTION_VALIDITY_WINDOW_BLOCKS() { + const ret = wasm.policy_transaction_validity_window_blocks(); + return ret >>> 0; + } + /** + * How many batches constitute an epoch + * @returns {number} + */ + static get BATCHES_PER_EPOCH() { + const ret = wasm.policy_batches_per_epoch(); + return ret; + } + /** + * Length of a batch including the macro block + * @returns {number} + */ + static get BLOCKS_PER_BATCH() { + const ret = wasm.policy_blocks_per_batch(); + return ret >>> 0; + } + /** + * Length of an epoch including the election block + * @returns {number} + */ + static get BLOCKS_PER_EPOCH() { + const ret = wasm.policy_blocks_per_epoch(); + return ret >>> 0; + } + /** + * Genesis block number + * @returns {number} + */ + static get GENESIS_BLOCK_NUMBER() { + const ret = wasm.policy_genesis_block_number(); + return ret >>> 0; + } + /** + * Maximum size of accounts trie chunks. + * @returns {number} + */ + static get STATE_CHUNKS_MAX_SIZE() { + const ret = wasm.policy_state_chunks_max_size(); + return ret >>> 0; + } + /** + * Returns the epoch number at a given block number (height). + * @param {number} block_number + * @returns {number} + */ + static epochAt(block_number) { + const ret = wasm.policy_epochAt(block_number); + return ret >>> 0; + } + /** + * Returns the epoch index at a given block number. The epoch index is the number of a block relative + * to the epoch it is in. For example, the first block of any epoch always has an epoch index of 0. + * @param {number} block_number + * @returns {number} + */ + static epochIndexAt(block_number) { + const ret = wasm.policy_epochIndexAt(block_number); + return ret >>> 0; + } + /** + * Returns the batch number at a given `block_number` (height) + * @param {number} block_number + * @returns {number} + */ + static batchAt(block_number) { + const ret = wasm.policy_batchAt(block_number); + return ret >>> 0; + } + /** + * Returns the batch index at a given block number. The batch index is the number of a block relative + * to the batch it is in. For example, the first block of any batch always has an batch index of 0. + * @param {number} block_number + * @returns {number} + */ + static batchIndexAt(block_number) { + const ret = wasm.policy_batchIndexAt(block_number); + return ret >>> 0; + } + /** + * Returns the number (height) of the next election macro block after a given block number (height). + * @param {number} block_number + * @returns {number} + */ + static electionBlockAfter(block_number) { + const ret = wasm.policy_electionBlockAfter(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the preceding election macro block before a given block number (height). + * If the given block number is an election macro block, it returns the election macro block before it. + * @param {number} block_number + * @returns {number} + */ + static electionBlockBefore(block_number) { + const ret = wasm.policy_electionBlockBefore(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the last election macro block at a given block number (height). + * If the given block number is an election macro block, then it returns that block number. + * @param {number} block_number + * @returns {number} + */ + static lastElectionBlock(block_number) { + const ret = wasm.policy_lastElectionBlock(block_number); + return ret >>> 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is an election macro block. + * @param {number} block_number + * @returns {boolean} + */ + static isElectionBlockAt(block_number) { + const ret = wasm.policy_isElectionBlockAt(block_number); + return ret !== 0; + } + /** + * Returns the block number (height) of the next macro block after a given block number (height). + * If the given block number is a macro block, it returns the macro block after it. + * @param {number} block_number + * @returns {number} + */ + static macroBlockAfter(block_number) { + const ret = wasm.policy_macroBlockAfter(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the preceding macro block before a given block number (height). + * If the given block number is a macro block, it returns the macro block before it. + * @param {number} block_number + * @returns {number} + */ + static macroBlockBefore(block_number) { + const ret = wasm.policy_macroBlockBefore(block_number); + return ret >>> 0; + } + /** + * Returns the block number (height) of the last macro block at a given block number (height). + * If the given block number is a macro block, then it returns that block number. + * @param {number} block_number + * @returns {number} + */ + static lastMacroBlock(block_number) { + const ret = wasm.policy_lastMacroBlock(block_number); + return ret >>> 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is a macro block. + * @param {number} block_number + * @returns {boolean} + */ + static isMacroBlockAt(block_number) { + const ret = wasm.policy_isMacroBlockAt(block_number); + return ret !== 0; + } + /** + * Returns a boolean expressing if the block at a given block number (height) is a micro block. + * @param {number} block_number + * @returns {boolean} + */ + static isMicroBlockAt(block_number) { + const ret = wasm.policy_isMicroBlockAt(block_number); + return ret !== 0; + } + /** + * Returns the block number of the first block of the given epoch (which is always a micro block). + * If the index is out of bounds, None is returned + * @param {number} epoch + * @returns {number | undefined} + */ + static firstBlockOf(epoch) { + const ret = wasm.policy_firstBlockOf(epoch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the first block of the given batch (which is always a micro block). + * If the index is out of bounds, None is returned + * @param {number} batch + * @returns {number | undefined} + */ + static firstBlockOfBatch(batch) { + const ret = wasm.policy_firstBlockOfBatch(batch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the election macro block of the given epoch (which is always the last block). + * If the index is out of bounds, None is returned + * @param {number} epoch + * @returns {number | undefined} + */ + static electionBlockOf(epoch) { + const ret = wasm.policy_electionBlockOf(epoch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns the block number of the macro block (checkpoint or election) of the given batch (which + * is always the last block). + * If the index is out of bounds, None is returned + * @param {number} batch + * @returns {number | undefined} + */ + static macroBlockOf(batch) { + const ret = wasm.policy_macroBlockOf(batch); + return ret === 0x100000001 ? undefined : ret; + } + /** + * Returns a boolean expressing if the batch at a given block number (height) is the first batch + * of the epoch. + * @param {number} block_number + * @returns {boolean} + */ + static firstBatchOfEpoch(block_number) { + const ret = wasm.policy_firstBatchOfEpoch(block_number); + return ret !== 0; + } + /** + * Returns the block height for the last block of the reporting window of a given block number. + * Note: This window is meant for reporting malicious behaviour (aka `jailable` behaviour). + * @param {number} block_number + * @returns {number} + */ + static lastBlockOfReportingWindow(block_number) { + const ret = wasm.policy_lastBlockOfReportingWindow(block_number); + return ret >>> 0; + } + /** + * Returns the first block after the reporting window of a given block number has ended. + * @param {number} block_number + * @returns {number} + */ + static blockAfterReportingWindow(block_number) { + const ret = wasm.policy_blockAfterReportingWindow(block_number); + return ret >>> 0; + } + /** + * Returns the first block after the jail period of a given block number has ended. + * @param {number} block_number + * @returns {number} + */ + static blockAfterJail(block_number) { + const ret = wasm.policy_blockAfterJail(block_number); + return ret >>> 0; + } + /** + * Returns the supply at a given time (as Unix time) in Lunas (1 NIM = 100,000 Lunas). It is + * calculated using the following formula: + * ```text + * supply(t) = total_supply - (total_supply - genesis_supply) * supply_decay^t + * ``` + * Where t is the time in milliseconds since the PoS genesis block and `genesis_supply` is the supply at + * the genesis of the Nimiq 2.0 chain. + * @param {bigint} genesis_supply + * @param {bigint} genesis_time + * @param {bigint} current_time + * @returns {bigint} + */ + static supplyAt(genesis_supply, genesis_time, current_time) { + const ret = wasm.policy_supplyAt(genesis_supply, genesis_time, current_time); + return BigInt.asUintN(64, ret); + } + /** + * Returns the percentage reduction that should be applied to the rewards due to a delayed batch. + * This function returns a float in the range [0, 1] + * I.e 1 means that the full rewards should be given, whereas 0.5 means that half of the rewards should be given + * The input to this function is the batch delay, in milliseconds + * The function is: [(1 - MINIMUM_REWARDS_PERCENTAGE) * BLOCKS_DELAY_DECAY ^ (t^2)] + MINIMUM_REWARDS_PERCENTAGE + * @param {bigint} delay + * @returns {number} + */ + static batchDelayPenalty(delay) { + const ret = wasm.policy_batchDelayPenalty(delay); + return ret; + } + /** + * This is the address for the staking contract. + * @returns {string} + */ + static get STAKING_CONTRACT_ADDRESS() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.policy_wasm_staking_contract_address(); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * This is the address for the coinbase. Note that this is not a real account, it is just the + * address we use to denote that some coins originated from a coinbase event. + * @returns {string} + */ + static get COINBASE_ADDRESS() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.policy_wasm_coinbase_address(); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * The maximum allowed size, in bytes, for a micro block body. + * @returns {number} + */ + static get MAX_SIZE_MICRO_BODY() { + const ret = wasm.policy_wasm_max_size_micro_body(); + return ret >>> 0; + } + /** + * The current version number of the protocol. Changing this always results in a hard fork. + * @returns {number} + */ + static get VERSION() { + const ret = wasm.policy_wasm_min_epochs_stored(); + return ret; + } + /** + * Number of available validator slots. Note that a single validator may own several validator slots. + * @returns {number} + */ + static get SLOTS() { + const ret = wasm.policy_wasm_slots(); + return ret; + } + /** + * Calculates 2f+1 slots which is the minimum number of slots necessary to produce a macro block, + * a skip block and other actions. + * It is also the minimum number of slots necessary to be guaranteed to have a majority of honest + * slots. That's because from a total of 3f+1 slots at most f will be malicious. If in a group of + * 2f+1 slots we have f malicious ones (which is the worst case scenario), that still leaves us + * with f+1 honest slots. Which is more than the f slots that are not in this group (which must all + * be honest). + * It is calculated as `ceil(SLOTS*2/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the + * ceiling division. + * @returns {number} + */ + static get TWO_F_PLUS_ONE() { + const ret = wasm.policy_wasm_two_f_plus_one(); + return ret; + } + /** + * Calculates f+1 slots which is the minimum number of slots necessary to be guaranteed to have at + * least one honest slots. That's because from a total of 3f+1 slots at most f will be malicious. + * It is calculated as `ceil(SLOTS/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the + * ceiling division. + * @returns {number} + */ + static get F_PLUS_ONE() { + const ret = wasm.policy_wasm_f_plus_one(); + return ret; + } + /** + * The minimum timeout in milliseconds for a validator to produce a block (4s) + * @returns {bigint} + */ + static get MIN_PRODUCER_TIMEOUT() { + const ret = wasm.policy_wasm_min_block_producer_timeout(); + return BigInt.asUintN(64, ret); + } + /** + * The optimal time in milliseconds between blocks (1s) + * @returns {bigint} + */ + static get BLOCK_SEPARATION_TIME() { + const ret = wasm.policy_wasm_block_separation_time(); + return BigInt.asUintN(64, ret); + } + /** + * Minimum number of epochs that the ChainStore will store fully + * @returns {number} + */ + static get MIN_EPOCHS_STORED() { + const ret = wasm.policy_wasm_min_epochs_stored(); + return ret >>> 0; + } + /** + * The maximum drift, in milliseconds, that is allowed between any block's timestamp and the node's + * system time. We only care about drifting to the future. + * @returns {bigint} + */ + static get TIMESTAMP_MAX_DRIFT() { + const ret = wasm.policy_wasm_timestamp_max_drift(); + return BigInt.asUintN(64, ret); + } + /** + * The minimum rewards percentage that we allow + * @returns {number} + */ + static get MINIMUM_REWARDS_PERCENTAGE() { + const ret = wasm.policy_wasm_minimum_rewards_percentage(); + return ret; + } + /** + * The deposit necessary to create a validator in Lunas (1 NIM = 100,000 Lunas). + * A validator is someone who actually participates in block production. They are akin to miners + * in proof-of-work. + * @returns {bigint} + */ + static get VALIDATOR_DEPOSIT() { + const ret = wasm.policy_wasm_validator_deposit(); + return BigInt.asUintN(64, ret); + } + /** + * The number of epochs a validator is put in jail for. The jailing only happens for severe offenses. + * @returns {number} + */ + static get JAIL_EPOCHS() { + const ret = wasm.policy_wasm_jail_epochs(); + return ret >>> 0; + } + /** + * Total supply in units. + * @returns {bigint} + */ + static get TOTAL_SUPPLY() { + const ret = wasm.policy_wasm_total_supply(); + return BigInt.asUintN(64, ret); + } + /** + * The maximum size of the BLS public key cache. + * @returns {number} + */ + static get BLS_CACHE_MAX_CAPACITY() { + const ret = wasm.policy_wasm_bls_cache_max_capacity(); + return ret >>> 0; + } + /** + * Maximum size of history chunks. + * 25 MB. + * @returns {bigint} + */ + static get HISTORY_CHUNKS_MAX_SIZE() { + const ret = wasm.policy_wasm_history_chunks_max_size(); + return BigInt.asUintN(64, ret); + } + } + __exports.Policy = Policy; + + const SignatureProofFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_signatureproof_free(ptr >>> 0, 1)); + /** + * A signature proof represents a signature together with its public key and the public key's merkle path. + * It is used as the proof for transactions. + */ + class SignatureProof { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(SignatureProof.prototype); + obj.__wbg_ptr = ptr; + SignatureProofFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + SignatureProofFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_signatureproof_free(ptr, 0); + } + /** + * Deserializes a signature proof from a byte array. + * @param {Uint8Array} bytes + * @returns {SignatureProof} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.signatureproof_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return SignatureProof.__wrap(ret[0]); + } + } + __exports.SignatureProof = SignatureProof; + + const StakingContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_stakingcontract_free(ptr >>> 0, 1)); + /** + * Utility class providing methods to parse Staking Contract transaction data and proofs. + */ + class StakingContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + StakingContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_stakingcontract_free(ptr, 0); + } + } + __exports.StakingContract = StakingContract; + + const TransactionFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_transaction_free(ptr >>> 0, 1)); + /** + * Transactions describe a transfer of value, usually from the sender to the recipient. + * However, transactions can also have no value, when they are used to _signal_ a change in the staking contract. + * + * Transactions can be used to create contracts, such as vesting contracts and HTLCs. + * + * Transactions require a valid signature proof over their serialized content. + * Furthermore, transactions are only valid for 2 hours after their validity-start block height. + */ + class Transaction { + + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Transaction.prototype); + obj.__wbg_ptr = ptr; + TransactionFinalization.register(obj, obj.__wbg_ptr, obj); + return obj; + } + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + TransactionFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_transaction_free(ptr, 0); + } + /** + * Creates a new unsigned transaction that transfers `value` amount of luna (NIM's smallest unit) + * from the sender to the recipient, where both sender and recipient can be any account type, + * and custom extra data can be added to the transaction. + * + * ### Basic transactions + * If both the sender and recipient types are omitted or `0` and both data and flags are empty, + * a smaller basic transaction is created. + * + * ### Extended transactions + * If no flags are given, but sender type is not basic (`0`) or data is set, an extended + * transaction is created. + * + * ### Contract creation transactions + * To create a new vesting or HTLC contract, set `flags` to `0b1` and specify the contract + * type as the `recipient_type`: `1` for vesting, `2` for HTLC. The `data` bytes must have + * the correct format of contract creation data for the respective contract type. + * + * ### Signaling transactions + * To interact with the staking contract, signaling transaction are often used to not + * transfer any value, but to simply _signal_ a state change instead, such as changing one's + * delegation from one validator to another. To create such a transaction, set `flags` to ` + * 0b10` and populate the `data` bytes accordingly. + * + * The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`. + * + * Throws when an account type is unknown, the numbers given for value and fee do not fit + * within a u64 or the networkId is unknown. Also throws when no data or recipient type is + * given for contract creation transactions, or no data is given for signaling transactions. + * @param {Address} sender + * @param {number | undefined} sender_type + * @param {Uint8Array | undefined} sender_data + * @param {Address} recipient + * @param {number | undefined} recipient_type + * @param {Uint8Array | undefined} recipient_data + * @param {bigint} value + * @param {bigint} fee + * @param {number | undefined} flags + * @param {number} validity_start_height + * @param {number} network_id + */ + constructor(sender, sender_type, sender_data, recipient, recipient_type, recipient_data, value, fee, flags, validity_start_height, network_id) { + _assertClass(sender, Address); + var ptr0 = isLikeNone(sender_data) ? 0 : passArray8ToWasm0(sender_data, wasm.__wbindgen_malloc); + var len0 = WASM_VECTOR_LEN; + _assertClass(recipient, Address); + var ptr1 = isLikeNone(recipient_data) ? 0 : passArray8ToWasm0(recipient_data, wasm.__wbindgen_malloc); + var len1 = WASM_VECTOR_LEN; + const ret = wasm.transaction_new(sender.__wbg_ptr, isLikeNone(sender_type) ? 0xFFFFFF : sender_type, ptr0, len0, recipient.__wbg_ptr, isLikeNone(recipient_type) ? 0xFFFFFF : recipient_type, ptr1, len1, value, fee, isLikeNone(flags) ? 0xFFFFFF : flags, validity_start_height, network_id); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + this.__wbg_ptr = ret[0] >>> 0; + TransactionFinalization.register(this, this.__wbg_ptr, this); + return this; + } + /** + * Computes the transaction's hash, which is used as its unique identifier on the blockchain. + * @returns {string} + */ + hash() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.transaction_hash(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Verifies that a transaction has valid properties and a valid signature proof. + * Optionally checks if the transaction is valid on the provided network. + * + * **Throws with any transaction validity error.** Returns without exception if the transaction is valid. + * + * Throws when the given networkId is unknown. + * @param {number | undefined} [network_id] + */ + verify(network_id) { + const ret = wasm.transaction_verify(this.__wbg_ptr, isLikeNone(network_id) ? 0xFFFFFF : network_id); + if (ret[1]) { + throw takeFromExternrefTable0(ret[0]); + } + } + /** + * Tests if the transaction is valid at the specified block height. + * @param {number} block_height + * @returns {boolean} + */ + isValidAt(block_height) { + const ret = wasm.transaction_isValidAt(this.__wbg_ptr, block_height); + return ret !== 0; + } + /** + * Returns the address of the contract that is created with this transaction. + * @returns {Address} + */ + getContractCreationAddress() { + const ret = wasm.transaction_getContractCreationAddress(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * Serializes the transaction's content to be used for creating its signature. + * @returns {Uint8Array} + */ + serializeContent() { + const ret = wasm.transaction_serializeContent(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Serializes the transaction to a byte array. + * @returns {Uint8Array} + */ + serialize() { + const ret = wasm.transaction_serialize(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * The transaction's {@link TransactionFormat}. + * @returns {TransactionFormat} + */ + get format() { + const ret = wasm.transaction_format(this.__wbg_ptr); + return ret; + } + /** + * The transaction's sender address. + * @returns {Address} + */ + get sender() { + const ret = wasm.transaction_sender(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * The transaction's sender {@link AccountType}. + * @returns {AccountType} + */ + get senderType() { + const ret = wasm.transaction_senderType(this.__wbg_ptr); + return ret; + } + /** + * The transaction's recipient address. + * @returns {Address} + */ + get recipient() { + const ret = wasm.transaction_recipient(this.__wbg_ptr); + return Address.__wrap(ret); + } + /** + * The transaction's recipient {@link AccountType}. + * @returns {AccountType} + */ + get recipientType() { + const ret = wasm.transaction_recipientType(this.__wbg_ptr); + return ret; + } + /** + * The transaction's value in luna (NIM's smallest unit). + * @returns {bigint} + */ + get value() { + const ret = wasm.transaction_value(this.__wbg_ptr); + return BigInt.asUintN(64, ret); + } + /** + * The transaction's fee in luna (NIM's smallest unit). + * @returns {bigint} + */ + get fee() { + const ret = wasm.transaction_fee(this.__wbg_ptr); + return BigInt.asUintN(64, ret); + } + /** + * The transaction's fee per byte in luna (NIM's smallest unit). + * @returns {number} + */ + get feePerByte() { + const ret = wasm.transaction_feePerByte(this.__wbg_ptr); + return ret; + } + /** + * The transaction's validity-start height. The transaction is valid for 2 hours after this block height. + * @returns {number} + */ + get validityStartHeight() { + const ret = wasm.transaction_validityStartHeight(this.__wbg_ptr); + return ret >>> 0; + } + /** + * The transaction's network ID. + * @returns {number} + */ + get networkId() { + const ret = wasm.transaction_networkId(this.__wbg_ptr); + return ret; + } + /** + * The transaction's flags: `0b1` = contract creation, `0b10` = signaling. + * @returns {TransactionFlag} + */ + get flags() { + const ret = wasm.transaction_flags(this.__wbg_ptr); + return ret; + } + /** + * The transaction's data as a byte array. + * @returns {Uint8Array} + */ + get data() { + const ret = wasm.transaction_data(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Set the transaction's data + * @param {Uint8Array} data + */ + set data(data) { + const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_set_data(this.__wbg_ptr, ptr0, len0); + } + /** + * The transaction's sender data as a byte array. + * @returns {Uint8Array} + */ + get senderData() { + const ret = wasm.transaction_senderData(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * The transaction's signature proof as a byte array. + * @returns {Uint8Array} + */ + get proof() { + const ret = wasm.transaction_proof(this.__wbg_ptr); + var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice(); + wasm.__wbindgen_free(ret[0], ret[1] * 1, 1); + return v1; + } + /** + * Set the transaction's signature proof. + * @param {Uint8Array} proof + */ + set proof(proof) { + const ptr0 = passArray8ToWasm0(proof, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + wasm.transaction_set_proof(this.__wbg_ptr, ptr0, len0); + } + /** + * The transaction's byte size. + * @returns {number} + */ + get serializedSize() { + const ret = wasm.transaction_serializedSize(this.__wbg_ptr); + return ret >>> 0; + } + /** + * Serializes the transaction into a HEX string. + * @returns {string} + */ + toHex() { + let deferred1_0; + let deferred1_1; + try { + const ret = wasm.transaction_toHex(this.__wbg_ptr); + deferred1_0 = ret[0]; + deferred1_1 = ret[1]; + return getStringFromWasm0(ret[0], ret[1]); + } finally { + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); + } + } + /** + * Creates a JSON-compatible plain object representing the transaction. + * @param {number | undefined} [genesis_number] + * @param {bigint | undefined} [genesis_timestamp] + * @returns {PlainTransaction} + */ + toPlain(genesis_number, genesis_timestamp) { + const ret = wasm.transaction_toPlain(this.__wbg_ptr, isLikeNone(genesis_number) ? 0x100000001 : (genesis_number) >>> 0, !isLikeNone(genesis_timestamp), isLikeNone(genesis_timestamp) ? BigInt(0) : genesis_timestamp); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return takeFromExternrefTable0(ret[0]); + } + /** + * Deserializes a transaction from a byte array. + * @param {Uint8Array} bytes + * @returns {Transaction} + */ + static deserialize(bytes) { + const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + const ret = wasm.transaction_deserialize(ptr0, len0); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Parses a transaction from a {@link Transaction} instance, a plain object, a hex string + * representation, or a byte array. + * + * Throws when a transaction cannot be parsed from the argument. + * @param {PlainTransaction | string | Uint8Array} tx + * @returns {Transaction} + */ + static fromAny(tx) { + const ret = wasm.transaction_fromAny(tx); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + /** + * Parses a transaction from a plain object. + * + * Throws when a transaction cannot be parsed from the argument. + * @param {PlainTransaction} plain + * @returns {Transaction} + */ + static fromPlain(plain) { + const ret = wasm.transaction_fromPlain(plain); + if (ret[2]) { + throw takeFromExternrefTable0(ret[1]); + } + return Transaction.__wrap(ret[0]); + } + } + __exports.Transaction = Transaction; + + const VestingContractFinalization = (typeof FinalizationRegistry === 'undefined') + ? { register: () => {}, unregister: () => {} } + : new FinalizationRegistry(ptr => wasm.__wbg_vestingcontract_free(ptr >>> 0, 1)); + /** + * Utility class providing methods to parse Vesting Contract transaction data and proofs. + */ + class VestingContract { + + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; + VestingContractFinalization.unregister(this); + return ptr; + } + + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_vestingcontract_free(ptr, 0); + } + } + __exports.VestingContract = VestingContract; + + async function __wbg_load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } + } + + function __wbg_get_imports() { + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) { + const ret = String(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbg_WorkerGlobalScope_4cdac01f57bb97d1 = function(arg0) { + const ret = arg0.WorkerGlobalScope; + return ret; + }; + imports.wbg.__wbg_addEventListener_0aa6c9470895f584 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.addEventListener(getStringFromWasm0(arg1, arg2), arg3); + }, arguments) }; + imports.wbg.__wbg_apply_e561e3b9b5a01b05 = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.apply(arg1, arg2); + return ret; + }, arguments) }; + imports.wbg.__wbg_buffer_6e1d53ff183194fc = function(arg0) { + const ret = arg0.buffer; + return ret; + }; + imports.wbg.__wbg_bufferedAmount_ee5f3d464214e678 = function(arg0) { + const ret = arg0.bufferedAmount; + return ret; + }; + imports.wbg.__wbg_call_0411c0c3c424db9a = function() { return handleError(function (arg0, arg1, arg2) { + const ret = arg0.call(arg1, arg2); + return ret; + }, arguments) }; + imports.wbg.__wbg_call_3114932863209ca6 = function() { return handleError(function (arg0, arg1) { + const ret = arg0.call(arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_clearInterval_5bbcdf9491cea345 = function(arg0, arg1) { + arg0.clearInterval(arg1); + }; + imports.wbg.__wbg_clearInterval_b4e165e64357b104 = function(arg0, arg1) { + arg0.clearInterval(arg1); + }; + imports.wbg.__wbg_clearInterval_dd1e598f425db353 = function(arg0) { + const ret = clearInterval(arg0); + return ret; + }; + imports.wbg.__wbg_clearTimeout_5a54f8841c30079a = function(arg0) { + const ret = clearTimeout(arg0); + return ret; + }; + imports.wbg.__wbg_clearTimeout_96804de0ab838f26 = function(arg0) { + const ret = clearTimeout(arg0); + return ret; + }; + imports.wbg.__wbg_client_new = function(arg0) { + const ret = Client.__wrap(arg0); + return ret; + }; + imports.wbg.__wbg_close_390354f70a3f15a7 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + arg0.close(arg1, getStringFromWasm0(arg2, arg3)); + }, arguments) }; + imports.wbg.__wbg_crypto_ed58b8e10a292839 = function(arg0) { + const ret = arg0.crypto; + return ret; + }; + imports.wbg.__wbg_data_6f313bee9ecc3082 = function(arg0) { + const ret = arg0.data; + return ret; + }; + imports.wbg.__wbg_debug_27dd03b8945e39d7 = function(arg0, arg1, arg2, arg3) { + console.debug(arg0, arg1, arg2, arg3); + }; + imports.wbg.__wbg_debug_347b3d1f33e1c28e = function(arg0) { + console.debug(arg0); + }; + imports.wbg.__wbg_done_adfd3f40364def50 = function(arg0) { + const ret = arg0.done; + return ret; + }; + imports.wbg.__wbg_entries_ce82e236f8300a53 = function(arg0) { + const ret = Object.entries(arg0); + return ret; + }; + imports.wbg.__wbg_error_2a6b93fdada7ff11 = function(arg0) { + console.error(arg0); + }; + imports.wbg.__wbg_error_818ac809371bfd77 = function(arg0, arg1, arg2, arg3) { + console.error(arg0, arg1, arg2, arg3); + }; + imports.wbg.__wbg_getRandomValues_bcb4912f16000dc4 = function() { return handleError(function (arg0, arg1) { + arg0.getRandomValues(arg1); + }, arguments) }; + imports.wbg.__wbg_getTime_701326a7a826723f = function(arg0) { + const ret = arg0.getTime(); + return ret; + }; + imports.wbg.__wbg_get_68aa371864aa301a = function(arg0, arg1) { + const ret = arg0[arg1 >>> 0]; + return ret; + }; + imports.wbg.__wbg_get_92a4780a3beb5fe9 = function() { return handleError(function (arg0, arg1) { + const ret = Reflect.get(arg0, arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_getwithrefkey_1dc361bd10053bfe = function(arg0, arg1) { + const ret = arg0[arg1]; + return ret; + }; + imports.wbg.__wbg_globalThis_1e2ac1d6eee845b3 = function() { return handleError(function () { + const ret = globalThis.globalThis; + return ret; + }, arguments) }; + imports.wbg.__wbg_global_f25a574ae080367c = function() { return handleError(function () { + const ret = global.global; + return ret; + }, arguments) }; + imports.wbg.__wbg_info_ab0093df83f380f1 = function(arg0, arg1, arg2, arg3) { + console.info(arg0, arg1, arg2, arg3); + }; + imports.wbg.__wbg_info_b6bd3cb6471c2b4c = function(arg0) { + console.info(arg0); + }; + imports.wbg.__wbg_instanceof_ArrayBuffer_435fcead703e2827 = function(arg0) { + let result; + try { + result = arg0 instanceof ArrayBuffer; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Map_77fd223783fe0068 = function(arg0) { + let result; + try { + result = arg0 instanceof Map; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Uint8Array_9b67296cab48238f = function(arg0) { + let result; + try { + result = arg0 instanceof Uint8Array; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_instanceof_Window_a959820eb267fe22 = function(arg0) { + let result; + try { + result = arg0 instanceof Window; + } catch (_) { + result = false; + } + const ret = result; + return ret; + }; + imports.wbg.__wbg_isArray_fcd559a3bcfde1e9 = function(arg0) { + const ret = Array.isArray(arg0); + return ret; + }; + imports.wbg.__wbg_isSafeInteger_4de146aa53f6e470 = function(arg0) { + const ret = Number.isSafeInteger(arg0); + return ret; + }; + imports.wbg.__wbg_is_20768e55ad2a7c3f = function(arg0, arg1) { + const ret = Object.is(arg0, arg1); + return ret; + }; + imports.wbg.__wbg_iterator_7a20c20ce22add0f = function() { + const ret = Symbol.iterator; + return ret; + }; + imports.wbg.__wbg_length_2e63ba34c4121df5 = function(arg0) { + const ret = arg0.length; + return ret; + }; + imports.wbg.__wbg_length_e74df4881604f1d9 = function(arg0) { + const ret = arg0.length; + return ret; + }; + imports.wbg.__wbg_msCrypto_0a36e2ec3a343d26 = function(arg0) { + const ret = arg0.msCrypto; + return ret; + }; + imports.wbg.__wbg_new0_207938728f108bf6 = function() { + const ret = new Date(); + return ret; + }; + imports.wbg.__wbg_new_076cac58bb698dd4 = function() { + const ret = new Object(); + return ret; + }; + imports.wbg.__wbg_new_0c28e72025e00594 = function() { + const ret = new Array(); + return ret; + }; + imports.wbg.__wbg_new_1e8ca58d170d6ad0 = function(arg0, arg1) { + try { + var state0 = {a: arg0, b: arg1}; + var cb0 = (arg0, arg1) => { + const a = state0.a; + state0.a = 0; + try { + return __wbg_adapter_324(a, state0.b, arg0, arg1); + } finally { + state0.a = a; + } + }; + const ret = new Promise(cb0); + return ret; + } finally { + state0.a = state0.b = 0; + } + }; + imports.wbg.__wbg_new_23362fa370a0a372 = function(arg0) { + const ret = new Uint8Array(arg0); + return ret; + }; + imports.wbg.__wbg_new_789d26a8cd0beaf6 = function() { return handleError(function (arg0, arg1) { + const ret = new WebSocket(getStringFromWasm0(arg0, arg1)); + return ret; + }, arguments) }; + imports.wbg.__wbg_newnoargs_19a249f4eceaaac3 = function(arg0, arg1) { + const ret = new Function(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbg_newwithbyteoffsetandlength_ee8def7000b7b2be = function(arg0, arg1, arg2) { + const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0); + return ret; + }; + imports.wbg.__wbg_newwithlength_91de49dea5643c87 = function(arg0) { + const ret = new Uint8Array(arg0 >>> 0); + return ret; + }; + imports.wbg.__wbg_next_c591766a7286b02a = function() { return handleError(function (arg0) { + const ret = arg0.next(); + return ret; + }, arguments) }; + imports.wbg.__wbg_next_f387ecc56a94ba00 = function(arg0) { + const ret = arg0.next; + return ret; + }; + imports.wbg.__wbg_node_02999533c4ea02e3 = function(arg0) { + const ret = arg0.node; + return ret; + }; + imports.wbg.__wbg_now_2c95c9de01293173 = function(arg0) { + const ret = arg0.now(); + return ret; + }; + imports.wbg.__wbg_now_5b0cbad8de553ec4 = function(arg0) { + const ret = arg0.now(); + return ret; + }; + imports.wbg.__wbg_now_5cf792f3426feb88 = function() { + const ret = Date.now(); + return ret; + }; + imports.wbg.__wbg_performance_7a3ffd0b17f663ad = function(arg0) { + const ret = arg0.performance; + return ret; + }; + imports.wbg.__wbg_process_5c1d670bc53614b8 = function(arg0) { + const ret = arg0.process; + return ret; + }; + imports.wbg.__wbg_push_3e9ce81246ef1d1b = function(arg0, arg1) { + const ret = arg0.push(arg1); + return ret; + }; + imports.wbg.__wbg_queueMicrotask_3d422e1ba49c2500 = function(arg0) { + const ret = arg0.queueMicrotask; + return ret; + }; + imports.wbg.__wbg_queueMicrotask_f301663ccadbb7d0 = function(arg0) { + queueMicrotask(arg0); + }; + imports.wbg.__wbg_randomFillSync_ab2cfe79ebbf2740 = function() { return handleError(function (arg0, arg1) { + arg0.randomFillSync(arg1); + }, arguments) }; + imports.wbg.__wbg_readyState_bb59e8f3ca88bf33 = function(arg0) { + const ret = arg0.readyState; + return ret; + }; + imports.wbg.__wbg_require_79b1e9274cde3c87 = function() { return handleError(function () { + const ret = module.require; + return ret; + }, arguments) }; + imports.wbg.__wbg_resolve_6a311e8bb26423ab = function(arg0) { + const ret = Promise.resolve(arg0); + return ret; + }; + imports.wbg.__wbg_self_ac4343e4047b83cc = function() { return handleError(function () { + const ret = self.self; + return ret; + }, arguments) }; + imports.wbg.__wbg_send_c7dc9a93fb67d64a = function() { return handleError(function (arg0, arg1, arg2) { + arg0.send(getArrayU8FromWasm0(arg1, arg2)); + }, arguments) }; + imports.wbg.__wbg_setInterval_ed3b5e3c3ebb8a6d = function() { return handleError(function (arg0, arg1) { + const ret = setInterval(arg0, arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_setInterval_ee98dc1e6d169e47 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = arg0.setInterval(arg1, arg2, ...arg3); + return ret; + }, arguments) }; + imports.wbg.__wbg_setInterval_fff3494d956a67e1 = function() { return handleError(function (arg0, arg1, arg2, arg3) { + const ret = arg0.setInterval(arg1, arg2, ...arg3); + return ret; + }, arguments) }; + imports.wbg.__wbg_setTimeout_db2dbaeefb6f39c7 = function() { return handleError(function (arg0, arg1) { + const ret = setTimeout(arg0, arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_setTimeout_eefe7f4c234b0c6b = function() { return handleError(function (arg0, arg1) { + const ret = setTimeout(arg0, arg1); + return ret; + }, arguments) }; + imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) { + arg0[arg1] = arg2; + }; + imports.wbg.__wbg_set_7b70226104a82921 = function(arg0, arg1, arg2) { + arg0.set(arg1, arg2 >>> 0); + }; + imports.wbg.__wbg_set_a1fb6291729caffb = function(arg0, arg1, arg2) { + arg0[arg1 >>> 0] = arg2; + }; + imports.wbg.__wbg_setbinaryType_a14c2d713cda3a76 = function(arg0, arg1) { + arg0.binaryType = __wbindgen_enum_BinaryType[arg1]; + }; + imports.wbg.__wbg_setonclose_56cab8b0dca39584 = function(arg0, arg1) { + arg0.onclose = arg1; + }; + imports.wbg.__wbg_setonerror_b89f06e280aad698 = function(arg0, arg1) { + arg0.onerror = arg1; + }; + imports.wbg.__wbg_setonmessage_0096de047fd76d58 = function(arg0, arg1) { + arg0.onmessage = arg1; + }; + imports.wbg.__wbg_setonopen_027cab001d09f6a8 = function(arg0, arg1) { + arg0.onopen = arg1; + }; + imports.wbg.__wbg_subarray_b4e9772c34a7f5ba = function(arg0, arg1, arg2) { + const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0); + return ret; + }; + imports.wbg.__wbg_then_5c6469c1e1da9e59 = function(arg0, arg1) { + const ret = arg0.then(arg1); + return ret; + }; + imports.wbg.__wbg_value_30db1d77772f3236 = function(arg0) { + const ret = arg0.value; + return ret; + }; + imports.wbg.__wbg_versions_c71aa1626a93e0a1 = function(arg0) { + const ret = arg0.versions; + return ret; + }; + imports.wbg.__wbg_warn_43ba5f40fc329fe9 = function(arg0, arg1, arg2, arg3) { + console.warn(arg0, arg1, arg2, arg3); + }; + imports.wbg.__wbg_warn_a6963915e4da61f6 = function(arg0) { + console.warn(arg0); + }; + imports.wbg.__wbg_window_1a23defd102c72f4 = function() { return handleError(function () { + const ret = window.window; + return ret; + }, arguments) }; + imports.wbg.__wbindgen_as_number = function(arg0) { + const ret = +arg0; + return ret; + }; + imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) { + const ret = arg0; + return ret; + }; + imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) { + const ret = BigInt.asUintN(64, arg0); + return ret; + }; + imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) { + const v = arg1; + const ret = typeof(v) === 'bigint' ? v : undefined; + getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_boolean_get = function(arg0) { + const v = arg0; + const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2; + return ret; + }; + imports.wbg.__wbindgen_cb_drop = function(arg0) { + const obj = arg0.original; + if (obj.cnt-- == 1) { + obj.a = 0; + return true; + } + const ret = false; + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper13017 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 2645, __wbg_adapter_68); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper3710 = function(arg0, arg1, arg2) { + const ret = makeClosure(arg0, arg1, 650, __wbg_adapter_52); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper7592 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 1714, __wbg_adapter_55); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper7594 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 1714, __wbg_adapter_55); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper7597 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 1714, __wbg_adapter_55); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper9726 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 2229, __wbg_adapter_62); + return ret; + }; + imports.wbg.__wbindgen_closure_wrapper9885 = function(arg0, arg1, arg2) { + const ret = makeMutClosure(arg0, arg1, 2264, __wbg_adapter_65); + return ret; + }; + imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { + const ret = debugString(arg1); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_error_new = function(arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return ret; + }; + imports.wbg.__wbindgen_in = function(arg0, arg1) { + const ret = arg0 in arg1; + return ret; + }; + imports.wbg.__wbindgen_init_externref_table = function() { + const table = wasm.__wbindgen_export_4; + const offset = table.grow(4); + table.set(0, undefined); + table.set(offset + 0, undefined); + table.set(offset + 1, null); + table.set(offset + 2, true); + table.set(offset + 3, false); + ; + }; + imports.wbg.__wbindgen_is_bigint = function(arg0) { + const ret = typeof(arg0) === 'bigint'; + return ret; + }; + imports.wbg.__wbindgen_is_function = function(arg0) { + const ret = typeof(arg0) === 'function'; + return ret; + }; + imports.wbg.__wbindgen_is_object = function(arg0) { + const val = arg0; + const ret = typeof(val) === 'object' && val !== null; + return ret; + }; + imports.wbg.__wbindgen_is_string = function(arg0) { + const ret = typeof(arg0) === 'string'; + return ret; + }; + imports.wbg.__wbindgen_is_undefined = function(arg0) { + const ret = arg0 === undefined; + return ret; + }; + imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) { + const ret = arg0 === arg1; + return ret; + }; + imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) { + const ret = arg0 == arg1; + return ret; + }; + imports.wbg.__wbindgen_memory = function() { + const ret = wasm.memory; + return ret; + }; + imports.wbg.__wbindgen_number_get = function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'number' ? obj : undefined; + getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true); + }; + imports.wbg.__wbindgen_number_new = function(arg0) { + const ret = arg0; + return ret; + }; + imports.wbg.__wbindgen_string_get = function(arg0, arg1) { + const obj = arg1; + const ret = typeof(obj) === 'string' ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); + getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return ret; + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + + return imports; + } + + function __wbg_init_memory(imports, memory) { + + } + + function __wbg_finalize_init(instance, module) { + wasm = instance.exports; + __wbg_init.__wbindgen_wasm_module = module; + cachedDataViewMemory0 = null; + cachedUint8ArrayMemory0 = null; + + + wasm.__wbindgen_start(); + return wasm; + } + + function initSync(module) { + if (wasm !== undefined) return wasm; + + + if (typeof module !== 'undefined') { + if (Object.getPrototypeOf(module) === Object.prototype) { + ({module} = module) + } else { + console.warn('using deprecated parameters for `initSync()`; pass a single object instead') + } + } + + const imports = __wbg_get_imports(); + + __wbg_init_memory(imports); + + if (!(module instanceof WebAssembly.Module)) { + module = new WebAssembly.Module(module); + } + + const instance = new WebAssembly.Instance(module, imports); + + return __wbg_finalize_init(instance, module); + } + + async function __wbg_init(module_or_path) { + if (wasm !== undefined) return wasm; + + + if (typeof module_or_path !== 'undefined') { + if (Object.getPrototypeOf(module_or_path) === Object.prototype) { + ({module_or_path} = module_or_path) + } else { + console.warn('using deprecated parameters for the initialization function; pass a single object instead') + } + } + + if (typeof module_or_path === 'undefined' && typeof script_src !== 'undefined') { + module_or_path = script_src.replace(/\.js$/, '_bg.wasm'); + } + const imports = __wbg_get_imports(); + + if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { + module_or_path = fetch(module_or_path); + } + + __wbg_init_memory(imports); + + const { instance, module } = await __wbg_load(await module_or_path, imports); + + return __wbg_finalize_init(instance, module); + } + + wasm_bindgen = Object.assign(__wbg_init, { initSync }, __exports); + +})(); diff --git a/public/nimiq/2.0.5-history-fix/web/worker-wasm/index_bg.wasm b/public/nimiq/2.0.5-history-fix/web/worker-wasm/index_bg.wasm new file mode 100644 index 00000000..c59d797e Binary files /dev/null and b/public/nimiq/2.0.5-history-fix/web/worker-wasm/index_bg.wasm differ diff --git a/public/nimiq/2.0.5-history-fix/web/worker.js b/public/nimiq/2.0.5-history-fix/web/worker.js new file mode 100644 index 00000000..b8dc0a61 --- /dev/null +++ b/public/nimiq/2.0.5-history-fix/web/worker.js @@ -0,0 +1,57 @@ +// The worker has its own scope and no direct access to functions/objects of the +// global scope. We import the generated JS file to make `wasm_bindgen` +// available which we need to initialize our WASM code. +importScripts( + './comlink.min.js', + './worker-wasm/index.js', +); + +const { Client } = wasm_bindgen; + +// Defined both here and in main thread exports.js +Comlink.transferHandlers.set('function', { + canHandle: (_obj) => false, // Cannot send functions to main thread + deserialize(port) { + return Comlink.transferHandlers.get('proxy').deserialize(port); + }, +}); + +Comlink.transferHandlers.set('plain', { + canHandle: (_obj) => false, // Cannot send class instances to main thread + deserialize(plain) { + return plain; + }, +}); + +let initialized = false; + +async function init(config) { + if (initialized) throw new Error('Already initialized'); + initialized = true; + + console.log('Initializing client WASM worker'); + + // Load the wasm file by awaiting the Promise returned by `wasm_bindgen`. + await wasm_bindgen('./worker-wasm/index_bg.wasm'); + + const client = await Client.create(config); + Comlink.expose(client); +}; + +self.addEventListener('message', async (event) => { + const { type } = event.data; + if (type !== 'NIMIQ_INIT') return; + + let { config } = event.data; + if (!config || typeof config !== 'object') config = {}; + + try { + await init(config); + self.postMessage({ ok: true }); + } catch (error) { + self.postMessage({ ok: false, error: error.message, stack: error.stack }); + } +}); + +self.postMessage('NIMIQ_ONLOAD'); +console.debug('Launched client WASM worker, ready for init'); diff --git a/vue.config.js b/vue.config.js index 338fc6a7..ddfee5f6 100644 --- a/vue.config.js +++ b/vue.config.js @@ -8,15 +8,15 @@ const createHash = require('crypto').createHash; // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const PoLoaderOptimizer = require('webpack-i18n-tools')(); -let coreVersion = ''; -try { - // Will fail until @nimiq/core export map is updated to also make the package.json file available - coreVersion = require('@nimiq/core/package.json').version; -} catch (e) { - // Fallback to reading the package.json file directly - pkgJson = require('fs').readFileSync(path.join(__dirname, 'node_modules/@nimiq/core/package.json')); - coreVersion = JSON.parse(pkgJson).version; -} +let coreVersion = '2.0.5-history-fix'; +// try { +// // Will fail until @nimiq/core export map is updated to also make the package.json file available +// coreVersion = require('@nimiq/core/package.json').version; +// } catch (e) { +// // Fallback to reading the package.json file directly +// pkgJson = require('fs').readFileSync(path.join(__dirname, 'node_modules/@nimiq/core/package.json')); +// coreVersion = JSON.parse(pkgJson).version; +// } if (!coreVersion) throw new Error('Could not determine @nimiq/core version'); @@ -81,10 +81,10 @@ const configureWebpack = { return path.replace('.min', ''); }, }, - { - from: 'node_modules/@nimiq/core', - to: `./nimiq/v${coreVersion}/`, - }, + // { + // from: 'node_modules/@nimiq/core', + // to: `./nimiq/v${coreVersion}/`, + // }, ]}), new WriteFileWebpackPlugin(), new PoLoaderOptimizer(),