From ec64a17fffed0f71dfcc524059f5c5f97527f09f Mon Sep 17 00:00:00 2001 From: Sebastian Pape Date: Thu, 8 Jun 2023 08:56:20 +0200 Subject: [PATCH] 1.24.0: adds Solana MWA libraries --- README.md | 4 +- dist/esm/index.js | 41538 +++++++++++++++++++++++--------------------- dist/umd/index.js | 41538 +++++++++++++++++++++++--------------------- package.json | 4 +- src/index.js | 5 + yarn.lock | 31 + 6 files changed, 43023 insertions(+), 40097 deletions(-) diff --git a/README.md b/README.md index 8a5a9c3..6fa6234 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,9 @@ import { blob, Buffer, BN, - Keypair + Keypair, + transact, + Web3MobileWallet } from "@depay/solana-web3.js" ``` diff --git a/dist/esm/index.js b/dist/esm/index.js index d380a84..10e65a1 100644 --- a/dist/esm/index.js +++ b/dist/esm/index.js @@ -36,8086 +36,8088 @@ function getAugmentedNamespace(n) { return a; } -var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; -var inited = false; -function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + return keys; } -function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - return arr + return target; } -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} +function _regeneratorRuntime() { + /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ -function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') -} + _regeneratorRuntime = function () { + return exports; + }; -function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 + var exports = {}, + Op = Object.prototype, + hasOwn = Op.hasOwnProperty, + $Symbol = "function" == typeof Symbol ? Symbol : {}, + iteratorSymbol = $Symbol.iterator || "@@iterator", + asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", + toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + function define(obj, key, value) { + return Object.defineProperty(obj, key, { + value: value, + enumerable: !0, + configurable: !0, + writable: !0 + }), obj[key]; } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; + try { + define({}, ""); + } catch (err) { + define = function (obj, key, value) { + return obj[key] = value; + }; } - parts.push(output); - - return parts.join('') -} - -function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, + generator = Object.create(protoGenerator.prototype), + context = new Context(tryLocsList || []); + return generator._invoke = function (innerFn, self, context) { + var state = "suspendedStart"; + return function (method, arg) { + if ("executing" === state) throw new Error("Generator is already running"); - i += d; + if ("completed" === state) { + if ("throw" === method) throw arg; + return doneResult(); + } - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + for (context.method = method, context.arg = arg;;) { + var delegate = context.delegate; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } -function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { + if ("suspendedStart" === state) throw state = "completed", context.arg; + context.dispatchException(context.arg); + } else "return" === context.method && context.abrupt("return", context.arg); + state = "executing"; + var record = tryCatch(innerFn, self, context); - value = Math.abs(value); + if ("normal" === record.type) { + if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; + return { + value: record.arg, + done: context.done + }; + } - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } + "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); + } + }; + }(innerFn, self, context), generator; + } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; } } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + exports.wrap = wrap; + var ContinueSentinel = {}; - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + function Generator() {} - buffer[offset + i - d] |= s * 128; -} + function GeneratorFunction() {} -var toString = {}.toString; + function GeneratorFunctionPrototype() {} -var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf, + NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); + } -var INSPECT_MAX_BYTES = 50; + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. + if ("throw" !== record.type) { + var result = record.arg, + value = result.value; + return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }) : PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped, resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); + } - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; + reject(record.arg); + } -/* - * Export kMaxLength after typed array support is determined. - */ -var _kMaxLength = kMaxLength(); + var previousPromise; -function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} + this._invoke = function (method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + }; } - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; -function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } + if (undefined === method) { + if (context.delegate = null, "throw" === context.method) { + if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; + context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); + } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) + return ContinueSentinel; } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer$1.poolSize = 8192; // not used by this implementation -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr -}; + var record = tryCatch(method, delegate.iterator, context.arg); + if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; + var info = record.arg; + return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + } -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal", delete record.arg, entry.completion = record; } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } - return fromObject(that, value) -} + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) return iteratorMethod.call(iterable); + if ("function" == typeof iterable.next) return iterable; -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -}; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; -if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; -} + return next.value = undefined, next.done = !0, next; + }; -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} + return next.next = next; + } + } -function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + return { + next: doneResult + }; } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -}; -function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } + function doneResult() { + return { + value: undefined, + done: !0 + }; } - return that -} -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) -}; -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -}; + return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { + var ctor = "function" == typeof genFun && genFun.constructor; + return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); + }, exports.mark = function (genFun) { + return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; + }, exports.awrap = function (arg) { + return { + __await: arg + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + void 0 === PromiseImpl && (PromiseImpl = Promise); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { + return this; + }), define(Gp, "toString", function () { + return "[object Generator]"; + }), exports.keys = function (object) { + var keys = []; -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } + for (var key in object) keys.push(key); - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } + return keys.reverse(), function next() { + for (; keys.length;) { + var key = keys.pop(); + if (key in object) return next.value = key, next.done = !1, next; + } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + return next.done = !0, next; + }; + }, exports.values = values, Context.prototype = { + constructor: Context, + reset: function (skipTempReset) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); + }, + stop: function () { + this.done = !0; + var rootRecord = this.tryEntries[0].completion; + if ("throw" === rootRecord.type) throw rootRecord.arg; + return this.rval; + }, + dispatchException: function (exception) { + if (this.done) throw exception; + var context = this; - var actual = that.write(string, encoding); + function handle(loc, caught) { + return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; + } - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i], + record = entry.completion; + if ("root" === entry.tryLoc) return handle("end"); - return that -} + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"), + hasFinally = hasOwn.call(entry, "finallyLoc"); -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that -} + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } else if (hasCatch) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + } else { + if (!hasFinally) throw new Error("try statement without catch or finally"); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } + } + } + }, + abrupt: function (type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } + finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); + var record = finallyEntry ? finallyEntry.completion : {}; + return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); + }, + complete: function (record, afterLoc) { + if ("throw" === record.type) throw record.arg; + return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; + }, + finish: function (finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; + } + }, + catch: function (tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + if (entry.tryLoc === tryLoc) { + var record = entry.completion; - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } + if ("throw" === record.type) { + var thrown = record.arg; + resetTryEntry(entry); + } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that + return thrown; + } + } + + throw new Error("illegal catch attempt"); + }, + delegateYield: function (iterable, resultName, nextLoc) { + return this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }, "next" === this.method && (this.arg = undefined), ContinueSentinel; + } + }, exports; } -function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); +function _typeof$1(obj) { + "@babel/helpers - typeof"; - if (that.length === 0) { - return that - } + return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof$1(obj); +} - obj.copy(that, 0, 0, len); - return that +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } - return fromArrayLike(that, obj) - } - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + _next(undefined); + }); + }; } -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); } - return length | 0 } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); } - return Buffer$1.alloc(+length) } -Buffer$1.isBuffer = isBuffer; -function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; } -Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; } - if (a === b) return 0 + return obj; +} - var x = a.length; - var y = b.length; +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true } - } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} -Buffer$1.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -}; +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); +} -Buffer$1.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; - if (list.length === 0) { - return Buffer$1.alloc(0) + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; } +} - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } +function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; } - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer -}; + return _construct.apply(null, arguments); +} -function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} - var len = string.length; - if (len === 0) return 0 +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes$1(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); } - } -} -Buffer$1.byteLength = byteLength; -function slowToString (encoding, start, end) { - var loweredCase = false; + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + _cache.set(Class, Wrapper); + } - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } - if (end === undefined || end > this.length) { - end = this.length; - } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; - if (end <= 0) { - return '' - } + return _wrapNativeSuper(Class); +} - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (end <= start) { - return '' + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - if (!encoding) encoding = 'utf8'; + return target; +} - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + var target = _objectWithoutPropertiesLoose(source, excluded); - case 'ascii': - return asciiSlice(this, start, end) + var key, i; - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; } } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer$1.prototype._isBuffer = true; -function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; + return target; } -Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return this -}; -Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this -}; + return self; +} -Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); +function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); } - return this -}; -Buffer$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -}; + return _assertThisInitialized(self); +} -Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 -}; +function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); -Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' -}; + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), + result; -Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + return _possibleConstructorReturn(this, result); + }; +} - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + return object; +} - if (this === target) return 0 +function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get.bind(); + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } + return desc.value; + }; } - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; + return _get.apply(this, arguments); +} -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); +} - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } +function _toArray(arr) { + return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); +} - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} - throw new TypeError('val must be string, number or Buffer') +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; +function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + var _s, _e; - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; } } - return -1 + return _arr; } -Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -}; - -Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -}; - -Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -}; +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i + return arr2; } -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} +function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} + if (!it) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} + var F = function () {}; -Buffer$1.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + var normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = it.call(o); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; +} - case 'ascii': - return asciiWrite(this, string, offset, length) +var cjs$1 = {}; - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } +function toByteArray (b64) { + if (!inited) { + init(); } -}; + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; -Buffer$1.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -}; - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } + var L = 0; - res.push(codePoint); - i += bytesPerSequence; + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; } - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000; - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res + return arr } -function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } -function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); } - return ret + return output.join('') } -function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); } - return out -} -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; } - return res + + parts.push(output); + + return parts.join('') } -Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } + i += d; - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - if (end < start) end = start; + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } + m = m + Math.pow(2, mLen); + e = e - eBias; } - - return newBuf -}; - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } -Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } + value = Math.abs(value); - return val -}; + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } -Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - return val -}; + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] -}; + buffer[offset + i - d] |= s * 128; +} -Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) -}; +var toString = {}.toString; -Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] +var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; -Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -}; +var INSPECT_MAX_BYTES = 50; -Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -}; + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; -Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); +/* + * Export kMaxLength after typed array support is determined. + */ +var _kMaxLength = kMaxLength(); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; +function kMaxLength () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return that +} - return val -}; +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ -Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); +function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) } - mul *= 0x80; + return from(this, arg, encodingOrOffset, length) +} - if (val >= mul) val -= Math.pow(2, 8 * byteLength); +Buffer$1.poolSize = 8192; // not used by this implementation - return val +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr }; -Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -}; +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } -Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } -Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } -Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + return fromObject(that, value) +} - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer$1.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) }; -Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); +if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; +} - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -}; +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} -Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) -}; +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} -Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer$1.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) }; -Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) -}; +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} -Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer$1.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) }; -function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } - return offset + byteLength -}; + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); -Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + var actual = that.write(string, encoding); - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); } - return offset + byteLength -}; - -Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 -}; + return that +} -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; } + return that } -Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 -}; +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer -Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } - return offset + 2 -}; -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } -} -Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); } else { - objectWriteUInt32(this, value, offset, true); + array = new Uint8Array(array, byteOffset, length); } - return offset + 4 -}; -Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; } else { - objectWriteUInt32(this, value, offset, false); + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); } - return offset + 4 -}; + return that +} -Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - checkInt(this, value, offset, byteLength, limit - 1, -limit); + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } - return offset + byteLength -}; + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} -Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} - checkInt(this, value, offset, byteLength, limit - 1, -limit); +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; } + return Buffer$1.alloc(+length) +} +Buffer$1.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; +Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - return offset + byteLength -}; + if (a === b) return 0 -Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 -}; + var x = a.length; + var y = b.length; -Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } } - return offset + 2 -}; -Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + if (x < y) return -1 + if (y < x) return 1 + return 0 }; -Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); +Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } - return offset + 4 }; -Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); +Buffer$1.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - return offset + 4 -}; -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} + if (list.length === 0) { + return Buffer$1.alloc(0) + } -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 -} -Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer }; -Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -}; +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes$1(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 } +Buffer$1.byteLength = byteLength; -Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -}; +function slowToString (encoding, start, end) { + var loweredCase = false; -Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -}; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + if (end === undefined || end > this.length) { + end = this.length; + } - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') + if (end <= 0) { + return '' } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' } - var len = end - start; - var i; + if (!encoding) encoding = 'utf8'; - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); } +} - return len -}; +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer$1.prototype._isBuffer = true; -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer$1.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); } + return this +}; - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') +Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this +}; - if (end <= start) { - return this +Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); } + return this +}; - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; +Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; - if (!val) val = 0; +Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 +}; - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } +Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; } - - return this + return '' }; -// HELPER FUNCTIONS -// ================ +Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - return str -} -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; -function utf8ToBytes$1 (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + if (this === target) return 0 - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - // valid lead - leadSurrogate = codePoint; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } - continue - } + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } - leadSurrogate = null; + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - return bytes + throw new TypeError('val must be string, number or Buffer') } -function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } } - return byteArray -} -function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } } - return byteArray + return -1 } +Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; -function base64ToBytes (str) { - return toByteArray(base64clean(str)) -} +Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; -function blitBuffer (src, dst, offset, length) { +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; } return i } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) } +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} -// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } -var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ - __proto__: null, - Buffer: Buffer$1, - INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, - SlowBuffer: SlowBuffer, - isBuffer: isBuffer, - kMaxLength: _kMaxLength -}); +Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } -var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_buffer); + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } - return keys; -} + if (!encoding) encoding = 'utf8'; -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - return target; -} + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) -function _regeneratorRuntime() { - /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + case 'ascii': + return asciiWrite(this, string, offset, length) - _regeneratorRuntime = function () { - return exports; - }; + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - var exports = {}, - Op = Object.prototype, - hasOwn = Op.hasOwnProperty, - $Symbol = "function" == typeof Symbol ? Symbol : {}, - iteratorSymbol = $Symbol.iterator || "@@iterator", - asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", - toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - function define(obj, key, value) { - return Object.defineProperty(obj, key, { - value: value, - enumerable: !0, - configurable: !0, - writable: !0 - }), obj[key]; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } } +}; - try { - define({}, ""); - } catch (err) { - define = function (obj, key, value) { - return obj[key] = value; - }; +Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } +}; - function wrap(innerFn, outerFn, self, tryLocsList) { - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, - generator = Object.create(protoGenerator.prototype), - context = new Context(tryLocsList || []); - return generator._invoke = function (innerFn, self, context) { - var state = "suspendedStart"; - return function (method, arg) { - if ("executing" === state) throw new Error("Generator is already running"); +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} - if ("completed" === state) { - if ("throw" === method) throw arg; - return doneResult(); - } +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - for (context.method = method, context.arg = arg;;) { - var delegate = context.delegate; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; } } - - if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { - if ("suspendedStart" === state) throw state = "completed", context.arg; - context.dispatchException(context.arg); - } else "return" === context.method && context.abrupt("return", context.arg); - state = "executing"; - var record = tryCatch(innerFn, self, context); - - if ("normal" === record.type) { - if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; - return { - value: record.arg, - done: context.done - }; + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } - "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); - } - }; - }(innerFn, self, context), generator; - } - - function tryCatch(fn, obj, arg) { - try { - return { - type: "normal", - arg: fn.call(obj, arg) - }; - } catch (err) { - return { - type: "throw", - arg: err - }; + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; } + + res.push(codePoint); + i += bytesPerSequence; } - exports.wrap = wrap; - var ContinueSentinel = {}; + return decodeCodePointsArray(res) +} - function Generator() {} +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; - function GeneratorFunction() {} +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - function GeneratorFunctionPrototype() {} + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} - var IteratorPrototype = {}; - define(IteratorPrototype, iteratorSymbol, function () { - return this; - }); - var getProto = Object.getPrototypeOf, - NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - define(prototype, method, function (arg) { - return this._invoke(method, arg); - }); - }); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); } + return ret +} - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - - if ("throw" !== record.type) { - var result = record.arg, - value = result.value; - return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }) : PromiseImpl.resolve(value).then(function (unwrapped) { - result.value = unwrapped, resolve(result); - }, function (error) { - return invoke("throw", error, resolve, reject); - }); - } +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - reject(record.arg); - } + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} - var previousPromise; +function hexSlice (buf, start, end) { + var len = buf.length; - this._invoke = function (method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - }; + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); } + return out +} - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - - if (undefined === method) { - if (context.delegate = null, "throw" === context.method) { - if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; - context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} - return ContinueSentinel; - } +Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - var record = tryCatch(method, delegate.iterator, context.arg); - if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; - var info = record.arg; - return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; } - function pushTryEntry(locs) { - var entry = { - tryLoc: locs[0] - }; - 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal", delete record.arg, entry.completion = record; - } + if (end < start) end = start; - function Context(tryLocsList) { - this.tryEntries = [{ - tryLoc: "root" - }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } } - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) return iteratorMethod.call(iterable); - if ("function" == typeof iterable.next) return iterable; + return newBuf +}; - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} - return next.value = undefined, next.done = !0, next; - }; +Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - return next.next = next; - } - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - return { - next: doneResult - }; + return val +}; + +Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - function doneResult() { - return { - value: undefined, - done: !0 - }; + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { - var ctor = "function" == typeof genFun && genFun.constructor; - return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); - }, exports.mark = function (genFun) { - return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; - }, exports.awrap = function (arg) { - return { - __await: arg - }; - }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { - return this; - }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { - void 0 === PromiseImpl && (PromiseImpl = Promise); - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); - return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { - return this; - }), define(Gp, "toString", function () { - return "[object Generator]"; - }), exports.keys = function (object) { - var keys = []; + return val +}; - for (var key in object) keys.push(key); +Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; - return keys.reverse(), function next() { - for (; keys.length;) { - var key = keys.pop(); - if (key in object) return next.value = key, next.done = !1, next; - } +Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; - return next.done = !0, next; - }; - }, exports.values = values, Context.prototype = { - constructor: Context, - reset: function (skipTempReset) { - if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); - }, - stop: function () { - this.done = !0; - var rootRecord = this.tryEntries[0].completion; - if ("throw" === rootRecord.type) throw rootRecord.arg; - return this.rval; - }, - dispatchException: function (exception) { - if (this.done) throw exception; - var context = this; +Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; - function handle(loc, caught) { - return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; - } +Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i], - record = entry.completion; - if ("root" === entry.tryLoc) return handle("end"); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"), - hasFinally = hasOwn.call(entry, "finallyLoc"); +Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); - if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); - } else if (hasCatch) { - if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); - } else { - if (!hasFinally) throw new Error("try statement without catch or finally"); - if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); - } - } - } - }, - abrupt: function (type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } +Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); - var record = finallyEntry ? finallyEntry.completion : {}; - return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); - }, - complete: function (record, afterLoc) { - if ("throw" === record.type) throw record.arg; - return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; - }, - finish: function (finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; - } - }, - catch: function (tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if ("throw" === record.type) { - var thrown = record.arg; - resetTryEntry(entry); - } + return val +}; - return thrown; - } - } +Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - throw new Error("illegal catch attempt"); - }, - delegateYield: function (iterable, resultName, nextLoc) { - return this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }, "next" === this.method && (this.arg = undefined), ContinueSentinel; - } - }, exports; -} + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; -function _typeof$1(obj) { - "@babel/helpers - typeof"; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }, _typeof$1(obj); -} + return val +}; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } +Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } -} +Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; -function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); +Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } +Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; - _next(undefined); - }); - }; -} +Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} +Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; -} +Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } +Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; - return obj; +Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); +Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - Object.defineProperty(subClass, "prototype", { - writable: false - }); - if (superClass) _setPrototypeOf(subClass, superClass); -} + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } -function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} + return offset + byteLength +}; -function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); -} +Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; + return offset + byteLength +}; + +Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; } } -function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct.bind(); +Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; + objectWriteUInt16(this, value, offset, true); } + return offset + 2 +}; - return _construct.apply(null, arguments); -} +Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; -function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } } -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; +Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } +Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); +Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - _cache.set(Class, Wrapper); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} + return offset + byteLength +}; -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; +Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - var target = _objectWithoutPropertiesLoose(source, excluded); + return offset + byteLength +}; - var key, i; +Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); +Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } +Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); } + return offset + 2 +}; - return target; -} +Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); +Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); } + return offset + 4 +}; - return self; +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') } -function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); } - - return _assertThisInitialized(self); + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 } -function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); +Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; +Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } +Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; - return _possibleConstructorReturn(this, result); - }; -} +Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; -function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - return object; -} + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } -function _get() { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get.bind(); + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); + return len +}; - if (desc.get) { - return desc.get.call(arguments.length < 3 ? target : receiver); +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } - return desc.value; - }; + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') } - return _get.apply(this, arguments); -} + if (end <= start) { + return this + } -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); -} + if (!val) val = 0; -function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); -} + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } -function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str } -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') } -function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) } -function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; +function utf8ToBytes$1 (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - var _s, _e; + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); + // valid lead + leadSurrogate = codePoint; - if (i && _arr.length === i) break; + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') } } - return _arr; + return bytes } -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray } -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - return arr2; + return byteArray } -function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +function base64ToBytes (str) { + return toByteArray(base64clean(str)) } -function _createForOfIteratorHelper(o, allowArrayLike) { - var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} - if (!it) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} - var F = function () {}; - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = it.call(o); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } -var bn$1 = {exports: {}}; +var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + Buffer: Buffer$1, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + SlowBuffer: SlowBuffer, + isBuffer: isBuffer, + kMaxLength: _kMaxLength +}); -(function (module) { - (function (module, exports) { +function number$1(n) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error("Wrong positive integer: ".concat(n)); +} +function bool(b) { + if (typeof b !== 'boolean') throw new Error("Expected boolean, not ".concat(b)); +} +function bytes(b) { + if (!(b instanceof Uint8Array)) throw new TypeError('Expected Uint8Array'); - function assert(val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } // Could use `inherits` module, but don't want to move from single file - // architecture yet. + for (var _len = arguments.length, lengths = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + lengths[_key - 1] = arguments[_key]; + } + if (lengths.length > 0 && !lengths.includes(b.length)) throw new TypeError("Expected Uint8Array of length ".concat(lengths, ", not of length=").concat(b.length)); +} +function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number$1(hash.outputLen); + number$1(hash.blockLen); +} +function exists(instance) { + var checkFinished = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + var min = instance.outputLen; - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least ".concat(min)); + } +} +var assert$1 = { + number: number$1, + bool: bool, + bytes: bytes, + hash: hash, + exists: exists, + output: output +}; +var assert$2 = assert$1; - var TempCtor = function TempCtor() {}; +var u32$1 = function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +}; // Cast array to view - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } // BN +var createView = function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +}; // The rotate right (circular right shift) operation for uint32 +var rotr = function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +}; // big-endian hardware is rare. Just in case someone still decides to run hashes: +// early-throw an error because we don't support BE yet. - function BN(number, base, endian) { - if (BN.isBN(number)) { - return number; - } +var isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +if (!isLE) throw new Error('Non little-endian hardware is not supported'); +Array.from({ + length: 256 +}, function (v, i) { + return i.toString(16).padStart(2, '0'); +}); - this.negative = 0; - this.words = null; - this.length = 0; // Reduction context +function utf8ToBytes(str) { + if (typeof str !== 'string') { + throw new TypeError("utf8ToBytes expected string, got ".concat(_typeof$1(str))); + } - this.red = null; + return new TextEncoder().encode(str); +} +function toBytes(data) { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!(data instanceof Uint8Array)) throw new TypeError("Expected input type is Uint8Array (got ".concat(_typeof$1(data), ")")); + return data; +} - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } +var Hash = /*#__PURE__*/function () { + function Hash() { + _classCallCheck(this, Hash); + } - this._init(number || 0, base || 10, endian || 'be'); - } + _createClass(Hash, [{ + key: "clone", + value: // Safe version that clones internal state + function clone() { + return this._cloneInto(); } + }]); - if (_typeof$1(module) === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } + return Hash; +}(); // Check if object doens't have custom constructor (like Uint8Array/Array) +function wrapConstructor(hashConstructor) { + var hashC = function hashC(message) { + return hashConstructor().update(toBytes(message)).digest(); + }; - BN.BN = BN; - BN.wordSize = 26; - var Buffer; + var tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require$$0$1.Buffer; - } - } catch (e) {} + hashC.create = function () { + return hashConstructor(); + }; - BN.isBN = function isBN(num) { - if (num instanceof BN) { - return true; - } + return hashC; +} +function wrapConstructorWithOpts(hashCons) { + var hashC = function hashC(msg, opts) { + return hashCons(opts).update(toBytes(msg)).digest(); + }; - return num !== null && _typeof$1(num) === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; + var tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; - BN.max = function max(left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + hashC.create = function (opts) { + return hashCons(opts); + }; - BN.min = function min(left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + return hashC; +} - BN.prototype._init = function init(number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); - if (_typeof$1(number) === 'object') { - return this._initArray(number, base, endian); - } + var _32n = BigInt(32); - if (base === 'hex') { - base = 16; - } + var _u32_max = BigInt(0xffffffff); - assert(base === (base | 0) && base >= 2 && base <= 36); - number = number.toString().replace(/\s+/g, ''); - var start = 0; + var wh = Number(value >> _32n & _u32_max); + var wl = Number(value & _u32_max); + var h = isLE ? 4 : 0; + var l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} // Base SHA2 class (RFC 6234) - if (number[0] === '-') { - start++; - this.negative = 1; - } - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); +var SHA2 = /*#__PURE__*/function (_Hash) { + _inherits(SHA2, _Hash); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; + var _super = _createSuper(SHA2); - BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } + function SHA2(blockLen, outputLen, padOffset, isLE) { + var _this; - if (number < 0x4000000) { - this.words = [number & 0x3ffffff]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + _classCallCheck(this, SHA2); - this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1]; - this.length = 3; - } + _this = _super.call(this); + _this.blockLen = blockLen; + _this.outputLen = outputLen; + _this.padOffset = padOffset; + _this.isLE = isLE; + _this.finished = false; + _this.length = 0; + _this.pos = 0; + _this.destroyed = false; + _this.buffer = new Uint8Array(blockLen); + _this.view = createView(_this.buffer); + return _this; + } - if (endian !== 'le') return; // Reverse the bytes + _createClass(SHA2, [{ + key: "update", + value: function update(data) { + assert$2.exists(this); + var view = this.view, + buffer = this.buffer, + blockLen = this.blockLen; + data = toBytes(data); + var len = data.length; - this._initArray(this.toArray(), base, endian); - }; + for (var pos = 0; pos < len;) { + var take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process - BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); + if (take === blockLen) { + var dataView = createView(data); - if (number.length <= 0) { - this.words = [0]; - this.length = 1; - return this; - } + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); + continue; + } - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } } - var j, w; - var off = 0; + this.length += data.length; + this.roundClean(); + return this; + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.exists(this); + assert$2.output(out, this); + this.finished = true; // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; - this.words[j] |= w << off & 0x3ffffff; - this.words[j + 1] = w >>> 26 - off & 0x3ffffff; - off += 24; + var buffer = this.buffer, + view = this.view, + blockLen = this.blockLen, + isLE = this.isLE; + var pos = this.pos; // append the bit '1' to the message - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; - this.words[j] |= w << off & 0x3ffffff; - this.words[j + 1] = w >>> 26 - off & 0x3ffffff; - off += 24; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (off >= 26) { - off -= 26; - j++; - } - } - } + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } // Pad until full block byte with zeros - return this._strip(); - }; - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); // '0' - '9' + for (var i = pos; i < blockLen; i++) buffer[i] = 0; // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. - if (c >= 48 && c <= 57) { - return c - 48; // 'A' - 'F' - } else if (c >= 65 && c <= 70) { - return c - 55; // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, 'Invalid character in ' + string); - } - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + var oview = createView(out); + var len = this.outputLen; // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + var outLen = len / 4; + var state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); - return r; + for (var _i2 = 0; _i2 < outLen; _i2++) oview.setUint32(4 * _i2, state[_i2], isLE); } + }, { + key: "digest", + value: function digest() { + var buffer = this.buffer, + outputLen = this.outputLen; + this.digestInto(buffer); + var res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + var _to; - BN.prototype._parseHex = function _parseHex(number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } // 24-bits chunks - + to || (to = new this.constructor()); - var off = 0; - var j = 0; - var w; + (_to = to).set.apply(_to, _toConsumableArray(this.get())); - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; + var blockLen = this.blockLen, + buffer = this.buffer, + length = this.length, + finished = this.finished, + destroyed = this.destroyed, + pos = this.pos; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } + }]); - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; + return SHA2; +}(Hash); - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; +var U32_MASK64 = BigInt(Math.pow(2, 32) - 1); - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } +var _32n = BigInt(32); // We are not using BigUint64Array, because they are extremely slow as per 2022 - this._strip(); - }; - function parseBase(str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); +function fromBig(n) { + var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (le) return { + h: Number(n & U32_MASK64), + l: Number(n >> _32n & U32_MASK64) + }; + return { + h: Number(n >> _32n & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0 + }; +} +function split(lst) { + var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var Ah = new Uint32Array(lst.length); + var Al = new Uint32Array(lst.length); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - r *= mul; // 'a' + for (var i = 0; i < lst.length; i++) { + var _fromBig2 = fromBig(lst[i], le), + h = _fromBig2.h, + l = _fromBig2.l; - if (c >= 49) { - b = c - 49 + 0xa; // 'A' - } else if (c >= 17) { - b = c - 17 + 0xa; // '0' - '9' - } else { - b = c; - } + var _ref = [h, l]; + Ah[i] = _ref[0]; + Al[i] = _ref[1]; + } - assert(c >= 0 && b < mul, 'Invalid character'); - r += b; - } + return [Ah, Al]; +} +var toBig = function toBig(h, l) { + return BigInt(h >>> 0) << _32n | BigInt(l >>> 0); +}; // for Shift in [0, 32) - return r; - } +var shrSH = function shrSH(h, l, s) { + return h >>> s; +}; - BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [0]; - this.length = 1; // Find length of limb in base +var shrSL = function shrSL(h, l, s) { + return h << 32 - s | l >>> s; +}; // Right rotate for Shift in [1, 32) - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = limbPow / base | 0; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - var word = 0; +var rotrSH = function rotrSH(h, l, s) { + return h >>> s | l << 32 - s; +}; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); +var rotrSL = function rotrSL(h, l, s) { + return h << 32 - s | l >>> s; +}; // Right rotate for Shift in (32, 64), NOTE: 32 is special case. - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); +var rotrBH = function rotrBH(h, l, s) { + return h << 64 - s | l >>> s - 32; +}; - for (i = 0; i < mod; i++) { - pow *= base; - } +var rotrBL = function rotrBL(h, l, s) { + return h >>> s - 32 | l << 64 - s; +}; // Right rotate for shift===32 (just swaps l&h) - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } +var rotr32H = function rotr32H(h, l) { + return l; +}; - this._strip(); - }; +var rotr32L = function rotr32L(h, l) { + return h; +}; // Left rotate for Shift in [1, 32) - BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } +var rotlSH = function rotlSH(h, l, s) { + return h << s | l >>> 32 - s; +}; - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; +var rotlSL = function rotlSL(h, l, s) { + return l << s | h >>> 32 - s; +}; // Left rotate for Shift in (32, 64), NOTE: 32 is special case. - function move(dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; - } - BN.prototype._move = function _move(dest) { - move(dest, this); - }; +var rotlBH = function rotlBH(h, l, s) { + return l << s - 32 | h >>> 64 - s; +}; - BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; - }; +var rotlBL = function rotlBL(h, l, s) { + return h << s - 32 | l >>> 64 - s; +}; // JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +// Removing "export" has 5% perf penalty -_- - BN.prototype._expand = function _expand(size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; // Remove leading `0` from `this` +function add(Ah, Al, Bh, Bl) { + var l = (Al >>> 0) + (Bl >>> 0); + return { + h: Ah + Bh + (l / Math.pow(2, 32) | 0) | 0, + l: l | 0 + }; +} // Addition with more than 2 elements +var add3L = function add3L(Al, Bl, Cl) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +}; - BN.prototype._strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } +var add3H = function add3H(low, Ah, Bh, Ch) { + return Ah + Bh + Ch + (low / Math.pow(2, 32) | 0) | 0; +}; - return this._normSign(); - }; +var add4L = function add4L(Al, Bl, Cl, Dl) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +}; - BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } +var add4H = function add4H(low, Ah, Bh, Ch, Dh) { + return Ah + Bh + Ch + Dh + (low / Math.pow(2, 32) | 0) | 0; +}; - return this; - }; // Check Symbol.for because not everywhere where Symbol defined - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility +var add5L = function add5L(Al, Bl, Cl, Dl, El) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +}; +var add5H = function add5H(low, Ah, Bh, Ch, Dh, Eh) { + return Ah + Bh + Ch + Dh + Eh + (low / Math.pow(2, 32) | 0) | 0; +}; // prettier-ignore - if (typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function') { - try { - BN.prototype[Symbol["for"]('nodejs.util.inspect.custom')] = inspect; - } catch (e) { - BN.prototype.inspect = inspect; - } - } else { - BN.prototype.inspect = inspect; - } - function inspect() { - return (this.red ? ''; - } - /* - var zeros = []; - var groupSizes = []; - var groupBases = []; - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - */ +var u64$1 = { + fromBig: fromBig, + split: split, + toBig: toBig, + shrSH: shrSH, + shrSL: shrSL, + rotrSH: rotrSH, + rotrSL: rotrSL, + rotrBH: rotrBH, + rotrBL: rotrBL, + rotr32H: rotr32H, + rotr32L: rotr32L, + rotlSH: rotlSH, + rotlSL: rotlSL, + rotlBH: rotlBH, + rotlBL: rotlBL, + add: add, + add3L: add3L, + add3H: add3H, + add4L: add4L, + add4H: add4H, + add5H: add5H, + add5L: add5L +}; +var u64$2 = u64$1; +// prettier-ignore - var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000']; - var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; - var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; +var _u64$split$1 = u64$2.split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(function (n) { + return BigInt(n); +})), + _u64$split2$1 = _slicedToArray(_u64$split$1, 2), + SHA512_Kh = _u64$split2$1[0], + SHA512_Kl = _u64$split2$1[1]; // Temporary buffer, not used to store anything between runs - BN.prototype.toString = function toString(base, padding) { - base = base || 10; - padding = padding | 0 || 1; - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; +var SHA512_W_H = new Uint32Array(80); +var SHA512_W_L = new Uint32Array(80); +var SHA512 = /*#__PURE__*/function (_SHA) { + _inherits(SHA512, _SHA); - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = ((w << off | carry) & 0xffffff).toString(16); - carry = w >>> 24 - off & 0xffffff; + var _super = _createSuper(SHA512); - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } + function SHA512() { + var _this; - off += 2; + _classCallCheck(this, SHA512); - if (off >= 26) { - off -= 26; - i--; - } - } + _this = _super.call(this, 128, 64, 16, false); // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits - if (carry !== 0) { - out = carry.toString(16) + out; - } + _this.Ah = 0x6a09e667 | 0; + _this.Al = 0xf3bcc908 | 0; + _this.Bh = 0xbb67ae85 | 0; + _this.Bl = 0x84caa73b | 0; + _this.Ch = 0x3c6ef372 | 0; + _this.Cl = 0xfe94f82b | 0; + _this.Dh = 0xa54ff53a | 0; + _this.Dl = 0x5f1d36f1 | 0; + _this.Eh = 0x510e527f | 0; + _this.El = 0xade682d1 | 0; + _this.Fh = 0x9b05688c | 0; + _this.Fl = 0x2b3e6c1f | 0; + _this.Gh = 0x1f83d9ab | 0; + _this.Gl = 0xfb41bd6b | 0; + _this.Hh = 0x5be0cd19 | 0; + _this.Hl = 0x137e2179 | 0; + return _this; + } // prettier-ignore - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } + _createClass(SHA512, [{ + key: "get", + value: function get() { + var Ah = this.Ah, + Al = this.Al, + Bh = this.Bh, + Bl = this.Bl, + Ch = this.Ch, + Cl = this.Cl, + Dh = this.Dh, + Dl = this.Dl, + Eh = this.Eh, + El = this.El, + Fh = this.Fh, + Fl = this.Fl, + Gh = this.Gh, + Gl = this.Gl, + Hh = this.Hh, + Hl = this.Hl; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } // prettier-ignore - return out; + }, { + key: "set", + value: function set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + }, { + key: "process", + value: function process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (var i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); } - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); + for (var _i2 = 16; _i2 < 80; _i2++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + var W15h = SHA512_W_H[_i2 - 15] | 0; + var W15l = SHA512_W_L[_i2 - 15] | 0; + var s0h = u64$2.rotrSH(W15h, W15l, 1) ^ u64$2.rotrSH(W15h, W15l, 8) ^ u64$2.shrSH(W15h, W15l, 7); + var s0l = u64$2.rotrSL(W15h, W15l, 1) ^ u64$2.rotrSL(W15h, W15l, 8) ^ u64$2.shrSL(W15h, W15l, 7); // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; + var W2h = SHA512_W_H[_i2 - 2] | 0; + var W2l = SHA512_W_L[_i2 - 2] | 0; + var s1h = u64$2.rotrSH(W2h, W2l, 19) ^ u64$2.rotrBH(W2h, W2l, 61) ^ u64$2.shrSH(W2h, W2l, 6); + var s1l = u64$2.rotrSL(W2h, W2l, 19) ^ u64$2.rotrBL(W2h, W2l, 61) ^ u64$2.shrSL(W2h, W2l, 6); // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - while (!c.isZero()) { - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); + var SUMl = u64$2.add4L(s0l, s1l, SHA512_W_L[_i2 - 7], SHA512_W_L[_i2 - 16]); + var SUMh = u64$2.add4H(SUMl, s0h, s1h, SHA512_W_H[_i2 - 7], SHA512_W_H[_i2 - 16]); + SHA512_W_H[_i2] = SUMh | 0; + SHA512_W_L[_i2] = SUMl | 0; + } - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } + var Ah = this.Ah, + Al = this.Al, + Bh = this.Bh, + Bl = this.Bl, + Ch = this.Ch, + Cl = this.Cl, + Dh = this.Dh, + Dl = this.Dl, + Eh = this.Eh, + El = this.El, + Fh = this.Fh, + Fl = this.Fl, + Gh = this.Gh, + Gl = this.Gl, + Hh = this.Hh, + Hl = this.Hl; // Compression function main loop, 80 rounds - if (this.isZero()) { - out = '0' + out; - } + for (var _i4 = 0; _i4 < 80; _i4++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + var sigma1h = u64$2.rotrSH(Eh, El, 14) ^ u64$2.rotrSH(Eh, El, 18) ^ u64$2.rotrBH(Eh, El, 41); + var sigma1l = u64$2.rotrSL(Eh, El, 14) ^ u64$2.rotrSL(Eh, El, 18) ^ u64$2.rotrBL(Eh, El, 41); //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - while (out.length % padding !== 0) { - out = '0' + out; - } + var CHIh = Eh & Fh ^ ~Eh & Gh; + var CHIl = El & Fl ^ ~El & Gl; // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore - if (this.negative !== 0) { - out = '-' + out; - } + var T1ll = u64$2.add5L(Hl, sigma1l, CHIl, SHA512_Kl[_i4], SHA512_W_L[_i4]); + var T1h = u64$2.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[_i4], SHA512_W_H[_i4]); + var T1l = T1ll | 0; // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) - return out; - } + var sigma0h = u64$2.rotrSH(Ah, Al, 28) ^ u64$2.rotrBH(Ah, Al, 34) ^ u64$2.rotrBH(Ah, Al, 39); + var sigma0l = u64$2.rotrSL(Ah, Al, 28) ^ u64$2.rotrBL(Ah, Al, 34) ^ u64$2.rotrBL(Ah, Al, 39); + var MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + var MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; - assert(false, 'Base should be between 2 and 36'); - }; + var _u64$add = u64$2.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0); - BN.prototype.toNumber = function toNumber() { - var ret = this.words[0]; + Eh = _u64$add.h; + El = _u64$add.l; + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + var All = u64$2.add3L(T1l, sigma0l, MAJl); + Ah = u64$2.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } // Add the compressed chunk to the current hash value - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + this.words[1] * 0x4000000; - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return this.negative !== 0 ? -ret : ret; - }; + var _u64$add2 = u64$2.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0); - BN.prototype.toJSON = function toJSON() { - return this.toString(16, 2); - }; + Ah = _u64$add2.h; + Al = _u64$add2.l; - if (Buffer) { - BN.prototype.toBuffer = function toBuffer(endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; - } + var _u64$add3 = u64$2.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0); - BN.prototype.toArray = function toArray(endian, length) { - return this.toArrayLike(Array, endian, length); - }; + Bh = _u64$add3.h; + Bl = _u64$add3.l; - var allocate = function allocate(ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); - } + var _u64$add4 = u64$2.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0); - return new ArrayType(size); - }; + Ch = _u64$add4.h; + Cl = _u64$add4.l; - BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { - this._strip(); + var _u64$add5 = u64$2.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0); - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - var res = allocate(ArrayType, reqLength); - var postfix = endian === 'le' ? 'LE' : 'BE'; - this['_toArrayLike' + postfix](res, byteLength); - return res; - }; + Dh = _u64$add5.h; + Dl = _u64$add5.l; - BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { - var position = 0; - var carry = 0; + var _u64$add6 = u64$2.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0); - for (var i = 0, shift = 0; i < this.length; i++) { - var word = this.words[i] << shift | carry; - res[position++] = word & 0xff; + Eh = _u64$add6.h; + El = _u64$add6.l; - if (position < res.length) { - res[position++] = word >> 8 & 0xff; - } + var _u64$add7 = u64$2.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0); - if (position < res.length) { - res[position++] = word >> 16 & 0xff; - } + Fh = _u64$add7.h; + Fl = _u64$add7.l; - if (shift === 6) { - if (position < res.length) { - res[position++] = word >> 24 & 0xff; - } + var _u64$add8 = u64$2.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0); - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } + Gh = _u64$add8.h; + Gl = _u64$add8.l; - if (position < res.length) { - res[position++] = carry; + var _u64$add9 = u64$2.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0); - while (position < res.length) { - res[position++] = 0; - } - } - }; + Hh = _u64$add9.h; + Hl = _u64$add9.l; + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + }, { + key: "roundClean", + value: function roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + }, { + key: "destroy", + value: function destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + }]); - BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { - var position = res.length - 1; - var carry = 0; + return SHA512; +}(SHA2); - for (var i = 0, shift = 0; i < this.length; i++) { - var word = this.words[i] << shift | carry; - res[position--] = word & 0xff; +var SHA512_224 = /*#__PURE__*/function (_SHA2) { + _inherits(SHA512_224, _SHA2); - if (position >= 0) { - res[position--] = word >> 8 & 0xff; - } + var _super2 = _createSuper(SHA512_224); - if (position >= 0) { - res[position--] = word >> 16 & 0xff; - } + function SHA512_224() { + var _this2; - if (shift === 6) { - if (position >= 0) { - res[position--] = word >> 24 & 0xff; - } + _classCallCheck(this, SHA512_224); - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } + _this2 = _super2.call(this); // h -- high 32 bits, l -- low 32 bits - if (position >= 0) { - res[position--] = carry; + _this2.Ah = 0x8c3d37c8 | 0; + _this2.Al = 0x19544da2 | 0; + _this2.Bh = 0x73e19966 | 0; + _this2.Bl = 0x89dcd4d6 | 0; + _this2.Ch = 0x1dfab7ae | 0; + _this2.Cl = 0x32ff9c82 | 0; + _this2.Dh = 0x679dd514 | 0; + _this2.Dl = 0x582f9fcf | 0; + _this2.Eh = 0x0f6d2b69 | 0; + _this2.El = 0x7bd44da8 | 0; + _this2.Fh = 0x77e36f73 | 0; + _this2.Fl = 0x04c48942 | 0; + _this2.Gh = 0x3f9d85a8 | 0; + _this2.Gl = 0x6a1d36c8 | 0; + _this2.Hh = 0x1112e6ad | 0; + _this2.Hl = 0x91d692a1 | 0; + _this2.outputLen = 28; + return _this2; + } - while (position >= 0) { - res[position--] = 0; - } - } - }; + return _createClass(SHA512_224); +}(SHA512); - if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; +var SHA512_256 = /*#__PURE__*/function (_SHA3) { + _inherits(SHA512_256, _SHA3); - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } + var _super3 = _createSuper(SHA512_256); - if (t >= 0x40) { - r += 7; - t >>>= 7; - } + function SHA512_256() { + var _this3; - if (t >= 0x8) { - r += 4; - t >>>= 4; - } + _classCallCheck(this, SHA512_256); - if (t >= 0x02) { - r += 2; - t >>>= 2; - } + _this3 = _super3.call(this); // h -- high 32 bits, l -- low 32 bits - return r + t; - }; - } + _this3.Ah = 0x22312194 | 0; + _this3.Al = 0xfc2bf72c | 0; + _this3.Bh = 0x9f555fa3 | 0; + _this3.Bl = 0xc84c64c2 | 0; + _this3.Ch = 0x2393b86b | 0; + _this3.Cl = 0x6f53b151 | 0; + _this3.Dh = 0x96387719 | 0; + _this3.Dl = 0x5940eabd | 0; + _this3.Eh = 0x96283ee2 | 0; + _this3.El = 0xa88effe3 | 0; + _this3.Fh = 0xbe5e1e25 | 0; + _this3.Fl = 0x53863992 | 0; + _this3.Gh = 0x2b0199fc | 0; + _this3.Gl = 0x2c85b8aa | 0; + _this3.Hh = 0x0eb72ddc | 0; + _this3.Hl = 0x81c52ca2 | 0; + _this3.outputLen = 32; + return _this3; + } - BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) return 26; - var t = w; - var r = 0; + return _createClass(SHA512_256); +}(SHA512); - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } +var SHA384 = /*#__PURE__*/function (_SHA4) { + _inherits(SHA384, _SHA4); - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } + var _super4 = _createSuper(SHA384); - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } + function SHA384() { + var _this4; - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } + _classCallCheck(this, SHA384); - if ((t & 0x1) === 0) { - r++; - } - - return r; - }; // Return number of used bits in a BN + _this4 = _super4.call(this); // h -- high 32 bits, l -- low 32 bits + _this4.Ah = 0xcbbb9d5d | 0; + _this4.Al = 0xc1059ed8 | 0; + _this4.Bh = 0x629a292a | 0; + _this4.Bl = 0x367cd507 | 0; + _this4.Ch = 0x9159015a | 0; + _this4.Cl = 0x3070dd17 | 0; + _this4.Dh = 0x152fecd8 | 0; + _this4.Dl = 0xf70e5939 | 0; + _this4.Eh = 0x67332667 | 0; + _this4.El = 0xffc00b31 | 0; + _this4.Fh = 0x8eb44a87 | 0; + _this4.Fl = 0x68581511 | 0; + _this4.Gh = 0xdb0c2e0d | 0; + _this4.Gl = 0x64f98fa7 | 0; + _this4.Hh = 0x47b5481d | 0; + _this4.Hl = 0xbefa4fa4 | 0; + _this4.outputLen = 48; + return _this4; + } - BN.prototype.bitLength = function bitLength() { - var w = this.words[this.length - 1]; + return _createClass(SHA384); +}(SHA512); - var hi = this._countBits(w); +var sha512 = wrapConstructor(function () { + return new SHA512(); +}); +wrapConstructor(function () { + return new SHA512_224(); +}); +wrapConstructor(function () { + return new SHA512_256(); +}); +wrapConstructor(function () { + return new SHA384(); +}); - return (this.length - 1) * 26 + hi; - }; +var _polyfillNode_crypto = {}; - function toBitArray(num) { - var w = new Array(num.bitLength()); +var nodeCrypto = _global$1.crypto; - for (var bit = 0; bit < w.length; bit++) { - var off = bit / 26 | 0; - var wbit = bit % 26; - w[bit] = num.words[off] >>> wbit & 0x01; - } +var _0n$2 = BigInt(0); - return w; - } // Number of trailing zero bits +var _1n$2 = BigInt(1); +var _2n$2 = BigInt(2); - BN.prototype.zeroBits = function zeroBits() { - if (this.isZero()) return 0; - var r = 0; +var _8n$1 = BigInt(8); - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); +var CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'); +var CURVE$1 = Object.freeze({ + a: BigInt(-1), + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'), + l: CU_O, + n: CU_O, + h: BigInt(8), + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960') +}); +var POW_2_256$1 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); +var SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742'); +var SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +var INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +var ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +var D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); - r += b; - if (b !== 26) break; - } +var ExtendedPoint = /*#__PURE__*/function () { + function ExtendedPoint(x, y, z, t) { + _classCallCheck(this, ExtendedPoint); - return r; - }; + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } - BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); - }; + _createClass(ExtendedPoint, [{ + key: "equals", + value: function equals(other) { + assertExtPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + var X1Z2 = mod$1(X1 * Z2); + var X2Z1 = mod$1(X2 * Z1); + var Y1Z2 = mod$1(Y1 * Z2); + var Y2Z1 = mod$1(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + }, { + key: "negate", + value: function negate() { + return new ExtendedPoint(mod$1(-this.x), this.y, this.z, mod$1(-this.t)); + } + }, { + key: "double", + value: function double() { + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var a = CURVE$1.a; + var A = mod$1(X1 * X1); + var B = mod$1(Y1 * Y1); + var C = mod$1(_2n$2 * mod$1(Z1 * Z1)); + var D = mod$1(a * A); + var x1y1 = X1 + Y1; + var E = mod$1(mod$1(x1y1 * x1y1) - A - B); + var G = D + B; + var F = G - C; + var H = D - B; + var X3 = mod$1(E * F); + var Y3 = mod$1(G * H); + var T3 = mod$1(E * H); + var Z3 = mod$1(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + }, { + key: "add", + value: function add(other) { + assertExtPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z, + T1 = this.t; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z, + T2 = other.t; + var A = mod$1((Y1 - X1) * (Y2 + X2)); + var B = mod$1((Y1 + X1) * (Y2 - X2)); + var F = mod$1(B - A); + if (F === _0n$2) return this["double"](); + var C = mod$1(Z1 * _2n$2 * T2); + var D = mod$1(T1 * _2n$2 * Z2); + var E = D + C; + var G = B + A; + var H = D - C; + var X3 = mod$1(E * F); + var Y3 = mod$1(G * H); + var T3 = mod$1(E * H); + var Z3 = mod$1(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "precomputeWindow", + value: function precomputeWindow(W) { + var windows = 1 + 256 / W; + var points = []; + var p = this; + var base = p; - BN.prototype.toTwos = function toTwos(width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } + for (var window = 0; window < windows; window++) { + base = p; + points.push(base); - return this.clone(); - }; + for (var i = 1; i < Math.pow(2, W - 1); i++) { + base = base.add(p); + points.push(base); + } - BN.prototype.fromTwos = function fromTwos(width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + p = base["double"](); } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg() { - return this.negative !== 0; - }; // Return negative clone of `this` - - - BN.prototype.neg = function neg() { - return this.clone().ineg(); - }; + return points; + } + }, { + key: "wNAF", + value: function wNAF(n, affinePoint) { + if (!affinePoint && this.equals(ExtendedPoint.BASE)) affinePoint = Point$1.BASE; + var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - BN.prototype.ineg = function ineg() { - if (!this.isZero()) { - this.negative ^= 1; + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); } - return this; - }; // Or `num` with `this` in-place - + var precomputes = affinePoint && pointPrecomputes$1.get(affinePoint); - BN.prototype.iuor = function iuor(num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + if (!precomputes) { + precomputes = this.precomputeWindow(W); - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + if (affinePoint && W !== 1) { + precomputes = ExtendedPoint.normalizeZ(precomputes); + pointPrecomputes$1.set(affinePoint, precomputes); + } } - return this._strip(); - }; - - BN.prototype.ior = function ior(num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; // Or `num` with `this` - - - BN.prototype.or = function or(num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor(num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; // And `num` with `this` in-place + var p = ExtendedPoint.ZERO; + var f = ExtendedPoint.BASE; + var windows = 1 + 256 / W; + var windowSize = Math.pow(2, W - 1); + var mask = BigInt(Math.pow(2, W) - 1); + var maxNumber = Math.pow(2, W); + var shiftBy = BigInt(W); + for (var window = 0; window < windows; window++) { + var offset = window * windowSize; + var wbits = Number(n & mask); + n >>= shiftBy; - BN.prototype.iuand = function iuand(num) { - // b = min-length(num, this) - var b; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$2; + } - if (this.length > num.length) { - b = num; - } else { - b = this; - } + var offset1 = offset; + var offset2 = offset + Math.abs(wbits) - 1; + var cond1 = window % 2 !== 0; + var cond2 = wbits < 0; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + if (wbits === 0) { + f = f.add(constTimeNegate$1(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate$1(cond2, precomputes[offset2])); + } } - this.length = b.length; - return this._strip(); - }; - - BN.prototype.iand = function iand(num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; // And `num` with `this` - - - BN.prototype.and = function and(num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand(num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; // Xor `num` with `this` in-place - - - BN.prototype.iuxor = function iuxor(num) { - // a.length > b.length - var a; - var b; - - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return ExtendedPoint.normalizeZ([p, f])[0]; + } + }, { + key: "multiply", + value: function multiply(scalar, affinePoint) { + return this.wNAF(normalizeScalar$1(scalar, CURVE$1.l), affinePoint); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + var n = normalizeScalar$1(scalar, CURVE$1.l, false); + var G = ExtendedPoint.BASE; + var P0 = ExtendedPoint.ZERO; + if (n === _0n$2) return P0; + if (this.equals(P0) || n === _1n$2) return this; + if (this.equals(G)) return this.wNAF(n); + var p = P0; + var d = this; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + while (n > _0n$2) { + if (n & _1n$2) p = p.add(d); + d = d["double"](); + n >>= _1n$2; } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + return p; + } + }, { + key: "isSmallOrder", + value: function isSmallOrder() { + return this.multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); + } + }, { + key: "isTorsionFree", + value: function isTorsionFree() { + var p = this.multiplyUnsafe(CURVE$1.l / _2n$2)["double"](); + if (CURVE$1.l % _2n$2) p = p.add(this); + return p.equals(ExtendedPoint.ZERO); + } + }, { + key: "toAffine", + value: function toAffine(invZ) { + var x = this.x, + y = this.y, + z = this.z; + var is0 = this.equals(ExtendedPoint.ZERO); + if (invZ == null) invZ = is0 ? _8n$1 : invert$1(z); + var ax = mod$1(x * invZ); + var ay = mod$1(y * invZ); + var zz = mod$1(z * invZ); + if (is0) return Point$1.ZERO; + if (zz !== _1n$2) throw new Error('invZ was invalid'); + return new Point$1(ax, ay); + } + }, { + key: "fromRistrettoBytes", + value: function fromRistrettoBytes() { + legacyRist(); + } + }, { + key: "toRistrettoBytes", + value: function toRistrettoBytes() { + legacyRist(); + } + }, { + key: "fromRistrettoHash", + value: function fromRistrettoHash() { + legacyRist(); + } + }], [{ + key: "fromAffine", + value: function fromAffine(p) { + if (!(p instanceof Point$1)) { + throw new TypeError('ExtendedPoint#fromAffine: expected Point'); } - this.length = a.length; - return this._strip(); - }; - - BN.prototype.ixor = function ixor(num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; // Xor `num` with `this` - - - BN.prototype.xor = function xor(num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor(num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; // Not ``this`` with ``width`` bitwidth - + if (p.equals(Point$1.ZERO)) return ExtendedPoint.ZERO; + return new ExtendedPoint(p.x, p.y, _1n$2, mod$1(p.x * p.y)); + } + }, { + key: "toAffineBatch", + value: function toAffineBatch(points) { + var toInv = invertBatch$1(points.map(function (p) { + return p.z; + })); + return points.map(function (p, i) { + return p.toAffine(toInv[i]); + }); + } + }, { + key: "normalizeZ", + value: function normalizeZ(points) { + return this.toAffineBatch(points).map(this.fromAffine); + } + }]); - BN.prototype.inotn = function inotn(width) { - assert(typeof width === 'number' && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; // Extend the buffer with leading zeroes + return ExtendedPoint; +}(); - this._expand(bytesNeeded); +ExtendedPoint.BASE = new ExtendedPoint(CURVE$1.Gx, CURVE$1.Gy, _1n$2, mod$1(CURVE$1.Gx * CURVE$1.Gy)); +ExtendedPoint.ZERO = new ExtendedPoint(_0n$2, _1n$2, _1n$2, _0n$2); - if (bitsLeft > 0) { - bytesNeeded--; - } // Handle complete words +function constTimeNegate$1(condition, item) { + var neg = item.negate(); + return condition ? neg : item; +} +function assertExtPoint(other) { + if (!(other instanceof ExtendedPoint)) throw new TypeError('ExtendedPoint expected'); +} - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } // Handle the residue +function assertRstPoint(other) { + if (!(other instanceof RistrettoPoint)) throw new TypeError('RistrettoPoint expected'); +} +function legacyRist() { + throw new Error('Legacy method: switch to RistrettoPoint'); +} - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft; - } // And remove leading zeroes +var RistrettoPoint = /*#__PURE__*/function () { + function RistrettoPoint(ep) { + _classCallCheck(this, RistrettoPoint); + this.ep = ep; + } - return this._strip(); - }; + _createClass(RistrettoPoint, [{ + key: "toRawBytes", + value: function toRawBytes() { + var _this$ep = this.ep, + x = _this$ep.x, + y = _this$ep.y, + z = _this$ep.z, + t = _this$ep.t; + var u1 = mod$1(mod$1(z + y) * mod$1(z - y)); + var u2 = mod$1(x * y); + var u2sq = mod$1(u2 * u2); - BN.prototype.notn = function notn(width) { - return this.clone().inotn(width); - }; // Set `bit` of `this` + var _invertSqrt = invertSqrt(mod$1(u1 * u2sq)), + invsqrt = _invertSqrt.value; + var D1 = mod$1(invsqrt * u1); + var D2 = mod$1(invsqrt * u2); + var zInv = mod$1(D1 * D2 * t); + var D; - BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === 'number' && bit >= 0); - var off = bit / 26 | 0; - var wbit = bit % 26; + if (edIsNegative(t * zInv)) { + var _x = mod$1(y * SQRT_M1); - this._expand(off + 1); + var _y = mod$1(x * SQRT_M1); - if (val) { - this.words[off] = this.words[off] | 1 << wbit; + x = _x; + y = _y; + D = mod$1(D1 * INVSQRT_A_MINUS_D); } else { - this.words[off] = this.words[off] & ~(1 << wbit); + D = D2; } - return this._strip(); - }; // Add `num` to `this` in-place - - - BN.prototype.iadd = function iadd(num) { - var r; // negative + positive - - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } // a.length > b.length + if (edIsNegative(x * zInv)) y = mod$1(-y); + var s = mod$1((z - y) * D); + if (edIsNegative(s)) s = mod$1(-s); + return numberTo32BytesLE(s); + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }, { + key: "toString", + value: function toString() { + return this.toHex(); + } + }, { + key: "equals", + value: function equals(other) { + assertRstPoint(other); + var a = this.ep; + var b = other.ep; + var one = mod$1(a.x * b.y) === mod$1(a.y * b.x); + var two = mod$1(a.y * b.y) === mod$1(a.x * b.x); + return one || two; + } + }, { + key: "add", + value: function add(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.add(other.ep)); + } + }, { + key: "subtract", + value: function subtract(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.subtract(other.ep)); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return new RistrettoPoint(this.ep.multiply(scalar)); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + return new RistrettoPoint(this.ep.multiplyUnsafe(scalar)); + } + }], [{ + key: "calcElligatorRistrettoMap", + value: function calcElligatorRistrettoMap(r0) { + var d = CURVE$1.d; + var r = mod$1(SQRT_M1 * r0 * r0); + var Ns = mod$1((r + _1n$2) * ONE_MINUS_D_SQ); + var c = BigInt(-1); + var D = mod$1((c - d * r) * mod$1(r + d)); + var _uvRatio = uvRatio(Ns, D), + Ns_D_is_sq = _uvRatio.isValid, + s = _uvRatio.value; - var a, b; + var s_ = mod$1(s * r0); + if (!edIsNegative(s_)) s_ = mod$1(-s_); + if (!Ns_D_is_sq) s = s_; + if (!Ns_D_is_sq) c = r; + var Nt = mod$1(c * (r - _1n$2) * D_MINUS_ONE_SQ - D); + var s2 = s * s; + var W0 = mod$1((s + s) * D); + var W1 = mod$1(Nt * SQRT_AD_MINUS_ONE); + var W2 = mod$1(_1n$2 - s2); + var W3 = mod$1(_1n$2 + s2); + return new ExtendedPoint(mod$1(W0 * W3), mod$1(W2 * W1), mod$1(W1 * W3), mod$1(W0 * W2)); + } + }, { + key: "hashToCurve", + value: function hashToCurve(hex) { + hex = ensureBytes$1(hex, 64); + var r1 = bytes255ToNumberLE(hex.slice(0, 32)); + var R1 = this.calcElligatorRistrettoMap(r1); + var r2 = bytes255ToNumberLE(hex.slice(32, 64)); + var R2 = this.calcElligatorRistrettoMap(r2); + return new RistrettoPoint(R1.add(R2)); + } + }, { + key: "fromHex", + value: function fromHex(hex) { + hex = ensureBytes$1(hex, 32); + var a = CURVE$1.a, + d = CURVE$1.d; + var emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + var s = bytes255ToNumberLE(hex); + if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s)) throw new Error(emsg); + var s2 = mod$1(s * s); + var u1 = mod$1(_1n$2 + a * s2); + var u2 = mod$1(_1n$2 - a * s2); + var u1_2 = mod$1(u1 * u1); + var u2_2 = mod$1(u2 * u2); + var v = mod$1(a * d * u1_2 - u2_2); - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + var _invertSqrt2 = invertSqrt(mod$1(v * u2_2)), + isValid = _invertSqrt2.isValid, + I = _invertSqrt2.value; - var carry = 0; + var Dx = mod$1(I * u2); + var Dy = mod$1(I * Dx * v); + var x = mod$1((s + s) * Dx); + if (edIsNegative(x)) x = mod$1(-x); + var y = mod$1(u1 * Dy); + var t = mod$1(x * y); + if (!isValid || edIsNegative(t) || y === _0n$2) throw new Error(emsg); + return new RistrettoPoint(new ExtendedPoint(x, y, _1n$2, t)); + } + }]); - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } + return RistrettoPoint; +}(); - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } +RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE); +RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO); +var pointPrecomputes$1 = new WeakMap(); - this.length = a.length; +var Point$1 = /*#__PURE__*/function () { + function Point(x, y) { + _classCallCheck(this, Point); - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + this.x = x; + this.y = y; + } + + _createClass(Point, [{ + key: "_setWindowSize", + value: function _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes$1["delete"](this); + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var bytes = numberTo32BytesLE(this.y); + bytes[31] |= this.x & _1n$2 ? 0x80 : 0; + return bytes; + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }, { + key: "toX25519", + value: function toX25519() { + var y = this.y; + var u = mod$1((_1n$2 + y) * invert$1(_1n$2 - y)); + return numberTo32BytesLE(u); + } + }, { + key: "isTorsionFree", + value: function isTorsionFree() { + return ExtendedPoint.fromAffine(this).isTorsionFree(); + } + }, { + key: "equals", + value: function equals(other) { + return this.x === other.x && this.y === other.y; + } + }, { + key: "negate", + value: function negate() { + return new Point(mod$1(-this.x), this.y); + } + }, { + key: "add", + value: function add(other) { + return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine(); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + }], [{ + key: "fromHex", + value: function fromHex(hex) { + var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var d = CURVE$1.d, + P = CURVE$1.P; + hex = ensureBytes$1(hex, 32); + var normed = hex.slice(); + normed[31] = hex[31] & ~0x80; + var y = bytesToNumberLE(normed); + if (strict && y >= P) throw new Error('Expected 0 < hex < P'); + if (!strict && y >= POW_2_256$1) throw new Error('Expected 0 < hex < 2**256'); + var y2 = mod$1(y * y); + var u = mod$1(y2 - _1n$2); + var v = mod$1(d * y2 + _1n$2); + + var _uvRatio2 = uvRatio(u, v), + isValid = _uvRatio2.isValid, + x = _uvRatio2.value; + + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + var isXOdd = (x & _1n$2) === _1n$2; + var isLastByteOdd = (hex[31] & 0x80) !== 0; + + if (isLastByteOdd !== isXOdd) { + x = mod$1(-x); } - return this; - }; // Add `num` to `this` + return new Point(x, y); + } + }, { + key: "fromPrivateKey", + value: function () { + var _fromPrivateKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(privateKey) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return getExtendedPublicKey(privateKey); + case 2: + return _context.abrupt("return", _context.sent.point); - BN.prototype.add = function add(num) { - var res; + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; + function fromPrivateKey(_x2) { + return _fromPrivateKey.apply(this, arguments); } - if (this.length > num.length) return this.clone().iadd(num); - return num.clone().iadd(this); - }; // Subtract `num` from `this` in-place + return fromPrivateKey; + }() + }]); + return Point; +}(); - BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } // At this point both numbers are positive +Point$1.BASE = new Point$1(CURVE$1.Gx, CURVE$1.Gy); +Point$1.ZERO = new Point$1(_0n$2, _1n$2); +var Signature$1 = /*#__PURE__*/function () { + function Signature(r, s) { + _classCallCheck(this, Signature); - var cmp = this.cmp(num); // Optimization - zeroify + this.r = r; + this.s = s; + this.assertValidity(); + } - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } // a > b + _createClass(Signature, [{ + key: "assertValidity", + value: function assertValidity() { + var r = this.r, + s = this.s; + if (!(r instanceof Point$1)) throw new Error('Expected Point instance'); + normalizeScalar$1(s, CURVE$1.l, false); + return this; + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var u8 = new Uint8Array(64); + u8.set(this.r.toRawBytes()); + u8.set(numberTo32BytesLE(this.s), 32); + return u8; + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }], [{ + key: "fromHex", + value: function fromHex(hex) { + var bytes = ensureBytes$1(hex, 64); + var r = Point$1.fromHex(bytes.slice(0, 32), false); + var s = bytesToNumberLE(bytes.slice(32, 64)); + return new Signature(r, s); + } + }]); + return Signature; +}(); - var a, b; +function concatBytes$1() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; + } - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + if (!arrays.every(function (a) { + return a instanceof Uint8Array; + })) throw new Error('Expected Uint8Array list'); + if (arrays.length === 1) return arrays[0]; + var length = arrays.reduce(function (a, arr) { + return a + arr.length; + }, 0); + var result = new Uint8Array(length); - var carry = 0; + for (var i = 0, pad = 0; i < arrays.length; i++) { + var arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } + return result; +} - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } // Copy rest of the words +var hexes$1 = Array.from({ + length: 256 +}, function (v, i) { + return i.toString(16).padStart(2, '0'); +}); +function bytesToHex$1(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); + var hex = ''; - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + for (var i = 0; i < uint8a.length; i++) { + hex += hexes$1[uint8a[i]]; + } - this.length = Math.max(this.length, i); + return hex; +} - if (a !== this) { - this.negative = 1; - } +function hexToBytes$1(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); + } - return this._strip(); - }; // Subtract `num` from `this` + if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); + var array = new Uint8Array(hex.length / 2); + for (var i = 0; i < array.length; i++) { + var j = i * 2; + var hexByte = hex.slice(j, j + 2); - BN.prototype.sub = function sub(num) { - return this.clone().isub(num); - }; + var _byte = Number.parseInt(hexByte, 16); - function smallMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - var len = self.length + num.length | 0; - out.length = len; - len = len - 1 | 0; // Peel one iteration (compiler can't do it, because of code complexity) + if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); + array[i] = _byte; + } - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - var lo = r & 0x3ffffff; - var carry = r / 0x4000000 | 0; - out.words[0] = lo; + return array; +} - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); +function numberTo32BytesBE(num) { + var length = 32; + var hex = num.toString(16).padStart(length * 2, '0'); + return hexToBytes$1(hex); +} - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += r / 0x4000000 | 0; - rword = r & 0x3ffffff; - } +function numberTo32BytesLE(num) { + return numberTo32BytesBE(num).reverse(); +} - out.words[k] = rword | 0; - carry = ncarry | 0; - } +function edIsNegative(num) { + return (mod$1(num) & _1n$2) === _1n$2; +} - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } +function bytesToNumberLE(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + return BigInt('0x' + bytesToHex$1(Uint8Array.from(uint8a).reverse())); +} - return out._strip(); - } // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). +var MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +function bytes255ToNumberLE(bytes) { + return mod$1(bytesToNumberLE(bytes) & MAX_255B); +} - var comb10MulTo = function comb10MulTo(self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = mid + Math.imul(ah0, bl0) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = mid + Math.imul(ah1, bl0) | 0; - hi = Math.imul(ah1, bh0); - lo = lo + Math.imul(al0, bl1) | 0; - mid = mid + Math.imul(al0, bh1) | 0; - mid = mid + Math.imul(ah0, bl1) | 0; - hi = hi + Math.imul(ah0, bh1) | 0; - var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = mid + Math.imul(ah2, bl0) | 0; - hi = Math.imul(ah2, bh0); - lo = lo + Math.imul(al1, bl1) | 0; - mid = mid + Math.imul(al1, bh1) | 0; - mid = mid + Math.imul(ah1, bl1) | 0; - hi = hi + Math.imul(ah1, bh1) | 0; - lo = lo + Math.imul(al0, bl2) | 0; - mid = mid + Math.imul(al0, bh2) | 0; - mid = mid + Math.imul(ah0, bl2) | 0; - hi = hi + Math.imul(ah0, bh2) | 0; - var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = mid + Math.imul(ah3, bl0) | 0; - hi = Math.imul(ah3, bh0); - lo = lo + Math.imul(al2, bl1) | 0; - mid = mid + Math.imul(al2, bh1) | 0; - mid = mid + Math.imul(ah2, bl1) | 0; - hi = hi + Math.imul(ah2, bh1) | 0; - lo = lo + Math.imul(al1, bl2) | 0; - mid = mid + Math.imul(al1, bh2) | 0; - mid = mid + Math.imul(ah1, bl2) | 0; - hi = hi + Math.imul(ah1, bh2) | 0; - lo = lo + Math.imul(al0, bl3) | 0; - mid = mid + Math.imul(al0, bh3) | 0; - mid = mid + Math.imul(ah0, bl3) | 0; - hi = hi + Math.imul(ah0, bh3) | 0; - var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = mid + Math.imul(ah4, bl0) | 0; - hi = Math.imul(ah4, bh0); - lo = lo + Math.imul(al3, bl1) | 0; - mid = mid + Math.imul(al3, bh1) | 0; - mid = mid + Math.imul(ah3, bl1) | 0; - hi = hi + Math.imul(ah3, bh1) | 0; - lo = lo + Math.imul(al2, bl2) | 0; - mid = mid + Math.imul(al2, bh2) | 0; - mid = mid + Math.imul(ah2, bl2) | 0; - hi = hi + Math.imul(ah2, bh2) | 0; - lo = lo + Math.imul(al1, bl3) | 0; - mid = mid + Math.imul(al1, bh3) | 0; - mid = mid + Math.imul(ah1, bl3) | 0; - hi = hi + Math.imul(ah1, bh3) | 0; - lo = lo + Math.imul(al0, bl4) | 0; - mid = mid + Math.imul(al0, bh4) | 0; - mid = mid + Math.imul(ah0, bl4) | 0; - hi = hi + Math.imul(ah0, bh4) | 0; - var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = mid + Math.imul(ah5, bl0) | 0; - hi = Math.imul(ah5, bh0); - lo = lo + Math.imul(al4, bl1) | 0; - mid = mid + Math.imul(al4, bh1) | 0; - mid = mid + Math.imul(ah4, bl1) | 0; - hi = hi + Math.imul(ah4, bh1) | 0; - lo = lo + Math.imul(al3, bl2) | 0; - mid = mid + Math.imul(al3, bh2) | 0; - mid = mid + Math.imul(ah3, bl2) | 0; - hi = hi + Math.imul(ah3, bh2) | 0; - lo = lo + Math.imul(al2, bl3) | 0; - mid = mid + Math.imul(al2, bh3) | 0; - mid = mid + Math.imul(ah2, bl3) | 0; - hi = hi + Math.imul(ah2, bh3) | 0; - lo = lo + Math.imul(al1, bl4) | 0; - mid = mid + Math.imul(al1, bh4) | 0; - mid = mid + Math.imul(ah1, bl4) | 0; - hi = hi + Math.imul(ah1, bh4) | 0; - lo = lo + Math.imul(al0, bl5) | 0; - mid = mid + Math.imul(al0, bh5) | 0; - mid = mid + Math.imul(ah0, bl5) | 0; - hi = hi + Math.imul(ah0, bh5) | 0; - var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = mid + Math.imul(ah6, bl0) | 0; - hi = Math.imul(ah6, bh0); - lo = lo + Math.imul(al5, bl1) | 0; - mid = mid + Math.imul(al5, bh1) | 0; - mid = mid + Math.imul(ah5, bl1) | 0; - hi = hi + Math.imul(ah5, bh1) | 0; - lo = lo + Math.imul(al4, bl2) | 0; - mid = mid + Math.imul(al4, bh2) | 0; - mid = mid + Math.imul(ah4, bl2) | 0; - hi = hi + Math.imul(ah4, bh2) | 0; - lo = lo + Math.imul(al3, bl3) | 0; - mid = mid + Math.imul(al3, bh3) | 0; - mid = mid + Math.imul(ah3, bl3) | 0; - hi = hi + Math.imul(ah3, bh3) | 0; - lo = lo + Math.imul(al2, bl4) | 0; - mid = mid + Math.imul(al2, bh4) | 0; - mid = mid + Math.imul(ah2, bl4) | 0; - hi = hi + Math.imul(ah2, bh4) | 0; - lo = lo + Math.imul(al1, bl5) | 0; - mid = mid + Math.imul(al1, bh5) | 0; - mid = mid + Math.imul(ah1, bl5) | 0; - hi = hi + Math.imul(ah1, bh5) | 0; - lo = lo + Math.imul(al0, bl6) | 0; - mid = mid + Math.imul(al0, bh6) | 0; - mid = mid + Math.imul(ah0, bl6) | 0; - hi = hi + Math.imul(ah0, bh6) | 0; - var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = mid + Math.imul(ah7, bl0) | 0; - hi = Math.imul(ah7, bh0); - lo = lo + Math.imul(al6, bl1) | 0; - mid = mid + Math.imul(al6, bh1) | 0; - mid = mid + Math.imul(ah6, bl1) | 0; - hi = hi + Math.imul(ah6, bh1) | 0; - lo = lo + Math.imul(al5, bl2) | 0; - mid = mid + Math.imul(al5, bh2) | 0; - mid = mid + Math.imul(ah5, bl2) | 0; - hi = hi + Math.imul(ah5, bh2) | 0; - lo = lo + Math.imul(al4, bl3) | 0; - mid = mid + Math.imul(al4, bh3) | 0; - mid = mid + Math.imul(ah4, bl3) | 0; - hi = hi + Math.imul(ah4, bh3) | 0; - lo = lo + Math.imul(al3, bl4) | 0; - mid = mid + Math.imul(al3, bh4) | 0; - mid = mid + Math.imul(ah3, bl4) | 0; - hi = hi + Math.imul(ah3, bh4) | 0; - lo = lo + Math.imul(al2, bl5) | 0; - mid = mid + Math.imul(al2, bh5) | 0; - mid = mid + Math.imul(ah2, bl5) | 0; - hi = hi + Math.imul(ah2, bh5) | 0; - lo = lo + Math.imul(al1, bl6) | 0; - mid = mid + Math.imul(al1, bh6) | 0; - mid = mid + Math.imul(ah1, bl6) | 0; - hi = hi + Math.imul(ah1, bh6) | 0; - lo = lo + Math.imul(al0, bl7) | 0; - mid = mid + Math.imul(al0, bh7) | 0; - mid = mid + Math.imul(ah0, bl7) | 0; - hi = hi + Math.imul(ah0, bh7) | 0; - var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = mid + Math.imul(ah8, bl0) | 0; - hi = Math.imul(ah8, bh0); - lo = lo + Math.imul(al7, bl1) | 0; - mid = mid + Math.imul(al7, bh1) | 0; - mid = mid + Math.imul(ah7, bl1) | 0; - hi = hi + Math.imul(ah7, bh1) | 0; - lo = lo + Math.imul(al6, bl2) | 0; - mid = mid + Math.imul(al6, bh2) | 0; - mid = mid + Math.imul(ah6, bl2) | 0; - hi = hi + Math.imul(ah6, bh2) | 0; - lo = lo + Math.imul(al5, bl3) | 0; - mid = mid + Math.imul(al5, bh3) | 0; - mid = mid + Math.imul(ah5, bl3) | 0; - hi = hi + Math.imul(ah5, bh3) | 0; - lo = lo + Math.imul(al4, bl4) | 0; - mid = mid + Math.imul(al4, bh4) | 0; - mid = mid + Math.imul(ah4, bl4) | 0; - hi = hi + Math.imul(ah4, bh4) | 0; - lo = lo + Math.imul(al3, bl5) | 0; - mid = mid + Math.imul(al3, bh5) | 0; - mid = mid + Math.imul(ah3, bl5) | 0; - hi = hi + Math.imul(ah3, bh5) | 0; - lo = lo + Math.imul(al2, bl6) | 0; - mid = mid + Math.imul(al2, bh6) | 0; - mid = mid + Math.imul(ah2, bl6) | 0; - hi = hi + Math.imul(ah2, bh6) | 0; - lo = lo + Math.imul(al1, bl7) | 0; - mid = mid + Math.imul(al1, bh7) | 0; - mid = mid + Math.imul(ah1, bl7) | 0; - hi = hi + Math.imul(ah1, bh7) | 0; - lo = lo + Math.imul(al0, bl8) | 0; - mid = mid + Math.imul(al0, bh8) | 0; - mid = mid + Math.imul(ah0, bl8) | 0; - hi = hi + Math.imul(ah0, bh8) | 0; - var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = mid + Math.imul(ah9, bl0) | 0; - hi = Math.imul(ah9, bh0); - lo = lo + Math.imul(al8, bl1) | 0; - mid = mid + Math.imul(al8, bh1) | 0; - mid = mid + Math.imul(ah8, bl1) | 0; - hi = hi + Math.imul(ah8, bh1) | 0; - lo = lo + Math.imul(al7, bl2) | 0; - mid = mid + Math.imul(al7, bh2) | 0; - mid = mid + Math.imul(ah7, bl2) | 0; - hi = hi + Math.imul(ah7, bh2) | 0; - lo = lo + Math.imul(al6, bl3) | 0; - mid = mid + Math.imul(al6, bh3) | 0; - mid = mid + Math.imul(ah6, bl3) | 0; - hi = hi + Math.imul(ah6, bh3) | 0; - lo = lo + Math.imul(al5, bl4) | 0; - mid = mid + Math.imul(al5, bh4) | 0; - mid = mid + Math.imul(ah5, bl4) | 0; - hi = hi + Math.imul(ah5, bh4) | 0; - lo = lo + Math.imul(al4, bl5) | 0; - mid = mid + Math.imul(al4, bh5) | 0; - mid = mid + Math.imul(ah4, bl5) | 0; - hi = hi + Math.imul(ah4, bh5) | 0; - lo = lo + Math.imul(al3, bl6) | 0; - mid = mid + Math.imul(al3, bh6) | 0; - mid = mid + Math.imul(ah3, bl6) | 0; - hi = hi + Math.imul(ah3, bh6) | 0; - lo = lo + Math.imul(al2, bl7) | 0; - mid = mid + Math.imul(al2, bh7) | 0; - mid = mid + Math.imul(ah2, bl7) | 0; - hi = hi + Math.imul(ah2, bh7) | 0; - lo = lo + Math.imul(al1, bl8) | 0; - mid = mid + Math.imul(al1, bh8) | 0; - mid = mid + Math.imul(ah1, bl8) | 0; - hi = hi + Math.imul(ah1, bh8) | 0; - lo = lo + Math.imul(al0, bl9) | 0; - mid = mid + Math.imul(al0, bh9) | 0; - mid = mid + Math.imul(ah0, bl9) | 0; - hi = hi + Math.imul(ah0, bh9) | 0; - var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = mid + Math.imul(ah9, bl1) | 0; - hi = Math.imul(ah9, bh1); - lo = lo + Math.imul(al8, bl2) | 0; - mid = mid + Math.imul(al8, bh2) | 0; - mid = mid + Math.imul(ah8, bl2) | 0; - hi = hi + Math.imul(ah8, bh2) | 0; - lo = lo + Math.imul(al7, bl3) | 0; - mid = mid + Math.imul(al7, bh3) | 0; - mid = mid + Math.imul(ah7, bl3) | 0; - hi = hi + Math.imul(ah7, bh3) | 0; - lo = lo + Math.imul(al6, bl4) | 0; - mid = mid + Math.imul(al6, bh4) | 0; - mid = mid + Math.imul(ah6, bl4) | 0; - hi = hi + Math.imul(ah6, bh4) | 0; - lo = lo + Math.imul(al5, bl5) | 0; - mid = mid + Math.imul(al5, bh5) | 0; - mid = mid + Math.imul(ah5, bl5) | 0; - hi = hi + Math.imul(ah5, bh5) | 0; - lo = lo + Math.imul(al4, bl6) | 0; - mid = mid + Math.imul(al4, bh6) | 0; - mid = mid + Math.imul(ah4, bl6) | 0; - hi = hi + Math.imul(ah4, bh6) | 0; - lo = lo + Math.imul(al3, bl7) | 0; - mid = mid + Math.imul(al3, bh7) | 0; - mid = mid + Math.imul(ah3, bl7) | 0; - hi = hi + Math.imul(ah3, bh7) | 0; - lo = lo + Math.imul(al2, bl8) | 0; - mid = mid + Math.imul(al2, bh8) | 0; - mid = mid + Math.imul(ah2, bl8) | 0; - hi = hi + Math.imul(ah2, bh8) | 0; - lo = lo + Math.imul(al1, bl9) | 0; - mid = mid + Math.imul(al1, bh9) | 0; - mid = mid + Math.imul(ah1, bl9) | 0; - hi = hi + Math.imul(ah1, bh9) | 0; - var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = mid + Math.imul(ah9, bl2) | 0; - hi = Math.imul(ah9, bh2); - lo = lo + Math.imul(al8, bl3) | 0; - mid = mid + Math.imul(al8, bh3) | 0; - mid = mid + Math.imul(ah8, bl3) | 0; - hi = hi + Math.imul(ah8, bh3) | 0; - lo = lo + Math.imul(al7, bl4) | 0; - mid = mid + Math.imul(al7, bh4) | 0; - mid = mid + Math.imul(ah7, bl4) | 0; - hi = hi + Math.imul(ah7, bh4) | 0; - lo = lo + Math.imul(al6, bl5) | 0; - mid = mid + Math.imul(al6, bh5) | 0; - mid = mid + Math.imul(ah6, bl5) | 0; - hi = hi + Math.imul(ah6, bh5) | 0; - lo = lo + Math.imul(al5, bl6) | 0; - mid = mid + Math.imul(al5, bh6) | 0; - mid = mid + Math.imul(ah5, bl6) | 0; - hi = hi + Math.imul(ah5, bh6) | 0; - lo = lo + Math.imul(al4, bl7) | 0; - mid = mid + Math.imul(al4, bh7) | 0; - mid = mid + Math.imul(ah4, bl7) | 0; - hi = hi + Math.imul(ah4, bh7) | 0; - lo = lo + Math.imul(al3, bl8) | 0; - mid = mid + Math.imul(al3, bh8) | 0; - mid = mid + Math.imul(ah3, bl8) | 0; - hi = hi + Math.imul(ah3, bh8) | 0; - lo = lo + Math.imul(al2, bl9) | 0; - mid = mid + Math.imul(al2, bh9) | 0; - mid = mid + Math.imul(ah2, bl9) | 0; - hi = hi + Math.imul(ah2, bh9) | 0; - var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = mid + Math.imul(ah9, bl3) | 0; - hi = Math.imul(ah9, bh3); - lo = lo + Math.imul(al8, bl4) | 0; - mid = mid + Math.imul(al8, bh4) | 0; - mid = mid + Math.imul(ah8, bl4) | 0; - hi = hi + Math.imul(ah8, bh4) | 0; - lo = lo + Math.imul(al7, bl5) | 0; - mid = mid + Math.imul(al7, bh5) | 0; - mid = mid + Math.imul(ah7, bl5) | 0; - hi = hi + Math.imul(ah7, bh5) | 0; - lo = lo + Math.imul(al6, bl6) | 0; - mid = mid + Math.imul(al6, bh6) | 0; - mid = mid + Math.imul(ah6, bl6) | 0; - hi = hi + Math.imul(ah6, bh6) | 0; - lo = lo + Math.imul(al5, bl7) | 0; - mid = mid + Math.imul(al5, bh7) | 0; - mid = mid + Math.imul(ah5, bl7) | 0; - hi = hi + Math.imul(ah5, bh7) | 0; - lo = lo + Math.imul(al4, bl8) | 0; - mid = mid + Math.imul(al4, bh8) | 0; - mid = mid + Math.imul(ah4, bl8) | 0; - hi = hi + Math.imul(ah4, bh8) | 0; - lo = lo + Math.imul(al3, bl9) | 0; - mid = mid + Math.imul(al3, bh9) | 0; - mid = mid + Math.imul(ah3, bl9) | 0; - hi = hi + Math.imul(ah3, bh9) | 0; - var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = mid + Math.imul(ah9, bl4) | 0; - hi = Math.imul(ah9, bh4); - lo = lo + Math.imul(al8, bl5) | 0; - mid = mid + Math.imul(al8, bh5) | 0; - mid = mid + Math.imul(ah8, bl5) | 0; - hi = hi + Math.imul(ah8, bh5) | 0; - lo = lo + Math.imul(al7, bl6) | 0; - mid = mid + Math.imul(al7, bh6) | 0; - mid = mid + Math.imul(ah7, bl6) | 0; - hi = hi + Math.imul(ah7, bh6) | 0; - lo = lo + Math.imul(al6, bl7) | 0; - mid = mid + Math.imul(al6, bh7) | 0; - mid = mid + Math.imul(ah6, bl7) | 0; - hi = hi + Math.imul(ah6, bh7) | 0; - lo = lo + Math.imul(al5, bl8) | 0; - mid = mid + Math.imul(al5, bh8) | 0; - mid = mid + Math.imul(ah5, bl8) | 0; - hi = hi + Math.imul(ah5, bh8) | 0; - lo = lo + Math.imul(al4, bl9) | 0; - mid = mid + Math.imul(al4, bh9) | 0; - mid = mid + Math.imul(ah4, bl9) | 0; - hi = hi + Math.imul(ah4, bh9) | 0; - var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = mid + Math.imul(ah9, bl5) | 0; - hi = Math.imul(ah9, bh5); - lo = lo + Math.imul(al8, bl6) | 0; - mid = mid + Math.imul(al8, bh6) | 0; - mid = mid + Math.imul(ah8, bl6) | 0; - hi = hi + Math.imul(ah8, bh6) | 0; - lo = lo + Math.imul(al7, bl7) | 0; - mid = mid + Math.imul(al7, bh7) | 0; - mid = mid + Math.imul(ah7, bl7) | 0; - hi = hi + Math.imul(ah7, bh7) | 0; - lo = lo + Math.imul(al6, bl8) | 0; - mid = mid + Math.imul(al6, bh8) | 0; - mid = mid + Math.imul(ah6, bl8) | 0; - hi = hi + Math.imul(ah6, bh8) | 0; - lo = lo + Math.imul(al5, bl9) | 0; - mid = mid + Math.imul(al5, bh9) | 0; - mid = mid + Math.imul(ah5, bl9) | 0; - hi = hi + Math.imul(ah5, bh9) | 0; - var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = mid + Math.imul(ah9, bl6) | 0; - hi = Math.imul(ah9, bh6); - lo = lo + Math.imul(al8, bl7) | 0; - mid = mid + Math.imul(al8, bh7) | 0; - mid = mid + Math.imul(ah8, bl7) | 0; - hi = hi + Math.imul(ah8, bh7) | 0; - lo = lo + Math.imul(al7, bl8) | 0; - mid = mid + Math.imul(al7, bh8) | 0; - mid = mid + Math.imul(ah7, bl8) | 0; - hi = hi + Math.imul(ah7, bh8) | 0; - lo = lo + Math.imul(al6, bl9) | 0; - mid = mid + Math.imul(al6, bh9) | 0; - mid = mid + Math.imul(ah6, bl9) | 0; - hi = hi + Math.imul(ah6, bh9) | 0; - var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = mid + Math.imul(ah9, bl7) | 0; - hi = Math.imul(ah9, bh7); - lo = lo + Math.imul(al8, bl8) | 0; - mid = mid + Math.imul(al8, bh8) | 0; - mid = mid + Math.imul(ah8, bl8) | 0; - hi = hi + Math.imul(ah8, bh8) | 0; - lo = lo + Math.imul(al7, bl9) | 0; - mid = mid + Math.imul(al7, bh9) | 0; - mid = mid + Math.imul(ah7, bl9) | 0; - hi = hi + Math.imul(ah7, bh9) | 0; - var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = mid + Math.imul(ah9, bl8) | 0; - hi = Math.imul(ah9, bh8); - lo = lo + Math.imul(al8, bl9) | 0; - mid = mid + Math.imul(al8, bh9) | 0; - mid = mid + Math.imul(ah8, bl9) | 0; - hi = hi + Math.imul(ah8, bh9) | 0; - var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = mid + Math.imul(ah9, bl9) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - - if (c !== 0) { - o[19] = c; - out.length++; - } - - return out; - }; // Polyfill comb - - - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - var carry = 0; - var hncarry = 0; - - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - var lo = r & 0x3ffffff; - ncarry = ncarry + (r / 0x4000000 | 0) | 0; - lo = lo + rword | 0; - rword = lo & 0x3ffffff; - ncarry = ncarry + (lo >>> 26) | 0; - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } +function mod$1(a) { + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var res = a % b; + return res >= _0n$2 ? res : b + res; +} - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } +function invert$1(number) { + var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } + if (number === _0n$2 || modulo <= _0n$2) { + throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); + } - return out._strip(); - } + var a = mod$1(number, modulo); + var b = modulo; + var x = _0n$2, + u = _1n$2; - function jumboMulTo(self, num, out) { - // Temporary disable, see https://github.com/indutny/bn.js/issues/211 - // var fftm = new FFTM(); - // return fftm.mulp(self, num, out); - return bigMulTo(self, num, out); - } + while (a !== _0n$2) { + var q = b / a; + var r = b % a; + var m = x - u * q; + b = a, a = r, x = u, u = m; + } - BN.prototype.mulTo = function mulTo(num, out) { - var res; - var len = this.length + num.length; + var gcd = b; + if (gcd !== _1n$2) throw new Error('invert: does not exist'); + return mod$1(x, modulo); +} - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } +function invertBatch$1(nums) { + var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var tmp = new Array(nums.length); + var lastMultiplied = nums.reduce(function (acc, num, i) { + if (num === _0n$2) return acc; + tmp[i] = acc; + return mod$1(acc * num, p); + }, _1n$2); + var inverted = invert$1(lastMultiplied, p); + nums.reduceRight(function (acc, num, i) { + if (num === _0n$2) return acc; + tmp[i] = mod$1(acc * tmp[i], p); + return mod$1(acc * num, p); + }, inverted); + return tmp; +} - return res; - }; // Cooley-Tukey algorithm for FFT +function pow2$1(x, power) { + var P = CURVE$1.P; + var res = x; + while (power-- > _0n$2) { + res *= res; + res %= P; + } - BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; // Multiply employing FFT + return res; +} +function pow_2_252_3(x) { + var P = CURVE$1.P; - BN.prototype.mulf = function mulf(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; // In-place Multiplication + var _5n = BigInt(5); + var _10n = BigInt(10); - BN.prototype.imul = function imul(num) { - return this.clone().mulTo(num, this); - }; + var _20n = BigInt(20); - BN.prototype.imuln = function imuln(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(typeof num === 'number'); - assert(num < 0x4000000); // Carry + var _40n = BigInt(40); - var carry = 0; + var _80n = BigInt(80); - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += w / 0x4000000 | 0; // NOTE: lo is 27bit maximum + var x2 = x * x % P; + var b2 = x2 * x % P; + var b4 = pow2$1(b2, _2n$2) * b2 % P; + var b5 = pow2$1(b4, _1n$2) * x % P; + var b10 = pow2$1(b5, _5n) * b5 % P; + var b20 = pow2$1(b10, _10n) * b10 % P; + var b40 = pow2$1(b20, _20n) * b20 % P; + var b80 = pow2$1(b40, _40n) * b40 % P; + var b160 = pow2$1(b80, _80n) * b80 % P; + var b240 = pow2$1(b160, _80n) * b80 % P; + var b250 = pow2$1(b240, _10n) * b10 % P; + var pow_p_5_8 = pow2$1(b250, _2n$2) * x % P; + return { + pow_p_5_8: pow_p_5_8, + b2: b2 + }; +} - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } +function uvRatio(u, v) { + var v3 = mod$1(v * v * v); + var v7 = mod$1(v3 * v3 * v); + var pow = pow_2_252_3(u * v7).pow_p_5_8; + var x = mod$1(u * v3 * pow); + var vx2 = mod$1(v * x * x); + var root1 = x; + var root2 = mod$1(x * SQRT_M1); + var useRoot1 = vx2 === u; + var useRoot2 = vx2 === mod$1(-u); + var noRoot = vx2 === mod$1(-u * SQRT_M1); + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; + if (edIsNegative(x)) x = mod$1(-x); + return { + isValid: useRoot1 || useRoot2, + value: x + }; +} - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } +function invertSqrt(number) { + return uvRatio(_1n$2, number); +} - return isNegNum ? this.ineg() : this; - }; +function modlLE(hash) { + return mod$1(bytesToNumberLE(hash), CURVE$1.l); +} - BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); - }; // `this` * `this` +function equalBytes(b1, b2) { + if (b1.length !== b2.length) { + return false; + } + for (var i = 0; i < b1.length; i++) { + if (b1[i] !== b2[i]) { + return false; + } + } - BN.prototype.sqr = function sqr() { - return this.mul(this); - }; // `this` * `this` in-place + return true; +} +function ensureBytes$1(hex, expectedLength) { + var bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex); + if (typeof expectedLength === 'number' && bytes.length !== expectedLength) throw new Error("Expected ".concat(expectedLength, " bytes")); + return bytes; +} - BN.prototype.isqr = function isqr() { - return this.imul(this.clone()); - }; // Math.pow(`this`, `num`) +function normalizeScalar$1(num, max) { + var strict = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + if (!max) throw new TypeError('Specify max value'); + if (typeof num === 'number' && Number.isSafeInteger(num)) num = BigInt(num); + if (typeof num === 'bigint' && num < max) { + if (strict) { + if (_0n$2 < num) return num; + } else { + if (_0n$2 <= num) return num; + } + } - BN.prototype.pow = function pow(num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); // Skip leading zeroes + throw new TypeError('Expected valid scalar: 0 < scalar < max'); +} - var res = this; +function adjustBytes25519(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; +} - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } +function checkPrivateKey(key) { + key = typeof key === 'bigint' || typeof key === 'number' ? numberTo32BytesBE(normalizeScalar$1(key, POW_2_256$1)) : ensureBytes$1(key); + if (key.length !== 32) throw new Error("Expected 32 bytes"); + return key; +} - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - res = res.mul(q); - } - } +function getKeyFromHash(hashed) { + var head = adjustBytes25519(hashed.slice(0, 32)); + var prefix = hashed.slice(32, 64); + var scalar = modlLE(head); + var point = Point$1.BASE.multiply(scalar); + var pointBytes = point.toRawBytes(); + return { + head: head, + prefix: prefix, + scalar: scalar, + point: point, + pointBytes: pointBytes + }; +} - return res; - }; // Shift-left in-place +var _sha512Sync; +function sha512s() { + if (typeof _sha512Sync !== 'function') throw new Error('utils.sha512Sync must be set to use sync methods'); + return _sha512Sync.apply(void 0, arguments); +} - BN.prototype.iushln = function iushln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = 0x3ffffff >>> 26 - r << 26 - r; - var i; +function getExtendedPublicKey(_x3) { + return _getExtendedPublicKey.apply(this, arguments); +} - if (r !== 0) { - var carry = 0; +function _getExtendedPublicKey() { + _getExtendedPublicKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.t0 = getKeyFromHash; + _context3.next = 3; + return utils$1.sha512(checkPrivateKey(key)); - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] | 0) - newCarry << r; - this.words[i] = c | carry; - carry = newCarry >>> 26 - r; - } + case 3: + _context3.t1 = _context3.sent; + return _context3.abrupt("return", (0, _context3.t0)(_context3.t1)); - if (carry) { - this.words[i] = carry; - this.length++; - } + case 5: + case "end": + return _context3.stop(); } + }, _callee3); + })); + return _getExtendedPublicKey.apply(this, arguments); +} - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } +function getExtendedPublicKeySync(key) { + return getKeyFromHash(sha512s(checkPrivateKey(key))); +} - this.length += s; - } +function getPublicKeySync(privateKey) { + return getExtendedPublicKeySync(privateKey).pointBytes; +} - return this._strip(); - }; +function signSync$1(message, privateKey) { + message = ensureBytes$1(message); - BN.prototype.ishln = function ishln(bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits + var _getExtendedPublicKey2 = getExtendedPublicKeySync(privateKey), + prefix = _getExtendedPublicKey2.prefix, + scalar = _getExtendedPublicKey2.scalar, + pointBytes = _getExtendedPublicKey2.pointBytes; + var r = modlLE(sha512s(prefix, message)); + var R = Point$1.BASE.multiply(r); + var k = modlLE(sha512s(R.toRawBytes(), pointBytes, message)); + var s = mod$1(r + k * scalar, CURVE$1.l); + return new Signature$1(R, s).toRawBytes(); +} - BN.prototype.iushrn = function iushrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; +function prepareVerification(sig, message, publicKey) { + message = ensureBytes$1(message); + if (!(publicKey instanceof Point$1)) publicKey = Point$1.fromHex(publicKey, false); - if (hint) { - h = (hint - hint % 26) / 26; - } else { - h = 0; - } + var _ref = sig instanceof Signature$1 ? sig.assertValidity() : Signature$1.fromHex(sig), + r = _ref.r, + s = _ref.s; - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; - var maskedWords = extended; - h -= s; - h = Math.max(0, h); // Extended mode, copy masked part + var SB = ExtendedPoint.BASE.multiplyUnsafe(s); + return { + r: r, + s: s, + SB: SB, + pub: publicKey, + msg: message + }; +} - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } +function finishVerification(publicKey, r, SB, hashed) { + var k = modlLE(hashed); + var kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k); + var RkA = ExtendedPoint.fromAffine(r).add(kA); + return RkA.subtract(SB).multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); +} - maskedWords.length = s; - } +function verifySync(sig, message, publicKey) { + var _prepareVerification = prepareVerification(sig, message, publicKey), + r = _prepareVerification.r, + SB = _prepareVerification.SB, + msg = _prepareVerification.msg, + pub = _prepareVerification.pub; - if (s === 0) ; else if (this.length > s) { - this.length -= s; + var hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg); + return finishVerification(pub, r, SB, hashed); +} - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } +var sync = { + getExtendedPublicKey: getExtendedPublicKeySync, + getPublicKey: getPublicKeySync, + sign: signSync$1, + verify: verifySync +}; - var carry = 0; +Point$1.BASE._setWindowSize(8); +var crypto$2 = { + node: nodeCrypto, + web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined +}; +var utils$1 = { + bytesToHex: bytesToHex$1, + hexToBytes: hexToBytes$1, + concatBytes: concatBytes$1, + getExtendedPublicKey: getExtendedPublicKey, + mod: mod$1, + invert: invert$1, + TORSION_SUBGROUP: ['0100000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', '0000000000000000000000000000000000000000000000000000000000000080', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', '0000000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa'], + hashToPrivateScalar: function hashToPrivateScalar(hash) { + hash = ensureBytes$1(hash); + if (hash.length < 40 || hash.length > 1024) throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); + return mod$1(bytesToNumberLE(hash), CURVE$1.l - _1n$2) + _1n$2; + }, + randomBytes: function randomBytes() { + var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = carry << 26 - r | word >>> r; - carry = word & mask; - } // Push carried bits as a mask + if (crypto$2.web) { + return crypto$2.web.getRandomValues(new Uint8Array(bytesLength)); + } else if (crypto$2.node) { + var randomBytes = crypto$2.node.randomBytes; + return new Uint8Array(randomBytes(bytesLength).buffer); + } else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: function randomPrivateKey() { + return utils$1.randomBytes(32); + }, + sha512: function () { + var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var message, + buffer, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + message = concatBytes$1.apply(void 0, _args2); + if (!crypto$2.web) { + _context2.next = 8; + break; + } - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } + _context2.next = 4; + return crypto$2.web.subtle.digest('SHA-512', message.buffer); - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } + case 4: + buffer = _context2.sent; + return _context2.abrupt("return", new Uint8Array(buffer)); - return this._strip(); - }; + case 8: + if (!crypto$2.node) { + _context2.next = 12; + break; + } - BN.prototype.ishrn = function ishrn(bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; // Shift-left + return _context2.abrupt("return", Uint8Array.from(crypto$2.node.createHash('sha512').update(message).digest())); + case 12: + throw new Error("The environment doesn't have sha512 function"); - BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); - }; + case 13: + case "end": + return _context2.stop(); + } + }, _callee2); + })); - BN.prototype.ushln = function ushln(bits) { - return this.clone().iushln(bits); - }; // Shift-right + function sha512() { + return _sha.apply(this, arguments); + } + return sha512; + }(), + precompute: function precompute() { + var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; + var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point$1.BASE; + var cached = point.equals(Point$1.BASE) ? point : new Point$1(point.x, point.y); - BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); - }; + cached._setWindowSize(windowSize); - BN.prototype.ushrn = function ushrn(bits) { - return this.clone().iushrn(bits); - }; // Test if n bit is set + cached.multiply(_2n$2); + return cached; + }, + sha512Sync: undefined +}; +Object.defineProperties(utils$1, { + sha512Sync: { + configurable: false, + get: function get() { + return _sha512Sync; + }, + set: function set(val) { + if (!_sha512Sync) _sha512Sync = val; + } + } +}); +var bn$1 = {exports: {}}; - BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; // Fast case: bit is much higher than all existing words +var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_buffer); - if (this.length <= s) return false; // Check bit and return +(function (module) { + (function (module, exports) { - var w = this.words[s]; - return !!(w & q); - }; // Return only lowers bits of number (in-place) + function assert(val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } // Could use `inherits` module, but don't want to move from single file + // architecture yet. - BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; - if (this.length <= s) { - return this; - } + var TempCtor = function TempCtor() {}; - if (r !== 0) { - s++; - } + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } // BN - this.length = Math.min(s, this.length); - if (r !== 0) { - var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; - this.words[this.length - 1] &= mask; + function BN(number, base, endian) { + if (BN.isBN(number)) { + return number; } - return this._strip(); - }; // Return only lowers bits of number + this.negative = 0; + this.words = null; + this.length = 0; // Reduction context + this.red = null; - BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); - }; // Add plain number `num` to `this` + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + this._init(number || 0, base || 10, endian || 'be'); + } + } - BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); // Possible sign change + if (_typeof$1(module) === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } + BN.BN = BN; + BN.wordSize = 26; + var Buffer; - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } // Add without checks + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require$$1$1.Buffer; + } + } catch (e) {} + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } - return this._iaddn(num); + return num !== null && _typeof$1(num) === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; - BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; // Carry + BN.max = function max(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; + BN.min = function min(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } + BN.prototype._init = function init(number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); } - this.length = Math.max(this.length, i + 1); - return this; - }; // Subtract plain number `num` from `this` + if (_typeof$1(number) === 'object') { + return this._initArray(number, base, endian); + } + if (base === 'hex') { + base = 16; + } - BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); + assert(base === (base | 0) && base >= 2 && base <= 36); + number = number.toString().replace(/\s+/g, ''); + var start = 0; - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); + if (number[0] === '-') { + start++; this.negative = 1; - return this; } - this.words[0] -= num; + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } } } - - return this._strip(); }; - BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); - }; + BN.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } - BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); - }; + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - BN.prototype.iabs = function iabs() { - this.negative = 0; - return this; - }; + this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1]; + this.length = 3; + } - BN.prototype.abs = function abs() { - return this.clone().iabs(); + if (endian !== 'le') return; // Reverse the bytes + + this._initArray(this.toArray(), base, endian); }; - BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - var len = num.length + shift; - var i; + BN.prototype._initArray = function _initArray(number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); - this._expand(len); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } - var w; - var carry = 0; + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - (right / 0x4000000 | 0); - this.words[i + shift] = w & 0x3ffffff; + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } + var j, w; + var off = 0; - if (carry === 0) return this._strip(); // Subtraction overflow + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 0x3ffffff; + this.words[j + 1] = w >>> 26 - off & 0x3ffffff; + off += 24; - assert(carry === -1); - carry = 0; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 0x3ffffff; + this.words[j + 1] = w >>> 26 - off & 0x3ffffff; + off += 24; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; + if (off >= 26) { + off -= 26; + j++; + } + } } - this.negative = 1; return this._strip(); }; - BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - var a = this.clone(); - var b = num; // Normalize + function parseHex4Bits(string, index) { + var c = string.charCodeAt(index); // '0' - '9' - var bhi = b.words[b.length - 1] | 0; + if (c >= 48 && c <= 57) { + return c - 48; // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } + } - var bhiBits = this._countBits(bhi); + function parseHexByte(string, lowerBound, index) { + var r = parseHex4Bits(string, index); - shift = 26 - bhiBits; + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } // Initialize quotient + return r; + } + + BN.prototype._parseHex = function _parseHex(number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } // 24-bits chunks - var m = a.length - b.length; - var q; - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); + var off = 0; + var j = 0; + var w; - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } } } - var diff = a.clone()._ishlnsubmul(b, 1, m); + this._strip(); + }; - if (diff.negative === 0) { - a = diff; + function parseBase(str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); - if (q) { - q.words[m] = 1; + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; // 'a' + + if (c >= 49) { + b = c - 49 + 0xa; // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; // '0' - '9' + } else { + b = c; } + + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; } - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) + return r; + } - qj = Math.min(qj / bhi | 0, 0x3ffffff); + BN.prototype._parseBase = function _parseBase(number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; // Find length of limb in base - a._ishlnsubmul(b, qj, j); + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } - while (a.negative !== 0) { - qj--; - a.negative = 0; + limbLen--; + limbPow = limbPow / base | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; - a._ishlnsubmul(b, 1, j); + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + this.imuln(limbPow); - if (!a.isZero()) { - a.negative ^= 1; - } + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); } + } - if (q) { - q.words[j] = qj; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; } - } - if (q) { - q._strip(); + this.imuln(pow); + + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - a._strip(); // Denormalize + this._strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; } - return { - div: q || null, - mod: a - }; - }; // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + function move(dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } - BN.prototype.divmod = function divmod(num, mode, positive) { - assert(!num.isZero()); + BN.prototype._move = function _move(dest) { + move(dest, this); + }; - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; - var div, mod, res; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); + return this; + }; // Remove leading `0` from `this` - if (mode !== 'mod') { - div = res.div.neg(); - } - if (mode !== 'div') { - mod = res.mod.neg(); + BN.prototype._strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + return this._normSign(); + }; - return { - div: div, - mod: mod - }; + BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + return this; + }; // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility - if (mode !== 'mod') { - div = res.div.neg(); - } - return { - div: div, - mod: res.mod - }; + if (typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function') { + try { + BN.prototype[Symbol["for"]('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; } + } else { + BN.prototype.inspect = inspect; + } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + function inspect() { + return (this.red ? ''; + } + /* + var zeros = []; + var groupSizes = []; + var groupBases = []; + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + */ - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000']; + var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; + var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; - return { - div: res.div, - mod: mod - }; - } // Both numbers are positive at this point - // Strip both numbers to approximate shift value + BN.prototype.toString = function toString(base, padding) { + base = base || 10; + padding = padding | 0 || 1; + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } // Very short reduction + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 0xffffff).toString(16); + carry = w >>> 24 - off & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; + off += 2; + + if (off >= 26) { + off -= 26; + i--; + } } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modrn(num.words[0])) - }; + if (carry !== 0) { + out = carry.toString(16) + out; } - return { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])) - }; - } + while (out.length % padding !== 0) { + out = '0' + out; + } - return this._wordDiv(num, mode); - }; // Find `this` / `num` + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } - BN.prototype.div = function div(num) { - return this.divmod(num, 'div', false).div; - }; // Find `this` % `num` + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; - BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod', false).mod; - }; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); - BN.prototype.umod = function umod(num) { - return this.divmod(num, 'mod', true).mod; - }; // Find Round(`this` / `num`) + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } - BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); // Fast case - exact division + while (out.length % padding !== 0) { + out = '0' + out; + } - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); // Round down + if (this.negative !== 0) { + out = '-' + out; + } - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up + return out; + } - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + assert(false, 'Base should be between 2 and 36'); }; - BN.prototype.modrn = function modrn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - var acc = 0; - - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; - return isNegNum ? -acc : acc; - }; // WARNING: DEPRECATED + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + this.words[1] * 0x4000000; + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return this.negative !== 0 ? -ret : ret; + }; - BN.prototype.modn = function modn(num) { - return this.modrn(num); - }; // In-place division by number + BN.prototype.toJSON = function toJSON() { + return this.toString(16, 2); + }; + if (Buffer) { + BN.prototype.toBuffer = function toBuffer(endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } - BN.prototype.idivn = function idivn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 0x3ffffff); - var carry = 0; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = w / num | 0; - carry = w % num; + var allocate = function allocate(ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); } - this._strip(); - - return isNegNum ? this.ineg() : this; + return new ArrayType(size); }; - BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; }; - BN.prototype.egcd = function egcd(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var x = this; - var y = p.clone(); + BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { + var position = 0; + var carry = 0; - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } // A * x + B * y = x + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = word >> 8 & 0xff; + } - var A = new BN(1); - var B = new BN(0); // C * x + D * y = y + if (position < res.length) { + res[position++] = word >> 16 & 0xff; + } - var C = new BN(0); - var D = new BN(1); - var g = 0; + if (shift === 6) { + if (position < res.length) { + res[position++] = word >> 24 & 0xff; + } - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } } - var yp = y.clone(); - var xp = x.clone(); + if (position < res.length) { + res[position++] = carry; - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + while (position < res.length) { + res[position++] = 0; + } + } + }; - if (i > 0) { - x.iushrn(i); + BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { + var position = res.length - 1; + var carry = 0; - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position--] = word & 0xff; - A.iushrn(1); - B.iushrn(1); - } + if (position >= 0) { + res[position--] = word >> 8 & 0xff; } - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - - if (j > 0) { - y.iushrn(j); - - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } + if (position >= 0) { + res[position--] = word >> 16 & 0xff; + } - C.iushrn(1); - D.iushrn(1); + if (shift === 6) { + if (position >= 0) { + res[position--] = word >> 24 & 0xff; } - } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + carry = 0; + shift = 0; } else { - y.isub(x); - C.isub(A); - D.isub(B); + carry = word >>> 24; + shift += 2; } } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - - - BN.prototype._invmp = function _invmp(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var a = this; - var b = p.clone(); + if (position >= 0) { + res[position--] = carry; - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + while (position >= 0) { + res[position--] = 0; + } } + }; - var x1 = new BN(1); - var x2 = new BN(0); - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; - if (i > 0) { - a.iushrn(i); + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } - x1.iushrn(1); - } + if (t >= 0x8) { + r += 4; + t >>>= 4; } - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (t >= 0x02) { + r += 2; + t >>>= 2; + } - if (j > 0) { - b.iushrn(j); + return r + t; + }; + } - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } + BN.prototype._zeroBits = function _zeroBits(w) { + // Short-cut + if (w === 0) return 26; + var t = w; + var r = 0; - x2.iushrn(1); - } - } + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; } - var res; + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; } - if (res.cmpn(0) < 0) { - res.iadd(p); + if ((t & 0x1) === 0) { + r++; } - return res; - }; + return r; + }; // Return number of used bits in a BN - BN.prototype.gcd = function gcd(num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; - do { - while (a.isEven()) { - a.iushrn(1); - } + var hi = this._countBits(w); - while (b.isEven()) { - b.iushrn(1); - } + return (this.length - 1) * 26 + hi; + }; - var r = a.cmp(b); + function toBitArray(num) { + var w = new Array(num.bitLength()); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = num.words[off] >>> wbit & 0x01; + } - a.isub(b); - } while (true); + return w; + } // Number of trailing zero bits - return b.iushln(shift); - }; // Invert number in the field F(num) + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; - BN.prototype.invm = function invm(num) { - return this.egcd(num).a.umod(num); + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + + r += b; + if (b !== 26) break; + } + + return r; }; - BN.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); }; - BN.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; - }; // And first word and num + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - BN.prototype.andln = function andln(num) { - return this.words[0] & num; - }; // Increment at the bit position in-line + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; // Fast case: bit is much higher than all existing words + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; // Return negative clone of `this` - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } // Add bit and propagate, if needed + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } - var carry = q; + return this; + }; // Or `num` with `this` in-place - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; + + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; } - return this; + return this._strip(); }; - BN.prototype.isZero = function isZero() { - return this.length === 1 && this.words[0] === 0; + BN.prototype.ior = function ior(num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; // Or `num` with `this` + + + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); }; - BN.prototype.cmpn = function cmpn(num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; // And `num` with `this` in-place - this._strip(); - var res; + BN.prototype.iuand = function iuand(num) { + // b = min-length(num, this) + var b; - if (this.length > 1) { - res = 1; + if (this.length > num.length) { + b = num; } else { - if (negative) { - num = -num; - } + b = this; + } - assert(num <= 0x3ffffff, 'Number is too big'); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; } - if (this.negative !== 0) return -res | 0; - return res; - }; // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` + this.length = b.length; + return this._strip(); + }; + BN.prototype.iand = function iand(num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; // And `num` with `this` - BN.prototype.cmp = function cmp(num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; // Unsigned comparison + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; - BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - var res = 0; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; // Xor `num` with `this` in-place - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } + BN.prototype.iuxor = function iuxor(num) { + // a.length > b.length + var a; + var b; - break; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - return res; - }; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - BN.prototype.gtn = function gtn(num) { - return this.cmpn(num) === 1; - }; + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - BN.prototype.gt = function gt(num) { - return this.cmp(num) === 1; + this.length = a.length; + return this._strip(); }; - BN.prototype.gten = function gten(num) { - return this.cmpn(num) >= 0; - }; + BN.prototype.ixor = function ixor(num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; // Xor `num` with `this` - BN.prototype.gte = function gte(num) { - return this.cmp(num) >= 0; + + BN.prototype.xor = function xor(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); }; - BN.prototype.ltn = function ltn(num) { - return this.cmpn(num) === -1; - }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; // Not ``this`` with ``width`` bitwidth + + + BN.prototype.inotn = function inotn(width) { + assert(typeof width === 'number' && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; // Extend the buffer with leading zeroes + + this._expand(bytesNeeded); - BN.prototype.lt = function lt(num) { - return this.cmp(num) === -1; - }; + if (bitsLeft > 0) { + bytesNeeded--; + } // Handle complete words - BN.prototype.lten = function lten(num) { - return this.cmpn(num) <= 0; - }; - BN.prototype.lte = function lte(num) { - return this.cmp(num) <= 0; - }; + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } // Handle the residue - BN.prototype.eqn = function eqn(num) { - return this.cmpn(num) === 0; - }; - BN.prototype.eq = function eq(num) { - return this.cmp(num) === 0; - }; // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft; + } // And remove leading zeroes - BN.red = function red(num) { - return new Red(num); + return this._strip(); }; - BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; // Set `bit` of `this` - BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; - }; + BN.prototype.setn = function setn(bit, val) { + assert(typeof bit === 'number' && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; - BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + this._expand(off + 1); - BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + return this._strip(); + }; // Add `num` to `this` in-place - BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + BN.prototype.iadd = function iadd(num) { + var r; // negative + positive - BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } // a.length > b.length - BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); + var a, b; - return this.red.mul(this, num); - }; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } - BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); + var carry = 0; - this.red._verify2(this, num); + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - return this.red.imul(this, num); - }; + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); + this.length = a.length; - this.red._verify1(this); + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - return this.red.sqr(this); - }; + return this; + }; // Add `num` to `this` - BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); + BN.prototype.add = function add(num) { + var res; - return this.red.isqr(this); - }; // Square root over p + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; // Subtract `num` from `this` in-place - BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); + BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } // At this point both numbers are positive - return this.red.sqrt(this); - }; - BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); + var cmp = this.cmp(num); // Optimization - zeroify - this.red._verify1(this); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } // a > b - return this.red.invm(this); - }; // Return negative clone of `this` % `red modulo` + var a, b; - BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - this.red._verify1(this); + var carry = 0; - return this.red.neg(this); - }; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } - BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } // Copy rest of the words - this.red._verify1(this); - return this.red.pow(this, num); - }; // Prime numbers with efficient reduction + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; // Pseudo-Mersenne prime + if (a !== this) { + this.negative = 1; + } - function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - this.tmp = this._tmp(); - } + return this._strip(); + }; // Subtract `num` from `this` - MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; + + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); }; - MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; + function smallMulTo(self, num, out) { + out.negative = num.negative ^ self.negative; + var len = self.length + num.length | 0; + out.length = len; + len = len - 1 | 0; // Peel one iteration (compiler can't do it, because of code complexity) - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 0x3ffffff; + var carry = r / 0x4000000 | 0; + out.words[0] = lo; - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is a BN v4 instance - r.strip(); - } else { - // r is a BN v5 instance - r._strip(); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 0x4000000 | 0; + rword = r & 0x3ffffff; } + + out.words[k] = rword | 0; + carry = ncarry | 0; } - return r; - }; + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } - MPrime.prototype.split = function split(input, out) { - input.iushrn(this.n, 0, out); - }; + return out._strip(); + } // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). - MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); - }; - function K256() { - MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } + var comb10MulTo = function comb10MulTo(self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ - inherits(K256, MPrime); + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ - K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - var outLen = Math.min(input.length, 9); + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ - output.length = outLen; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } // Shift by 9 limbs + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = (next & mask) << 4 | prev >>> 22; - prev = next; - } + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ - prev >>>= 22; - input.words[i - 10] = prev; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ - K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ - var lo = 0; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + (lo / 0x4000000 | 0); - } // Fast length reduction + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ - if (num.words[num.length - 1] === 0) { - num.length--; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; - if (num.words[num.length - 1] === 0) { - num.length--; - } + if (c !== 0) { + o[19] = c; + out.length++; } - return num; - }; - - function P224() { - MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } + return out; + }; // Polyfill comb - inherits(P224, MPrime); - function P192() { - MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + if (!Math.imul) { + comb10MulTo = smallMulTo; } - inherits(P192, MPrime); - - function P25519() { - // 2 ^ 255 - 19 - MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } + function bigMulTo(self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + var carry = 0; + var hncarry = 0; - inherits(P25519, MPrime); + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); - P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 0x3ffffff; + ncarry = ncarry + (r / 0x4000000 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 0x3ffffff; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - num.words[i] = lo; - carry = hi; + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; } if (carry !== 0) { - num.words[num.length++] = carry; - } - - return num; - }; // Exported mostly for testing purposes, use plain name instead - - - BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) return primes[name]; - var prime; - - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); + out.words[k] = carry; } else { - throw new Error('Unknown prime ' + name); + out.length--; } - primes[name] = prime; - return prime; - }; // - // Base reduction engine - // + return out._strip(); + } + function jumboMulTo(self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } - function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; - this.m = prime.p; - this.prime = prime; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; + res = jumboMulTo(this, num, out); } - } - Red.prototype._verify1 = function _verify1(a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + return res; + }; // Cooley-Tukey algorithm for FFT - Red.prototype._verify2 = function _verify2(a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, 'red works only with red numbers'); - }; - Red.prototype.imod = function imod(a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - move(a, a.umod(this.m)._forceRed(this)); - return a; - }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; // Multiply employing FFT - Red.prototype.neg = function neg(a) { - if (a.isZero()) { - return a.clone(); - } - return this.m.sub(a)._forceRed(this); - }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; // In-place Multiplication - Red.prototype.add = function add(a, b) { - this._verify2(a, b); - var res = a.add(b); + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } + BN.prototype.imuln = function imuln(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(typeof num === 'number'); + assert(num < 0x4000000); // Carry - return res._forceRed(this); - }; + var carry = 0; - Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += w / 0x4000000 | 0; // NOTE: lo is 27bit maximum - var res = a.iadd(b); + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - return res; + return isNegNum ? this.ineg() : this; }; - Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; // `this` * `this` - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; // `this` * `this` in-place - return res._forceRed(this); - }; - Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; // Math.pow(`this`, `num`) - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + BN.prototype.pow = function pow(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); // Skip leading zeroes + + var res = this; + + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } } return res; - }; + }; // Shift-left in-place - Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; + BN.prototype.iushln = function iushln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 0x3ffffff >>> 26 - r << 26 - r; + var i; - Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); + if (r !== 0) { + var carry = 0; - return this.imod(a.imul(b)); - }; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } - Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); + if (carry) { + this.words[i] = carry; + this.length++; + } + } - return this.imod(a.mul(b)); - }; + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } - Red.prototype.isqr = function isqr(a) { - return this.imul(a, a.clone()); - }; + for (i = 0; i < s; i++) { + this.words[i] = 0; + } - Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); - }; + this.length += s; + } - Red.prototype.sqrt = function sqrt(a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); // Fast case + return this._strip(); + }; - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) + BN.prototype.ishln = function ishln(bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits - var q = this.m.subn(1); - var s = 0; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; } - assert(!q.isZero()); - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); // Extended mode, copy masked part - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); + maskedWords.length = s; } - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - - while (t.cmp(one) !== 0) { - var tmp = t; + if (s === 0) ; else if (this.length > s) { + this.length -= s; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; } - - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + } else { + this.words[0] = 0; + this.length = 1; } - return r; - }; + var carry = 0; - Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } // Push carried bits as a mask - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); + + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; } + + return this._strip(); }; - Red.prototype.pow = function pow(a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; // Shift-left - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; - if (start === 0) { - start = 26; - } + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; // Shift-right - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = word >> j & 1; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; - if (res !== wnd[0]) { - res = this.sqr(res); - } + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; // Test if n bit is set - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } + BN.prototype.testn = function testn(bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; // Fast case: bit is much higher than all existing words - start = 26; - } + if (this.length <= s) return false; // Check bit and return - return res; - }; + var w = this.words[s]; + return !!(w & q); + }; // Return only lowers bits of number (in-place) - Red.prototype.convertTo = function convertTo(num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }; - Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; - }; // - // Montgomery method engine - // + BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert(this.negative === 0, 'imaskn works only with positive numbers'); + if (this.length <= s) { + return this; + } - BN.mont = function mont(num) { - return new Mont(num); - }; + if (r !== 0) { + s++; + } - function Mont(m) { - Red.call(this, m); - this.shift = this.m.bitLength(); + this.length = Math.min(s, this.length); - if (this.shift % 26 !== 0) { - this.shift += 26 - this.shift % 26; + if (r !== 0) { + var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; + this.words[this.length - 1] &= mask; } - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } + return this._strip(); + }; // Return only lowers bits of number - inherits(Mont, Red); - Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.ushln(this.shift)); - }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; // Add plain number `num` to `this` - Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - Mont.prototype.imul = function imul(a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } + BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); // Possible sign change - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } // Add without checks - return res._forceRed(this); + + return this._iaddn(num); }; - Mont.prototype.mul = function mul(a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; // Carry - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } } - return res._forceRed(this); - }; + this.length = Math.max(this.length, i + 1); + return this; + }; // Subtract plain number `num` from `this` - Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; - })(module, commonjsGlobal); -})(bn$1); -var BN$1 = bn$1.exports; + BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); -function number$1(n) { - if (!Number.isSafeInteger(n) || n < 0) throw new Error("Wrong positive integer: ".concat(n)); -} -function bool(b) { - if (typeof b !== 'boolean') throw new Error("Expected boolean, not ".concat(b)); -} -function bytes(b) { - if (!(b instanceof Uint8Array)) throw new TypeError('Expected Uint8Array'); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } - for (var _len = arguments.length, lengths = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - lengths[_key - 1] = arguments[_key]; - } + this.words[0] -= num; - if (lengths.length > 0 && !lengths.includes(b.length)) throw new TypeError("Expected Uint8Array of length ".concat(lengths, ", not of length=").concat(b.length)); -} -function hash(hash) { - if (typeof hash !== 'function' || typeof hash.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); - number$1(hash.outputLen); - number$1(hash.blockLen); -} -function exists(instance) { - var checkFinished = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - if (instance.destroyed) throw new Error('Hash instance has been destroyed'); - if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); -} -function output(out, instance) { - bytes(out); - var min = instance.outputLen; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least ".concat(min)); - } -} -var assert$1 = { - number: number$1, - bool: bool, - bytes: bytes, - hash: hash, - exists: exists, - output: output -}; -var assert$2 = assert$1; + return this._strip(); + }; -var u32$1 = function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -}; // Cast array to view + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; -var createView = function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -}; // The rotate right (circular right shift) operation for uint32 + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; -var rotr = function rotr(word, shift) { - return word << 32 - shift | word >>> shift; -}; // big-endian hardware is rare. Just in case someone still decides to run hashes: -// early-throw an error because we don't support BE yet. + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; -var isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; -if (!isLE) throw new Error('Non little-endian hardware is not supported'); -Array.from({ - length: 256 -}, function (v, i) { - return i.toString(16).padStart(2, '0'); -}); + BN.prototype.abs = function abs() { + return this.clone().iabs(); + }; -function utf8ToBytes(str) { - if (typeof str !== 'string') { - throw new TypeError("utf8ToBytes expected string, got ".concat(_typeof$1(str))); - } + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; - return new TextEncoder().encode(str); -} -function toBytes(data) { - if (typeof data === 'string') data = utf8ToBytes(data); - if (!(data instanceof Uint8Array)) throw new TypeError("Expected input type is Uint8Array (got ".concat(_typeof$1(data), ")")); - return data; -} + this._expand(len); -var Hash = /*#__PURE__*/function () { - function Hash() { - _classCallCheck(this, Hash); - } + var w; + var carry = 0; - _createClass(Hash, [{ - key: "clone", - value: // Safe version that clones internal state - function clone() { - return this._cloneInto(); - } - }]); + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - (right / 0x4000000 | 0); + this.words[i + shift] = w & 0x3ffffff; + } - return Hash; -}(); // Check if object doens't have custom constructor (like Uint8Array/Array) -function wrapConstructor(hashConstructor) { - var hashC = function hashC(message) { - return hashConstructor().update(toBytes(message)).digest(); - }; + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } - var tmp = hashConstructor(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; + if (carry === 0) return this._strip(); // Subtraction overflow - hashC.create = function () { - return hashConstructor(); - }; + assert(carry === -1); + carry = 0; - return hashC; -} -function wrapConstructorWithOpts(hashCons) { - var hashC = function hashC(msg, opts) { - return hashCons(opts).update(toBytes(msg)).digest(); - }; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } - var tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; + this.negative = 1; + return this._strip(); + }; - hashC.create = function (opts) { - return hashCons(opts); - }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; // Normalize - return hashC; -} + var bhi = b.words[b.length - 1] | 0; -function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + var bhiBits = this._countBits(bhi); - var _32n = BigInt(32); + shift = 26 - bhiBits; - var _u32_max = BigInt(0xffffffff); + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } // Initialize quotient - var wh = Number(value >> _32n & _u32_max); - var wl = Number(value & _u32_max); - var h = isLE ? 4 : 0; - var l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); -} // Base SHA2 class (RFC 6234) + var m = a.length - b.length; + var q; -var SHA2 = /*#__PURE__*/function (_Hash) { - _inherits(SHA2, _Hash); + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); - var _super = _createSuper(SHA2); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } - function SHA2(blockLen, outputLen, padOffset, isLE) { - var _this; + var diff = a.clone()._ishlnsubmul(b, 1, m); - _classCallCheck(this, SHA2); + if (diff.negative === 0) { + a = diff; - _this = _super.call(this); - _this.blockLen = blockLen; - _this.outputLen = outputLen; - _this.padOffset = padOffset; - _this.isLE = isLE; - _this.finished = false; - _this.length = 0; - _this.pos = 0; - _this.destroyed = false; - _this.buffer = new Uint8Array(blockLen); - _this.view = createView(_this.buffer); - return _this; - } + if (q) { + q.words[m] = 1; + } + } - _createClass(SHA2, [{ - key: "update", - value: function update(data) { - assert$2.exists(this); - var view = this.view, - buffer = this.buffer, - blockLen = this.blockLen; - data = toBytes(data); - var len = data.length; + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) - for (var pos = 0; pos < len;) { - var take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process + qj = Math.min(qj / bhi | 0, 0x3ffffff); - if (take === blockLen) { - var dataView = createView(data); + a._ishlnsubmul(b, qj, j); - for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + while (a.negative !== 0) { + qj--; + a.negative = 0; - continue; - } + a._ishlnsubmul(b, 1, j); - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; + if (!a.isZero()) { + a.negative ^= 1; + } + } - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; + if (q) { + q.words[j] = qj; } } - this.length += data.length; - this.roundClean(); - return this; - } - }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.exists(this); - assert$2.output(out, this); - this.finished = true; // Padding - // We can avoid allocation of buffer for padding completely if it - // was previously not allocated here. But it won't change performance. + if (q) { + q._strip(); + } - var buffer = this.buffer, - view = this.view, - blockLen = this.blockLen, - isLE = this.isLE; - var pos = this.pos; // append the bit '1' to the message + a._strip(); // Denormalize - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } // Pad until full block byte with zeros + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested - for (var i = pos; i < blockLen; i++) buffer[i] = 0; // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that - // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. - // So we just write lowest 64 bits of that value. + BN.prototype.divmod = function divmod(num, mode, positive) { + assert(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - var oview = createView(out); - var len = this.outputLen; // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + var div, mod, res; - if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); - var outLen = len / 4; - var state = this.get(); - if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - for (var _i2 = 0; _i2 < outLen; _i2++) oview.setUint32(4 * _i2, state[_i2], isLE); - } - }, { - key: "digest", - value: function digest() { - var buffer = this.buffer, - outputLen = this.outputLen; - this.digestInto(buffer); - var res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - }, { - key: "_cloneInto", - value: function _cloneInto(to) { - var _to; + if (mode !== 'mod') { + div = res.div.neg(); + } - to || (to = new this.constructor()); + if (mode !== 'div') { + mod = res.mod.neg(); - (_to = to).set.apply(_to, _toConsumableArray(this.get())); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } - var blockLen = this.blockLen, - buffer = this.buffer, - length = this.length, - finished = this.finished, - destroyed = this.destroyed, - pos = this.pos; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) to.buffer.set(buffer); - return to; - } - }]); + return { + div: div, + mod: mod + }; + } - return SHA2; -}(Hash); + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); -var U32_MASK64 = BigInt(Math.pow(2, 32) - 1); + if (mode !== 'mod') { + div = res.div.neg(); + } -var _32n = BigInt(32); // We are not using BigUint64Array, because they are extremely slow as per 2022 + return { + div: div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); -function fromBig(n) { - var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (le) return { - h: Number(n & U32_MASK64), - l: Number(n >> _32n & U32_MASK64) - }; - return { - h: Number(n >> _32n & U32_MASK64) | 0, - l: Number(n & U32_MASK64) | 0 - }; -} -function split(lst) { - var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var Ah = new Uint32Array(lst.length); - var Al = new Uint32Array(lst.length); + if (mode !== 'div') { + mod = res.mod.neg(); - for (var i = 0; i < lst.length; i++) { - var _fromBig2 = fromBig(lst[i], le), - h = _fromBig2.h, - l = _fromBig2.l; + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } - var _ref = [h, l]; - Ah[i] = _ref[0]; - Al[i] = _ref[1]; - } + return { + div: res.div, + mod: mod + }; + } // Both numbers are positive at this point + // Strip both numbers to approximate shift value - return [Ah, Al]; -} -var toBig = function toBig(h, l) { - return BigInt(h >>> 0) << _32n | BigInt(l >>> 0); -}; // for Shift in [0, 32) -var shrSH = function shrSH(h, l, s) { - return h >>> s; -}; + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } // Very short reduction -var shrSL = function shrSL(h, l, s) { - return h << 32 - s | l >>> s; -}; // Right rotate for Shift in [1, 32) + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } -var rotrSH = function rotrSH(h, l, s) { - return h >>> s | l << 32 - s; -}; + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } -var rotrSL = function rotrSL(h, l, s) { - return h << 32 - s | l >>> s; -}; // Right rotate for Shift in (32, 64), NOTE: 32 is special case. + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; // Find `this` / `num` -var rotrBH = function rotrBH(h, l, s) { - return h << 64 - s | l >>> s - 32; -}; -var rotrBL = function rotrBL(h, l, s) { - return h >>> s - 32 | l << 64 - s; -}; // Right rotate for shift===32 (just swaps l&h) + BN.prototype.div = function div(num) { + return this.divmod(num, 'div', false).div; + }; // Find `this` % `num` -var rotr32H = function rotr32H(h, l) { - return l; -}; + BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod', false).mod; + }; -var rotr32L = function rotr32L(h, l) { - return h; -}; // Left rotate for Shift in [1, 32) + BN.prototype.umod = function umod(num) { + return this.divmod(num, 'mod', true).mod; + }; // Find Round(`this` / `num`) -var rotlSH = function rotlSH(h, l, s) { - return h << s | l >>> 32 - s; -}; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); // Fast case - exact division -var rotlSL = function rotlSL(h, l, s) { - return l << s | h >>> 32 - s; -}; // Left rotate for Shift in (32, 64), NOTE: 32 is special case. + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up -var rotlBH = function rotlBH(h, l, s) { - return l << s - 32 | h >>> 64 - s; -}; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; -var rotlBL = function rotlBL(h, l, s) { - return h << s - 32 | l >>> 64 - s; -}; // JS uses 32-bit signed integers for bitwise operations which means we cannot -// simple take carry out of low bit sum by shift, we need to use division. -// Removing "export" has 5% perf penalty -_- + BN.prototype.modrn = function modrn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } -function add(Ah, Al, Bh, Bl) { - var l = (Al >>> 0) + (Bl >>> 0); - return { - h: Ah + Bh + (l / Math.pow(2, 32) | 0) | 0, - l: l | 0 - }; -} // Addition with more than 2 elements + return isNegNum ? -acc : acc; + }; // WARNING: DEPRECATED -var add3L = function add3L(Al, Bl, Cl) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); -}; -var add3H = function add3H(low, Ah, Bh, Ch) { - return Ah + Bh + Ch + (low / Math.pow(2, 32) | 0) | 0; -}; + BN.prototype.modn = function modn(num) { + return this.modrn(num); + }; // In-place division by number + + + BN.prototype.idivn = function idivn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 0x3ffffff); + var carry = 0; + + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = w / num | 0; + carry = w % num; + } + + this._strip(); -var add4L = function add4L(Al, Bl, Cl, Dl) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); -}; + return isNegNum ? this.ineg() : this; + }; -var add4H = function add4H(low, Ah, Bh, Ch, Dh) { - return Ah + Bh + Ch + Dh + (low / Math.pow(2, 32) | 0) | 0; -}; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; -var add5L = function add5L(Al, Bl, Cl, Dl, El) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); -}; + BN.prototype.egcd = function egcd(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var x = this; + var y = p.clone(); -var add5H = function add5H(low, Ah, Bh, Ch, Dh, Eh) { - return Ah + Bh + Ch + Dh + Eh + (low / Math.pow(2, 32) | 0) | 0; -}; // prettier-ignore + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } // A * x + B * y = x -var u64$1 = { - fromBig: fromBig, - split: split, - toBig: toBig, - shrSH: shrSH, - shrSL: shrSL, - rotrSH: rotrSH, - rotrSL: rotrSL, - rotrBH: rotrBH, - rotrBL: rotrBL, - rotr32H: rotr32H, - rotr32L: rotr32L, - rotlSH: rotlSH, - rotlSL: rotlSL, - rotlBH: rotlBH, - rotlBL: rotlBL, - add: add, - add3L: add3L, - add3H: add3H, - add4L: add4L, - add4H: add4H, - add5H: add5H, - add5L: add5L -}; -var u64$2 = u64$1; + var A = new BN(1); + var B = new BN(0); // C * x + D * y = y -// prettier-ignore + var C = new BN(0); + var D = new BN(1); + var g = 0; -var _u64$split$1 = u64$2.split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(function (n) { - return BigInt(n); -})), - _u64$split2$1 = _slicedToArray(_u64$split$1, 2), - SHA512_Kh = _u64$split2$1[0], - SHA512_Kl = _u64$split2$1[1]; // Temporary buffer, not used to store anything between runs + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); -var SHA512_W_H = new Uint32Array(80); -var SHA512_W_L = new Uint32Array(80); -var SHA512 = /*#__PURE__*/function (_SHA) { - _inherits(SHA512, _SHA); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - var _super = _createSuper(SHA512); + if (i > 0) { + x.iushrn(i); - function SHA512() { - var _this; + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } - _classCallCheck(this, SHA512); + A.iushrn(1); + B.iushrn(1); + } + } - _this = _super.call(this, 128, 64, 16, false); // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. - // Also looks cleaner and easier to verify with spec. - // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - // h -- high 32 bits, l -- low 32 bits + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - _this.Ah = 0x6a09e667 | 0; - _this.Al = 0xf3bcc908 | 0; - _this.Bh = 0xbb67ae85 | 0; - _this.Bl = 0x84caa73b | 0; - _this.Ch = 0x3c6ef372 | 0; - _this.Cl = 0xfe94f82b | 0; - _this.Dh = 0xa54ff53a | 0; - _this.Dl = 0x5f1d36f1 | 0; - _this.Eh = 0x510e527f | 0; - _this.El = 0xade682d1 | 0; - _this.Fh = 0x9b05688c | 0; - _this.Fl = 0x2b3e6c1f | 0; - _this.Gh = 0x1f83d9ab | 0; - _this.Gl = 0xfb41bd6b | 0; - _this.Hh = 0x5be0cd19 | 0; - _this.Hl = 0x137e2179 | 0; - return _this; - } // prettier-ignore + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } - _createClass(SHA512, [{ - key: "get", - value: function get() { - var Ah = this.Ah, - Al = this.Al, - Bh = this.Bh, - Bl = this.Bl, - Ch = this.Ch, - Cl = this.Cl, - Dh = this.Dh, - Dl = this.Dl, - Eh = this.Eh, - El = this.El, - Fh = this.Fh, - Fl = this.Fl, - Gh = this.Gh, - Gl = this.Gl, - Hh = this.Hh, - Hl = this.Hl; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } // prettier-ignore + C.iushrn(1); + D.iushrn(1); + } + } - }, { - key: "set", - value: function set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - }, { - key: "process", - value: function process(view, offset) { - // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array - for (var i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } } - for (var _i2 = 16; _i2 < 80; _i2++) { - // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) - var W15h = SHA512_W_H[_i2 - 15] | 0; - var W15l = SHA512_W_L[_i2 - 15] | 0; - var s0h = u64$2.rotrSH(W15h, W15l, 1) ^ u64$2.rotrSH(W15h, W15l, 8) ^ u64$2.shrSH(W15h, W15l, 7); - var s0l = u64$2.rotrSL(W15h, W15l, 1) ^ u64$2.rotrSL(W15h, W15l, 8) ^ u64$2.shrSL(W15h, W15l, 7); // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed - var W2h = SHA512_W_H[_i2 - 2] | 0; - var W2l = SHA512_W_L[_i2 - 2] | 0; - var s1h = u64$2.rotrSH(W2h, W2l, 19) ^ u64$2.rotrBH(W2h, W2l, 61) ^ u64$2.shrSH(W2h, W2l, 6); - var s1l = u64$2.rotrSL(W2h, W2l, 19) ^ u64$2.rotrBL(W2h, W2l, 61) ^ u64$2.shrSL(W2h, W2l, 6); // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - var SUMl = u64$2.add4L(s0l, s1l, SHA512_W_L[_i2 - 7], SHA512_W_L[_i2 - 16]); - var SUMh = u64$2.add4H(SUMl, s0h, s1h, SHA512_W_H[_i2 - 7], SHA512_W_H[_i2 - 16]); - SHA512_W_H[_i2] = SUMh | 0; - SHA512_W_L[_i2] = SUMl | 0; + BN.prototype._invmp = function _invmp(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); } - var Ah = this.Ah, - Al = this.Al, - Bh = this.Bh, - Bl = this.Bl, - Ch = this.Ch, - Cl = this.Cl, - Dh = this.Dh, - Dl = this.Dl, - Eh = this.Eh, - El = this.El, - Fh = this.Fh, - Fl = this.Fl, - Gh = this.Gh, - Gl = this.Gl, - Hh = this.Hh, - Hl = this.Hl; // Compression function main loop, 80 rounds + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); - for (var _i4 = 0; _i4 < 80; _i4++) { - // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) - var sigma1h = u64$2.rotrSH(Eh, El, 14) ^ u64$2.rotrSH(Eh, El, 18) ^ u64$2.rotrBH(Eh, El, 41); - var sigma1l = u64$2.rotrSL(Eh, El, 14) ^ u64$2.rotrSL(Eh, El, 18) ^ u64$2.rotrBL(Eh, El, 41); //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - var CHIh = Eh & Fh ^ ~Eh & Gh; - var CHIl = El & Fl ^ ~El & Gl; // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] - // prettier-ignore + if (i > 0) { + a.iushrn(i); - var T1ll = u64$2.add5L(Hl, sigma1l, CHIl, SHA512_Kl[_i4], SHA512_W_L[_i4]); - var T1h = u64$2.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[_i4], SHA512_W_H[_i4]); - var T1l = T1ll | 0; // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } - var sigma0h = u64$2.rotrSH(Ah, Al, 28) ^ u64$2.rotrBH(Ah, Al, 34) ^ u64$2.rotrBH(Ah, Al, 39); - var sigma0l = u64$2.rotrSL(Ah, Al, 28) ^ u64$2.rotrBL(Ah, Al, 34) ^ u64$2.rotrBL(Ah, Al, 39); - var MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - var MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; + x1.iushrn(1); + } + } - var _u64$add = u64$2.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0); + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - Eh = _u64$add.h; - El = _u64$add.l; - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - var All = u64$2.add3L(T1l, sigma0l, MAJl); - Ah = u64$2.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } // Add the compressed chunk to the current hash value + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } - var _u64$add2 = u64$2.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0); + x2.iushrn(1); + } + } - Ah = _u64$add2.h; - Al = _u64$add2.l; + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } - var _u64$add3 = u64$2.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0); + var res; - Bh = _u64$add3.h; - Bl = _u64$add3.l; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - var _u64$add4 = u64$2.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0); + if (res.cmpn(0) < 0) { + res.iadd(p); + } - Ch = _u64$add4.h; - Cl = _u64$add4.l; + return res; + }; - var _u64$add5 = u64$2.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0); + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; // Remove common factor of two - Dh = _u64$add5.h; - Dl = _u64$add5.l; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } - var _u64$add6 = u64$2.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0); + do { + while (a.isEven()) { + a.iushrn(1); + } - Eh = _u64$add6.h; - El = _u64$add6.l; + while (b.isEven()) { + b.iushrn(1); + } - var _u64$add7 = u64$2.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0); + var r = a.cmp(b); - Fh = _u64$add7.h; - Fl = _u64$add7.l; + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } - var _u64$add8 = u64$2.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0); + a.isub(b); + } while (true); - Gh = _u64$add8.h; - Gl = _u64$add8.l; + return b.iushln(shift); + }; // Invert number in the field F(num) - var _u64$add9 = u64$2.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0); - Hh = _u64$add9.h; - Hl = _u64$add9.l; - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - }, { - key: "roundClean", - value: function roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); - } - }, { - key: "destroy", - value: function destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - }]); + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; - return SHA512; -}(SHA2); + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; -var SHA512_224 = /*#__PURE__*/function (_SHA2) { - _inherits(SHA512_224, _SHA2); + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; // And first word and num - var _super2 = _createSuper(SHA512_224); - function SHA512_224() { - var _this2; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; // Increment at the bit position in-line - _classCallCheck(this, SHA512_224); - _this2 = _super2.call(this); // h -- high 32 bits, l -- low 32 bits + BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; // Fast case: bit is much higher than all existing words - _this2.Ah = 0x8c3d37c8 | 0; - _this2.Al = 0x19544da2 | 0; - _this2.Bh = 0x73e19966 | 0; - _this2.Bl = 0x89dcd4d6 | 0; - _this2.Ch = 0x1dfab7ae | 0; - _this2.Cl = 0x32ff9c82 | 0; - _this2.Dh = 0x679dd514 | 0; - _this2.Dl = 0x582f9fcf | 0; - _this2.Eh = 0x0f6d2b69 | 0; - _this2.El = 0x7bd44da8 | 0; - _this2.Fh = 0x77e36f73 | 0; - _this2.Fl = 0x04c48942 | 0; - _this2.Gh = 0x3f9d85a8 | 0; - _this2.Gl = 0x6a1d36c8 | 0; - _this2.Hh = 0x1112e6ad | 0; - _this2.Hl = 0x91d692a1 | 0; - _this2.outputLen = 28; - return _this2; - } + if (this.length <= s) { + this._expand(s + 1); - return _createClass(SHA512_224); -}(SHA512); + this.words[s] |= q; + return this; + } // Add bit and propagate, if needed -var SHA512_256 = /*#__PURE__*/function (_SHA3) { - _inherits(SHA512_256, _SHA3); - var _super3 = _createSuper(SHA512_256); + var carry = q; - function SHA512_256() { - var _this3; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } - _classCallCheck(this, SHA512_256); + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } - _this3 = _super3.call(this); // h -- high 32 bits, l -- low 32 bits + return this; + }; - _this3.Ah = 0x22312194 | 0; - _this3.Al = 0xfc2bf72c | 0; - _this3.Bh = 0x9f555fa3 | 0; - _this3.Bl = 0xc84c64c2 | 0; - _this3.Ch = 0x2393b86b | 0; - _this3.Cl = 0x6f53b151 | 0; - _this3.Dh = 0x96387719 | 0; - _this3.Dl = 0x5940eabd | 0; - _this3.Eh = 0x96283ee2 | 0; - _this3.El = 0xa88effe3 | 0; - _this3.Fh = 0xbe5e1e25 | 0; - _this3.Fl = 0x53863992 | 0; - _this3.Gh = 0x2b0199fc | 0; - _this3.Gl = 0x2c85b8aa | 0; - _this3.Hh = 0x0eb72ddc | 0; - _this3.Hl = 0x81c52ca2 | 0; - _this3.outputLen = 32; - return _this3; - } + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; - return _createClass(SHA512_256); -}(SHA512); + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; -var SHA384 = /*#__PURE__*/function (_SHA4) { - _inherits(SHA384, _SHA4); + this._strip(); - var _super4 = _createSuper(SHA384); + var res; - function SHA384() { - var _this4; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - _classCallCheck(this, SHA384); + assert(num <= 0x3ffffff, 'Number is too big'); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } - _this4 = _super4.call(this); // h -- high 32 bits, l -- low 32 bits + if (this.negative !== 0) return -res | 0; + return res; + }; // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + + + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; // Unsigned comparison - _this4.Ah = 0xcbbb9d5d | 0; - _this4.Al = 0xc1059ed8 | 0; - _this4.Bh = 0x629a292a | 0; - _this4.Bl = 0x367cd507 | 0; - _this4.Ch = 0x9159015a | 0; - _this4.Cl = 0x3070dd17 | 0; - _this4.Dh = 0x152fecd8 | 0; - _this4.Dl = 0xf70e5939 | 0; - _this4.Eh = 0x67332667 | 0; - _this4.El = 0xffc00b31 | 0; - _this4.Fh = 0x8eb44a87 | 0; - _this4.Fl = 0x68581511 | 0; - _this4.Gh = 0xdb0c2e0d | 0; - _this4.Gl = 0x64f98fa7 | 0; - _this4.Hh = 0x47b5481d | 0; - _this4.Hl = 0xbefa4fa4 | 0; - _this4.outputLen = 48; - return _this4; - } - return _createClass(SHA384); -}(SHA512); + BN.prototype.ucmp = function ucmp(num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; -var sha512 = wrapConstructor(function () { - return new SHA512(); -}); -wrapConstructor(function () { - return new SHA512_224(); -}); -wrapConstructor(function () { - return new SHA512_256(); -}); -wrapConstructor(function () { - return new SHA384(); -}); + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; -var _polyfillNode_crypto = {}; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } -var nodeCrypto = _global$1.crypto; + break; + } -var _0n$2 = BigInt(0); + return res; + }; -var _1n$2 = BigInt(1); + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; -var _2n$2 = BigInt(2); + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; -var _8n$1 = BigInt(8); + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; -var CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'); -var CURVE$1 = Object.freeze({ - a: BigInt(-1), - d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), - P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'), - l: CU_O, - n: CU_O, - h: BigInt(8), - Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), - Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960') -}); -var POW_2_256$1 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); -var SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); -BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742'); -var SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); -var INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); -var ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); -var D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; -var ExtendedPoint = /*#__PURE__*/function () { - function ExtendedPoint(x, y, z, t) { - _classCallCheck(this, ExtendedPoint); + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; - this.x = x; - this.y = y; - this.z = z; - this.t = t; - } + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; - _createClass(ExtendedPoint, [{ - key: "equals", - value: function equals(other) { - assertExtPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - var X1Z2 = mod$1(X1 * Z2); - var X2Z1 = mod$1(X2 * Z1); - var Y1Z2 = mod$1(Y1 * Z2); - var Y2Z1 = mod$1(Y2 * Z1); - return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; - } - }, { - key: "negate", - value: function negate() { - return new ExtendedPoint(mod$1(-this.x), this.y, this.z, mod$1(-this.t)); - } - }, { - key: "double", - value: function double() { - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var a = CURVE$1.a; - var A = mod$1(X1 * X1); - var B = mod$1(Y1 * Y1); - var C = mod$1(_2n$2 * mod$1(Z1 * Z1)); - var D = mod$1(a * A); - var x1y1 = X1 + Y1; - var E = mod$1(mod$1(x1y1 * x1y1) - A - B); - var G = D + B; - var F = G - C; - var H = D - B; - var X3 = mod$1(E * F); - var Y3 = mod$1(G * H); - var T3 = mod$1(E * H); - var Z3 = mod$1(F * G); - return new ExtendedPoint(X3, Y3, Z3, T3); - } - }, { - key: "add", - value: function add(other) { - assertExtPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z, - T1 = this.t; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z, - T2 = other.t; - var A = mod$1((Y1 - X1) * (Y2 + X2)); - var B = mod$1((Y1 + X1) * (Y2 - X2)); - var F = mod$1(B - A); - if (F === _0n$2) return this["double"](); - var C = mod$1(Z1 * _2n$2 * T2); - var D = mod$1(T1 * _2n$2 * Z2); - var E = D + C; - var G = B + A; - var H = D - C; - var X3 = mod$1(E * F); - var Y3 = mod$1(G * H); - var T3 = mod$1(E * H); - var Z3 = mod$1(F * G); - return new ExtendedPoint(X3, Y3, Z3, T3); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "precomputeWindow", - value: function precomputeWindow(W) { - var windows = 1 + 256 / W; - var points = []; - var p = this; - var base = p; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; - for (var window = 0; window < windows; window++) { - base = p; - points.push(base); + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; - for (var i = 1; i < Math.pow(2, W - 1); i++) { - base = base.add(p); - points.push(base); - } + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; - p = base["double"](); - } + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // - return points; - } - }, { - key: "wNAF", - value: function wNAF(n, affinePoint) { - if (!affinePoint && this.equals(ExtendedPoint.BASE)) affinePoint = Point$1.BASE; - var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - if (256 % W) { - throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); - } + BN.red = function red(num) { + return new Red(num); + }; - var precomputes = affinePoint && pointPrecomputes$1.get(affinePoint); + BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; - if (!precomputes) { - precomputes = this.precomputeWindow(W); + BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; - if (affinePoint && W !== 1) { - precomputes = ExtendedPoint.normalizeZ(precomputes); - pointPrecomputes$1.set(affinePoint, precomputes); - } - } + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; - var p = ExtendedPoint.ZERO; - var f = ExtendedPoint.BASE; - var windows = 1 + 256 / W; - var windowSize = Math.pow(2, W - 1); - var mask = BigInt(Math.pow(2, W) - 1); - var maxNumber = Math.pow(2, W); - var shiftBy = BigInt(W); + BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - for (var window = 0; window < windows; window++) { - var offset = window * windowSize; - var wbits = Number(n & mask); - n >>= shiftBy; + BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n$2; - } + BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - var offset1 = offset; - var offset2 = offset + Math.abs(wbits) - 1; - var cond1 = window % 2 !== 0; - var cond2 = wbits < 0; + BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - if (wbits === 0) { - f = f.add(constTimeNegate$1(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate$1(cond2, precomputes[offset2])); - } - } + BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - return ExtendedPoint.normalizeZ([p, f])[0]; - } - }, { - key: "multiply", - value: function multiply(scalar, affinePoint) { - return this.wNAF(normalizeScalar$1(scalar, CURVE$1.l), affinePoint); - } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - var n = normalizeScalar$1(scalar, CURVE$1.l, false); - var G = ExtendedPoint.BASE; - var P0 = ExtendedPoint.ZERO; - if (n === _0n$2) return P0; - if (this.equals(P0) || n === _1n$2) return this; - if (this.equals(G)) return this.wNAF(n); - var p = P0; - var d = this; + BN.prototype.redShl = function redShl(num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; - while (n > _0n$2) { - if (n & _1n$2) p = p.add(d); - d = d["double"](); - n >>= _1n$2; - } + BN.prototype.redMul = function redMul(num) { + assert(this.red, 'redMul works only with red numbers'); - return p; - } - }, { - key: "isSmallOrder", - value: function isSmallOrder() { - return this.multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); - } - }, { - key: "isTorsionFree", - value: function isTorsionFree() { - var p = this.multiplyUnsafe(CURVE$1.l / _2n$2)["double"](); - if (CURVE$1.l % _2n$2) p = p.add(this); - return p.equals(ExtendedPoint.ZERO); - } - }, { - key: "toAffine", - value: function toAffine(invZ) { - var x = this.x, - y = this.y, - z = this.z; - var is0 = this.equals(ExtendedPoint.ZERO); - if (invZ == null) invZ = is0 ? _8n$1 : invert$1(z); - var ax = mod$1(x * invZ); - var ay = mod$1(y * invZ); - var zz = mod$1(z * invZ); - if (is0) return Point$1.ZERO; - if (zz !== _1n$2) throw new Error('invZ was invalid'); - return new Point$1(ax, ay); - } - }, { - key: "fromRistrettoBytes", - value: function fromRistrettoBytes() { - legacyRist(); - } - }, { - key: "toRistrettoBytes", - value: function toRistrettoBytes() { - legacyRist(); - } - }, { - key: "fromRistrettoHash", - value: function fromRistrettoHash() { - legacyRist(); - } - }], [{ - key: "fromAffine", - value: function fromAffine(p) { - if (!(p instanceof Point$1)) { - throw new TypeError('ExtendedPoint#fromAffine: expected Point'); - } + this.red._verify2(this, num); - if (p.equals(Point$1.ZERO)) return ExtendedPoint.ZERO; - return new ExtendedPoint(p.x, p.y, _1n$2, mod$1(p.x * p.y)); - } - }, { - key: "toAffineBatch", - value: function toAffineBatch(points) { - var toInv = invertBatch$1(points.map(function (p) { - return p.z; - })); - return points.map(function (p, i) { - return p.toAffine(toInv[i]); - }); - } - }, { - key: "normalizeZ", - value: function normalizeZ(points) { - return this.toAffineBatch(points).map(this.fromAffine); - } - }]); + return this.red.mul(this, num); + }; - return ExtendedPoint; -}(); + BN.prototype.redIMul = function redIMul(num) { + assert(this.red, 'redMul works only with red numbers'); -ExtendedPoint.BASE = new ExtendedPoint(CURVE$1.Gx, CURVE$1.Gy, _1n$2, mod$1(CURVE$1.Gx * CURVE$1.Gy)); -ExtendedPoint.ZERO = new ExtendedPoint(_0n$2, _1n$2, _1n$2, _0n$2); + this.red._verify2(this, num); -function constTimeNegate$1(condition, item) { - var neg = item.negate(); - return condition ? neg : item; -} + return this.red.imul(this, num); + }; -function assertExtPoint(other) { - if (!(other instanceof ExtendedPoint)) throw new TypeError('ExtendedPoint expected'); -} + BN.prototype.redSqr = function redSqr() { + assert(this.red, 'redSqr works only with red numbers'); -function assertRstPoint(other) { - if (!(other instanceof RistrettoPoint)) throw new TypeError('RistrettoPoint expected'); -} + this.red._verify1(this); -function legacyRist() { - throw new Error('Legacy method: switch to RistrettoPoint'); -} + return this.red.sqr(this); + }; -var RistrettoPoint = /*#__PURE__*/function () { - function RistrettoPoint(ep) { - _classCallCheck(this, RistrettoPoint); + BN.prototype.redISqr = function redISqr() { + assert(this.red, 'redISqr works only with red numbers'); - this.ep = ep; - } + this.red._verify1(this); - _createClass(RistrettoPoint, [{ - key: "toRawBytes", - value: function toRawBytes() { - var _this$ep = this.ep, - x = _this$ep.x, - y = _this$ep.y, - z = _this$ep.z, - t = _this$ep.t; - var u1 = mod$1(mod$1(z + y) * mod$1(z - y)); - var u2 = mod$1(x * y); - var u2sq = mod$1(u2 * u2); + return this.red.isqr(this); + }; // Square root over p - var _invertSqrt = invertSqrt(mod$1(u1 * u2sq)), - invsqrt = _invertSqrt.value; - var D1 = mod$1(invsqrt * u1); - var D2 = mod$1(invsqrt * u2); - var zInv = mod$1(D1 * D2 * t); - var D; + BN.prototype.redSqrt = function redSqrt() { + assert(this.red, 'redSqrt works only with red numbers'); - if (edIsNegative(t * zInv)) { - var _x = mod$1(y * SQRT_M1); + this.red._verify1(this); - var _y = mod$1(x * SQRT_M1); + return this.red.sqrt(this); + }; - x = _x; - y = _y; - D = mod$1(D1 * INVSQRT_A_MINUS_D); - } else { - D = D2; - } + BN.prototype.redInvm = function redInvm() { + assert(this.red, 'redInvm works only with red numbers'); - if (edIsNegative(x * zInv)) y = mod$1(-y); - var s = mod$1((z - y) * D); - if (edIsNegative(s)) s = mod$1(-s); - return numberTo32BytesLE(s); - } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); - } - }, { - key: "toString", - value: function toString() { - return this.toHex(); - } - }, { - key: "equals", - value: function equals(other) { - assertRstPoint(other); - var a = this.ep; - var b = other.ep; - var one = mod$1(a.x * b.y) === mod$1(a.y * b.x); - var two = mod$1(a.y * b.y) === mod$1(a.x * b.x); - return one || two; - } - }, { - key: "add", - value: function add(other) { - assertRstPoint(other); - return new RistrettoPoint(this.ep.add(other.ep)); - } - }, { - key: "subtract", - value: function subtract(other) { - assertRstPoint(other); - return new RistrettoPoint(this.ep.subtract(other.ep)); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return new RistrettoPoint(this.ep.multiply(scalar)); - } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - return new RistrettoPoint(this.ep.multiplyUnsafe(scalar)); - } - }], [{ - key: "calcElligatorRistrettoMap", - value: function calcElligatorRistrettoMap(r0) { - var d = CURVE$1.d; - var r = mod$1(SQRT_M1 * r0 * r0); - var Ns = mod$1((r + _1n$2) * ONE_MINUS_D_SQ); - var c = BigInt(-1); - var D = mod$1((c - d * r) * mod$1(r + d)); + this.red._verify1(this); - var _uvRatio = uvRatio(Ns, D), - Ns_D_is_sq = _uvRatio.isValid, - s = _uvRatio.value; + return this.red.invm(this); + }; // Return negative clone of `this` % `red modulo` - var s_ = mod$1(s * r0); - if (!edIsNegative(s_)) s_ = mod$1(-s_); - if (!Ns_D_is_sq) s = s_; - if (!Ns_D_is_sq) c = r; - var Nt = mod$1(c * (r - _1n$2) * D_MINUS_ONE_SQ - D); - var s2 = s * s; - var W0 = mod$1((s + s) * D); - var W1 = mod$1(Nt * SQRT_AD_MINUS_ONE); - var W2 = mod$1(_1n$2 - s2); - var W3 = mod$1(_1n$2 + s2); - return new ExtendedPoint(mod$1(W0 * W3), mod$1(W2 * W1), mod$1(W1 * W3), mod$1(W0 * W2)); - } - }, { - key: "hashToCurve", - value: function hashToCurve(hex) { - hex = ensureBytes$1(hex, 64); - var r1 = bytes255ToNumberLE(hex.slice(0, 32)); - var R1 = this.calcElligatorRistrettoMap(r1); - var r2 = bytes255ToNumberLE(hex.slice(32, 64)); - var R2 = this.calcElligatorRistrettoMap(r2); - return new RistrettoPoint(R1.add(R2)); - } - }, { - key: "fromHex", - value: function fromHex(hex) { - hex = ensureBytes$1(hex, 32); - var a = CURVE$1.a, - d = CURVE$1.d; - var emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; - var s = bytes255ToNumberLE(hex); - if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s)) throw new Error(emsg); - var s2 = mod$1(s * s); - var u1 = mod$1(_1n$2 + a * s2); - var u2 = mod$1(_1n$2 - a * s2); - var u1_2 = mod$1(u1 * u1); - var u2_2 = mod$1(u2 * u2); - var v = mod$1(a * d * u1_2 - u2_2); - var _invertSqrt2 = invertSqrt(mod$1(v * u2_2)), - isValid = _invertSqrt2.isValid, - I = _invertSqrt2.value; + BN.prototype.redNeg = function redNeg() { + assert(this.red, 'redNeg works only with red numbers'); - var Dx = mod$1(I * u2); - var Dy = mod$1(I * Dx * v); - var x = mod$1((s + s) * Dx); - if (edIsNegative(x)) x = mod$1(-x); - var y = mod$1(u1 * Dy); - var t = mod$1(x * y); - if (!isValid || edIsNegative(t) || y === _0n$2) throw new Error(emsg); - return new RistrettoPoint(new ExtendedPoint(x, y, _1n$2, t)); - } - }]); + this.red._verify1(this); - return RistrettoPoint; -}(); + return this.red.neg(this); + }; -RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE); -RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO); -var pointPrecomputes$1 = new WeakMap(); + BN.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, 'redPow(normalNum)'); -var Point$1 = /*#__PURE__*/function () { - function Point(x, y) { - _classCallCheck(this, Point); + this.red._verify1(this); - this.x = x; - this.y = y; - } + return this.red.pow(this, num); + }; // Prime numbers with efficient reduction - _createClass(Point, [{ - key: "_setWindowSize", - value: function _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes$1["delete"](this); - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var bytes = numberTo32BytesLE(this.y); - bytes[31] |= this.x & _1n$2 ? 0x80 : 0; - return bytes; - } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); - } - }, { - key: "toX25519", - value: function toX25519() { - var y = this.y; - var u = mod$1((_1n$2 + y) * invert$1(_1n$2 - y)); - return numberTo32BytesLE(u); - } - }, { - key: "isTorsionFree", - value: function isTorsionFree() { - return ExtendedPoint.fromAffine(this).isTorsionFree(); - } - }, { - key: "equals", - value: function equals(other) { - return this.x === other.x && this.y === other.y; - } - }, { - key: "negate", - value: function negate() { - return new Point(mod$1(-this.x), this.y); - } - }, { - key: "add", - value: function add(other) { - return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine(); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine(); + + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; // Pseudo-Mersenne prime + + function MPrime(name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); } - }], [{ - key: "fromHex", - value: function fromHex(hex) { - var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var d = CURVE$1.d, - P = CURVE$1.P; - hex = ensureBytes$1(hex, 32); - var normed = hex.slice(); - normed[31] = hex[31] & ~0x80; - var y = bytesToNumberLE(normed); - if (strict && y >= P) throw new Error('Expected 0 < hex < P'); - if (!strict && y >= POW_2_256$1) throw new Error('Expected 0 < hex < 2**256'); - var y2 = mod$1(y * y); - var u = mod$1(y2 - _1n$2); - var v = mod$1(d * y2 + _1n$2); - var _uvRatio2 = uvRatio(u, v), - isValid = _uvRatio2.isValid, - x = _uvRatio2.value; + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); - var isXOdd = (x & _1n$2) === _1n$2; - var isLastByteOdd = (hex[31] & 0x80) !== 0; + MPrime.prototype.ireduce = function ireduce(num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; - if (isLastByteOdd !== isXOdd) { - x = mod$1(-x); + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } } - return new Point(x, y); + return r; + }; + + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + + function K256() { + MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } - }, { - key: "fromPrivateKey", - value: function () { - var _fromPrivateKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(privateKey) { - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return getExtendedPublicKey(privateKey); - case 2: - return _context.abrupt("return", _context.sent.point); + inherits(K256, MPrime); - case 3: - case "end": - return _context.stop(); - } - }, _callee); - })); + K256.prototype.split = function split(input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + var outLen = Math.min(input.length, 9); - function fromPrivateKey(_x2) { - return _fromPrivateKey.apply(this, arguments); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; } - return fromPrivateKey; - }() - }]); + output.length = outLen; - return Point; -}(); + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } // Shift by 9 limbs -Point$1.BASE = new Point$1(CURVE$1.Gx, CURVE$1.Gy); -Point$1.ZERO = new Point$1(_0n$2, _1n$2); -var Signature$1 = /*#__PURE__*/function () { - function Signature(r, s) { - _classCallCheck(this, Signature); + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - this.r = r; - this.s = s; - this.assertValidity(); - } + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } - _createClass(Signature, [{ - key: "assertValidity", - value: function assertValidity() { - var r = this.r, - s = this.s; - if (!(r instanceof Point$1)) throw new Error('Expected Point instance'); - normalizeScalar$1(s, CURVE$1.l, false); - return this; - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var u8 = new Uint8Array(64); - u8.set(this.r.toRawBytes()); - u8.set(numberTo32BytesLE(this.s), 32); - return u8; + prev >>>= 22; + input.words[i - 10] = prev; + + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + + var lo = 0; + + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + (lo / 0x4000000 | 0); + } // Fast length reduction + + + if (num.words[num.length - 1] === 0) { + num.length--; + + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + + return num; + }; + + function P224() { + MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); + + inherits(P224, MPrime); + + function P192() { + MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } - }], [{ - key: "fromHex", - value: function fromHex(hex) { - var bytes = ensureBytes$1(hex, 64); - var r = Point$1.fromHex(bytes.slice(0, 32), false); - var s = bytesToNumberLE(bytes.slice(32, 64)); - return new Signature(r, s); + + inherits(P192, MPrime); + + function P25519() { + // 2 ^ 255 - 19 + MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } - }]); - return Signature; -}(); + inherits(P25519, MPrime); -function concatBytes$1() { - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } + P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; - if (!arrays.every(function (a) { - return a instanceof Uint8Array; - })) throw new Error('Expected Uint8Array list'); - if (arrays.length === 1) return arrays[0]; - var length = arrays.reduce(function (a, arr) { - return a + arr.length; - }, 0); - var result = new Uint8Array(length); + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } - for (var i = 0, pad = 0; i < arrays.length; i++) { - var arr = arrays[i]; - result.set(arr, pad); - pad += arr.length; - } + if (carry !== 0) { + num.words[num.length++] = carry; + } - return result; -} + return num; + }; // Exported mostly for testing purposes, use plain name instead -var hexes$1 = Array.from({ - length: 256 -}, function (v, i) { - return i.toString(16).padStart(2, '0'); -}); -function bytesToHex$1(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); - var hex = ''; + BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) return primes[name]; + var prime; - for (var i = 0; i < uint8a.length; i++) { - hex += hexes$1[uint8a[i]]; - } + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } - return hex; -} + primes[name] = prime; + return prime; + }; // + // Base reduction engine + // -function hexToBytes$1(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); - } - if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); - var array = new Uint8Array(hex.length / 2); + function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); - for (var i = 0; i < array.length; i++) { - var j = i * 2; - var hexByte = hex.slice(j, j + 2); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } - var _byte = Number.parseInt(hexByte, 16); + Red.prototype._verify1 = function _verify1(a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); - array[i] = _byte; - } + Red.prototype._verify2 = function _verify2(a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, 'red works only with red numbers'); + }; - return array; -} + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; -function numberTo32BytesBE(num) { - var length = 32; - var hex = num.toString(16).padStart(length * 2, '0'); - return hexToBytes$1(hex); -} + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } -function numberTo32BytesLE(num) { - return numberTo32BytesBE(num).reverse(); -} + return this.m.sub(a)._forceRed(this); + }; -function edIsNegative(num) { - return (mod$1(num) & _1n$2) === _1n$2; -} + Red.prototype.add = function add(a, b) { + this._verify2(a, b); -function bytesToNumberLE(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); - return BigInt('0x' + bytesToHex$1(Uint8Array.from(uint8a).reverse())); -} + var res = a.add(b); -var MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } -function bytes255ToNumberLE(bytes) { - return mod$1(bytesToNumberLE(bytes) & MAX_255B); -} + return res._forceRed(this); + }; -function mod$1(a) { - var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - var res = a % b; - return res >= _0n$2 ? res : b + res; -} + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); -function invert$1(number) { - var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var res = a.iadd(b); - if (number === _0n$2 || modulo <= _0n$2) { - throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); - } + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + + return res; + }; + + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + + var res = a.sub(b); - var a = mod$1(number, modulo); - var b = modulo; - var x = _0n$2, - u = _1n$2; + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } - while (a !== _0n$2) { - var q = b / a; - var r = b % a; - var m = x - u * q; - b = a, a = r, x = u, u = m; - } + return res._forceRed(this); + }; - var gcd = b; - if (gcd !== _1n$2) throw new Error('invert: does not exist'); - return mod$1(x, modulo); -} + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); -function invertBatch$1(nums) { - var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - var tmp = new Array(nums.length); - var lastMultiplied = nums.reduce(function (acc, num, i) { - if (num === _0n$2) return acc; - tmp[i] = acc; - return mod$1(acc * num, p); - }, _1n$2); - var inverted = invert$1(lastMultiplied, p); - nums.reduceRight(function (acc, num, i) { - if (num === _0n$2) return acc; - tmp[i] = mod$1(acc * tmp[i], p); - return mod$1(acc * num, p); - }, inverted); - return tmp; -} + var res = a.isub(b); -function pow2$1(x, power) { - var P = CURVE$1.P; - var res = x; + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } - while (power-- > _0n$2) { - res *= res; - res %= P; - } + return res; + }; - return res; -} + Red.prototype.shl = function shl(a, num) { + this._verify1(a); -function pow_2_252_3(x) { - var P = CURVE$1.P; + return this.imod(a.ushln(num)); + }; - var _5n = BigInt(5); + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); - var _10n = BigInt(10); + return this.imod(a.imul(b)); + }; - var _20n = BigInt(20); + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); - var _40n = BigInt(40); + return this.imod(a.mul(b)); + }; - var _80n = BigInt(80); + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; - var x2 = x * x % P; - var b2 = x2 * x % P; - var b4 = pow2$1(b2, _2n$2) * b2 % P; - var b5 = pow2$1(b4, _1n$2) * x % P; - var b10 = pow2$1(b5, _5n) * b5 % P; - var b20 = pow2$1(b10, _10n) * b10 % P; - var b40 = pow2$1(b20, _20n) * b20 % P; - var b80 = pow2$1(b40, _40n) * b40 % P; - var b160 = pow2$1(b80, _80n) * b80 % P; - var b240 = pow2$1(b160, _80n) * b80 % P; - var b250 = pow2$1(b240, _10n) * b10 % P; - var pow_p_5_8 = pow2$1(b250, _2n$2) * x % P; - return { - pow_p_5_8: pow_p_5_8, - b2: b2 - }; -} + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; -function uvRatio(u, v) { - var v3 = mod$1(v * v * v); - var v7 = mod$1(v3 * v3 * v); - var pow = pow_2_252_3(u * v7).pow_p_5_8; - var x = mod$1(u * v3 * pow); - var vx2 = mod$1(v * x * x); - var root1 = x; - var root2 = mod$1(x * SQRT_M1); - var useRoot1 = vx2 === u; - var useRoot2 = vx2 === mod$1(-u); - var noRoot = vx2 === mod$1(-u * SQRT_M1); - if (useRoot1) x = root1; - if (useRoot2 || noRoot) x = root2; - if (edIsNegative(x)) x = mod$1(-x); - return { - isValid: useRoot1 || useRoot2, - value: x - }; -} + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); // Fast case -function invertSqrt(number) { - return uvRatio(_1n$2, number); -} + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) -function modlLE(hash) { - return mod$1(bytesToNumberLE(hash), CURVE$1.l); -} -function equalBytes(b1, b2) { - if (b1.length !== b2.length) { - return false; - } + var q = this.m.subn(1); + var s = 0; - for (var i = 0; i < b1.length; i++) { - if (b1[i] !== b2[i]) { - return false; - } - } + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } - return true; -} + assert(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. -function ensureBytes$1(hex, expectedLength) { - var bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex); - if (typeof expectedLength === 'number' && bytes.length !== expectedLength) throw new Error("Expected ".concat(expectedLength, " bytes")); - return bytes; -} + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); -function normalizeScalar$1(num, max) { - var strict = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; - if (!max) throw new TypeError('Specify max value'); - if (typeof num === 'number' && Number.isSafeInteger(num)) num = BigInt(num); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - if (typeof num === 'bigint' && num < max) { - if (strict) { - if (_0n$2 < num) return num; - } else { - if (_0n$2 <= num) return num; - } - } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; - throw new TypeError('Expected valid scalar: 0 < scalar < max'); -} + while (t.cmp(one) !== 0) { + var tmp = t; -function adjustBytes25519(bytes) { - bytes[0] &= 248; - bytes[31] &= 127; - bytes[31] |= 64; - return bytes; -} + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } -function checkPrivateKey(key) { - key = typeof key === 'bigint' || typeof key === 'number' ? numberTo32BytesBE(normalizeScalar$1(key, POW_2_256$1)) : ensureBytes$1(key); - if (key.length !== 32) throw new Error("Expected 32 bytes"); - return key; -} + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } -function getKeyFromHash(hashed) { - var head = adjustBytes25519(hashed.slice(0, 32)); - var prefix = hashed.slice(32, 64); - var scalar = modlLE(head); - var point = Point$1.BASE.multiply(scalar); - var pointBytes = point.toRawBytes(); - return { - head: head, - prefix: prefix, - scalar: scalar, - point: point, - pointBytes: pointBytes - }; -} + return r; + }; -var _sha512Sync; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); -function sha512s() { - if (typeof _sha512Sync !== 'function') throw new Error('utils.sha512Sync must be set to use sync methods'); - return _sha512Sync.apply(void 0, arguments); -} + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; -function getExtendedPublicKey(_x3) { - return _getExtendedPublicKey.apply(this, arguments); -} + Red.prototype.pow = function pow(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; -function _getExtendedPublicKey() { - _getExtendedPublicKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) { - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.t0 = getKeyFromHash; - _context3.next = 3; - return utils$1.sha512(checkPrivateKey(key)); + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } - case 3: - _context3.t1 = _context3.sent; - return _context3.abrupt("return", (0, _context3.t0)(_context3.t1)); + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; - case 5: - case "end": - return _context3.stop(); + if (start === 0) { + start = 26; } - }, _callee3); - })); - return _getExtendedPublicKey.apply(this, arguments); -} -function getExtendedPublicKeySync(key) { - return getKeyFromHash(sha512s(checkPrivateKey(key))); -} + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; -function getPublicKeySync(privateKey) { - return getExtendedPublicKeySync(privateKey).pointBytes; -} + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; -function signSync$1(message, privateKey) { - message = ensureBytes$1(message); + if (res !== wnd[0]) { + res = this.sqr(res); + } - var _getExtendedPublicKey2 = getExtendedPublicKeySync(privateKey), - prefix = _getExtendedPublicKey2.prefix, - scalar = _getExtendedPublicKey2.scalar, - pointBytes = _getExtendedPublicKey2.pointBytes; + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - var r = modlLE(sha512s(prefix, message)); - var R = Point$1.BASE.multiply(r); - var k = modlLE(sha512s(R.toRawBytes(), pointBytes, message)); - var s = mod$1(r + k * scalar, CURVE$1.l); - return new Signature$1(R, s).toRawBytes(); -} + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } -function prepareVerification(sig, message, publicKey) { - message = ensureBytes$1(message); - if (!(publicKey instanceof Point$1)) publicKey = Point$1.fromHex(publicKey, false); + start = 26; + } - var _ref = sig instanceof Signature$1 ? sig.assertValidity() : Signature$1.fromHex(sig), - r = _ref.r, - s = _ref.s; + return res; + }; - var SB = ExtendedPoint.BASE.multiplyUnsafe(s); - return { - r: r, - s: s, - SB: SB, - pub: publicKey, - msg: message - }; -} + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; -function finishVerification(publicKey, r, SB, hashed) { - var k = modlLE(hashed); - var kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k); - var RkA = ExtendedPoint.fromAffine(r).add(kA); - return RkA.subtract(SB).multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); -} + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; // + // Montgomery method engine + // -function verifySync(sig, message, publicKey) { - var _prepareVerification = prepareVerification(sig, message, publicKey), - r = _prepareVerification.r, - SB = _prepareVerification.SB, - msg = _prepareVerification.msg, - pub = _prepareVerification.pub; - var hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg); - return finishVerification(pub, r, SB, hashed); -} + BN.mont = function mont(num) { + return new Mont(num); + }; -var sync = { - getExtendedPublicKey: getExtendedPublicKeySync, - getPublicKey: getPublicKeySync, - sign: signSync$1, - verify: verifySync -}; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); -Point$1.BASE._setWindowSize(8); -var crypto$2 = { - node: nodeCrypto, - web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined -}; -var utils$1 = { - bytesToHex: bytesToHex$1, - hexToBytes: hexToBytes$1, - concatBytes: concatBytes$1, - getExtendedPublicKey: getExtendedPublicKey, - mod: mod$1, - invert: invert$1, - TORSION_SUBGROUP: ['0100000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', '0000000000000000000000000000000000000000000000000000000000000080', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', '0000000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa'], - hashToPrivateScalar: function hashToPrivateScalar(hash) { - hash = ensureBytes$1(hash); - if (hash.length < 40 || hash.length > 1024) throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); - return mod$1(bytesToNumberLE(hash), CURVE$1.l - _1n$2) + _1n$2; - }, - randomBytes: function randomBytes() { - var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } - if (crypto$2.web) { - return crypto$2.web.getRandomValues(new Uint8Array(bytesLength)); - } else if (crypto$2.node) { - var randomBytes = crypto$2.node.randomBytes; - return new Uint8Array(randomBytes(bytesLength).buffer); - } else { - throw new Error("The environment doesn't have randomBytes function"); + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); } - }, - randomPrivateKey: function randomPrivateKey() { - return utils$1.randomBytes(32); - }, - sha512: function () { - var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var message, - buffer, - _args2 = arguments; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - message = concatBytes$1.apply(void 0, _args2); - if (!crypto$2.web) { - _context2.next = 8; - break; - } + inherits(Mont, Red); - _context2.next = 4; - return crypto$2.web.subtle.digest('SHA-512', message.buffer); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; - case 4: - buffer = _context2.sent; - return _context2.abrupt("return", new Uint8Array(buffer)); + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - case 8: - if (!crypto$2.node) { - _context2.next = 12; - break; - } + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - return _context2.abrupt("return", Uint8Array.from(crypto$2.node.createHash('sha512').update(message).digest())); + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; - case 12: - throw new Error("The environment doesn't have sha512 function"); + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - case 13: - case "end": - return _context2.stop(); - } - }, _callee2); - })); + return res._forceRed(this); + }; - function sha512() { - return _sha.apply(this, arguments); - } + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; - return sha512; - }(), - precompute: function precompute() { - var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; - var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point$1.BASE; - var cached = point.equals(Point$1.BASE) ? point : new Point$1(point.x, point.y); + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - cached._setWindowSize(windowSize); + return res._forceRed(this); + }; - cached.multiply(_2n$2); - return cached; - }, - sha512Sync: undefined -}; -Object.defineProperties(utils$1, { - sha512Sync: { - configurable: false, - get: function get() { - return _sha512Sync; - }, - set: function set(val) { - if (!_sha512Sync) _sha512Sync = val; - } - } -}); + Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, commonjsGlobal); +})(bn$1); + +var BN$1 = bn$1.exports; var safeBuffer = {exports: {}}; @@ -8123,7 +8125,7 @@ var safeBuffer = {exports: {}}; (function (module, exports) { /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0$1; + var buffer = require$$1$1; var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { @@ -8202,7 +8204,7 @@ var safeBuffer = {exports: {}}; var _Buffer = safeBuffer.exports.Buffer; -function base(ALPHABET) { +function base$1(ALPHABET) { if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long'); } @@ -8378,12 +8380,12 @@ function base(ALPHABET) { }; } -var src = base; +var src$1 = base$1; -var basex = src; -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; -var bs58 = basex(ALPHABET); -var bs58$1 = bs58; +var basex$1 = src$1; +var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +var bs58$2 = basex$1(ALPHABET$1); +var bs58$3 = bs58$2; var Chi = function Chi(a, b, c) { return a & b ^ ~a & c; @@ -9218,7 +9220,7 @@ var deserializeUnchecked_1 = lib$1.deserializeUnchecked = deserialize_1 = lib$1. var bn_js_1 = __importDefault(bn$1.exports); -var bs58_1 = __importDefault(bs58); // TODO: Make sure this polyfill not included when not required +var bs58_1 = __importDefault(bs58$2); // TODO: Make sure this polyfill not included when not required var encoding = __importStar(require$$2); @@ -9790,7 +9792,7 @@ Object.defineProperty(Layout$3, "__esModule", { }); Layout$3.s16 = Layout$3.s8 = Layout$3.nu64be = Layout$3.u48be = Layout$3.u40be = Layout$3.u32be = Layout$3.u24be = Layout$3.u16be = nu64$1 = Layout$3.nu64 = Layout$3.u48 = Layout$3.u40 = u32 = Layout$3.u32 = Layout$3.u24 = u16 = Layout$3.u16 = u8 = Layout$3.u8 = offset$1 = Layout$3.offset = Layout$3.greedy = Layout$3.Constant = Layout$3.UTF8 = Layout$3.CString = Layout$3.Blob = Layout$3.Boolean = Layout$3.BitField = Layout$3.BitStructure = Layout$3.VariantLayout = Layout$3.Union = Layout$3.UnionLayoutDiscriminator = Layout$3.UnionDiscriminator = Layout$3.Structure = Layout$3.Sequence = Layout$3.DoubleBE = Layout$3.Double = Layout$3.FloatBE = Layout$3.Float = Layout$3.NearInt64BE = Layout$3.NearInt64 = Layout$3.NearUInt64BE = Layout$3.NearUInt64 = Layout$3.IntBE = Layout$3.Int = Layout$3.UIntBE = Layout$3.UInt = Layout$3.OffsetLayout = Layout$3.GreedyCount = Layout$3.ExternalLayout = Layout$3.bindConstructorLayout = Layout$3.nameWithProperty = Layout$3.Layout = Layout$3.uint8ArrayToBuffer = Layout$3.checkUint8Array = void 0; Layout$3.constant = Layout$3.utf8 = Layout$3.cstr = blob$1 = Layout$3.blob = Layout$3.unionLayoutDiscriminator = Layout$3.union = seq$1 = Layout$3.seq = Layout$3.bits = struct = Layout$3.struct = Layout$3.f64be = Layout$3.f64 = Layout$3.f32be = Layout$3.f32 = Layout$3.ns64be = Layout$3.s48be = Layout$3.s40be = Layout$3.s32be = Layout$3.s24be = Layout$3.s16be = ns64 = Layout$3.ns64 = Layout$3.s48 = Layout$3.s40 = Layout$3.s32 = Layout$3.s24 = void 0; -var buffer_1 = require$$0$1; +var buffer_1 = require$$1$1; /* Check if a value is a Uint8Array. * * @ignore */ @@ -14536,7 +14538,7 @@ function stringToBytes(str) { } var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; function v35 (name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { if (typeof value === 'string') { @@ -14581,7 +14583,7 @@ function v35 (name, version, hashfunc) { generateUUID.DNS = DNS; - generateUUID.URL = URL; + generateUUID.URL = URL$1; return generateUUID; } @@ -16144,57 +16146,572 @@ function requireEventemitter3() { // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt); - } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt); + } + + return this; + }; + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + + + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; // + // Alias methods names because people roll like that. + // + + + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; // + // Expose the prefix. + // + + EventEmitter.prefixed = prefix; // + // Allow `EventEmitter` to be imported as module namespace. + // + + EventEmitter.EventEmitter = EventEmitter; // + // Expose the module. + // + + { + module.exports = EventEmitter; + } + })(eventemitter3); + + return eventemitter3.exports; +} + +(function (exports) { + + var _interopRequireDefault = interopRequireDefault.exports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + + var _regenerator = _interopRequireDefault(requireRegenerator()); + + var _asyncToGenerator2 = _interopRequireDefault(requireAsyncToGenerator()); + + var _typeof2 = _interopRequireDefault(require_typeof()); + + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + + var _createClass2 = _interopRequireDefault(requireCreateClass()); + + var _inherits2 = _interopRequireDefault(requireInherits()); + + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + + var _eventemitter = requireEventemitter3(); + + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = (0, _getPrototypeOf2["default"])(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return (0, _possibleConstructorReturn2["default"])(this, result); + }; + } + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + var __rest = function (s, e) { + var t = {}; + + for (var p in s) { + if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + } + + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + }; // @ts-ignore + + + var CommonClient = /*#__PURE__*/function (_EventEmitter) { + (0, _inherits2["default"])(CommonClient, _EventEmitter); + + var _super = _createSuper(CommonClient); + /** + * Instantiate a Client class. + * @constructor + * @param {webSocketFactory} webSocketFactory - factory method for WebSocket + * @param {String} address - url to a websocket server + * @param {Object} options - ws options object with reconnect parameters + * @param {Function} generate_request_id - custom generation request Id + * @return {CommonClient} + */ + + + function CommonClient(webSocketFactory) { + var _this; + + var address = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "ws://localhost:8080"; + + var _a = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var generate_request_id = arguments.length > 3 ? arguments[3] : undefined; + (0, _classCallCheck2["default"])(this, CommonClient); + + var _a$autoconnect = _a.autoconnect, + autoconnect = _a$autoconnect === void 0 ? true : _a$autoconnect, + _a$reconnect = _a.reconnect, + reconnect = _a$reconnect === void 0 ? true : _a$reconnect, + _a$reconnect_interval = _a.reconnect_interval, + reconnect_interval = _a$reconnect_interval === void 0 ? 1000 : _a$reconnect_interval, + _a$max_reconnects = _a.max_reconnects, + max_reconnects = _a$max_reconnects === void 0 ? 5 : _a$max_reconnects, + rest_options = __rest(_a, ["autoconnect", "reconnect", "reconnect_interval", "max_reconnects"]); + + _this = _super.call(this); + _this.webSocketFactory = webSocketFactory; + _this.queue = {}; + _this.rpc_id = 0; + _this.address = address; + _this.autoconnect = autoconnect; + _this.ready = false; + _this.reconnect = reconnect; + _this.reconnect_timer_id = undefined; + _this.reconnect_interval = reconnect_interval; + _this.max_reconnects = max_reconnects; + _this.rest_options = rest_options; + _this.current_reconnects = 0; + + _this.generate_request_id = generate_request_id || function () { + return ++_this.rpc_id; + }; + + if (_this.autoconnect) _this._connect(_this.address, Object.assign({ + autoconnect: _this.autoconnect, + reconnect: _this.reconnect, + reconnect_interval: _this.reconnect_interval, + max_reconnects: _this.max_reconnects + }, _this.rest_options)); + return _this; + } + /** + * Connects to a defined server if not connected already. + * @method + * @return {Undefined} + */ + + + (0, _createClass2["default"])(CommonClient, [{ + key: "connect", + value: function connect() { + if (this.socket) return; + + this._connect(this.address, Object.assign({ + autoconnect: this.autoconnect, + reconnect: this.reconnect, + reconnect_interval: this.reconnect_interval, + max_reconnects: this.max_reconnects + }, this.rest_options)); + } + /** + * Calls a registered RPC method on server. + * @method + * @param {String} method - RPC method name + * @param {Object|Array} params - optional method parameters + * @param {Number} timeout - RPC reply timeout value + * @param {Object} ws_opts - options passed to ws + * @return {Promise} + */ + + }, { + key: "call", + value: function call(method, params, timeout, ws_opts) { + var _this2 = this; + + if (!ws_opts && "object" === (0, _typeof2["default"])(timeout)) { + ws_opts = timeout; + timeout = null; + } + + return new Promise(function (resolve, reject) { + if (!_this2.ready) return reject(new Error("socket not ready")); + + var rpc_id = _this2.generate_request_id(method, params); + + var message = { + jsonrpc: "2.0", + method: method, + params: params || null, + id: rpc_id + }; + + _this2.socket.send(JSON.stringify(message), ws_opts, function (error) { + if (error) return reject(error); + _this2.queue[rpc_id] = { + promise: [resolve, reject] + }; + + if (timeout) { + _this2.queue[rpc_id].timeout = setTimeout(function () { + delete _this2.queue[rpc_id]; + reject(new Error("reply timeout")); + }, timeout); + } + }); + }); + } + /** + * Logins with the other side of the connection. + * @method + * @param {Object} params - Login credentials object + * @return {Promise} + */ + + }, { + key: "login", + value: function () { + var _login = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var resp; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.call("rpc.login", params); + + case 2: + resp = _context.sent; + + if (resp) { + _context.next = 5; + break; + } + + throw new Error("authentication failed"); + + case 5: + return _context.abrupt("return", resp); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function login(_x) { + return _login.apply(this, arguments); + } + + return login; + }() + /** + * Fetches a list of client's methods registered on server. + * @method + * @return {Array} + */ + + }, { + key: "listMethods", + value: function () { + var _listMethods = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.call("__listMethods"); + + case 2: + return _context2.abrupt("return", _context2.sent); + + case 3: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function listMethods() { + return _listMethods.apply(this, arguments); + } + + return listMethods; + }() + /** + * Sends a JSON-RPC 2.0 notification to server. + * @method + * @param {String} method - RPC method name + * @param {Object} params - optional method parameters + * @return {Promise} + */ + + }, { + key: "notify", + value: function notify(method, params) { + var _this3 = this; + + return new Promise(function (resolve, reject) { + if (!_this3.ready) return reject(new Error("socket not ready")); + var message = { + jsonrpc: "2.0", + method: method, + params: params || null + }; + + _this3.socket.send(JSON.stringify(message), function (error) { + if (error) return reject(error); + resolve(); + }); + }); + } + /** + * Subscribes for a defined event. + * @method + * @param {String|Array} event - event name + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "subscribe", + value: function () { + var _subscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(event) { + var result; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + if (typeof event === "string") event = [event]; + _context3.next = 3; + return this.call("rpc.on", event); + + case 3: + result = _context3.sent; + + if (!(typeof event === "string" && result[event] !== "ok")) { + _context3.next = 6; + break; + } + + throw new Error("Failed subscribing to an event '" + event + "' with: " + result[event]); + + case 6: + return _context3.abrupt("return", result); + + case 7: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function subscribe(_x2) { + return _subscribe.apply(this, arguments); + } + + return subscribe; + }() + /** + * Unsubscribes from a defined event. + * @method + * @param {String|Array} event - event name + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "unsubscribe", + value: function () { + var _unsubscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(event) { + var result; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (typeof event === "string") event = [event]; + _context4.next = 3; + return this.call("rpc.off", event); + + case 3: + result = _context4.sent; + + if (!(typeof event === "string" && result[event] !== "ok")) { + _context4.next = 6; + break; + } + + throw new Error("Failed unsubscribing from an event with: " + result); + + case 6: + return _context4.abrupt("return", result); + + case 7: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + function unsubscribe(_x3) { + return _unsubscribe.apply(this, arguments); + } + + return unsubscribe; + }() + /** + * Closes a WebSocket connection gracefully. + * @method + * @param {Number} code - socket close code + * @param {String} data - optional data to be sent before closing + * @return {Undefined} + */ + + }, { + key: "close", + value: function close(code, data) { + this.socket.close(code || 1000, data); + } + /** + * Connection/Message handler. + * @method + * @private + * @param {String} address - WebSocket API address + * @param {Object} options - ws options object + * @return {Undefined} + */ + + }, { + key: "_connect", + value: function _connect(address, options) { + var _this4 = this; + + clearTimeout(this.reconnect_timer_id); + this.socket = this.webSocketFactory(address, options); + this.socket.addEventListener("open", function () { + _this4.ready = true; + + _this4.emit("open"); - return this; - }; - /** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ + _this4.current_reconnects = 0; + }); + this.socket.addEventListener("message", function (_ref) { + var message = _ref.data; + if (message instanceof ArrayBuffer) message = Buffer$1.from(message).toString(); + try { + message = JSON.parse(message); + } catch (error) { + return; + } // check if any listeners are attached and forward event - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } + if (message.notification && _this4.listeners(message.notification).length) { + if (!Object.keys(message.params).length) return _this4.emit(message.notification); + var args = [message.notification]; + if (message.params.constructor === Object) args.push(message.params);else // using for-loop instead of unshift/spread because performance is better + for (var i = 0; i < message.params.length; i++) { + args.push(message.params[i]); + } // run as microtask so that pending queue messages are resolved first + // eslint-disable-next-line prefer-spread - return this; - }; // - // Alias methods names because people roll like that. - // + return Promise.resolve().then(function () { + _this4.emit.apply(_this4, args); + }); + } + if (!_this4.queue[message.id]) { + // general JSON RPC 2.0 events + if (message.method && message.params) { + // run as microtask so that pending queue messages are resolved first + return Promise.resolve().then(function () { + _this4.emit(message.method, message.params); + }); + } - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; // - // Expose the prefix. - // + return; + } // reject early since server's response is invalid - EventEmitter.prefixed = prefix; // - // Allow `EventEmitter` to be imported as module namespace. - // - EventEmitter.EventEmitter = EventEmitter; // - // Expose the module. - // + if ("error" in message === "result" in message) _this4.queue[message.id].promise[1](new Error("Server response malformed. Response must include either \"result\"" + " or \"error\", but not both.")); + if (_this4.queue[message.id].timeout) clearTimeout(_this4.queue[message.id].timeout); + if (message.error) _this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result); + delete _this4.queue[message.id]; + }); + this.socket.addEventListener("error", function (error) { + return _this4.emit("error", error); + }); + this.socket.addEventListener("close", function (_ref2) { + var code = _ref2.code, + reason = _ref2.reason; + if (_this4.ready) // Delay close event until internal state is updated + setTimeout(function () { + return _this4.emit("close", code, reason); + }, 0); + _this4.ready = false; + _this4.socket = undefined; + if (code === 1000) return; + _this4.current_reconnects++; + if (_this4.reconnect && (_this4.max_reconnects > _this4.current_reconnects || _this4.max_reconnects === 0)) _this4.reconnect_timer_id = setTimeout(function () { + return _this4._connect(address, options); + }, _this4.reconnect_interval); + }); + } + }]); + return CommonClient; + }(_eventemitter.EventEmitter); - { - module.exports = EventEmitter; - } - })(eventemitter3); + exports["default"] = CommonClient; +})(client); - return eventemitter3.exports; -} +var RpcWebSocketCommonClient = /*@__PURE__*/getDefaultExportFromCjs(client); + +var websocket_browser = {}; + +/** + * WebSocket implements a browser-side WebSocket specification. + * @module Client + */ (function (exports) { @@ -16202,13 +16719,7 @@ function requireEventemitter3() { Object.defineProperty(exports, "__esModule", { value: true }); - exports["default"] = void 0; - - var _regenerator = _interopRequireDefault(requireRegenerator()); - - var _asyncToGenerator2 = _interopRequireDefault(requireAsyncToGenerator()); - - var _typeof2 = _interopRequireDefault(require_typeof()); + exports["default"] = _default; var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); @@ -16253,13513 +16764,14535 @@ function requireEventemitter3() { } } - var __rest = function (s, e) { - var t = {}; + var WebSocketBrowserImpl = /*#__PURE__*/function (_EventEmitter) { + (0, _inherits2["default"])(WebSocketBrowserImpl, _EventEmitter); - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - } + var _super = _createSuper(WebSocketBrowserImpl); + /** Instantiate a WebSocket class + * @constructor + * @param {String} address - url to a websocket server + * @param {(Object)} options - websocket options + * @param {(String|Array)} protocols - a list of protocols + * @return {WebSocketBrowserImpl} - returns a WebSocket instance + */ - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; - }; // @ts-ignore + function WebSocketBrowserImpl(address, options, protocols) { + var _this; - var CommonClient = /*#__PURE__*/function (_EventEmitter) { - (0, _inherits2["default"])(CommonClient, _EventEmitter); + (0, _classCallCheck2["default"])(this, WebSocketBrowserImpl); + _this = _super.call(this); + _this.socket = new window.WebSocket(address, protocols); - var _super = _createSuper(CommonClient); + _this.socket.onopen = function () { + return _this.emit("open"); + }; + + _this.socket.onmessage = function (event) { + return _this.emit("message", event.data); + }; + + _this.socket.onerror = function (error) { + return _this.emit("error", error); + }; + + _this.socket.onclose = function (event) { + _this.emit("close", event.code, event.reason); + }; + + return _this; + } /** - * Instantiate a Client class. - * @constructor - * @param {webSocketFactory} webSocketFactory - factory method for WebSocket - * @param {String} address - url to a websocket server - * @param {Object} options - ws options object with reconnect parameters - * @param {Function} generate_request_id - custom generation request Id - * @return {CommonClient} + * Sends data through a websocket connection + * @method + * @param {(String|Object)} data - data to be sent via websocket + * @param {Object} optionsOrCallback - ws options + * @param {Function} callback - a callback called once the data is sent + * @return {Undefined} */ - function CommonClient(webSocketFactory) { - var _this; + (0, _createClass2["default"])(WebSocketBrowserImpl, [{ + key: "send", + value: function send(data, optionsOrCallback, callback) { + var cb = callback || optionsOrCallback; + + try { + this.socket.send(data); + cb(); + } catch (error) { + cb(error); + } + } + /** + * Closes an underlying socket + * @method + * @param {Number} code - status code explaining why the connection is being closed + * @param {String} reason - a description why the connection is closing + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "close", + value: function close(code, reason) { + this.socket.close(code, reason); + } + }, { + key: "addEventListener", + value: function addEventListener(type, listener, options) { + this.socket.addEventListener(type, listener, options); + } + }]); + return WebSocketBrowserImpl; + }(_eventemitter.EventEmitter); + /** + * factory method for common WebSocket instance + * @method + * @param {String} address - url to a websocket server + * @param {(Object)} options - websocket options + * @return {Undefined} + */ + + + function _default(address, options) { + return new WebSocketBrowserImpl(address, options); + } +})(websocket_browser); + +var createRpc = /*@__PURE__*/getDefaultExportFromCjs(websocket_browser); + +var SHA3_PI = [], + SHA3_ROTL = [], + _SHA3_IOTA = []; + +var _0n$1 = BigInt(0); + +var _1n$1 = BigInt(1); + +var _2n$1 = BigInt(2); + +var _7n = BigInt(7); + +var _256n = BigInt(256); + +var _0x71n = BigInt(0x71); + +for (var round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) { + // Pi + var _ref = [y, (2 * x + 3 * y) % 5]; + x = _ref[0]; + y = _ref[1]; + SHA3_PI.push(2 * (5 * y + x)); // Rotational + + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); // Iota + + var t = _0n$1; + + for (var j = 0; j < 7; j++) { + R = (R << _1n$1 ^ (R >> _7n) * _0x71n) % _256n; + if (R & _2n$1) t ^= _1n$1 << (_1n$1 << BigInt(j)) - _1n$1; + } + + _SHA3_IOTA.push(t); +} + +var _u64$split = u64$2.split(_SHA3_IOTA, true), + _u64$split2 = _slicedToArray(_u64$split, 2), + SHA3_IOTA_H = _u64$split2[0], + SHA3_IOTA_L = _u64$split2[1]; // Left rotation (without 0, 32, 64) + + +var rotlH = function rotlH(h, l, s) { + return s > 32 ? u64$2.rotlBH(h, l, s) : u64$2.rotlSH(h, l, s); +}; + +var rotlL = function rotlL(h, l, s) { + return s > 32 ? u64$2.rotlBL(h, l, s) : u64$2.rotlSL(h, l, s); +}; // Same as keccakf1600, but allows to skip some rounds + + +function keccakP(s) { + var rounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 24; + var B = new Uint32Array(5 * 2); // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + + for (var _round2 = 24 - rounds; _round2 < 24; _round2++) { + // Theta θ + for (var _x2 = 0; _x2 < 10; _x2++) B[_x2] = s[_x2] ^ s[_x2 + 10] ^ s[_x2 + 20] ^ s[_x2 + 30] ^ s[_x2 + 40]; + + for (var _x4 = 0; _x4 < 10; _x4 += 2) { + var idx1 = (_x4 + 8) % 10; + var idx0 = (_x4 + 2) % 10; + var B0 = B[idx0]; + var B1 = B[idx0 + 1]; + var Th = rotlH(B0, B1, 1) ^ B[idx1]; + var Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + + for (var _y2 = 0; _y2 < 50; _y2 += 10) { + s[_x4 + _y2] ^= Th; + s[_x4 + _y2 + 1] ^= Tl; + } + } // Rho (ρ) and Pi (π) + + + var curH = s[2]; + var curL = s[3]; + + for (var _t2 = 0; _t2 < 24; _t2++) { + var shift = SHA3_ROTL[_t2]; + + var _Th = rotlH(curH, curL, shift); + + var _Tl = rotlL(curH, curL, shift); + + var PI = SHA3_PI[_t2]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = _Th; + s[PI + 1] = _Tl; + } // Chi (χ) + + + for (var _y4 = 0; _y4 < 50; _y4 += 10) { + for (var _x6 = 0; _x6 < 10; _x6++) B[_x6] = s[_y4 + _x6]; + + for (var _x8 = 0; _x8 < 10; _x8++) s[_y4 + _x8] ^= ~B[(_x8 + 2) % 10] & B[(_x8 + 4) % 10]; + } // Iota (ι) + + + s[0] ^= SHA3_IOTA_H[_round2]; + s[1] ^= SHA3_IOTA_L[_round2]; + } + + B.fill(0); +} +var Keccak = /*#__PURE__*/function (_Hash) { + _inherits(Keccak, _Hash); + + var _super = _createSuper(Keccak); + + // NOTE: we accept arguments in bytes instead of bits here. + function Keccak(blockLen, suffix, outputLen) { + var _this; + + var enableXOF = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var rounds = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 24; + + _classCallCheck(this, Keccak); + + _this = _super.call(this); + _this.blockLen = blockLen; + _this.suffix = suffix; + _this.outputLen = outputLen; + _this.enableXOF = enableXOF; + _this.rounds = rounds; + _this.pos = 0; + _this.posOut = 0; + _this.finished = false; + _this.destroyed = false; // Can be passed from user as dkLen + + assert$2.number(outputLen); // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + + if (0 >= _this.blockLen || _this.blockLen >= 200) throw new Error('Sha3 supports only keccak-f1600 function'); + _this.state = new Uint8Array(200); + _this.state32 = u32$1(_this.state); + return _this; + } + + _createClass(Keccak, [{ + key: "keccak", + value: function keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + }, { + key: "update", + value: function update(data) { + assert$2.exists(this); + var blockLen = this.blockLen, + state = this.state; + data = toBytes(data); + var len = data.length; + + for (var pos = 0; pos < len;) { + var take = Math.min(blockLen - this.pos, len - pos); + + for (var i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + + if (this.pos === blockLen) this.keccak(); + } + + return this; + } + }, { + key: "finish", + value: function finish() { + if (this.finished) return; + this.finished = true; + var state = this.state, + suffix = this.suffix, + pos = this.pos, + blockLen = this.blockLen; // Do the padding + + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + }, { + key: "writeInto", + value: function writeInto(out) { + assert$2.exists(this, false); + assert$2.bytes(out); + this.finish(); + var bufferOut = this.state; + var blockLen = this.blockLen; + + for (var pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) this.keccak(); + var take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + + return out; + } + }, { + key: "xofInto", + value: function xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + }, { + key: "xof", + value: function xof(bytes) { + assert$2.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + }, { + key: "digest", + value: function digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + }, { + key: "destroy", + value: function destroy() { + this.destroyed = true; + this.state.fill(0); + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + var blockLen = this.blockLen, + suffix = this.suffix, + outputLen = this.outputLen, + rounds = this.rounds, + enableXOF = this.enableXOF; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; // Suffix can change in cSHAKE + + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } + }]); + + return Keccak; +}(Hash); + +var gen = function gen(suffix, blockLen, outputLen) { + return wrapConstructor(function () { + return new Keccak(blockLen, suffix, outputLen); + }); +}; + +gen(0x06, 144, 224 / 8); +/** + * SHA3-256 hash function + * @param message - that would be hashed + */ + +gen(0x06, 136, 256 / 8); +gen(0x06, 104, 384 / 8); +gen(0x06, 72, 512 / 8); +gen(0x01, 144, 224 / 8); +/** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ + +var keccak_256 = gen(0x01, 136, 256 / 8); +gen(0x01, 104, 384 / 8); +gen(0x01, 72, 512 / 8); + +var genShake = function genShake(suffix, blockLen, outputLen) { + return wrapConstructorWithOpts(function () { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true); + }); +}; - var address = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "ws://localhost:8080"; +genShake(0x1f, 168, 128 / 8); +genShake(0x1f, 136, 256 / 8); - var _a = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +var HMAC = /*#__PURE__*/function (_Hash) { + _inherits(HMAC, _Hash); - var generate_request_id = arguments.length > 3 ? arguments[3] : undefined; - (0, _classCallCheck2["default"])(this, CommonClient); + var _super = _createSuper(HMAC); - var _a$autoconnect = _a.autoconnect, - autoconnect = _a$autoconnect === void 0 ? true : _a$autoconnect, - _a$reconnect = _a.reconnect, - reconnect = _a$reconnect === void 0 ? true : _a$reconnect, - _a$reconnect_interval = _a.reconnect_interval, - reconnect_interval = _a$reconnect_interval === void 0 ? 1000 : _a$reconnect_interval, - _a$max_reconnects = _a.max_reconnects, - max_reconnects = _a$max_reconnects === void 0 ? 5 : _a$max_reconnects, - rest_options = __rest(_a, ["autoconnect", "reconnect", "reconnect_interval", "max_reconnects"]); + function HMAC(hash, _key) { + var _this; - _this = _super.call(this); - _this.webSocketFactory = webSocketFactory; - _this.queue = {}; - _this.rpc_id = 0; - _this.address = address; - _this.autoconnect = autoconnect; - _this.ready = false; - _this.reconnect = reconnect; - _this.reconnect_timer_id = undefined; - _this.reconnect_interval = reconnect_interval; - _this.max_reconnects = max_reconnects; - _this.rest_options = rest_options; - _this.current_reconnects = 0; + _classCallCheck(this, HMAC); - _this.generate_request_id = generate_request_id || function () { - return ++_this.rpc_id; - }; + _this = _super.call(this); + _this.finished = false; + _this.destroyed = false; + assert$2.hash(hash); + var key = toBytes(_key); + _this.iHash = hash.create(); + if (typeof _this.iHash.update !== 'function') throw new TypeError('Expected instance of class which extends utils.Hash'); + _this.blockLen = _this.iHash.blockLen; + _this.outputLen = _this.iHash.outputLen; + var blockLen = _this.blockLen; + var pad = new Uint8Array(blockLen); // blockLen can be bigger than outputLen - if (_this.autoconnect) _this._connect(_this.address, Object.assign({ - autoconnect: _this.autoconnect, - reconnect: _this.reconnect, - reconnect_interval: _this.reconnect_interval, - max_reconnects: _this.max_reconnects - }, _this.rest_options)); - return _this; - } - /** - * Connects to a defined server if not connected already. - * @method - * @return {Undefined} - */ + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (var i = 0; i < pad.length; i++) pad[i] ^= 0x36; - (0, _createClass2["default"])(CommonClient, [{ - key: "connect", - value: function connect() { - if (this.socket) return; + _this.iHash.update(pad); // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone - this._connect(this.address, Object.assign({ - autoconnect: this.autoconnect, - reconnect: this.reconnect, - reconnect_interval: this.reconnect_interval, - max_reconnects: this.max_reconnects - }, this.rest_options)); - } - /** - * Calls a registered RPC method on server. - * @method - * @param {String} method - RPC method name - * @param {Object|Array} params - optional method parameters - * @param {Number} timeout - RPC reply timeout value - * @param {Object} ws_opts - options passed to ws - * @return {Promise} - */ - }, { - key: "call", - value: function call(method, params, timeout, ws_opts) { - var _this2 = this; + _this.oHash = hash.create(); // Undo internal XOR && apply outer XOR - if (!ws_opts && "object" === (0, _typeof2["default"])(timeout)) { - ws_opts = timeout; - timeout = null; - } + for (var _i2 = 0; _i2 < pad.length; _i2++) pad[_i2] ^= 0x36 ^ 0x5c; - return new Promise(function (resolve, reject) { - if (!_this2.ready) return reject(new Error("socket not ready")); + _this.oHash.update(pad); - var rpc_id = _this2.generate_request_id(method, params); + pad.fill(0); + return _this; + } - var message = { - jsonrpc: "2.0", - method: method, - params: params || null, - id: rpc_id - }; + _createClass(HMAC, [{ + key: "update", + value: function update(buf) { + assert$2.exists(this); + this.iHash.update(buf); + return this; + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.exists(this); + assert$2.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + }, { + key: "digest", + value: function digest() { + var out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + var oHash = this.oHash, + iHash = this.iHash, + finished = this.finished, + destroyed = this.destroyed, + blockLen = this.blockLen, + outputLen = this.outputLen; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + }, { + key: "destroy", + value: function destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }]); - _this2.socket.send(JSON.stringify(message), ws_opts, function (error) { - if (error) return reject(error); - _this2.queue[rpc_id] = { - promise: [resolve, reject] - }; + return HMAC; +}(Hash); +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ - if (timeout) { - _this2.queue[rpc_id].timeout = setTimeout(function () { - delete _this2.queue[rpc_id]; - reject(new Error("reply timeout")); - }, timeout); - } - }); - }); - } - /** - * Logins with the other side of the connection. - * @method - * @param {Object} params - Login credentials object - * @return {Promise} - */ - }, { - key: "login", - value: function () { - var _login = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { - var resp; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.call("rpc.login", params); +var hmac = function hmac(hash, key, message) { + return new HMAC(hash, key).update(message).digest(); +}; - case 2: - resp = _context.sent; +hmac.create = function (hash, key) { + return new HMAC(hash, key); +}; - if (resp) { - _context.next = 5; - break; - } +var _0n = BigInt(0); - throw new Error("authentication failed"); +var _1n = BigInt(1); - case 5: - return _context.abrupt("return", resp); +var _2n = BigInt(2); - case 6: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); +var _3n = BigInt(3); - function login(_x) { - return _login.apply(this, arguments); - } +var _8n = BigInt(8); - return login; - }() - /** - * Fetches a list of client's methods registered on server. - * @method - * @return {Array} - */ +var CURVE = Object.freeze({ + a: _0n, + b: BigInt(7), + P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + h: _1n, + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee') +}); - }, { - key: "listMethods", - value: function () { - var _listMethods = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this.call("__listMethods"); +var divNearest = function divNearest(a, b) { + return (a + b / _2n) / b; +}; - case 2: - return _context2.abrupt("return", _context2.sent); +var endo = { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: function splitScalar(k) { + var n = CURVE.n; + var a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + var b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + var a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + var b2 = a1; + var POW_2_128 = BigInt('0x100000000000000000000000000000000'); + var c1 = divNearest(b2 * k, n); + var c2 = divNearest(-b1 * k, n); + var k1 = mod(k - c1 * a1 - c2 * a2, n); + var k2 = mod(-c1 * b1 - c2 * b2, n); + var k1neg = k1 > POW_2_128; + var k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; - case 3: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); + } - function listMethods() { - return _listMethods.apply(this, arguments); - } + return { + k1neg: k1neg, + k1: k1, + k2neg: k2neg, + k2: k2 + }; + } +}; +var fieldLen = 32; +var groupLen = 32; +var hashLen = 32; +var compressedLen = fieldLen + 1; +var uncompressedLen = 2 * fieldLen + 1; - return listMethods; - }() - /** - * Sends a JSON-RPC 2.0 notification to server. - * @method - * @param {String} method - RPC method name - * @param {Object} params - optional method parameters - * @return {Promise} - */ +function weierstrass(x) { + var a = CURVE.a, + b = CURVE.b; + var x2 = mod(x * x); + var x3 = mod(x2 * x); + return mod(x3 + a * x + b); +} - }, { - key: "notify", - value: function notify(method, params) { - var _this3 = this; +var USE_ENDOMORPHISM = CURVE.a === _0n; - return new Promise(function (resolve, reject) { - if (!_this3.ready) return reject(new Error("socket not ready")); - var message = { - jsonrpc: "2.0", - method: method, - params: params || null - }; +var ShaError = /*#__PURE__*/function (_Error) { + _inherits(ShaError, _Error); - _this3.socket.send(JSON.stringify(message), function (error) { - if (error) return reject(error); - resolve(); - }); - }); - } - /** - * Subscribes for a defined event. - * @method - * @param {String|Array} event - event name - * @return {Undefined} - * @throws {Error} - */ + var _super = _createSuper(ShaError); - }, { - key: "subscribe", - value: function () { - var _subscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(event) { - var result; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - if (typeof event === "string") event = [event]; - _context3.next = 3; - return this.call("rpc.on", event); + function ShaError(message) { + _classCallCheck(this, ShaError); - case 3: - result = _context3.sent; + return _super.call(this, message); + } - if (!(typeof event === "string" && result[event] !== "ok")) { - _context3.next = 6; - break; - } + return _createClass(ShaError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); - throw new Error("Failed subscribing to an event '" + event + "' with: " + result[event]); +function assertJacPoint(other) { + if (!(other instanceof JacobianPoint)) throw new TypeError('JacobianPoint expected'); +} - case 6: - return _context3.abrupt("return", result); +var JacobianPoint = /*#__PURE__*/function () { + function JacobianPoint(x, y, z) { + _classCallCheck(this, JacobianPoint); - case 7: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + this.x = x; + this.y = y; + this.z = z; + } - function subscribe(_x2) { - return _subscribe.apply(this, arguments); + _createClass(JacobianPoint, [{ + key: "equals", + value: function equals(other) { + assertJacPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + var Z1Z1 = mod(Z1 * Z1); + var Z2Z2 = mod(Z2 * Z2); + var U1 = mod(X1 * Z2Z2); + var U2 = mod(X2 * Z1Z1); + var S1 = mod(mod(Y1 * Z2) * Z2Z2); + var S2 = mod(mod(Y2 * Z1) * Z1Z1); + return U1 === U2 && S1 === S2; + } + }, { + key: "negate", + value: function negate() { + return new JacobianPoint(this.x, mod(-this.y), this.z); + } + }, { + key: "double", + value: function double() { + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var A = mod(X1 * X1); + var B = mod(Y1 * Y1); + var C = mod(B * B); + var x1b = X1 + B; + var D = mod(_2n * (mod(x1b * x1b) - A - C)); + var E = mod(_3n * A); + var F = mod(E * E); + var X3 = mod(F - _2n * D); + var Y3 = mod(E * (D - X3) - _8n * C); + var Z3 = mod(_2n * Y1 * Z1); + return new JacobianPoint(X3, Y3, Z3); + } + }, { + key: "add", + value: function add(other) { + assertJacPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + if (X2 === _0n || Y2 === _0n) return this; + if (X1 === _0n || Y1 === _0n) return other; + var Z1Z1 = mod(Z1 * Z1); + var Z2Z2 = mod(Z2 * Z2); + var U1 = mod(X1 * Z2Z2); + var U2 = mod(X2 * Z1Z1); + var S1 = mod(mod(Y1 * Z2) * Z2Z2); + var S2 = mod(mod(Y2 * Z1) * Z1Z1); + var H = mod(U2 - U1); + var r = mod(S2 - S1); + + if (H === _0n) { + if (r === _0n) { + return this["double"](); + } else { + return JacobianPoint.ZERO; } + } - return subscribe; - }() - /** - * Unsubscribes from a defined event. - * @method - * @param {String|Array} event - event name - * @return {Undefined} - * @throws {Error} - */ + var HH = mod(H * H); + var HHH = mod(H * HH); + var V = mod(U1 * HH); + var X3 = mod(r * r - HHH - _2n * V); + var Y3 = mod(r * (V - X3) - S1 * HHH); + var Z3 = mod(Z1 * Z2 * H); + return new JacobianPoint(X3, Y3, Z3); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + var P0 = JacobianPoint.ZERO; + if (typeof scalar === 'bigint' && scalar === _0n) return P0; + var n = normalizeScalar(scalar); + if (n === _1n) return this; + + if (!USE_ENDOMORPHISM) { + var p = P0; + + var _d = this; + + while (n > _0n) { + if (n & _1n) p = p.add(_d); + _d = _d["double"](); + n >>= _1n; + } - }, { - key: "unsubscribe", - value: function () { - var _unsubscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(event) { - var result; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (typeof event === "string") event = [event]; - _context4.next = 3; - return this.call("rpc.off", event); + return p; + } - case 3: - result = _context4.sent; + var _endo$splitScalar = endo.splitScalar(n), + k1neg = _endo$splitScalar.k1neg, + k1 = _endo$splitScalar.k1, + k2neg = _endo$splitScalar.k2neg, + k2 = _endo$splitScalar.k2; - if (!(typeof event === "string" && result[event] !== "ok")) { - _context4.next = 6; - break; - } + var k1p = P0; + var k2p = P0; + var d = this; - throw new Error("Failed unsubscribing from an event with: " + result); + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d["double"](); + k1 >>= _1n; + k2 >>= _1n; + } - case 6: - return _context4.abrupt("return", result); + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + return k1p.add(k2p); + } + }, { + key: "precomputeWindow", + value: function precomputeWindow(W) { + var windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; + var points = []; + var p = this; + var base = p; - case 7: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); + for (var window = 0; window < windows; window++) { + base = p; + points.push(base); - function unsubscribe(_x3) { - return _unsubscribe.apply(this, arguments); + for (var i = 1; i < Math.pow(2, W - 1); i++) { + base = base.add(p); + points.push(base); } - return unsubscribe; - }() - /** - * Closes a WebSocket connection gracefully. - * @method - * @param {Number} code - socket close code - * @param {String} data - optional data to be sent before closing - * @return {Undefined} - */ + p = base["double"](); + } - }, { - key: "close", - value: function close(code, data) { - this.socket.close(code || 1000, data); + return points; + } + }, { + key: "wNAF", + value: function wNAF(n, affinePoint) { + if (!affinePoint && this.equals(JacobianPoint.BASE)) affinePoint = Point.BASE; + var W = affinePoint && affinePoint._WINDOW_SIZE || 1; + + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); } - /** - * Connection/Message handler. - * @method - * @private - * @param {String} address - WebSocket API address - * @param {Object} options - ws options object - * @return {Undefined} - */ - }, { - key: "_connect", - value: function _connect(address, options) { - var _this4 = this; + var precomputes = affinePoint && pointPrecomputes.get(affinePoint); - clearTimeout(this.reconnect_timer_id); - this.socket = this.webSocketFactory(address, options); - this.socket.addEventListener("open", function () { - _this4.ready = true; + if (!precomputes) { + precomputes = this.precomputeWindow(W); - _this4.emit("open"); + if (affinePoint && W !== 1) { + precomputes = JacobianPoint.normalizeZ(precomputes); + pointPrecomputes.set(affinePoint, precomputes); + } + } - _this4.current_reconnects = 0; - }); - this.socket.addEventListener("message", function (_ref) { - var message = _ref.data; - if (message instanceof ArrayBuffer) message = Buffer$1.from(message).toString(); + var p = JacobianPoint.ZERO; + var f = JacobianPoint.BASE; + var windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); + var windowSize = Math.pow(2, W - 1); + var mask = BigInt(Math.pow(2, W) - 1); + var maxNumber = Math.pow(2, W); + var shiftBy = BigInt(W); - try { - message = JSON.parse(message); - } catch (error) { - return; - } // check if any listeners are attached and forward event + for (var window = 0; window < windows; window++) { + var offset = window * windowSize; + var wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } - if (message.notification && _this4.listeners(message.notification).length) { - if (!Object.keys(message.params).length) return _this4.emit(message.notification); - var args = [message.notification]; - if (message.params.constructor === Object) args.push(message.params);else // using for-loop instead of unshift/spread because performance is better - for (var i = 0; i < message.params.length; i++) { - args.push(message.params[i]); - } // run as microtask so that pending queue messages are resolved first - // eslint-disable-next-line prefer-spread + var offset1 = offset; + var offset2 = offset + Math.abs(wbits) - 1; + var cond1 = window % 2 !== 0; + var cond2 = wbits < 0; - return Promise.resolve().then(function () { - _this4.emit.apply(_this4, args); - }); - } + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } - if (!_this4.queue[message.id]) { - // general JSON RPC 2.0 events - if (message.method && message.params) { - // run as microtask so that pending queue messages are resolved first - return Promise.resolve().then(function () { - _this4.emit(message.method, message.params); - }); - } + return { + p: p, + f: f + }; + } + }, { + key: "multiply", + value: function multiply(scalar, affinePoint) { + var n = normalizeScalar(scalar); + var point; + var fake; - return; - } // reject early since server's response is invalid + if (USE_ENDOMORPHISM) { + var _endo$splitScalar3 = endo.splitScalar(n), + k1neg = _endo$splitScalar3.k1neg, + k1 = _endo$splitScalar3.k1, + k2neg = _endo$splitScalar3.k2neg, + k2 = _endo$splitScalar3.k2; + + var _this$wNAF2 = this.wNAF(k1, affinePoint), + k1p = _this$wNAF2.p, + f1p = _this$wNAF2.f; + var _this$wNAF4 = this.wNAF(k2, affinePoint), + k2p = _this$wNAF4.p, + f2p = _this$wNAF4.f; - if ("error" in message === "result" in message) _this4.queue[message.id].promise[1](new Error("Server response malformed. Response must include either \"result\"" + " or \"error\", but not both.")); - if (_this4.queue[message.id].timeout) clearTimeout(_this4.queue[message.id].timeout); - if (message.error) _this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result); - delete _this4.queue[message.id]; - }); - this.socket.addEventListener("error", function (error) { - return _this4.emit("error", error); - }); - this.socket.addEventListener("close", function (_ref2) { - var code = _ref2.code, - reason = _ref2.reason; - if (_this4.ready) // Delay close event until internal state is updated - setTimeout(function () { - return _this4.emit("close", code, reason); - }, 0); - _this4.ready = false; - _this4.socket = undefined; - if (code === 1000) return; - _this4.current_reconnects++; - if (_this4.reconnect && (_this4.max_reconnects > _this4.current_reconnects || _this4.max_reconnects === 0)) _this4.reconnect_timer_id = setTimeout(function () { - return _this4._connect(address, options); - }, _this4.reconnect_interval); - }); + k1p = constTimeNegate(k1neg, k1p); + k2p = constTimeNegate(k2neg, k2p); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + var _this$wNAF6 = this.wNAF(n, affinePoint), + p = _this$wNAF6.p, + f = _this$wNAF6.f; + + point = p; + fake = f; } - }]); - return CommonClient; - }(_eventemitter.EventEmitter); - exports["default"] = CommonClient; -})(client); + return JacobianPoint.normalizeZ([point, fake])[0]; + } + }, { + key: "toAffine", + value: function toAffine(invZ) { + var x = this.x, + y = this.y, + z = this.z; + var is0 = this.equals(JacobianPoint.ZERO); + if (invZ == null) invZ = is0 ? _8n : invert(z); + var iz1 = invZ; + var iz2 = mod(iz1 * iz1); + var iz3 = mod(iz2 * iz1); + var ax = mod(x * iz2); + var ay = mod(y * iz3); + var zz = mod(z * iz1); + if (is0) return Point.ZERO; + if (zz !== _1n) throw new Error('invZ was invalid'); + return new Point(ax, ay); + } + }], [{ + key: "fromAffine", + value: function fromAffine(p) { + if (!(p instanceof Point)) { + throw new TypeError('JacobianPoint#fromAffine: expected Point'); + } -var RpcWebSocketCommonClient = /*@__PURE__*/getDefaultExportFromCjs(client); + if (p.equals(Point.ZERO)) return JacobianPoint.ZERO; + return new JacobianPoint(p.x, p.y, _1n); + } + }, { + key: "toAffineBatch", + value: function toAffineBatch(points) { + var toInv = invertBatch(points.map(function (p) { + return p.z; + })); + return points.map(function (p, i) { + return p.toAffine(toInv[i]); + }); + } + }, { + key: "normalizeZ", + value: function normalizeZ(points) { + return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + } + }]); -var websocket_browser = {}; + return JacobianPoint; +}(); -/** - * WebSocket implements a browser-side WebSocket specification. - * @module Client - */ +JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); +JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); -(function (exports) { +function constTimeNegate(condition, item) { + var neg = item.negate(); + return condition ? neg : item; +} - var _interopRequireDefault = interopRequireDefault.exports; - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports["default"] = _default; +var pointPrecomputes = new WeakMap(); +var Point = /*#__PURE__*/function () { + function Point(x, y) { + _classCallCheck(this, Point); - var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + this.x = x; + this.y = y; + } - var _createClass2 = _interopRequireDefault(requireCreateClass()); + _createClass(Point, [{ + key: "_setWindowSize", + value: function _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes["delete"](this); + } + }, { + key: "hasEvenY", + value: function hasEvenY() { + return this.y % _2n === _0n; + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + return hexToBytes(this.toHex(isCompressed)); + } + }, { + key: "toHex", + value: function toHex() { + var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var x = numTo32bStr(this.x); - var _inherits2 = _interopRequireDefault(requireInherits()); + if (isCompressed) { + var prefix = this.hasEvenY() ? '02' : '03'; + return "".concat(prefix).concat(x); + } else { + return "04".concat(x).concat(numTo32bStr(this.y)); + } + } + }, { + key: "toHexX", + value: function toHexX() { + return this.toHex(true).slice(2); + } + }, { + key: "toRawX", + value: function toRawX() { + return this.toRawBytes(true).slice(1); + } + }, { + key: "assertValidity", + value: function assertValidity() { + var msg = 'Point is not on elliptic curve'; + var x = this.x, + y = this.y; + if (!isValidFieldElement(x) || !isValidFieldElement(y)) throw new Error(msg); + var left = mod(y * y); + var right = weierstrass(x); + if (mod(left - right) !== _0n) throw new Error(msg); + } + }, { + key: "equals", + value: function equals(other) { + return this.x === other.x && this.y === other.y; + } + }, { + key: "negate", + value: function negate() { + return new Point(this.x, mod(-this.y)); + } + }, { + key: "double", + value: function double() { + return JacobianPoint.fromAffine(this)["double"]().toAffine(); + } + }, { + key: "add", + value: function add(other) { + return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + }, { + key: "multiplyAndAddUnsafe", + value: function multiplyAndAddUnsafe(Q, a, b) { + var P = JacobianPoint.fromAffine(this); + var aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); + var bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); + var sum = aP.add(bQ); + return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + } + }], [{ + key: "fromCompressedHex", + value: function fromCompressedHex(bytes) { + var isShort = bytes.length === 32; + var x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); + if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); + var y2 = weierstrass(x); + var y = sqrtMod(y2); + var isYOdd = (y & _1n) === _1n; - var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + if (isShort) { + if (isYOdd) y = mod(-y); + } else { + var isFirstByteOdd = (bytes[0] & 1) === 1; + if (isFirstByteOdd !== isYOdd) y = mod(-y); + } - var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var point = new Point(x, y); + point.assertValidity(); + return point; + } + }, { + key: "fromUncompressedHex", + value: function fromUncompressedHex(bytes) { + var x = bytesToNumber(bytes.subarray(1, fieldLen + 1)); + var y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1)); + var point = new Point(x, y); + point.assertValidity(); + return point; + } + }, { + key: "fromHex", + value: function fromHex(hex) { + var bytes = ensureBytes(hex); + var len = bytes.length; + var header = bytes[0]; + if (len === fieldLen) return this.fromCompressedHex(bytes); - var _eventemitter = requireEventemitter3(); + if (len === compressedLen && (header === 0x02 || header === 0x03)) { + return this.fromCompressedHex(bytes); + } - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); + if (len === uncompressedLen && header === 0x04) return this.fromUncompressedHex(bytes); + throw new Error("Point.fromHex: received invalid point. Expected 32-".concat(compressedLen, " compressed bytes or ").concat(uncompressedLen, " uncompressed bytes, not ").concat(len)); + } + }, { + key: "fromPrivateKey", + value: function fromPrivateKey(privateKey) { + return Point.BASE.multiply(normalizePrivateKey(privateKey)); + } + }, { + key: "fromSignature", + value: function fromSignature(msgHash, signature, recovery) { + var _normalizeSignature = normalizeSignature(signature), + r = _normalizeSignature.r, + s = _normalizeSignature.s; - return function _createSuperInternal() { - var Super = (0, _getPrototypeOf2["default"])(Derived), - result; + if (![0, 1, 2, 3].includes(recovery)) throw new Error('Cannot recover: invalid recovery bit'); + var h = truncateHash(ensureBytes(msgHash)); + var n = CURVE.n; + var radj = recovery === 2 || recovery === 3 ? r + n : r; + var rinv = invert(radj, n); + var u1 = mod(-h * rinv, n); + var u2 = mod(s * rinv, n); + var prefix = recovery & 1 ? '03' : '02'; + var R = Point.fromHex(prefix + numTo32bStr(radj)); + var Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) throw new Error('Cannot recover signature: point at infinify'); + Q.assertValidity(); + return Q; + } + }]); - if (hasNativeReflectConstruct) { - var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } + return Point; +}(); +Point.BASE = new Point(CURVE.Gx, CURVE.Gy); +Point.ZERO = new Point(_0n, _0n); - return (0, _possibleConstructorReturn2["default"])(this, result); - }; +function sliceDER(s) { + return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; +} + +function parseDERInt(data) { + if (data.length < 2 || data[0] !== 0x02) { + throw new Error("Invalid signature integer tag: ".concat(bytesToHex(data))); } - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; + var len = data[1]; + var res = data.subarray(2, len + 2); - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } + if (!len || res.length !== len) { + throw new Error("Invalid signature integer: wrong length"); + } + + if (res[0] === 0x00 && res[1] <= 0x7f) { + throw new Error('Invalid signature integer: trailing length'); } - var WebSocketBrowserImpl = /*#__PURE__*/function (_EventEmitter) { - (0, _inherits2["default"])(WebSocketBrowserImpl, _EventEmitter); + return { + data: bytesToNumber(res), + left: data.subarray(len + 2) + }; +} - var _super = _createSuper(WebSocketBrowserImpl); - /** Instantiate a WebSocket class - * @constructor - * @param {String} address - url to a websocket server - * @param {(Object)} options - websocket options - * @param {(String|Array)} protocols - a list of protocols - * @return {WebSocketBrowserImpl} - returns a WebSocket instance - */ +function parseDERSignature(data) { + if (data.length < 2 || data[0] != 0x30) { + throw new Error("Invalid signature tag: ".concat(bytesToHex(data))); + } + if (data[1] !== data.length - 2) { + throw new Error('Invalid signature: incorrect length'); + } - function WebSocketBrowserImpl(address, options, protocols) { - var _this; + var _parseDERInt = parseDERInt(data.subarray(2)), + r = _parseDERInt.data, + sBytes = _parseDERInt.left; - (0, _classCallCheck2["default"])(this, WebSocketBrowserImpl); - _this = _super.call(this); - _this.socket = new window.WebSocket(address, protocols); + var _parseDERInt2 = parseDERInt(sBytes), + s = _parseDERInt2.data, + rBytesLeft = _parseDERInt2.left; - _this.socket.onopen = function () { - return _this.emit("open"); - }; + if (rBytesLeft.length) { + throw new Error("Invalid signature: left bytes after parsing: ".concat(bytesToHex(rBytesLeft))); + } - _this.socket.onmessage = function (event) { - return _this.emit("message", event.data); - }; + return { + r: r, + s: s + }; +} - _this.socket.onerror = function (error) { - return _this.emit("error", error); - }; +var Signature = /*#__PURE__*/function () { + function Signature(r, s) { + _classCallCheck(this, Signature); - _this.socket.onclose = function (event) { - _this.emit("close", event.code, event.reason); - }; + this.r = r; + this.s = s; + this.assertValidity(); + } - return _this; + _createClass(Signature, [{ + key: "assertValidity", + value: function assertValidity() { + var r = this.r, + s = this.s; + if (!isWithinCurveOrder(r)) throw new Error('Invalid Signature: r must be 0 < r < n'); + if (!isWithinCurveOrder(s)) throw new Error('Invalid Signature: s must be 0 < s < n'); } - /** - * Sends data through a websocket connection - * @method - * @param {(String|Object)} data - data to be sent via websocket - * @param {Object} optionsOrCallback - ws options - * @param {Function} callback - a callback called once the data is sent - * @return {Undefined} - */ - - - (0, _createClass2["default"])(WebSocketBrowserImpl, [{ - key: "send", - value: function send(data, optionsOrCallback, callback) { - var cb = callback || optionsOrCallback; + }, { + key: "hasHighS", + value: function hasHighS() { + var HALF = CURVE.n >> _1n; + return this.s > HALF; + } + }, { + key: "normalizeS", + value: function normalizeS() { + return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this; + } + }, { + key: "toDERRawBytes", + value: function toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + }, { + key: "toDERHex", + value: function toDERHex() { + var sHex = sliceDER(numberToHexUnpadded(this.s)); + var rHex = sliceDER(numberToHexUnpadded(this.r)); + var sHexL = sHex.length / 2; + var rHexL = rHex.length / 2; + var sLen = numberToHexUnpadded(sHexL); + var rLen = numberToHexUnpadded(rHexL); + var length = numberToHexUnpadded(rHexL + sHexL + 4); + return "30".concat(length, "02").concat(rLen).concat(rHex, "02").concat(sLen).concat(sHex); + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + return this.toDERRawBytes(); + } + }, { + key: "toHex", + value: function toHex() { + return this.toDERHex(); + } + }, { + key: "toCompactRawBytes", + value: function toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + }, { + key: "toCompactHex", + value: function toCompactHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } + }], [{ + key: "fromCompact", + value: function fromCompact(hex) { + var arr = hex instanceof Uint8Array; + var name = 'Signature.fromCompact'; + if (typeof hex !== 'string' && !arr) throw new TypeError("".concat(name, ": Expected string or Uint8Array")); + var str = arr ? bytesToHex(hex) : hex; + if (str.length !== 128) throw new Error("".concat(name, ": Expected 64-byte hex")); + return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + } + }, { + key: "fromDER", + value: function fromDER(hex) { + var arr = hex instanceof Uint8Array; + if (typeof hex !== 'string' && !arr) throw new TypeError("Signature.fromDER: Expected string or Uint8Array"); - try { - this.socket.send(data); - cb(); - } catch (error) { - cb(error); - } - } - /** - * Closes an underlying socket - * @method - * @param {Number} code - status code explaining why the connection is being closed - * @param {String} reason - a description why the connection is closing - * @return {Undefined} - * @throws {Error} - */ + var _parseDERSignature = parseDERSignature(arr ? hex : hexToBytes(hex)), + r = _parseDERSignature.r, + s = _parseDERSignature.s; - }, { - key: "close", - value: function close(code, reason) { - this.socket.close(code, reason); - } - }, { - key: "addEventListener", - value: function addEventListener(type, listener, options) { - this.socket.addEventListener(type, listener, options); - } - }]); - return WebSocketBrowserImpl; - }(_eventemitter.EventEmitter); - /** - * factory method for common WebSocket instance - * @method - * @param {String} address - url to a websocket server - * @param {(Object)} options - websocket options - * @return {Undefined} - */ + return new Signature(r, s); + } + }, { + key: "fromHex", + value: function fromHex(hex) { + return this.fromDER(hex); + } + }]); + return Signature; +}(); - function _default(address, options) { - return new WebSocketBrowserImpl(address, options); +function concatBytes() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; } -})(websocket_browser); -var createRpc = /*@__PURE__*/getDefaultExportFromCjs(websocket_browser); + if (!arrays.every(function (b) { + return b instanceof Uint8Array; + })) throw new Error('Uint8Array list expected'); + if (arrays.length === 1) return arrays[0]; + var length = arrays.reduce(function (a, arr) { + return a + arr.length; + }, 0); + var result = new Uint8Array(length); -var SHA3_PI = [], - SHA3_ROTL = [], - _SHA3_IOTA = []; + for (var i = 0, pad = 0; i < arrays.length; i++) { + var arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } -var _0n$1 = BigInt(0); + return result; +} -var _1n$1 = BigInt(1); +var hexes = Array.from({ + length: 256 +}, function (v, i) { + return i.toString(16).padStart(2, '0'); +}); -var _2n$1 = BigInt(2); +function bytesToHex(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + var hex = ''; -var _7n = BigInt(7); + for (var i = 0; i < uint8a.length; i++) { + hex += hexes[uint8a[i]]; + } -var _256n = BigInt(256); + return hex; +} -var _0x71n = BigInt(0x71); +var POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); -for (var round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) { - // Pi - var _ref = [y, (2 * x + 3 * y) % 5]; - x = _ref[0]; - y = _ref[1]; - SHA3_PI.push(2 * (5 * y + x)); // Rotational +function numTo32bStr(num) { + if (typeof num !== 'bigint') throw new Error('Expected bigint'); + if (!(_0n <= num && num < POW_2_256)) throw new Error('Expected number 0 <= n < 2^256'); + return num.toString(16).padStart(64, '0'); +} - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); // Iota +function numTo32b(num) { + var b = hexToBytes(numTo32bStr(num)); + if (b.length !== 32) throw new Error('Error: expected 32 bytes'); + return b; +} - var t = _0n$1; +function numberToHexUnpadded(num) { + var hex = num.toString(16); + return hex.length & 1 ? "0".concat(hex) : hex; +} - for (var j = 0; j < 7; j++) { - R = (R << _1n$1 ^ (R >> _7n) * _0x71n) % _256n; - if (R & _2n$1) t ^= _1n$1 << (_1n$1 << BigInt(j)) - _1n$1; +function hexToNumber(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToNumber: expected string, got ' + _typeof$1(hex)); } - _SHA3_IOTA.push(t); + return BigInt("0x".concat(hex)); } -var _u64$split = u64$2.split(_SHA3_IOTA, true), - _u64$split2 = _slicedToArray(_u64$split, 2), - SHA3_IOTA_H = _u64$split2[0], - SHA3_IOTA_L = _u64$split2[1]; // Left rotation (without 0, 32, 64) +function hexToBytes(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); + } + if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); + var array = new Uint8Array(hex.length / 2); -var rotlH = function rotlH(h, l, s) { - return s > 32 ? u64$2.rotlBH(h, l, s) : u64$2.rotlSH(h, l, s); -}; + for (var i = 0; i < array.length; i++) { + var j = i * 2; + var hexByte = hex.slice(j, j + 2); -var rotlL = function rotlL(h, l, s) { - return s > 32 ? u64$2.rotlBL(h, l, s) : u64$2.rotlSL(h, l, s); -}; // Same as keccakf1600, but allows to skip some rounds + var _byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); + array[i] = _byte; + } -function keccakP(s) { - var rounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 24; - var B = new Uint32Array(5 * 2); // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + return array; +} - for (var _round2 = 24 - rounds; _round2 < 24; _round2++) { - // Theta θ - for (var _x2 = 0; _x2 < 10; _x2++) B[_x2] = s[_x2] ^ s[_x2 + 10] ^ s[_x2 + 20] ^ s[_x2 + 30] ^ s[_x2 + 40]; +function bytesToNumber(bytes) { + return hexToNumber(bytesToHex(bytes)); +} - for (var _x4 = 0; _x4 < 10; _x4 += 2) { - var idx1 = (_x4 + 8) % 10; - var idx0 = (_x4 + 2) % 10; - var B0 = B[idx0]; - var B1 = B[idx0 + 1]; - var Th = rotlH(B0, B1, 1) ^ B[idx1]; - var Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; +function ensureBytes(hex) { + return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); +} - for (var _y2 = 0; _y2 < 50; _y2 += 10) { - s[_x4 + _y2] ^= Th; - s[_x4 + _y2 + 1] ^= Tl; - } - } // Rho (ρ) and Pi (π) +function normalizeScalar(num) { + if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) return BigInt(num); + if (typeof num === 'bigint' && isWithinCurveOrder(num)) return num; + throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); +} +function mod(a) { + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var result = a % b; + return result >= _0n ? result : b + result; +} - var curH = s[2]; - var curL = s[3]; +function pow2(x, power) { + var P = CURVE.P; + var res = x; - for (var _t2 = 0; _t2 < 24; _t2++) { - var shift = SHA3_ROTL[_t2]; + while (power-- > _0n) { + res *= res; + res %= P; + } - var _Th = rotlH(curH, curL, shift); + return res; +} - var _Tl = rotlL(curH, curL, shift); +function sqrtMod(x) { + var P = CURVE.P; - var PI = SHA3_PI[_t2]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = _Th; - s[PI + 1] = _Tl; - } // Chi (χ) + var _6n = BigInt(6); + var _11n = BigInt(11); - for (var _y4 = 0; _y4 < 50; _y4 += 10) { - for (var _x6 = 0; _x6 < 10; _x6++) B[_x6] = s[_y4 + _x6]; + var _22n = BigInt(22); - for (var _x8 = 0; _x8 < 10; _x8++) s[_y4 + _x8] ^= ~B[(_x8 + 2) % 10] & B[(_x8 + 4) % 10]; - } // Iota (ι) + var _23n = BigInt(23); + var _44n = BigInt(44); - s[0] ^= SHA3_IOTA_H[_round2]; - s[1] ^= SHA3_IOTA_L[_round2]; - } + var _88n = BigInt(88); - B.fill(0); + var b2 = x * x * x % P; + var b3 = b2 * b2 * x % P; + var b6 = pow2(b3, _3n) * b3 % P; + var b9 = pow2(b6, _3n) * b3 % P; + var b11 = pow2(b9, _2n) * b2 % P; + var b22 = pow2(b11, _11n) * b11 % P; + var b44 = pow2(b22, _22n) * b22 % P; + var b88 = pow2(b44, _44n) * b44 % P; + var b176 = pow2(b88, _88n) * b88 % P; + var b220 = pow2(b176, _44n) * b44 % P; + var b223 = pow2(b220, _3n) * b3 % P; + var t1 = pow2(b223, _23n) * b22 % P; + var t2 = pow2(t1, _6n) * b2 % P; + var rt = pow2(t2, _2n); + var xc = rt * rt % P; + if (xc !== x) throw new Error('Cannot find square root'); + return rt; } -var Keccak = /*#__PURE__*/function (_Hash) { - _inherits(Keccak, _Hash); - var _super = _createSuper(Keccak); - - // NOTE: we accept arguments in bytes instead of bits here. - function Keccak(blockLen, suffix, outputLen) { - var _this; +function invert(number) { + var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var enableXOF = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var rounds = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 24; + if (number === _0n || modulo <= _0n) { + throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); + } - _classCallCheck(this, Keccak); + var a = mod(number, modulo); + var b = modulo; + var x = _0n, + u = _1n; - _this = _super.call(this); - _this.blockLen = blockLen; - _this.suffix = suffix; - _this.outputLen = outputLen; - _this.enableXOF = enableXOF; - _this.rounds = rounds; - _this.pos = 0; - _this.posOut = 0; - _this.finished = false; - _this.destroyed = false; // Can be passed from user as dkLen + while (a !== _0n) { + var q = b / a; + var r = b % a; + var m = x - u * q; + b = a, a = r, x = u, u = m; + } - assert$2.number(outputLen); // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + var gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); +} - if (0 >= _this.blockLen || _this.blockLen >= 200) throw new Error('Sha3 supports only keccak-f1600 function'); - _this.state = new Uint8Array(200); - _this.state32 = u32$1(_this.state); - return _this; - } +function invertBatch(nums) { + var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var scratch = new Array(nums.length); + var lastMultiplied = nums.reduce(function (acc, num, i) { + if (num === _0n) return acc; + scratch[i] = acc; + return mod(acc * num, p); + }, _1n); + var inverted = invert(lastMultiplied, p); + nums.reduceRight(function (acc, num, i) { + if (num === _0n) return acc; + scratch[i] = mod(acc * scratch[i], p); + return mod(acc * num, p); + }, inverted); + return scratch; +} - _createClass(Keccak, [{ - key: "keccak", - value: function keccak() { - keccakP(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; - } - }, { - key: "update", - value: function update(data) { - assert$2.exists(this); - var blockLen = this.blockLen, - state = this.state; - data = toBytes(data); - var len = data.length; +function bits2int_2(bytes) { + var delta = bytes.length * 8 - groupLen * 8; + var num = bytesToNumber(bytes); + return delta > 0 ? num >> BigInt(delta) : num; +} - for (var pos = 0; pos < len;) { - var take = Math.min(blockLen - this.pos, len - pos); +function truncateHash(hash) { + var truncateOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var h = bits2int_2(hash); + if (truncateOnly) return h; + var n = CURVE.n; + return h >= n ? h - n : h; +} - for (var i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; +var _sha256Sync; - if (this.pos === blockLen) this.keccak(); - } +var _hmacSha256Sync; - return this; - } - }, { - key: "finish", - value: function finish() { - if (this.finished) return; - this.finished = true; - var state = this.state, - suffix = this.suffix, - pos = this.pos, - blockLen = this.blockLen; // Do the padding +var HmacDrbg = /*#__PURE__*/function () { + function HmacDrbg(hashLen, qByteLen) { + _classCallCheck(this, HmacDrbg); - state[pos] ^= suffix; - if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); - state[blockLen - 1] ^= 0x80; - this.keccak(); - } - }, { - key: "writeInto", - value: function writeInto(out) { - assert$2.exists(this, false); - assert$2.bytes(out); - this.finish(); - var bufferOut = this.state; - var blockLen = this.blockLen; + this.hashLen = hashLen; + this.qByteLen = qByteLen; + if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); + this.v = new Uint8Array(hashLen).fill(1); + this.k = new Uint8Array(hashLen).fill(0); + this.counter = 0; + } - for (var pos = 0, len = out.length; pos < len;) { - if (this.posOut >= blockLen) this.keccak(); - var take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; + _createClass(HmacDrbg, [{ + key: "hmac", + value: function hmac() { + for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + values[_key2] = arguments[_key2]; } - return out; + return utils.hmacSha256.apply(utils, [this.k].concat(values)); } }, { - key: "xofInto", - value: function xofInto(out) { - // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF - if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); - return this.writeInto(out); + key: "hmacSync", + value: function hmacSync() { + for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + values[_key3] = arguments[_key3]; + } + + return _hmacSha256Sync.apply(void 0, [this.k].concat(values)); } }, { - key: "xof", - value: function xof(bytes) { - assert$2.number(bytes); - return this.xofInto(new Uint8Array(bytes)); + key: "checkSync", + value: function checkSync() { + if (typeof _hmacSha256Sync !== 'function') throw new ShaError('hmacSha256Sync needs to be set'); } }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.output(out, this); - if (this.finished) throw new Error('digest() was already called'); - this.writeInto(out); - this.destroy(); - return out; + key: "incr", + value: function incr() { + if (this.counter >= 1000) throw new Error('Tried 1,000 k values for sign(), all were invalid'); + this.counter += 1; } }, { - key: "digest", - value: function digest() { - return this.digestInto(new Uint8Array(this.outputLen)); - } + key: "reseed", + value: function () { + var _reseed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var seed, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + seed = _args.length > 0 && _args[0] !== undefined ? _args[0] : new Uint8Array(); + _context.next = 3; + return this.hmac(this.v, Uint8Array.from([0x00]), seed); + + case 3: + this.k = _context.sent; + _context.next = 6; + return this.hmac(this.v); + + case 6: + this.v = _context.sent; + + if (!(seed.length === 0)) { + _context.next = 9; + break; + } + + return _context.abrupt("return"); + + case 9: + _context.next = 11; + return this.hmac(this.v, Uint8Array.from([0x01]), seed); + + case 11: + this.k = _context.sent; + _context.next = 14; + return this.hmac(this.v); + + case 14: + this.v = _context.sent; + + case 15: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + + function reseed() { + return _reseed.apply(this, arguments); + } + + return reseed; + }() }, { - key: "destroy", - value: function destroy() { - this.destroyed = true; - this.state.fill(0); + key: "reseedSync", + value: function reseedSync() { + var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Uint8Array(); + this.checkSync(); + this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); + this.v = this.hmacSync(this.v); + if (seed.length === 0) return; + this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); + this.v = this.hmacSync(this.v); } }, { - key: "_cloneInto", - value: function _cloneInto(to) { - var blockLen = this.blockLen, - suffix = this.suffix, - outputLen = this.outputLen, - rounds = this.rounds, - enableXOF = this.enableXOF; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; // Suffix can change in cSHAKE - - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } - }]); + key: "generate", + value: function () { + var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var len, out, sl; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + this.incr(); + len = 0; + out = []; - return Keccak; -}(Hash); + case 3: + if (!(len < this.qByteLen)) { + _context2.next = 12; + break; + } -var gen = function gen(suffix, blockLen, outputLen) { - return wrapConstructor(function () { - return new Keccak(blockLen, suffix, outputLen); - }); -}; + _context2.next = 6; + return this.hmac(this.v); -gen(0x06, 144, 224 / 8); -/** - * SHA3-256 hash function - * @param message - that would be hashed - */ + case 6: + this.v = _context2.sent; + sl = this.v.slice(); + out.push(sl); + len += this.v.length; + _context2.next = 3; + break; -gen(0x06, 136, 256 / 8); -gen(0x06, 104, 384 / 8); -gen(0x06, 72, 512 / 8); -gen(0x01, 144, 224 / 8); -/** - * keccak-256 hash function. Different from SHA3-256. - * @param message - that would be hashed - */ + case 12: + return _context2.abrupt("return", concatBytes.apply(void 0, out)); -var keccak_256 = gen(0x01, 136, 256 / 8); -gen(0x01, 104, 384 / 8); -gen(0x01, 72, 512 / 8); + case 13: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); -var genShake = function genShake(suffix, blockLen, outputLen) { - return wrapConstructorWithOpts(function () { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true); - }); -}; + function generate() { + return _generate.apply(this, arguments); + } -genShake(0x1f, 168, 128 / 8); -genShake(0x1f, 136, 256 / 8); + return generate; + }() + }, { + key: "generateSync", + value: function generateSync() { + this.checkSync(); + this.incr(); + var len = 0; + var out = []; -var HMAC = /*#__PURE__*/function (_Hash) { - _inherits(HMAC, _Hash); + while (len < this.qByteLen) { + this.v = this.hmacSync(this.v); + var sl = this.v.slice(); + out.push(sl); + len += this.v.length; + } - var _super = _createSuper(HMAC); + return concatBytes.apply(void 0, out); + } + }]); - function HMAC(hash, _key) { - var _this; + return HmacDrbg; +}(); - _classCallCheck(this, HMAC); +function isWithinCurveOrder(num) { + return _0n < num && num < CURVE.n; +} - _this = _super.call(this); - _this.finished = false; - _this.destroyed = false; - assert$2.hash(hash); - var key = toBytes(_key); - _this.iHash = hash.create(); - if (typeof _this.iHash.update !== 'function') throw new TypeError('Expected instance of class which extends utils.Hash'); - _this.blockLen = _this.iHash.blockLen; - _this.outputLen = _this.iHash.outputLen; - var blockLen = _this.blockLen; - var pad = new Uint8Array(blockLen); // blockLen can be bigger than outputLen +function isValidFieldElement(num) { + return _0n < num && num < CURVE.P; +} - pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); +function kmdToSig(kBytes, m, d) { + var lowS = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var n = CURVE.n; + var k = truncateHash(kBytes, true); + if (!isWithinCurveOrder(k)) return; + var kinv = invert(k, n); + var q = Point.BASE.multiply(k); + var r = mod(q.x, n); + if (r === _0n) return; + var s = mod(kinv * mod(m + d * r, n), n); + if (s === _0n) return; + var sig = new Signature(r, s); + var recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); - for (var i = 0; i < pad.length; i++) pad[i] ^= 0x36; + if (lowS && sig.hasHighS()) { + sig = sig.normalizeS(); + recovery ^= 1; + } - _this.iHash.update(pad); // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + return { + sig: sig, + recovery: recovery + }; +} +function normalizePrivateKey(key) { + var num; - _this.oHash = hash.create(); // Undo internal XOR && apply outer XOR + if (typeof key === 'bigint') { + num = key; + } else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { + num = BigInt(key); + } else if (typeof key === 'string') { + if (key.length !== 2 * groupLen) throw new Error('Expected 32 bytes of private key'); + num = hexToNumber(key); + } else if (key instanceof Uint8Array) { + if (key.length !== groupLen) throw new Error('Expected 32 bytes of private key'); + num = bytesToNumber(key); + } else { + throw new TypeError('Expected valid private key'); + } - for (var _i2 = 0; _i2 < pad.length; _i2++) pad[_i2] ^= 0x36 ^ 0x5c; + if (!isWithinCurveOrder(num)) throw new Error('Expected private key: 0 < key < n'); + return num; +} - _this.oHash.update(pad); +function normalizeSignature(signature) { + if (signature instanceof Signature) { + signature.assertValidity(); + return signature; + } - pad.fill(0); - return _this; + try { + return Signature.fromDER(signature); + } catch (error) { + return Signature.fromCompact(signature); } +} - _createClass(HMAC, [{ - key: "update", - value: function update(buf) { - assert$2.exists(this); - this.iHash.update(buf); - return this; - } - }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.exists(this); - assert$2.bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - }, { - key: "digest", - value: function digest() { - var out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - }, { - key: "_cloneInto", - value: function _cloneInto(to) { - // Create new instance without calling constructor since key already in state and we don't know it. - to || (to = Object.create(Object.getPrototypeOf(this), {})); - var oHash = this.oHash, - iHash = this.iHash, - finished = this.finished, - destroyed = this.destroyed, - blockLen = this.blockLen, - outputLen = this.outputLen; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - }, { - key: "destroy", - value: function destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }]); +function getPublicKey$1(privateKey) { + var isCompressed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); +} - return HMAC; -}(Hash); -/** - * HMAC: RFC2104 message authentication code. - * @param hash - function that would be used e.g. sha256 - * @param key - message key - * @param message - message data - */ +function bits2int(bytes) { + var slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes; + return bytesToNumber(slice); +} +function bits2octets(bytes) { + var z1 = bits2int(bytes); + var z2 = mod(z1, CURVE.n); + return int2octets(z2 < _0n ? z1 : z2); +} -var hmac = function hmac(hash, key, message) { - return new HMAC(hash, key).update(message).digest(); -}; +function int2octets(num) { + return numTo32b(num); +} -hmac.create = function (hash, key) { - return new HMAC(hash, key); -}; +function initSigArgs(msgHash, privateKey, extraEntropy) { + if (msgHash == null) throw new Error("sign: expected valid message hash, not \"".concat(msgHash, "\"")); + var h1 = ensureBytes(msgHash); + var d = normalizePrivateKey(privateKey); + var seedArgs = [int2octets(d), bits2octets(h1)]; -var _0n = BigInt(0); + if (extraEntropy != null) { + if (extraEntropy === true) extraEntropy = utils.randomBytes(fieldLen); + var e = ensureBytes(extraEntropy); + if (e.length !== fieldLen) throw new Error("sign: Expected ".concat(fieldLen, " bytes of extra data")); + seedArgs.push(e); + } -var _1n = BigInt(1); + var seed = concatBytes.apply(void 0, seedArgs); + var m = bits2int(h1); + return { + seed: seed, + m: m, + d: d + }; +} -var _2n = BigInt(2); +function finalizeSig(recSig, opts) { + var sig = recSig.sig, + recovery = recSig.recovery; -var _3n = BigInt(3); + var _Object$assign = Object.assign({ + canonical: true, + der: true + }, opts), + der = _Object$assign.der, + recovered = _Object$assign.recovered; -var _8n = BigInt(8); + var hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); + return recovered ? [hashed, recovery] : hashed; +} -var CURVE = Object.freeze({ - a: _0n, - b: BigInt(7), - P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), - n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), - h: _1n, - Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), - Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee') -}); +function signSync(msgHash, privKey) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; -var divNearest = function divNearest(a, b) { - return (a + b / _2n) / b; -}; + var _initSigArgs = initSigArgs(msgHash, privKey, opts.extraEntropy), + seed = _initSigArgs.seed, + m = _initSigArgs.m, + d = _initSigArgs.d; -var endo = { - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), - splitScalar: function splitScalar(k) { - var n = CURVE.n; - var a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); - var b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); - var a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); - var b2 = a1; - var POW_2_128 = BigInt('0x100000000000000000000000000000000'); - var c1 = divNearest(b2 * k, n); - var c2 = divNearest(-b1 * k, n); - var k1 = mod(k - c1 * a1 - c2 * a2, n); - var k2 = mod(-c1 * b1 - c2 * b2, n); - var k1neg = k1 > POW_2_128; - var k2neg = k2 > POW_2_128; - if (k1neg) k1 = n - k1; - if (k2neg) k2 = n - k2; + var drbg = new HmacDrbg(hashLen, groupLen); + drbg.reseedSync(seed); + var sig; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); - } + while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical))) drbg.reseedSync(); - return { - k1neg: k1neg, - k1: k1, - k2neg: k2neg, - k2: k2 - }; - } + return finalizeSig(sig, opts); +} + +Point.BASE._setWindowSize(8); + +var crypto$1 = { + node: nodeCrypto, + web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined }; -var fieldLen = 32; -var groupLen = 32; -var hashLen = 32; -var compressedLen = fieldLen + 1; -var uncompressedLen = 2 * fieldLen + 1; +var TAGGED_HASH_PREFIXES = {}; +var utils = { + bytesToHex: bytesToHex, + hexToBytes: hexToBytes, + concatBytes: concatBytes, + mod: mod, + invert: invert, + isValidPrivateKey: function isValidPrivateKey(privateKey) { + try { + normalizePrivateKey(privateKey); + return true; + } catch (error) { + return false; + } + }, + _bigintTo32Bytes: numTo32b, + _normalizePrivateKey: normalizePrivateKey, + hashToPrivateKey: function hashToPrivateKey(hash) { + hash = ensureBytes(hash); + var minLen = groupLen + 8; -function weierstrass(x) { - var a = CURVE.a, - b = CURVE.b; - var x2 = mod(x * x); - var x3 = mod(x2 * x); - return mod(x3 + a * x + b); -} + if (hash.length < minLen || hash.length > 1024) { + throw new Error("Expected valid bytes of private key as per FIPS 186"); + } -var USE_ENDOMORPHISM = CURVE.a === _0n; + var num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; -var ShaError = /*#__PURE__*/function (_Error) { - _inherits(ShaError, _Error); + return numTo32b(num); + }, + randomBytes: function randomBytes() { + var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; - var _super = _createSuper(ShaError); + if (crypto$1.web) { + return crypto$1.web.getRandomValues(new Uint8Array(bytesLength)); + } else if (crypto$1.node) { + var randomBytes = crypto$1.node.randomBytes; + return Uint8Array.from(randomBytes(bytesLength)); + } else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: function randomPrivateKey() { + return utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)); + }, + precompute: function precompute() { + var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; + var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point.BASE; + var cached = point === Point.BASE ? point : new Point(point.x, point.y); - function ShaError(message) { - _classCallCheck(this, ShaError); + cached._setWindowSize(windowSize); - return _super.call(this, message); - } + cached.multiply(_3n); + return cached; + }, + sha256: function () { + var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var _len4, + messages, + _key4, + buffer, + createHash, + hash, + _args4 = arguments; - return _createClass(ShaError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + for (_len4 = _args4.length, messages = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + messages[_key4] = _args4[_key4]; + } -function assertJacPoint(other) { - if (!(other instanceof JacobianPoint)) throw new TypeError('JacobianPoint expected'); -} + if (!crypto$1.web) { + _context4.next = 8; + break; + } -var JacobianPoint = /*#__PURE__*/function () { - function JacobianPoint(x, y, z) { - _classCallCheck(this, JacobianPoint); + _context4.next = 4; + return crypto$1.web.subtle.digest('SHA-256', concatBytes.apply(void 0, messages)); - this.x = x; - this.y = y; - this.z = z; - } + case 4: + buffer = _context4.sent; + return _context4.abrupt("return", new Uint8Array(buffer)); - _createClass(JacobianPoint, [{ - key: "equals", - value: function equals(other) { - assertJacPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - var Z1Z1 = mod(Z1 * Z1); - var Z2Z2 = mod(Z2 * Z2); - var U1 = mod(X1 * Z2Z2); - var U2 = mod(X2 * Z1Z1); - var S1 = mod(mod(Y1 * Z2) * Z2Z2); - var S2 = mod(mod(Y2 * Z1) * Z1Z1); - return U1 === U2 && S1 === S2; - } - }, { - key: "negate", - value: function negate() { - return new JacobianPoint(this.x, mod(-this.y), this.z); - } - }, { - key: "double", - value: function double() { - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var A = mod(X1 * X1); - var B = mod(Y1 * Y1); - var C = mod(B * B); - var x1b = X1 + B; - var D = mod(_2n * (mod(x1b * x1b) - A - C)); - var E = mod(_3n * A); - var F = mod(E * E); - var X3 = mod(F - _2n * D); - var Y3 = mod(E * (D - X3) - _8n * C); - var Z3 = mod(_2n * Y1 * Z1); - return new JacobianPoint(X3, Y3, Z3); - } - }, { - key: "add", - value: function add(other) { - assertJacPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - if (X2 === _0n || Y2 === _0n) return this; - if (X1 === _0n || Y1 === _0n) return other; - var Z1Z1 = mod(Z1 * Z1); - var Z2Z2 = mod(Z2 * Z2); - var U1 = mod(X1 * Z2Z2); - var U2 = mod(X2 * Z1Z1); - var S1 = mod(mod(Y1 * Z2) * Z2Z2); - var S2 = mod(mod(Y2 * Z1) * Z1Z1); - var H = mod(U2 - U1); - var r = mod(S2 - S1); + case 8: + if (!crypto$1.node) { + _context4.next = 15; + break; + } - if (H === _0n) { - if (r === _0n) { - return this["double"](); - } else { - return JacobianPoint.ZERO; + createHash = crypto$1.node.createHash; + hash = createHash('sha256'); + messages.forEach(function (m) { + return hash.update(m); + }); + return _context4.abrupt("return", Uint8Array.from(hash.digest())); + + case 15: + throw new Error("The environment doesn't have sha256 function"); + + case 16: + case "end": + return _context4.stop(); } - } + }, _callee4); + })); - var HH = mod(H * H); - var HHH = mod(H * HH); - var V = mod(U1 * HH); - var X3 = mod(r * r - HHH - _2n * V); - var Y3 = mod(r * (V - X3) - S1 * HHH); - var Z3 = mod(Z1 * Z2 * H); - return new JacobianPoint(X3, Y3, Z3); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); + function sha256() { + return _sha.apply(this, arguments); } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - var P0 = JacobianPoint.ZERO; - if (typeof scalar === 'bigint' && scalar === _0n) return P0; - var n = normalizeScalar(scalar); - if (n === _1n) return this; - if (!USE_ENDOMORPHISM) { - var p = P0; + return sha256; + }(), + hmacSha256: function () { + var _hmacSha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) { + var _len5, + messages, + _key5, + ckey, + message, + buffer, + createHmac, + hash, + _args5 = arguments; - var _d = this; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + for (_len5 = _args5.length, messages = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + messages[_key5 - 1] = _args5[_key5]; + } - while (n > _0n) { - if (n & _1n) p = p.add(_d); - _d = _d["double"](); - n >>= _1n; - } + if (!crypto$1.web) { + _context5.next = 12; + break; + } - return p; - } + _context5.next = 4; + return crypto$1.web.subtle.importKey('raw', key, { + name: 'HMAC', + hash: { + name: 'SHA-256' + } + }, false, ['sign']); - var _endo$splitScalar = endo.splitScalar(n), - k1neg = _endo$splitScalar.k1neg, - k1 = _endo$splitScalar.k1, - k2neg = _endo$splitScalar.k2neg, - k2 = _endo$splitScalar.k2; + case 4: + ckey = _context5.sent; + message = concatBytes.apply(void 0, messages); + _context5.next = 8; + return crypto$1.web.subtle.sign('HMAC', ckey, message); - var k1p = P0; - var k2p = P0; - var d = this; + case 8: + buffer = _context5.sent; + return _context5.abrupt("return", new Uint8Array(buffer)); - while (k1 > _0n || k2 > _0n) { - if (k1 & _1n) k1p = k1p.add(d); - if (k2 & _1n) k2p = k2p.add(d); - d = d["double"](); - k1 >>= _1n; - k2 >>= _1n; - } + case 12: + if (!crypto$1.node) { + _context5.next = 19; + break; + } - if (k1neg) k1p = k1p.negate(); - if (k2neg) k2p = k2p.negate(); - k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); - return k1p.add(k2p); - } - }, { - key: "precomputeWindow", - value: function precomputeWindow(W) { - var windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; - var points = []; - var p = this; - var base = p; + createHmac = crypto$1.node.createHmac; + hash = createHmac('sha256', key); + messages.forEach(function (m) { + return hash.update(m); + }); + return _context5.abrupt("return", Uint8Array.from(hash.digest())); - for (var window = 0; window < windows; window++) { - base = p; - points.push(base); + case 19: + throw new Error("The environment doesn't have hmac-sha256 function"); - for (var i = 1; i < Math.pow(2, W - 1); i++) { - base = base.add(p); - points.push(base); + case 20: + case "end": + return _context5.stop(); } + }, _callee5); + })); - p = base["double"](); - } - - return points; + function hmacSha256(_x9) { + return _hmacSha.apply(this, arguments); } - }, { - key: "wNAF", - value: function wNAF(n, affinePoint) { - if (!affinePoint && this.equals(JacobianPoint.BASE)) affinePoint = Point.BASE; - var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - - if (256 % W) { - throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); - } - var precomputes = affinePoint && pointPrecomputes.get(affinePoint); + return hmacSha256; + }(), + sha256Sync: undefined, + hmacSha256Sync: undefined, + taggedHash: function () { + var _taggedHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(tag) { + var tagP, + tagH, + _len6, + messages, + _key6, + _args6 = arguments; - if (!precomputes) { - precomputes = this.precomputeWindow(W); + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + tagP = TAGGED_HASH_PREFIXES[tag]; - if (affinePoint && W !== 1) { - precomputes = JacobianPoint.normalizeZ(precomputes); - pointPrecomputes.set(affinePoint, precomputes); - } - } + if (!(tagP === undefined)) { + _context6.next = 7; + break; + } - var p = JacobianPoint.ZERO; - var f = JacobianPoint.BASE; - var windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); - var windowSize = Math.pow(2, W - 1); - var mask = BigInt(Math.pow(2, W) - 1); - var maxNumber = Math.pow(2, W); - var shiftBy = BigInt(W); + _context6.next = 4; + return utils.sha256(Uint8Array.from(tag, function (c) { + return c.charCodeAt(0); + })); - for (var window = 0; window < windows; window++) { - var offset = window * windowSize; - var wbits = Number(n & mask); - n >>= shiftBy; + case 4: + tagH = _context6.sent; + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n; - } + case 7: + for (_len6 = _args6.length, messages = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + messages[_key6 - 1] = _args6[_key6]; + } - var offset1 = offset; - var offset2 = offset + Math.abs(wbits) - 1; - var cond1 = window % 2 !== 0; - var cond2 = wbits < 0; + return _context6.abrupt("return", utils.sha256.apply(utils, [tagP].concat(messages))); - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); + case 9: + case "end": + return _context6.stop(); } - } + }, _callee6); + })); - return { - p: p, - f: f - }; + function taggedHash(_x10) { + return _taggedHash.apply(this, arguments); } - }, { - key: "multiply", - value: function multiply(scalar, affinePoint) { - var n = normalizeScalar(scalar); - var point; - var fake; - - if (USE_ENDOMORPHISM) { - var _endo$splitScalar3 = endo.splitScalar(n), - k1neg = _endo$splitScalar3.k1neg, - k1 = _endo$splitScalar3.k1, - k2neg = _endo$splitScalar3.k2neg, - k2 = _endo$splitScalar3.k2; - var _this$wNAF2 = this.wNAF(k1, affinePoint), - k1p = _this$wNAF2.p, - f1p = _this$wNAF2.f; + return taggedHash; + }(), + taggedHashSync: function taggedHashSync(tag) { + if (typeof _sha256Sync !== 'function') throw new ShaError('sha256Sync is undefined, you need to set it'); + var tagP = TAGGED_HASH_PREFIXES[tag]; - var _this$wNAF4 = this.wNAF(k2, affinePoint), - k2p = _this$wNAF4.p, - f2p = _this$wNAF4.f; + if (tagP === undefined) { + var tagH = _sha256Sync(Uint8Array.from(tag, function (c) { + return c.charCodeAt(0); + })); - k1p = constTimeNegate(k1neg, k1p); - k2p = constTimeNegate(k2neg, k2p); - k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - var _this$wNAF6 = this.wNAF(n, affinePoint), - p = _this$wNAF6.p, - f = _this$wNAF6.f; + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } - point = p; - fake = f; - } + for (var _len7 = arguments.length, messages = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + messages[_key7 - 1] = arguments[_key7]; + } - return JacobianPoint.normalizeZ([point, fake])[0]; + return _sha256Sync.apply(void 0, [tagP].concat(messages)); + }, + _JacobianPoint: JacobianPoint +}; +Object.defineProperties(utils, { + sha256Sync: { + configurable: false, + get: function get() { + return _sha256Sync; + }, + set: function set(val) { + if (!_sha256Sync) _sha256Sync = val; } - }, { - key: "toAffine", - value: function toAffine(invZ) { - var x = this.x, - y = this.y, - z = this.z; - var is0 = this.equals(JacobianPoint.ZERO); - if (invZ == null) invZ = is0 ? _8n : invert(z); - var iz1 = invZ; - var iz2 = mod(iz1 * iz1); - var iz3 = mod(iz2 * iz1); - var ax = mod(x * iz2); - var ay = mod(y * iz3); - var zz = mod(z * iz1); - if (is0) return Point.ZERO; - if (zz !== _1n) throw new Error('invZ was invalid'); - return new Point(ax, ay); + }, + hmacSha256Sync: { + configurable: false, + get: function get() { + return _hmacSha256Sync; + }, + set: function set(val) { + if (!_hmacSha256Sync) _hmacSha256Sync = val; } - }], [{ - key: "fromAffine", - value: function fromAffine(p) { - if (!(p instanceof Point)) { - throw new TypeError('JacobianPoint#fromAffine: expected Point'); - } + } +}); + +var _excluded = ["commitment"], + _excluded2 = ["encoding"], + _excluded3 = ["commitment"], + _excluded4 = ["commitment"]; +/** + * A 64 byte secret key, the first 32 bytes of which is the + * private scalar and the last 32 bytes is the public key. + * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ + */ + +utils$1.sha512Sync = function () { + var _ed25519$utils; + + return sha512((_ed25519$utils = utils$1).concatBytes.apply(_ed25519$utils, arguments)); +}; + +var generatePrivateKey = utils$1.randomPrivateKey; + +var generateKeypair = function generateKeypair() { + var privateScalar = utils$1.randomPrivateKey(); + var publicKey = getPublicKey(privateScalar); + var secretKey = new Uint8Array(64); + secretKey.set(privateScalar); + secretKey.set(publicKey, 32); + return { + publicKey: publicKey, + secretKey: secretKey + }; +}; + +var getPublicKey = sync.getPublicKey; + +function _isOnCurve(publicKey) { + try { + Point$1.fromHex(publicKey, true + /* strict */ + ); + return true; + } catch (_unused) { + return false; + } +} + +var _sign = function sign(message, secretKey) { + return sync.sign(message, secretKey.slice(0, 32)); +}; + +var verify = sync.verify; + +var toBuffer = function toBuffer(arr) { + if (Buffer$1.isBuffer(arr)) { + return arr; + } else if (arr instanceof Uint8Array) { + return Buffer$1.from(arr.buffer, arr.byteOffset, arr.byteLength); + } else { + return Buffer$1.from(arr); + } +}; // Class wrapping a plain object - if (p.equals(Point.ZERO)) return JacobianPoint.ZERO; - return new JacobianPoint(p.x, p.y, _1n); + +var Struct = /*#__PURE__*/function () { + function Struct(properties) { + _classCallCheck(this, Struct); + + Object.assign(this, properties); + } + + _createClass(Struct, [{ + key: "encode", + value: function encode() { + return Buffer$1.from(serialize_1(SOLANA_SCHEMA, this)); } - }, { - key: "toAffineBatch", - value: function toAffineBatch(points) { - var toInv = invertBatch(points.map(function (p) { - return p.z; - })); - return points.map(function (p, i) { - return p.toAffine(toInv[i]); - }); + }], [{ + key: "decode", + value: function decode(data) { + return deserialize_1(SOLANA_SCHEMA, this, data); } }, { - key: "normalizeZ", - value: function normalizeZ(points) { - return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + key: "decodeUnchecked", + value: function decodeUnchecked(data) { + return deserializeUnchecked_1(SOLANA_SCHEMA, this, data); } }]); - return JacobianPoint; -}(); + return Struct; +}(); // Class representing a Rust-compatible enum, since enums are only strings or +// numbers in pure JS -JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); -JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); -function constTimeNegate(condition, item) { - var neg = item.negate(); - return condition ? neg : item; -} +var Enum = /*#__PURE__*/function (_Struct) { + _inherits(Enum, _Struct); -var pointPrecomputes = new WeakMap(); -var Point = /*#__PURE__*/function () { - function Point(x, y) { - _classCallCheck(this, Point); + var _super = _createSuper(Enum); - this.x = x; - this.y = y; - } + function Enum(properties) { + var _this; - _createClass(Point, [{ - key: "_setWindowSize", - value: function _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes["delete"](this); - } - }, { - key: "hasEvenY", - value: function hasEvenY() { - return this.y % _2n === _0n; - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return hexToBytes(this.toHex(isCompressed)); - } - }, { - key: "toHex", - value: function toHex() { - var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var x = numTo32bStr(this.x); + _classCallCheck(this, Enum); - if (isCompressed) { - var prefix = this.hasEvenY() ? '02' : '03'; - return "".concat(prefix).concat(x); - } else { - return "04".concat(x).concat(numTo32bStr(this.y)); - } - } - }, { - key: "toHexX", - value: function toHexX() { - return this.toHex(true).slice(2); - } - }, { - key: "toRawX", - value: function toRawX() { - return this.toRawBytes(true).slice(1); - } - }, { - key: "assertValidity", - value: function assertValidity() { - var msg = 'Point is not on elliptic curve'; - var x = this.x, - y = this.y; - if (!isValidFieldElement(x) || !isValidFieldElement(y)) throw new Error(msg); - var left = mod(y * y); - var right = weierstrass(x); - if (mod(left - right) !== _0n) throw new Error(msg); - } - }, { - key: "equals", - value: function equals(other) { - return this.x === other.x && this.y === other.y; - } - }, { - key: "negate", - value: function negate() { - return new Point(this.x, mod(-this.y)); - } - }, { - key: "double", - value: function double() { - return JacobianPoint.fromAffine(this)["double"]().toAffine(); - } - }, { - key: "add", - value: function add(other) { - return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); - } - }, { - key: "multiplyAndAddUnsafe", - value: function multiplyAndAddUnsafe(Q, a, b) { - var P = JacobianPoint.fromAffine(this); - var aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); - var bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); - var sum = aP.add(bQ); - return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + _this = _super.call(this, properties); + _this["enum"] = ''; + + if (Object.keys(properties).length !== 1) { + throw new Error('Enum can only take single value'); } - }], [{ - key: "fromCompressedHex", - value: function fromCompressedHex(bytes) { - var isShort = bytes.length === 32; - var x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); - if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); - var y2 = weierstrass(x); - var y = sqrtMod(y2); - var isYOdd = (y & _1n) === _1n; - if (isShort) { - if (isYOdd) y = mod(-y); - } else { - var isFirstByteOdd = (bytes[0] & 1) === 1; - if (isFirstByteOdd !== isYOdd) y = mod(-y); - } + Object.keys(properties).map(function (key) { + _this["enum"] = key; + }); + return _this; + } - var point = new Point(x, y); - point.assertValidity(); - return point; - } - }, { - key: "fromUncompressedHex", - value: function fromUncompressedHex(bytes) { - var x = bytesToNumber(bytes.subarray(1, fieldLen + 1)); - var y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1)); - var point = new Point(x, y); - point.assertValidity(); - return point; - } - }, { - key: "fromHex", - value: function fromHex(hex) { - var bytes = ensureBytes(hex); - var len = bytes.length; - var header = bytes[0]; - if (len === fieldLen) return this.fromCompressedHex(bytes); + return _createClass(Enum); +}(Struct); - if (len === compressedLen && (header === 0x02 || header === 0x03)) { - return this.fromCompressedHex(bytes); - } +var SOLANA_SCHEMA = new Map(); - if (len === uncompressedLen && header === 0x04) return this.fromUncompressedHex(bytes); - throw new Error("Point.fromHex: received invalid point. Expected 32-".concat(compressedLen, " compressed bytes or ").concat(uncompressedLen, " uncompressed bytes, not ").concat(len)); - } - }, { - key: "fromPrivateKey", - value: function fromPrivateKey(privateKey) { - return Point.BASE.multiply(normalizePrivateKey(privateKey)); - } - }, { - key: "fromSignature", - value: function fromSignature(msgHash, signature, recovery) { - var _normalizeSignature = normalizeSignature(signature), - r = _normalizeSignature.r, - s = _normalizeSignature.s; +var _Symbol$toStringTag; +/** + * Maximum length of derived pubkey seed + */ - if (![0, 1, 2, 3].includes(recovery)) throw new Error('Cannot recover: invalid recovery bit'); - var h = truncateHash(ensureBytes(msgHash)); - var n = CURVE.n; - var radj = recovery === 2 || recovery === 3 ? r + n : r; - var rinv = invert(radj, n); - var u1 = mod(-h * rinv, n); - var u2 = mod(s * rinv, n); - var prefix = recovery & 1 ? '03' : '02'; - var R = Point.fromHex(prefix + numTo32bStr(radj)); - var Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) throw new Error('Cannot recover signature: point at infinify'); - Q.assertValidity(); - return Q; - } - }]); - return Point; -}(); -Point.BASE = new Point(CURVE.Gx, CURVE.Gy); -Point.ZERO = new Point(_0n, _0n); +var MAX_SEED_LENGTH = 32; +/** + * Size of public key in bytes + */ -function sliceDER(s) { - return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; -} +var PUBLIC_KEY_LENGTH = 32; +/** + * Value to be converted into public key + */ -function parseDERInt(data) { - if (data.length < 2 || data[0] !== 0x02) { - throw new Error("Invalid signature integer tag: ".concat(bytesToHex(data))); - } +function isPublicKeyData(value) { + return value._bn !== undefined; +} // local counter used by PublicKey.unique() - var len = data[1]; - var res = data.subarray(2, len + 2); - if (!len || res.length !== len) { - throw new Error("Invalid signature integer: wrong length"); - } +var uniquePublicKeyCounter = 1; +/** + * A public key + */ - if (res[0] === 0x00 && res[1] <= 0x7f) { - throw new Error('Invalid signature integer: trailing length'); - } +_Symbol$toStringTag = Symbol.toStringTag; - return { - data: bytesToNumber(res), - left: data.subarray(len + 2) - }; -} +var PublicKey = /*#__PURE__*/function (_Struct2, _Symbol$toStringTag2) { + _inherits(PublicKey, _Struct2); -function parseDERSignature(data) { - if (data.length < 2 || data[0] != 0x30) { - throw new Error("Invalid signature tag: ".concat(bytesToHex(data))); - } + var _super2 = _createSuper(PublicKey); - if (data[1] !== data.length - 2) { - throw new Error('Invalid signature: incorrect length'); - } + /** @internal */ - var _parseDERInt = parseDERInt(data.subarray(2)), - r = _parseDERInt.data, - sBytes = _parseDERInt.left; + /** + * Create a new PublicKey object + * @param value ed25519 public key as buffer or base-58 encoded string + */ + function PublicKey(value) { + var _this2; - var _parseDERInt2 = parseDERInt(sBytes), - s = _parseDERInt2.data, - rBytesLeft = _parseDERInt2.left; + _classCallCheck(this, PublicKey); - if (rBytesLeft.length) { - throw new Error("Invalid signature: left bytes after parsing: ".concat(bytesToHex(rBytesLeft))); - } + _this2 = _super2.call(this, {}); + _this2._bn = void 0; - return { - r: r, - s: s - }; -} + if (isPublicKeyData(value)) { + _this2._bn = value._bn; + } else { + if (typeof value === 'string') { + // assume base 58 encoding by default + var decoded = bs58$3.decode(value); -var Signature = /*#__PURE__*/function () { - function Signature(r, s) { - _classCallCheck(this, Signature); + if (decoded.length != PUBLIC_KEY_LENGTH) { + throw new Error("Invalid public key input"); + } - this.r = r; - this.s = s; - this.assertValidity(); - } + _this2._bn = new BN$1(decoded); + } else { + _this2._bn = new BN$1(value); + } - _createClass(Signature, [{ - key: "assertValidity", - value: function assertValidity() { - var r = this.r, - s = this.s; - if (!isWithinCurveOrder(r)) throw new Error('Invalid Signature: r must be 0 < r < n'); - if (!isWithinCurveOrder(s)) throw new Error('Invalid Signature: s must be 0 < s < n'); - } - }, { - key: "hasHighS", - value: function hasHighS() { - var HALF = CURVE.n >> _1n; - return this.s > HALF; + if (_this2._bn.byteLength() > PUBLIC_KEY_LENGTH) { + throw new Error("Invalid public key input"); + } } - }, { - key: "normalizeS", - value: function normalizeS() { - return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this; + + return _this2; + } + /** + * Returns a unique PublicKey for tests and benchmarks using a counter + */ + + + _createClass(PublicKey, [{ + key: "equals", + value: + /** + * Default public key value. The base58-encoded string representation is all ones (as seen below) + * The underlying BN number is 32 bytes that are all zeros + */ + + /** + * Checks if two publicKeys are equal + */ + function equals(publicKey) { + return this._bn.eq(publicKey._bn); } + /** + * Return the base-58 representation of the public key + */ + }, { - key: "toDERRawBytes", - value: function toDERRawBytes() { - return hexToBytes(this.toDERHex()); + key: "toBase58", + value: function toBase58() { + return bs58$3.encode(this.toBytes()); } }, { - key: "toDERHex", - value: function toDERHex() { - var sHex = sliceDER(numberToHexUnpadded(this.s)); - var rHex = sliceDER(numberToHexUnpadded(this.r)); - var sHexL = sHex.length / 2; - var rHexL = rHex.length / 2; - var sLen = numberToHexUnpadded(sHexL); - var rLen = numberToHexUnpadded(rHexL); - var length = numberToHexUnpadded(rHexL + sHexL + 4); - return "30".concat(length, "02").concat(rLen).concat(rHex, "02").concat(sLen).concat(sHex); + key: "toJSON", + value: function toJSON() { + return this.toBase58(); } + /** + * Return the byte array representation of the public key in big endian + */ + }, { - key: "toRawBytes", - value: function toRawBytes() { - return this.toDERRawBytes(); + key: "toBytes", + value: function toBytes() { + var buf = this.toBuffer(); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } + /** + * Return the Buffer representation of the public key in big endian + */ + }, { - key: "toHex", - value: function toHex() { - return this.toDERHex(); + key: "toBuffer", + value: function toBuffer() { + var b = this._bn.toArrayLike(Buffer$1); + + if (b.length === PUBLIC_KEY_LENGTH) { + return b; + } + + var zeroPad = Buffer$1.alloc(32); + b.copy(zeroPad, 32 - b.length); + return zeroPad; } }, { - key: "toCompactRawBytes", - value: function toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); + key: _Symbol$toStringTag2, + get: function get() { + return "PublicKey(".concat(this.toString(), ")"); } + /** + * Return the base-58 representation of the public key + */ + }, { - key: "toCompactHex", - value: function toCompactHex() { - return numTo32bStr(this.r) + numTo32bStr(this.s); + key: "toString", + value: function toString() { + return this.toBase58(); } + /** + * Derive a public key from another key, a seed, and a program ID. + * The program ID will also serve as the owner of the public key, giving + * it permission to write data to the account. + */ + + /* eslint-disable require-await */ + }], [{ - key: "fromCompact", - value: function fromCompact(hex) { - var arr = hex instanceof Uint8Array; - var name = 'Signature.fromCompact'; - if (typeof hex !== 'string' && !arr) throw new TypeError("".concat(name, ": Expected string or Uint8Array")); - var str = arr ? bytesToHex(hex) : hex; - if (str.length !== 128) throw new Error("".concat(name, ": Expected 64-byte hex")); - return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + key: "unique", + value: function unique() { + var key = new PublicKey(uniquePublicKeyCounter); + uniquePublicKeyCounter += 1; + return new PublicKey(key.toBuffer()); } }, { - key: "fromDER", - value: function fromDER(hex) { - var arr = hex instanceof Uint8Array; - if (typeof hex !== 'string' && !arr) throw new TypeError("Signature.fromDER: Expected string or Uint8Array"); + key: "createWithSeed", + value: function () { + var _createWithSeed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(fromPublicKey, seed, programId) { + var buffer, publicKeyBytes; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + buffer = Buffer$1.concat([fromPublicKey.toBuffer(), Buffer$1.from(seed), programId.toBuffer()]); + publicKeyBytes = sha256(buffer); + return _context.abrupt("return", new PublicKey(publicKeyBytes)); - var _parseDERSignature = parseDERSignature(arr ? hex : hexToBytes(hex)), - r = _parseDERSignature.r, - s = _parseDERSignature.s; + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); - return new Signature(r, s); - } - }, { - key: "fromHex", - value: function fromHex(hex) { - return this.fromDER(hex); - } - }]); + function createWithSeed(_x, _x2, _x3) { + return _createWithSeed.apply(this, arguments); + } - return Signature; -}(); + return createWithSeed; + }() + /** + * Derive a program address from seeds and a program ID. + */ -function concatBytes() { - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } + /* eslint-disable require-await */ + + }, { + key: "createProgramAddressSync", + value: function createProgramAddressSync(seeds, programId) { + var buffer = Buffer$1.alloc(0); + seeds.forEach(function (seed) { + if (seed.length > MAX_SEED_LENGTH) { + throw new TypeError("Max seed length exceeded"); + } - if (!arrays.every(function (b) { - return b instanceof Uint8Array; - })) throw new Error('Uint8Array list expected'); - if (arrays.length === 1) return arrays[0]; - var length = arrays.reduce(function (a, arr) { - return a + arr.length; - }, 0); - var result = new Uint8Array(length); + buffer = Buffer$1.concat([buffer, toBuffer(seed)]); + }); + buffer = Buffer$1.concat([buffer, programId.toBuffer(), Buffer$1.from('ProgramDerivedAddress')]); + var publicKeyBytes = sha256(buffer); - for (var i = 0, pad = 0; i < arrays.length; i++) { - var arr = arrays[i]; - result.set(arr, pad); - pad += arr.length; - } + if (_isOnCurve(publicKeyBytes)) { + throw new Error("Invalid seeds, address must fall off the curve"); + } - return result; -} + return new PublicKey(publicKeyBytes); + } + /** + * Async version of createProgramAddressSync + * For backwards compatibility + * + * @deprecated Use {@link createProgramAddressSync} instead + */ -var hexes = Array.from({ - length: 256 -}, function (v, i) { - return i.toString(16).padStart(2, '0'); -}); + /* eslint-disable require-await */ -function bytesToHex(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); - var hex = ''; + }, { + key: "createProgramAddress", + value: function () { + var _createProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(seeds, programId) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", this.createProgramAddressSync(seeds, programId)); - for (var i = 0; i < uint8a.length; i++) { - hex += hexes[uint8a[i]]; - } + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); - return hex; -} + function createProgramAddress(_x4, _x5) { + return _createProgramAddress.apply(this, arguments); + } -var POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); + return createProgramAddress; + }() + /** + * Find a valid program address + * + * Valid program addresses must fall off the ed25519 curve. This function + * iterates a nonce until it finds one that when combined with the seeds + * results in a valid program address. + */ -function numTo32bStr(num) { - if (typeof num !== 'bigint') throw new Error('Expected bigint'); - if (!(_0n <= num && num < POW_2_256)) throw new Error('Expected number 0 <= n < 2^256'); - return num.toString(16).padStart(64, '0'); -} + }, { + key: "findProgramAddressSync", + value: function findProgramAddressSync(seeds, programId) { + var nonce = 255; + var address; -function numTo32b(num) { - var b = hexToBytes(numTo32bStr(num)); - if (b.length !== 32) throw new Error('Error: expected 32 bytes'); - return b; -} + while (nonce != 0) { + try { + var seedsWithNonce = seeds.concat(Buffer$1.from([nonce])); + address = this.createProgramAddressSync(seedsWithNonce, programId); + } catch (err) { + if (err instanceof TypeError) { + throw err; + } -function numberToHexUnpadded(num) { - var hex = num.toString(16); - return hex.length & 1 ? "0".concat(hex) : hex; -} + nonce--; + continue; + } -function hexToNumber(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToNumber: expected string, got ' + _typeof$1(hex)); - } + return [address, nonce]; + } - return BigInt("0x".concat(hex)); -} + throw new Error("Unable to find a viable program address nonce"); + } + /** + * Async version of findProgramAddressSync + * For backwards compatibility + * + * @deprecated Use {@link findProgramAddressSync} instead + */ -function hexToBytes(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); - } + }, { + key: "findProgramAddress", + value: function () { + var _findProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(seeds, programId) { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + return _context3.abrupt("return", this.findProgramAddressSync(seeds, programId)); - if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); - var array = new Uint8Array(hex.length / 2); + case 1: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); - for (var i = 0; i < array.length; i++) { - var j = i * 2; - var hexByte = hex.slice(j, j + 2); + function findProgramAddress(_x6, _x7) { + return _findProgramAddress.apply(this, arguments); + } - var _byte = Number.parseInt(hexByte, 16); + return findProgramAddress; + }() + /** + * Check that a pubkey is on the ed25519 curve. + */ - if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); - array[i] = _byte; - } + }, { + key: "isOnCurve", + value: function isOnCurve(pubkeyData) { + var pubkey = new PublicKey(pubkeyData); + return _isOnCurve(pubkey.toBytes()); + } + }]); - return array; -} + return PublicKey; +}(Struct, _Symbol$toStringTag); -function bytesToNumber(bytes) { - return hexToNumber(bytesToHex(bytes)); -} +PublicKey["default"] = new PublicKey('11111111111111111111111111111111'); +SOLANA_SCHEMA.set(PublicKey, { + kind: 'struct', + fields: [['_bn', 'u256']] +}); +/** + * An account key pair (public and secret keys). + * + * @deprecated since v1.10.0, please use {@link Keypair} instead. + */ -function ensureBytes(hex) { - return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); -} +var Account = /*#__PURE__*/function () { + /** @internal */ -function normalizeScalar(num) { - if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) return BigInt(num); - if (typeof num === 'bigint' && isWithinCurveOrder(num)) return num; - throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); -} + /** @internal */ -function mod(a) { - var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var result = a % b; - return result >= _0n ? result : b + result; -} + /** + * Create a new Account object + * + * If the secretKey parameter is not provided a new key pair is randomly + * created for the account + * + * @param secretKey Secret key for the account + */ + function Account(secretKey) { + _classCallCheck(this, Account); -function pow2(x, power) { - var P = CURVE.P; - var res = x; + this._publicKey = void 0; + this._secretKey = void 0; - while (power-- > _0n) { - res *= res; - res %= P; - } + if (secretKey) { + var secretKeyBuffer = toBuffer(secretKey); - return res; -} + if (secretKey.length !== 64) { + throw new Error('bad secret key size'); + } -function sqrtMod(x) { - var P = CURVE.P; + this._publicKey = secretKeyBuffer.slice(32, 64); + this._secretKey = secretKeyBuffer.slice(0, 32); + } else { + this._secretKey = toBuffer(generatePrivateKey()); + this._publicKey = toBuffer(getPublicKey(this._secretKey)); + } + } + /** + * The public key for this account + */ - var _6n = BigInt(6); - var _11n = BigInt(11); + _createClass(Account, [{ + key: "publicKey", + get: function get() { + return new PublicKey(this._publicKey); + } + /** + * The **unencrypted** secret key for this account. The first 32 bytes + * is the private scalar and the last 32 bytes is the public key. + * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ + */ - var _22n = BigInt(22); + }, { + key: "secretKey", + get: function get() { + return Buffer$1.concat([this._secretKey, this._publicKey], 64); + } + }]); - var _23n = BigInt(23); + return Account; +}(); - var _44n = BigInt(44); +var BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111'); +/** + * Maximum over-the-wire size of a Transaction + * + * 1280 is IPv6 minimum MTU + * 40 bytes is the size of the IPv6 header + * 8 bytes is the size of the fragment header + */ - var _88n = BigInt(88); +var PACKET_DATA_SIZE = 1280 - 40 - 8; +var VERSION_PREFIX_MASK = 0x7f; +var SIGNATURE_LENGTH_IN_BYTES = 64; - var b2 = x * x * x % P; - var b3 = b2 * b2 * x % P; - var b6 = pow2(b3, _3n) * b3 % P; - var b9 = pow2(b6, _3n) * b3 % P; - var b11 = pow2(b9, _2n) * b2 % P; - var b22 = pow2(b11, _11n) * b11 % P; - var b44 = pow2(b22, _22n) * b22 % P; - var b88 = pow2(b44, _44n) * b44 % P; - var b176 = pow2(b88, _88n) * b88 % P; - var b220 = pow2(b176, _44n) * b44 % P; - var b223 = pow2(b220, _3n) * b3 % P; - var t1 = pow2(b223, _23n) * b22 % P; - var t2 = pow2(t1, _6n) * b2 % P; - var rt = pow2(t2, _2n); - var xc = rt * rt % P; - if (xc !== x) throw new Error('Cannot find square root'); - return rt; -} +var TransactionExpiredBlockheightExceededError = /*#__PURE__*/function (_Error) { + _inherits(TransactionExpiredBlockheightExceededError, _Error); -function invert(number) { - var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var _super3 = _createSuper(TransactionExpiredBlockheightExceededError); - if (number === _0n || modulo <= _0n) { - throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); - } + function TransactionExpiredBlockheightExceededError(signature) { + var _this3; - var a = mod(number, modulo); - var b = modulo; - var x = _0n, - u = _1n; + _classCallCheck(this, TransactionExpiredBlockheightExceededError); - while (a !== _0n) { - var q = b / a; - var r = b % a; - var m = x - u * q; - b = a, a = r, x = u, u = m; + _this3 = _super3.call(this, "Signature ".concat(signature, " has expired: block height exceeded.")); + _this3.signature = void 0; + _this3.signature = signature; + return _this3; } - var gcd = b; - if (gcd !== _1n) throw new Error('invert: does not exist'); - return mod(x, modulo); -} - -function invertBatch(nums) { - var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var scratch = new Array(nums.length); - var lastMultiplied = nums.reduce(function (acc, num, i) { - if (num === _0n) return acc; - scratch[i] = acc; - return mod(acc * num, p); - }, _1n); - var inverted = invert(lastMultiplied, p); - nums.reduceRight(function (acc, num, i) { - if (num === _0n) return acc; - scratch[i] = mod(acc * scratch[i], p); - return mod(acc * num, p); - }, inverted); - return scratch; -} + return _createClass(TransactionExpiredBlockheightExceededError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); -function bits2int_2(bytes) { - var delta = bytes.length * 8 - groupLen * 8; - var num = bytesToNumber(bytes); - return delta > 0 ? num >> BigInt(delta) : num; -} +Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', { + value: 'TransactionExpiredBlockheightExceededError' +}); -function truncateHash(hash) { - var truncateOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var h = bits2int_2(hash); - if (truncateOnly) return h; - var n = CURVE.n; - return h >= n ? h - n : h; -} +var TransactionExpiredTimeoutError = /*#__PURE__*/function (_Error2) { + _inherits(TransactionExpiredTimeoutError, _Error2); -var _sha256Sync; + var _super4 = _createSuper(TransactionExpiredTimeoutError); -var _hmacSha256Sync; + function TransactionExpiredTimeoutError(signature, timeoutSeconds) { + var _this4; -var HmacDrbg = /*#__PURE__*/function () { - function HmacDrbg(hashLen, qByteLen) { - _classCallCheck(this, HmacDrbg); + _classCallCheck(this, TransactionExpiredTimeoutError); - this.hashLen = hashLen; - this.qByteLen = qByteLen; - if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); - if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); - this.v = new Uint8Array(hashLen).fill(1); - this.k = new Uint8Array(hashLen).fill(0); - this.counter = 0; + _this4 = _super4.call(this, "Transaction was not confirmed in ".concat(timeoutSeconds.toFixed(2), " seconds. It is ") + 'unknown if it succeeded or failed. Check signature ' + "".concat(signature, " using the Solana Explorer or CLI tools.")); + _this4.signature = void 0; + _this4.signature = signature; + return _this4; } - _createClass(HmacDrbg, [{ - key: "hmac", - value: function hmac() { - for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - values[_key2] = arguments[_key2]; - } + return _createClass(TransactionExpiredTimeoutError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); - return utils.hmacSha256.apply(utils, [this.k].concat(values)); - } - }, { - key: "hmacSync", - value: function hmacSync() { - for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - values[_key3] = arguments[_key3]; - } +Object.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', { + value: 'TransactionExpiredTimeoutError' +}); - return _hmacSha256Sync.apply(void 0, [this.k].concat(values)); - } - }, { - key: "checkSync", - value: function checkSync() { - if (typeof _hmacSha256Sync !== 'function') throw new ShaError('hmacSha256Sync needs to be set'); - } - }, { - key: "incr", - value: function incr() { - if (this.counter >= 1000) throw new Error('Tried 1,000 k values for sign(), all were invalid'); - this.counter += 1; - } - }, { - key: "reseed", - value: function () { - var _reseed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { - var seed, - _args = arguments; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - seed = _args.length > 0 && _args[0] !== undefined ? _args[0] : new Uint8Array(); - _context.next = 3; - return this.hmac(this.v, Uint8Array.from([0x00]), seed); +var TransactionExpiredNonceInvalidError = /*#__PURE__*/function (_Error3) { + _inherits(TransactionExpiredNonceInvalidError, _Error3); - case 3: - this.k = _context.sent; - _context.next = 6; - return this.hmac(this.v); + var _super5 = _createSuper(TransactionExpiredNonceInvalidError); - case 6: - this.v = _context.sent; + function TransactionExpiredNonceInvalidError(signature) { + var _this5; - if (!(seed.length === 0)) { - _context.next = 9; - break; - } + _classCallCheck(this, TransactionExpiredNonceInvalidError); - return _context.abrupt("return"); + _this5 = _super5.call(this, "Signature ".concat(signature, " has expired: the nonce is no longer valid.")); + _this5.signature = void 0; + _this5.signature = signature; + return _this5; + } - case 9: - _context.next = 11; - return this.hmac(this.v, Uint8Array.from([0x01]), seed); + return _createClass(TransactionExpiredNonceInvalidError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); - case 11: - this.k = _context.sent; - _context.next = 14; - return this.hmac(this.v); +Object.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', { + value: 'TransactionExpiredNonceInvalidError' +}); - case 14: - this.v = _context.sent; +var MessageAccountKeys = /*#__PURE__*/function () { + function MessageAccountKeys(staticAccountKeys, accountKeysFromLookups) { + _classCallCheck(this, MessageAccountKeys); - case 15: - case "end": - return _context.stop(); - } - }, _callee, this); - })); + this.staticAccountKeys = void 0; + this.accountKeysFromLookups = void 0; + this.staticAccountKeys = staticAccountKeys; + this.accountKeysFromLookups = accountKeysFromLookups; + } - function reseed() { - return _reseed.apply(this, arguments); + _createClass(MessageAccountKeys, [{ + key: "keySegments", + value: function keySegments() { + var keySegments = [this.staticAccountKeys]; + + if (this.accountKeysFromLookups) { + keySegments.push(this.accountKeysFromLookups.writable); + keySegments.push(this.accountKeysFromLookups.readonly); } - return reseed; - }() - }, { - key: "reseedSync", - value: function reseedSync() { - var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Uint8Array(); - this.checkSync(); - this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); - this.v = this.hmacSync(this.v); - if (seed.length === 0) return; - this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); - this.v = this.hmacSync(this.v); + return keySegments; } }, { - key: "generate", - value: function () { - var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var len, out, sl; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - this.incr(); - len = 0; - out = []; - - case 3: - if (!(len < this.qByteLen)) { - _context2.next = 12; - break; - } - - _context2.next = 6; - return this.hmac(this.v); - - case 6: - this.v = _context2.sent; - sl = this.v.slice(); - out.push(sl); - len += this.v.length; - _context2.next = 3; - break; + key: "get", + value: function get(index) { + var _iterator = _createForOfIteratorHelper(this.keySegments()), + _step; - case 12: - return _context2.abrupt("return", concatBytes.apply(void 0, out)); + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var keySegment = _step.value; - case 13: - case "end": - return _context2.stop(); + if (index < keySegment.length) { + return keySegment[index]; + } else { + index -= keySegment.length; } - }, _callee2, this); - })); - - function generate() { - return _generate.apply(this, arguments); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - return generate; - }() + return; + } }, { - key: "generateSync", - value: function generateSync() { - this.checkSync(); - this.incr(); - var len = 0; - var out = []; + key: "length", + get: function get() { + return this.keySegments().flat().length; + } + }, { + key: "compileInstructions", + value: function compileInstructions(instructions) { + // Bail early if any account indexes would overflow a u8 + var U8_MAX = 255; - while (len < this.qByteLen) { - this.v = this.hmacSync(this.v); - var sl = this.v.slice(); - out.push(sl); - len += this.v.length; + if (this.length > U8_MAX + 1) { + throw new Error('Account index overflow encountered during compilation'); } - return concatBytes.apply(void 0, out); + var keyIndexMap = new Map(); + this.keySegments().flat().forEach(function (key, index) { + keyIndexMap.set(key.toBase58(), index); + }); + + var findKeyIndex = function findKeyIndex(key) { + var keyIndex = keyIndexMap.get(key.toBase58()); + if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation'); + return keyIndex; + }; + + return instructions.map(function (instruction) { + return { + programIdIndex: findKeyIndex(instruction.programId), + accountKeyIndexes: instruction.keys.map(function (meta) { + return findKeyIndex(meta.pubkey); + }), + data: instruction.data + }; + }); } }]); - return HmacDrbg; + return MessageAccountKeys; }(); +/** + * Layout for a public key + */ -function isWithinCurveOrder(num) { - return _0n < num && num < CURVE.n; -} -function isValidFieldElement(num) { - return _0n < num && num < CURVE.P; -} +var publicKey = function publicKey() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'publicKey'; + return blob$1(32, property); +}; +/** + * Layout for a signature + */ -function kmdToSig(kBytes, m, d) { - var lowS = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; - var n = CURVE.n; - var k = truncateHash(kBytes, true); - if (!isWithinCurveOrder(k)) return; - var kinv = invert(k, n); - var q = Point.BASE.multiply(k); - var r = mod(q.x, n); - if (r === _0n) return; - var s = mod(kinv * mod(m + d * r, n), n); - if (s === _0n) return; - var sig = new Signature(r, s); - var recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); - if (lowS && sig.hasHighS()) { - sig = sig.normalizeS(); - recovery ^= 1; - } +var signature = function signature() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'signature'; + return blob$1(64, property); +}; +/** + * Layout for a Rust String type + */ - return { - sig: sig, - recovery: recovery - }; -} -function normalizePrivateKey(key) { - var num; +var rustString = function rustString() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'string'; + var rsl = struct([u32('length'), u32('lengthPadding'), blob$1(offset$1(u32(), -8), 'chars')], property); - if (typeof key === 'bigint') { - num = key; - } else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { - num = BigInt(key); - } else if (typeof key === 'string') { - if (key.length !== 2 * groupLen) throw new Error('Expected 32 bytes of private key'); - num = hexToNumber(key); - } else if (key instanceof Uint8Array) { - if (key.length !== groupLen) throw new Error('Expected 32 bytes of private key'); - num = bytesToNumber(key); - } else { - throw new TypeError('Expected valid private key'); - } + var _decode = rsl.decode.bind(rsl); - if (!isWithinCurveOrder(num)) throw new Error('Expected private key: 0 < key < n'); - return num; -} + var _encode = rsl.encode.bind(rsl); -function normalizeSignature(signature) { - if (signature instanceof Signature) { - signature.assertValidity(); - return signature; - } + var rslShim = rsl; - try { - return Signature.fromDER(signature); - } catch (error) { - return Signature.fromCompact(signature); - } -} + rslShim.decode = function (b, offset) { + var data = _decode(b, offset); -function getPublicKey$1(privateKey) { - var isCompressed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); -} + return data['chars'].toString(); + }; -function bits2int(bytes) { - var slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes; - return bytesToNumber(slice); -} + rslShim.encode = function (str, b, offset) { + var data = { + chars: Buffer$1.from(str, 'utf8') + }; + return _encode(data, b, offset); + }; -function bits2octets(bytes) { - var z1 = bits2int(bytes); - var z2 = mod(z1, CURVE.n); - return int2octets(z2 < _0n ? z1 : z2); -} + rslShim.alloc = function (str) { + return u32().span + u32().span + Buffer$1.from(str, 'utf8').length; + }; -function int2octets(num) { - return numTo32b(num); -} + return rslShim; +}; +/** + * Layout for an Authorized object + */ -function initSigArgs(msgHash, privateKey, extraEntropy) { - if (msgHash == null) throw new Error("sign: expected valid message hash, not \"".concat(msgHash, "\"")); - var h1 = ensureBytes(msgHash); - var d = normalizePrivateKey(privateKey); - var seedArgs = [int2octets(d), bits2octets(h1)]; - if (extraEntropy != null) { - if (extraEntropy === true) extraEntropy = utils.randomBytes(fieldLen); - var e = ensureBytes(extraEntropy); - if (e.length !== fieldLen) throw new Error("sign: Expected ".concat(fieldLen, " bytes of extra data")); - seedArgs.push(e); - } +var authorized = function authorized() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'authorized'; + return struct([publicKey('staker'), publicKey('withdrawer')], property); +}; +/** + * Layout for a Lockup object + */ - var seed = concatBytes.apply(void 0, seedArgs); - var m = bits2int(h1); - return { - seed: seed, - m: m, - d: d - }; -} -function finalizeSig(recSig, opts) { - var sig = recSig.sig, - recovery = recSig.recovery; +var lockup = function lockup() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'lockup'; + return struct([ns64('unixTimestamp'), ns64('epoch'), publicKey('custodian')], property); +}; +/** + * Layout for a VoteInit object + */ - var _Object$assign = Object.assign({ - canonical: true, - der: true - }, opts), - der = _Object$assign.der, - recovered = _Object$assign.recovered; - var hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); - return recovered ? [hashed, recovery] : hashed; -} +var voteInit = function voteInit() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteInit'; + return struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), u8('commission')], property); +}; +/** + * Layout for a VoteAuthorizeWithSeedArgs object + */ -function signSync(msgHash, privKey) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var _initSigArgs = initSigArgs(msgHash, privKey, opts.extraEntropy), - seed = _initSigArgs.seed, - m = _initSigArgs.m, - d = _initSigArgs.d; +var voteAuthorizeWithSeedArgs = function voteAuthorizeWithSeedArgs() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteAuthorizeWithSeedArgs'; + return struct([u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property); +}; - var drbg = new HmacDrbg(hashLen, groupLen); - drbg.reseedSync(seed); - var sig; +function getAlloc(type, fields) { + var getItemAlloc = function getItemAlloc(item) { + if (item.span >= 0) { + return item.span; + } else if (typeof item.alloc === 'function') { + return item.alloc(fields[item.property]); + } else if ('count' in item && 'elementLayout' in item) { + var field = fields[item.property]; - while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical))) drbg.reseedSync(); + if (Array.isArray(field)) { + return field.length * getItemAlloc(item.elementLayout); + } + } else if ('fields' in item) { + // This is a `Structure` whose size needs to be recursively measured. + return getAlloc({ + layout: item + }, fields[item.property]); + } // Couldn't determine allocated size of layout - return finalizeSig(sig, opts); + + return 0; + }; + + var alloc = 0; + type.layout.fields.forEach(function (item) { + alloc += getItemAlloc(item); + }); + return alloc; } -Point.BASE._setWindowSize(8); +function decodeLength(bytes) { + var len = 0; + var size = 0; -var crypto$1 = { - node: nodeCrypto, - web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined -}; -var TAGGED_HASH_PREFIXES = {}; -var utils = { - bytesToHex: bytesToHex, - hexToBytes: hexToBytes, - concatBytes: concatBytes, - mod: mod, - invert: invert, - isValidPrivateKey: function isValidPrivateKey(privateKey) { - try { - normalizePrivateKey(privateKey); - return true; - } catch (error) { - return false; - } - }, - _bigintTo32Bytes: numTo32b, - _normalizePrivateKey: normalizePrivateKey, - hashToPrivateKey: function hashToPrivateKey(hash) { - hash = ensureBytes(hash); - var minLen = groupLen + 8; + for (;;) { + var elem = bytes.shift(); + len |= (elem & 0x7f) << size * 7; + size += 1; - if (hash.length < minLen || hash.length > 1024) { - throw new Error("Expected valid bytes of private key as per FIPS 186"); + if ((elem & 0x80) === 0) { + break; } + } - var num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; + return len; +} - return numTo32b(num); - }, - randomBytes: function randomBytes() { - var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; +function encodeLength(bytes, len) { + var rem_len = len; - if (crypto$1.web) { - return crypto$1.web.getRandomValues(new Uint8Array(bytesLength)); - } else if (crypto$1.node) { - var randomBytes = crypto$1.node.randomBytes; - return Uint8Array.from(randomBytes(bytesLength)); + for (;;) { + var elem = rem_len & 0x7f; + rem_len >>= 7; + + if (rem_len == 0) { + bytes.push(elem); + break; } else { - throw new Error("The environment doesn't have randomBytes function"); + elem |= 0x80; + bytes.push(elem); } - }, - randomPrivateKey: function randomPrivateKey() { - return utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)); - }, - precompute: function precompute() { - var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; - var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point.BASE; - var cached = point === Point.BASE ? point : new Point(point.x, point.y); - - cached._setWindowSize(windowSize); - - cached.multiply(_3n); - return cached; - }, - sha256: function () { - var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { - var _len4, - messages, - _key4, - buffer, - createHash, - hash, - _args4 = arguments; - - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - for (_len4 = _args4.length, messages = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - messages[_key4] = _args4[_key4]; - } + } +} - if (!crypto$1.web) { - _context4.next = 8; - break; - } +function assert(condition, message) { + if (!condition) { + throw new Error(message || 'Assertion failed'); + } +} - _context4.next = 4; - return crypto$1.web.subtle.digest('SHA-256', concatBytes.apply(void 0, messages)); +var CompiledKeys = /*#__PURE__*/function () { + function CompiledKeys(payer, keyMetaMap) { + _classCallCheck(this, CompiledKeys); - case 4: - buffer = _context4.sent; - return _context4.abrupt("return", new Uint8Array(buffer)); + this.payer = void 0; + this.keyMetaMap = void 0; + this.payer = payer; + this.keyMetaMap = keyMetaMap; + } - case 8: - if (!crypto$1.node) { - _context4.next = 15; - break; - } + _createClass(CompiledKeys, [{ + key: "getMessageComponents", + value: function getMessageComponents() { + var mapEntries = _toConsumableArray(this.keyMetaMap.entries()); - createHash = crypto$1.node.createHash; - hash = createHash('sha256'); - messages.forEach(function (m) { - return hash.update(m); - }); - return _context4.abrupt("return", Uint8Array.from(hash.digest())); + assert(mapEntries.length <= 256, 'Max static account keys length exceeded'); + var writableSigners = mapEntries.filter(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + meta = _ref2[1]; - case 15: - throw new Error("The environment doesn't have sha256 function"); + return meta.isSigner && meta.isWritable; + }); + var readonlySigners = mapEntries.filter(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + meta = _ref4[1]; - case 16: - case "end": - return _context4.stop(); - } - }, _callee4); - })); + return meta.isSigner && !meta.isWritable; + }); + var writableNonSigners = mapEntries.filter(function (_ref5) { + var _ref6 = _slicedToArray(_ref5, 2), + meta = _ref6[1]; - function sha256() { - return _sha.apply(this, arguments); - } + return !meta.isSigner && meta.isWritable; + }); + var readonlyNonSigners = mapEntries.filter(function (_ref7) { + var _ref8 = _slicedToArray(_ref7, 2), + meta = _ref8[1]; - return sha256; - }(), - hmacSha256: function () { - var _hmacSha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) { - var _len5, - messages, - _key5, - ckey, - message, - buffer, - createHmac, - hash, - _args5 = arguments; + return !meta.isSigner && !meta.isWritable; + }); + var header = { + numRequiredSignatures: writableSigners.length + readonlySigners.length, + numReadonlySignedAccounts: readonlySigners.length, + numReadonlyUnsignedAccounts: readonlyNonSigners.length + }; // sanity checks - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - for (_len5 = _args5.length, messages = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - messages[_key5 - 1] = _args5[_key5]; - } + { + assert(writableSigners.length > 0, 'Expected at least one writable signer key'); - if (!crypto$1.web) { - _context5.next = 12; - break; - } + var _writableSigners$2 = _slicedToArray(writableSigners[0], 1), + payerAddress = _writableSigners$2[0]; - _context5.next = 4; - return crypto$1.web.subtle.importKey('raw', key, { - name: 'HMAC', - hash: { - name: 'SHA-256' - } - }, false, ['sign']); + assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer'); + } + var staticAccountKeys = [].concat(_toConsumableArray(writableSigners.map(function (_ref9) { + var _ref10 = _slicedToArray(_ref9, 1), + address = _ref10[0]; - case 4: - ckey = _context5.sent; - message = concatBytes.apply(void 0, messages); - _context5.next = 8; - return crypto$1.web.subtle.sign('HMAC', ckey, message); + return new PublicKey(address); + })), _toConsumableArray(readonlySigners.map(function (_ref11) { + var _ref12 = _slicedToArray(_ref11, 1), + address = _ref12[0]; - case 8: - buffer = _context5.sent; - return _context5.abrupt("return", new Uint8Array(buffer)); + return new PublicKey(address); + })), _toConsumableArray(writableNonSigners.map(function (_ref13) { + var _ref14 = _slicedToArray(_ref13, 1), + address = _ref14[0]; - case 12: - if (!crypto$1.node) { - _context5.next = 19; - break; - } + return new PublicKey(address); + })), _toConsumableArray(readonlyNonSigners.map(function (_ref15) { + var _ref16 = _slicedToArray(_ref15, 1), + address = _ref16[0]; - createHmac = crypto$1.node.createHmac; - hash = createHmac('sha256', key); - messages.forEach(function (m) { - return hash.update(m); - }); - return _context5.abrupt("return", Uint8Array.from(hash.digest())); + return new PublicKey(address); + }))); + return [header, staticAccountKeys]; + } + }, { + key: "extractTableLookup", + value: function extractTableLookup(lookupTable) { + var _this$drainKeysFoundI = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { + return !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable; + }), + _this$drainKeysFoundI2 = _slicedToArray(_this$drainKeysFoundI, 2), + writableIndexes = _this$drainKeysFoundI2[0], + drainedWritableKeys = _this$drainKeysFoundI2[1]; - case 19: - throw new Error("The environment doesn't have hmac-sha256 function"); + var _this$drainKeysFoundI3 = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { + return !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable; + }), + _this$drainKeysFoundI4 = _slicedToArray(_this$drainKeysFoundI3, 2), + readonlyIndexes = _this$drainKeysFoundI4[0], + drainedReadonlyKeys = _this$drainKeysFoundI4[1]; // Don't extract lookup if no keys were found - case 20: - case "end": - return _context5.stop(); - } - }, _callee5); - })); - function hmacSha256(_x9) { - return _hmacSha.apply(this, arguments); + if (writableIndexes.length === 0 && readonlyIndexes.length === 0) { + return; + } + + return [{ + accountKey: lookupTable.key, + writableIndexes: writableIndexes, + readonlyIndexes: readonlyIndexes + }, { + writable: drainedWritableKeys, + readonly: drainedReadonlyKeys + }]; } + /** @internal */ - return hmacSha256; - }(), - sha256Sync: undefined, - hmacSha256Sync: undefined, - taggedHash: function () { - var _taggedHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(tag) { - var tagP, - tagH, - _len6, - messages, - _key6, - _args6 = arguments; + }, { + key: "drainKeysFoundInLookupTable", + value: function drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) { + var _this6 = this; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - tagP = TAGGED_HASH_PREFIXES[tag]; + var lookupTableIndexes = new Array(); + var drainedKeys = new Array(); - if (!(tagP === undefined)) { - _context6.next = 7; - break; - } + var _iterator2 = _createForOfIteratorHelper(this.keyMetaMap.entries()), + _step2; - _context6.next = 4; - return utils.sha256(Uint8Array.from(tag, function (c) { - return c.charCodeAt(0); - })); + try { + var _loop = function _loop() { + var _step2$value = _slicedToArray(_step2.value, 2), + address = _step2$value[0], + keyMeta = _step2$value[1]; - case 4: - tagH = _context6.sent; - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; + if (keyMetaFilter(keyMeta)) { + var key = new PublicKey(address); + var lookupTableIndex = lookupTableEntries.findIndex(function (entry) { + return entry.equals(key); + }); - case 7: - for (_len6 = _args6.length, messages = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { - messages[_key6 - 1] = _args6[_key6]; - } + if (lookupTableIndex >= 0) { + assert(lookupTableIndex < 256, 'Max lookup table index exceeded'); + lookupTableIndexes.push(lookupTableIndex); + drainedKeys.push(key); - return _context6.abrupt("return", utils.sha256.apply(utils, [tagP].concat(messages))); + _this6.keyMetaMap["delete"](address); + } + } + }; - case 9: - case "end": - return _context6.stop(); + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + _loop(); } - }, _callee6); - })); + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } - function taggedHash(_x10) { - return _taggedHash.apply(this, arguments); + return [lookupTableIndexes, drainedKeys]; } + }], [{ + key: "compile", + value: function compile(instructions, payer) { + var keyMetaMap = new Map(); - return taggedHash; - }(), - taggedHashSync: function taggedHashSync(tag) { - if (typeof _sha256Sync !== 'function') throw new ShaError('sha256Sync is undefined, you need to set it'); - var tagP = TAGGED_HASH_PREFIXES[tag]; + var getOrInsertDefault = function getOrInsertDefault(pubkey) { + var address = pubkey.toBase58(); + var keyMeta = keyMetaMap.get(address); - if (tagP === undefined) { - var tagH = _sha256Sync(Uint8Array.from(tag, function (c) { - return c.charCodeAt(0); - })); + if (keyMeta === undefined) { + keyMeta = { + isSigner: false, + isWritable: false, + isInvoked: false + }; + keyMetaMap.set(address, keyMeta); + } - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } + return keyMeta; + }; - for (var _len7 = arguments.length, messages = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { - messages[_key7 - 1] = arguments[_key7]; - } + var payerKeyMeta = getOrInsertDefault(payer); + payerKeyMeta.isSigner = true; + payerKeyMeta.isWritable = true; - return _sha256Sync.apply(void 0, [tagP].concat(messages)); - }, - _JacobianPoint: JacobianPoint -}; -Object.defineProperties(utils, { - sha256Sync: { - configurable: false, - get: function get() { - return _sha256Sync; - }, - set: function set(val) { - if (!_sha256Sync) _sha256Sync = val; - } - }, - hmacSha256Sync: { - configurable: false, - get: function get() { - return _hmacSha256Sync; - }, - set: function set(val) { - if (!_hmacSha256Sync) _hmacSha256Sync = val; - } - } -}); + var _iterator3 = _createForOfIteratorHelper(instructions), + _step3; -var _excluded = ["commitment"], - _excluded2 = ["encoding"], - _excluded3 = ["commitment"], - _excluded4 = ["commitment"]; -/** - * A 64 byte secret key, the first 32 bytes of which is the - * private scalar and the last 32 bytes is the public key. - * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ - */ + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var ix = _step3.value; + getOrInsertDefault(ix.programId).isInvoked = true; -utils$1.sha512Sync = function () { - var _ed25519$utils; + var _iterator4 = _createForOfIteratorHelper(ix.keys), + _step4; - return sha512((_ed25519$utils = utils$1).concatBytes.apply(_ed25519$utils, arguments)); -}; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var accountMeta = _step4.value; + var keyMeta = getOrInsertDefault(accountMeta.pubkey); + keyMeta.isSigner || (keyMeta.isSigner = accountMeta.isSigner); + keyMeta.isWritable || (keyMeta.isWritable = accountMeta.isWritable); + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } -var generatePrivateKey = utils$1.randomPrivateKey; + return new CompiledKeys(payer, keyMetaMap); + } + }]); -var generateKeypair = function generateKeypair() { - var privateScalar = utils$1.randomPrivateKey(); - var publicKey = getPublicKey(privateScalar); - var secretKey = new Uint8Array(64); - secretKey.set(privateScalar); - secretKey.set(publicKey, 32); - return { - publicKey: publicKey, - secretKey: secretKey - }; -}; + return CompiledKeys; +}(); +/** + * An instruction to execute by a program + * + * @property {number} programIdIndex + * @property {number[]} accounts + * @property {string} data + */ -var getPublicKey = sync.getPublicKey; +/** + * List of instructions to be processed atomically + */ -function _isOnCurve(publicKey) { - try { - Point$1.fromHex(publicKey, true - /* strict */ - ); - return true; - } catch (_unused) { - return false; - } -} -var _sign = function sign(message, secretKey) { - return sync.sign(message, secretKey.slice(0, 32)); -}; +var Message = /*#__PURE__*/function () { + function Message(args) { + var _this7 = this; -var verify = sync.verify; + _classCallCheck(this, Message); -var toBuffer = function toBuffer(arr) { - if (Buffer$1.isBuffer(arr)) { - return arr; - } else if (arr instanceof Uint8Array) { - return Buffer$1.from(arr.buffer, arr.byteOffset, arr.byteLength); - } else { - return Buffer$1.from(arr); + this.header = void 0; + this.accountKeys = void 0; + this.recentBlockhash = void 0; + this.instructions = void 0; + this.indexToProgramIds = new Map(); + this.header = args.header; + this.accountKeys = args.accountKeys.map(function (account) { + return new PublicKey(account); + }); + this.recentBlockhash = args.recentBlockhash; + this.instructions = args.instructions; + this.instructions.forEach(function (ix) { + return _this7.indexToProgramIds.set(ix.programIdIndex, _this7.accountKeys[ix.programIdIndex]); + }); } -}; // Class wrapping a plain object + _createClass(Message, [{ + key: "version", + get: function get() { + return 'legacy'; + } + }, { + key: "staticAccountKeys", + get: function get() { + return this.accountKeys; + } + }, { + key: "compiledInstructions", + get: function get() { + return this.instructions.map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accounts, + data: bs58$3.decode(ix.data) + }; + }); + } + }, { + key: "addressTableLookups", + get: function get() { + return []; + } + }, { + key: "getAccountKeys", + value: function getAccountKeys() { + return new MessageAccountKeys(this.staticAccountKeys); + } + }, { + key: "isAccountSigner", + value: function isAccountSigner(index) { + return index < this.header.numRequiredSignatures; + } + }, { + key: "isAccountWritable", + value: function isAccountWritable(index) { + var numSignedAccounts = this.header.numRequiredSignatures; -var Struct = /*#__PURE__*/function () { - function Struct(properties) { - _classCallCheck(this, Struct); - - Object.assign(this, properties); - } - - _createClass(Struct, [{ - key: "encode", - value: function encode() { - return Buffer$1.from(serialize_1(SOLANA_SCHEMA, this)); + if (index >= this.header.numRequiredSignatures) { + var unsignedAccountIndex = index - numSignedAccounts; + var numUnsignedAccounts = this.accountKeys.length - numSignedAccounts; + var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; + return unsignedAccountIndex < numWritableUnsignedAccounts; + } else { + var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; + return index < numWritableSignedAccounts; + } } - }], [{ - key: "decode", - value: function decode(data) { - return deserialize_1(SOLANA_SCHEMA, this, data); + }, { + key: "isProgramId", + value: function isProgramId(index) { + return this.indexToProgramIds.has(index); } }, { - key: "decodeUnchecked", - value: function decodeUnchecked(data) { - return deserializeUnchecked_1(SOLANA_SCHEMA, this, data); + key: "programIds", + value: function programIds() { + return _toConsumableArray(this.indexToProgramIds.values()); } - }]); + }, { + key: "nonProgramIds", + value: function nonProgramIds() { + var _this8 = this; - return Struct; -}(); // Class representing a Rust-compatible enum, since enums are only strings or -// numbers in pure JS + return this.accountKeys.filter(function (_, index) { + return !_this8.isProgramId(index); + }); + } + }, { + key: "serialize", + value: function serialize() { + var numKeys = this.accountKeys.length; + var keyCount = []; + encodeLength(keyCount, numKeys); + var instructions = this.instructions.map(function (instruction) { + var accounts = instruction.accounts, + programIdIndex = instruction.programIdIndex; + var data = Array.from(bs58$3.decode(instruction.data)); + var keyIndicesCount = []; + encodeLength(keyIndicesCount, accounts.length); + var dataCount = []; + encodeLength(dataCount, data.length); + return { + programIdIndex: programIdIndex, + keyIndicesCount: Buffer$1.from(keyIndicesCount), + keyIndices: accounts, + dataLength: Buffer$1.from(dataCount), + data: data + }; + }); + var instructionCount = []; + encodeLength(instructionCount, instructions.length); + var instructionBuffer = Buffer$1.alloc(PACKET_DATA_SIZE); + Buffer$1.from(instructionCount).copy(instructionBuffer); + var instructionBufferLength = instructionCount.length; + instructions.forEach(function (instruction) { + var instructionLayout = struct([u8('programIdIndex'), blob$1(instruction.keyIndicesCount.length, 'keyIndicesCount'), seq$1(u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), blob$1(instruction.dataLength.length, 'dataLength'), seq$1(u8('userdatum'), instruction.data.length, 'data')]); + var length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength); + instructionBufferLength += length; + }); + instructionBuffer = instructionBuffer.slice(0, instructionBufferLength); + var signDataLayout = struct([blob$1(1, 'numRequiredSignatures'), blob$1(1, 'numReadonlySignedAccounts'), blob$1(1, 'numReadonlyUnsignedAccounts'), blob$1(keyCount.length, 'keyCount'), seq$1(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]); + var transaction = { + numRequiredSignatures: Buffer$1.from([this.header.numRequiredSignatures]), + numReadonlySignedAccounts: Buffer$1.from([this.header.numReadonlySignedAccounts]), + numReadonlyUnsignedAccounts: Buffer$1.from([this.header.numReadonlyUnsignedAccounts]), + keyCount: Buffer$1.from(keyCount), + keys: this.accountKeys.map(function (key) { + return toBuffer(key.toBytes()); + }), + recentBlockhash: bs58$3.decode(this.recentBlockhash) + }; + var signData = Buffer$1.alloc(2048); + var length = signDataLayout.encode(transaction, signData); + instructionBuffer.copy(signData, length); + return signData.slice(0, length + instructionBuffer.length); + } + /** + * Decode a compiled message into a Message object. + */ + }], [{ + key: "compile", + value: function compile(args) { + var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); -var Enum = /*#__PURE__*/function (_Struct) { - _inherits(Enum, _Struct); + var _compiledKeys$getMess = compiledKeys.getMessageComponents(), + _compiledKeys$getMess2 = _slicedToArray(_compiledKeys$getMess, 2), + header = _compiledKeys$getMess2[0], + staticAccountKeys = _compiledKeys$getMess2[1]; - var _super = _createSuper(Enum); + var accountKeys = new MessageAccountKeys(staticAccountKeys); + var instructions = accountKeys.compileInstructions(args.instructions).map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accounts: ix.accountKeyIndexes, + data: bs58$3.encode(ix.data) + }; + }); + return new Message({ + header: header, + accountKeys: staticAccountKeys, + recentBlockhash: args.recentBlockhash, + instructions: instructions + }); + } + }, { + key: "from", + value: function from(buffer) { + // Slice up wire data + var byteArray = _toConsumableArray(buffer); - function Enum(properties) { - var _this; + var numRequiredSignatures = byteArray.shift(); - _classCallCheck(this, Enum); + if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) { + throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()'); + } - _this = _super.call(this, properties); - _this["enum"] = ''; + var numReadonlySignedAccounts = byteArray.shift(); + var numReadonlyUnsignedAccounts = byteArray.shift(); + var accountCount = decodeLength(byteArray); + var accountKeys = []; - if (Object.keys(properties).length !== 1) { - throw new Error('Enum can only take single value'); - } + for (var i = 0; i < accountCount; i++) { + var account = byteArray.slice(0, PUBLIC_KEY_LENGTH); + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + accountKeys.push(new PublicKey(Buffer$1.from(account))); + } - Object.keys(properties).map(function (key) { - _this["enum"] = key; - }); - return _this; - } + var recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH); + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + var instructionCount = decodeLength(byteArray); + var instructions = []; - return _createClass(Enum); -}(Struct); + for (var _i2 = 0; _i2 < instructionCount; _i2++) { + var programIdIndex = byteArray.shift(); -var SOLANA_SCHEMA = new Map(); + var _accountCount = decodeLength(byteArray); + + var accounts = byteArray.slice(0, _accountCount); + byteArray = byteArray.slice(_accountCount); + var dataLength = decodeLength(byteArray); + var dataSlice = byteArray.slice(0, dataLength); + var data = bs58$3.encode(Buffer$1.from(dataSlice)); + byteArray = byteArray.slice(dataLength); + instructions.push({ + programIdIndex: programIdIndex, + accounts: accounts, + data: data + }); + } + + var messageArgs = { + header: { + numRequiredSignatures: numRequiredSignatures, + numReadonlySignedAccounts: numReadonlySignedAccounts, + numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts + }, + recentBlockhash: bs58$3.encode(Buffer$1.from(recentBlockhash)), + accountKeys: accountKeys, + instructions: instructions + }; + return new Message(messageArgs); + } + }]); -var _Symbol$toStringTag; + return Message; +}(); /** - * Maximum length of derived pubkey seed + * Message constructor arguments */ -var MAX_SEED_LENGTH = 32; -/** - * Size of public key in bytes - */ +var MessageV0 = /*#__PURE__*/function () { + function MessageV0(args) { + _classCallCheck(this, MessageV0); -var PUBLIC_KEY_LENGTH = 32; -/** - * Value to be converted into public key - */ + this.header = void 0; + this.staticAccountKeys = void 0; + this.recentBlockhash = void 0; + this.compiledInstructions = void 0; + this.addressTableLookups = void 0; + this.header = args.header; + this.staticAccountKeys = args.staticAccountKeys; + this.recentBlockhash = args.recentBlockhash; + this.compiledInstructions = args.compiledInstructions; + this.addressTableLookups = args.addressTableLookups; + } -function isPublicKeyData(value) { - return value._bn !== undefined; -} // local counter used by PublicKey.unique() + _createClass(MessageV0, [{ + key: "version", + get: function get() { + return 0; + } + }, { + key: "numAccountKeysFromLookups", + get: function get() { + var count = 0; + var _iterator5 = _createForOfIteratorHelper(this.addressTableLookups), + _step5; -var uniquePublicKeyCounter = 1; -/** - * A public key - */ + try { + for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { + var lookup = _step5.value; + count += lookup.readonlyIndexes.length + lookup.writableIndexes.length; + } + } catch (err) { + _iterator5.e(err); + } finally { + _iterator5.f(); + } -_Symbol$toStringTag = Symbol.toStringTag; + return count; + } + }, { + key: "getAccountKeys", + value: function getAccountKeys(args) { + var accountKeysFromLookups; -var PublicKey = /*#__PURE__*/function (_Struct2, _Symbol$toStringTag2) { - _inherits(PublicKey, _Struct2); + if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) { + if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) { + throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups'); + } - var _super2 = _createSuper(PublicKey); + accountKeysFromLookups = args.accountKeysFromLookups; + } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) { + accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts); + } else if (this.addressTableLookups.length > 0) { + throw new Error('Failed to get account keys because address table lookups were not resolved'); + } - /** @internal */ + return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups); + } + }, { + key: "isAccountSigner", + value: function isAccountSigner(index) { + return index < this.header.numRequiredSignatures; + } + }, { + key: "isAccountWritable", + value: function isAccountWritable(index) { + var numSignedAccounts = this.header.numRequiredSignatures; + var numStaticAccountKeys = this.staticAccountKeys.length; - /** - * Create a new PublicKey object - * @param value ed25519 public key as buffer or base-58 encoded string - */ - function PublicKey(value) { - var _this2; + if (index >= numStaticAccountKeys) { + var lookupAccountKeysIndex = index - numStaticAccountKeys; + var numWritableLookupAccountKeys = this.addressTableLookups.reduce(function (count, lookup) { + return count + lookup.writableIndexes.length; + }, 0); + return lookupAccountKeysIndex < numWritableLookupAccountKeys; + } else if (index >= this.header.numRequiredSignatures) { + var unsignedAccountIndex = index - numSignedAccounts; + var numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts; + var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; + return unsignedAccountIndex < numWritableUnsignedAccounts; + } else { + var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; + return index < numWritableSignedAccounts; + } + } + }, { + key: "resolveAddressTableLookups", + value: function resolveAddressTableLookups(addressLookupTableAccounts) { + var accountKeysFromLookups = { + writable: [], + readonly: [] + }; - _classCallCheck(this, PublicKey); + var _iterator6 = _createForOfIteratorHelper(this.addressTableLookups), + _step6; - _this2 = _super2.call(this, {}); - _this2._bn = void 0; + try { + var _loop2 = function _loop2() { + var tableLookup = _step6.value; + var tableAccount = addressLookupTableAccounts.find(function (account) { + return account.key.equals(tableLookup.accountKey); + }); - if (isPublicKeyData(value)) { - _this2._bn = value._bn; - } else { - if (typeof value === 'string') { - // assume base 58 encoding by default - var decoded = bs58$1.decode(value); + if (!tableAccount) { + throw new Error("Failed to find address lookup table account for table key ".concat(tableLookup.accountKey.toBase58())); + } - if (decoded.length != PUBLIC_KEY_LENGTH) { - throw new Error("Invalid public key input"); - } + var _iterator7 = _createForOfIteratorHelper(tableLookup.writableIndexes), + _step7; - _this2._bn = new BN$1(decoded); - } else { - _this2._bn = new BN$1(value); - } + try { + for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { + var index = _step7.value; - if (_this2._bn.byteLength() > PUBLIC_KEY_LENGTH) { - throw new Error("Invalid public key input"); - } - } + if (index < tableAccount.state.addresses.length) { + accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]); + } else { + throw new Error("Failed to find address for index ".concat(index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); + } + } + } catch (err) { + _iterator7.e(err); + } finally { + _iterator7.f(); + } - return _this2; - } - /** - * Returns a unique PublicKey for tests and benchmarks using a counter - */ + var _iterator8 = _createForOfIteratorHelper(tableLookup.readonlyIndexes), + _step8; + try { + for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { + var _index = _step8.value; - _createClass(PublicKey, [{ - key: "equals", - value: - /** - * Default public key value. The base58-encoded string representation is all ones (as seen below) - * The underlying BN number is 32 bytes that are all zeros - */ + if (_index < tableAccount.state.addresses.length) { + accountKeysFromLookups.readonly.push(tableAccount.state.addresses[_index]); + } else { + throw new Error("Failed to find address for index ".concat(_index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); + } + } + } catch (err) { + _iterator8.e(err); + } finally { + _iterator8.f(); + } + }; - /** - * Checks if two publicKeys are equal - */ - function equals(publicKey) { - return this._bn.eq(publicKey._bn); - } - /** - * Return the base-58 representation of the public key - */ + for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { + _loop2(); + } + } catch (err) { + _iterator6.e(err); + } finally { + _iterator6.f(); + } - }, { - key: "toBase58", - value: function toBase58() { - return bs58$1.encode(this.toBytes()); + return accountKeysFromLookups; } }, { - key: "toJSON", - value: function toJSON() { - return this.toBase58(); + key: "serialize", + value: function serialize() { + var encodedStaticAccountKeysLength = Array(); + encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length); + var serializedInstructions = this.serializeInstructions(); + var encodedInstructionsLength = Array(); + encodeLength(encodedInstructionsLength, this.compiledInstructions.length); + var serializedAddressTableLookups = this.serializeAddressTableLookups(); + var encodedAddressTableLookupsLength = Array(); + encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length); + var messageLayout = struct([u8('prefix'), struct([u8('numRequiredSignatures'), u8('numReadonlySignedAccounts'), u8('numReadonlyUnsignedAccounts')], 'header'), blob$1(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), seq$1(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), blob$1(encodedInstructionsLength.length, 'instructionsLength'), blob$1(serializedInstructions.length, 'serializedInstructions'), blob$1(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), blob$1(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]); + var serializedMessage = new Uint8Array(PACKET_DATA_SIZE); + var MESSAGE_VERSION_0_PREFIX = 1 << 7; + var serializedMessageLength = messageLayout.encode({ + prefix: MESSAGE_VERSION_0_PREFIX, + header: this.header, + staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength), + staticAccountKeys: this.staticAccountKeys.map(function (key) { + return key.toBytes(); + }), + recentBlockhash: bs58$3.decode(this.recentBlockhash), + instructionsLength: new Uint8Array(encodedInstructionsLength), + serializedInstructions: serializedInstructions, + addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength), + serializedAddressTableLookups: serializedAddressTableLookups + }, serializedMessage); + return serializedMessage.slice(0, serializedMessageLength); } - /** - * Return the byte array representation of the public key in big endian - */ - }, { - key: "toBytes", - value: function toBytes() { - var buf = this.toBuffer(); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - /** - * Return the Buffer representation of the public key in big endian - */ + key: "serializeInstructions", + value: function serializeInstructions() { + var serializedLength = 0; + var serializedInstructions = new Uint8Array(PACKET_DATA_SIZE); - }, { - key: "toBuffer", - value: function toBuffer() { - var b = this._bn.toArrayLike(Buffer$1); + var _iterator9 = _createForOfIteratorHelper(this.compiledInstructions), + _step9; - if (b.length === PUBLIC_KEY_LENGTH) { - return b; + try { + for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { + var instruction = _step9.value; + var encodedAccountKeyIndexesLength = Array(); + encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length); + var encodedDataLength = Array(); + encodeLength(encodedDataLength, instruction.data.length); + var instructionLayout = struct([u8('programIdIndex'), blob$1(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), seq$1(u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), blob$1(encodedDataLength.length, 'encodedDataLength'), blob$1(instruction.data.length, 'data')]); + serializedLength += instructionLayout.encode({ + programIdIndex: instruction.programIdIndex, + encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength), + accountKeyIndexes: instruction.accountKeyIndexes, + encodedDataLength: new Uint8Array(encodedDataLength), + data: instruction.data + }, serializedInstructions, serializedLength); + } + } catch (err) { + _iterator9.e(err); + } finally { + _iterator9.f(); } - var zeroPad = Buffer$1.alloc(32); - b.copy(zeroPad, 32 - b.length); - return zeroPad; + return serializedInstructions.slice(0, serializedLength); } }, { - key: _Symbol$toStringTag2, - get: function get() { - return "PublicKey(".concat(this.toString(), ")"); - } - /** - * Return the base-58 representation of the public key - */ + key: "serializeAddressTableLookups", + value: function serializeAddressTableLookups() { + var serializedLength = 0; + var serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE); - }, { - key: "toString", - value: function toString() { - return this.toBase58(); - } - /** - * Derive a public key from another key, a seed, and a program ID. - * The program ID will also serve as the owner of the public key, giving - * it permission to write data to the account. - */ + var _iterator10 = _createForOfIteratorHelper(this.addressTableLookups), + _step10; - /* eslint-disable require-await */ + try { + for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { + var lookup = _step10.value; + var encodedWritableIndexesLength = Array(); + encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length); + var encodedReadonlyIndexesLength = Array(); + encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length); + var addressTableLookupLayout = struct([publicKey('accountKey'), blob$1(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), seq$1(u8(), lookup.writableIndexes.length, 'writableIndexes'), blob$1(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), seq$1(u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]); + serializedLength += addressTableLookupLayout.encode({ + accountKey: lookup.accountKey.toBytes(), + encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength), + writableIndexes: lookup.writableIndexes, + encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength), + readonlyIndexes: lookup.readonlyIndexes + }, serializedAddressTableLookups, serializedLength); + } + } catch (err) { + _iterator10.e(err); + } finally { + _iterator10.f(); + } - }], [{ - key: "unique", - value: function unique() { - var key = new PublicKey(uniquePublicKeyCounter); - uniquePublicKeyCounter += 1; - return new PublicKey(key.toBuffer()); + return serializedAddressTableLookups.slice(0, serializedLength); } - }, { - key: "createWithSeed", - value: function () { - var _createWithSeed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(fromPublicKey, seed, programId) { - var buffer, publicKeyBytes; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - buffer = Buffer$1.concat([fromPublicKey.toBuffer(), Buffer$1.from(seed), programId.toBuffer()]); - publicKeyBytes = sha256(buffer); - return _context.abrupt("return", new PublicKey(publicKeyBytes)); + }], [{ + key: "compile", + value: function compile(args) { + var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); + var addressTableLookups = new Array(); + var accountKeysFromLookups = { + writable: new Array(), + readonly: new Array() + }; + var lookupTableAccounts = args.addressLookupTableAccounts || []; - case 3: - case "end": - return _context.stop(); - } - }, _callee); - })); + var _iterator11 = _createForOfIteratorHelper(lookupTableAccounts), + _step11; - function createWithSeed(_x, _x2, _x3) { - return _createWithSeed.apply(this, arguments); - } + try { + for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { + var lookupTable = _step11.value; + var extractResult = compiledKeys.extractTableLookup(lookupTable); - return createWithSeed; - }() - /** - * Derive a program address from seeds and a program ID. - */ + if (extractResult !== undefined) { + var _accountKeysFromLooku, _accountKeysFromLooku2; - /* eslint-disable require-await */ + var _extractResult2 = _slicedToArray(extractResult, 2), + addressTableLookup = _extractResult2[0], + _extractResult$2 = _extractResult2[1], + writable = _extractResult$2.writable, + readonly = _extractResult$2.readonly; - }, { - key: "createProgramAddressSync", - value: function createProgramAddressSync(seeds, programId) { - var buffer = Buffer$1.alloc(0); - seeds.forEach(function (seed) { - if (seed.length > MAX_SEED_LENGTH) { - throw new TypeError("Max seed length exceeded"); - } + addressTableLookups.push(addressTableLookup); - buffer = Buffer$1.concat([buffer, toBuffer(seed)]); - }); - buffer = Buffer$1.concat([buffer, programId.toBuffer(), Buffer$1.from('ProgramDerivedAddress')]); - var publicKeyBytes = sha256(buffer); + (_accountKeysFromLooku = accountKeysFromLookups.writable).push.apply(_accountKeysFromLooku, _toConsumableArray(writable)); - if (_isOnCurve(publicKeyBytes)) { - throw new Error("Invalid seeds, address must fall off the curve"); + (_accountKeysFromLooku2 = accountKeysFromLookups.readonly).push.apply(_accountKeysFromLooku2, _toConsumableArray(readonly)); + } + } + } catch (err) { + _iterator11.e(err); + } finally { + _iterator11.f(); } - return new PublicKey(publicKeyBytes); - } - /** - * Async version of createProgramAddressSync - * For backwards compatibility - * - * @deprecated Use {@link createProgramAddressSync} instead - */ - - /* eslint-disable require-await */ + var _compiledKeys$getMess3 = compiledKeys.getMessageComponents(), + _compiledKeys$getMess4 = _slicedToArray(_compiledKeys$getMess3, 2), + header = _compiledKeys$getMess4[0], + staticAccountKeys = _compiledKeys$getMess4[1]; + var accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups); + var compiledInstructions = accountKeys.compileInstructions(args.instructions); + return new MessageV0({ + header: header, + staticAccountKeys: staticAccountKeys, + recentBlockhash: args.recentBlockhash, + compiledInstructions: compiledInstructions, + addressTableLookups: addressTableLookups + }); + } }, { - key: "createProgramAddress", - value: function () { - var _createProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(seeds, programId) { - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - return _context2.abrupt("return", this.createProgramAddressSync(seeds, programId)); + key: "deserialize", + value: function deserialize(serializedMessage) { + var byteArray = _toConsumableArray(serializedMessage); - case 1: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); + var prefix = byteArray.shift(); + var maskedPrefix = prefix & VERSION_PREFIX_MASK; + assert(prefix !== maskedPrefix, "Expected versioned message but received legacy message"); + var version = maskedPrefix; + assert(version === 0, "Expected versioned message with version 0 but found version ".concat(version)); + var header = { + numRequiredSignatures: byteArray.shift(), + numReadonlySignedAccounts: byteArray.shift(), + numReadonlyUnsignedAccounts: byteArray.shift() + }; + var staticAccountKeys = []; + var staticAccountKeysLength = decodeLength(byteArray); - function createProgramAddress(_x4, _x5) { - return _createProgramAddress.apply(this, arguments); + for (var i = 0; i < staticAccountKeysLength; i++) { + staticAccountKeys.push(new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH))); } - return createProgramAddress; - }() - /** - * Find a valid program address - * - * Valid program addresses must fall off the ed25519 curve. This function - * iterates a nonce until it finds one that when combined with the seeds - * results in a valid program address. - */ - - }, { - key: "findProgramAddressSync", - value: function findProgramAddressSync(seeds, programId) { - var nonce = 255; - var address; - - while (nonce != 0) { - try { - var seedsWithNonce = seeds.concat(Buffer$1.from([nonce])); - address = this.createProgramAddressSync(seedsWithNonce, programId); - } catch (err) { - if (err instanceof TypeError) { - throw err; - } + var recentBlockhash = bs58$3.encode(byteArray.splice(0, PUBLIC_KEY_LENGTH)); + var instructionCount = decodeLength(byteArray); + var compiledInstructions = []; - nonce--; - continue; - } + for (var _i4 = 0; _i4 < instructionCount; _i4++) { + var programIdIndex = byteArray.shift(); + var accountKeyIndexesLength = decodeLength(byteArray); + var accountKeyIndexes = byteArray.splice(0, accountKeyIndexesLength); + var dataLength = decodeLength(byteArray); + var data = new Uint8Array(byteArray.splice(0, dataLength)); + compiledInstructions.push({ + programIdIndex: programIdIndex, + accountKeyIndexes: accountKeyIndexes, + data: data + }); + } - return [address, nonce]; + var addressTableLookupsCount = decodeLength(byteArray); + var addressTableLookups = []; + + for (var _i6 = 0; _i6 < addressTableLookupsCount; _i6++) { + var accountKey = new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH)); + var writableIndexesLength = decodeLength(byteArray); + var writableIndexes = byteArray.splice(0, writableIndexesLength); + var readonlyIndexesLength = decodeLength(byteArray); + var readonlyIndexes = byteArray.splice(0, readonlyIndexesLength); + addressTableLookups.push({ + accountKey: accountKey, + writableIndexes: writableIndexes, + readonlyIndexes: readonlyIndexes + }); } - throw new Error("Unable to find a viable program address nonce"); + return new MessageV0({ + header: header, + staticAccountKeys: staticAccountKeys, + recentBlockhash: recentBlockhash, + compiledInstructions: compiledInstructions, + addressTableLookups: addressTableLookups + }); } - /** - * Async version of findProgramAddressSync - * For backwards compatibility - * - * @deprecated Use {@link findProgramAddressSync} instead - */ + }]); - }, { - key: "findProgramAddress", - value: function () { - var _findProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(seeds, programId) { - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - return _context3.abrupt("return", this.findProgramAddressSync(seeds, programId)); + return MessageV0; +}(); // eslint-disable-next-line no-redeclare - case 1: - case "end": - return _context3.stop(); - } - }, _callee3, this); - })); - function findProgramAddress(_x6, _x7) { - return _findProgramAddress.apply(this, arguments); - } +var VersionedMessage = { + deserializeMessageVersion: function deserializeMessageVersion(serializedMessage) { + var prefix = serializedMessage[0]; + var maskedPrefix = prefix & VERSION_PREFIX_MASK; // if the highest bit of the prefix is not set, the message is not versioned - return findProgramAddress; - }() - /** - * Check that a pubkey is on the ed25519 curve. - */ + if (maskedPrefix === prefix) { + return 'legacy'; + } // the lower 7 bits of the prefix indicate the message version - }, { - key: "isOnCurve", - value: function isOnCurve(pubkeyData) { - var pubkey = new PublicKey(pubkeyData); - return _isOnCurve(pubkey.toBytes()); + + return maskedPrefix; + }, + deserialize: function deserialize(serializedMessage) { + var version = VersionedMessage.deserializeMessageVersion(serializedMessage); + + if (version === 'legacy') { + return Message.from(serializedMessage); } - }]); - return PublicKey; -}(Struct, _Symbol$toStringTag); + if (version === 0) { + return MessageV0.deserialize(serializedMessage); + } else { + throw new Error("Transaction message version ".concat(version, " deserialization is not supported")); + } + } +}; +/** + * Transaction signature as base-58 encoded string + */ -PublicKey["default"] = new PublicKey('11111111111111111111111111111111'); -SOLANA_SCHEMA.set(PublicKey, { - kind: 'struct', - fields: [['_bn', 'u256']] -}); +var TransactionStatus; /** - * An account key pair (public and secret keys). - * - * @deprecated since v1.10.0, please use {@link Keypair} instead. + * Default (empty) signature */ -var Account = /*#__PURE__*/function () { - /** @internal */ +(function (TransactionStatus) { + TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"] = 0] = "BLOCKHEIGHT_EXCEEDED"; + TransactionStatus[TransactionStatus["PROCESSED"] = 1] = "PROCESSED"; + TransactionStatus[TransactionStatus["TIMED_OUT"] = 2] = "TIMED_OUT"; + TransactionStatus[TransactionStatus["NONCE_INVALID"] = 3] = "NONCE_INVALID"; +})(TransactionStatus || (TransactionStatus = {})); - /** @internal */ +var DEFAULT_SIGNATURE = Buffer$1.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0); +/** + * Account metadata used to define instructions + */ + +/** + * Transaction Instruction class + */ +var TransactionInstruction = /*#__PURE__*/function () { /** - * Create a new Account object - * - * If the secretKey parameter is not provided a new key pair is randomly - * created for the account - * - * @param secretKey Secret key for the account + * Public keys to include in this transaction + * Boolean represents whether this pubkey needs to sign the transaction */ - function Account(secretKey) { - _classCallCheck(this, Account); - this._publicKey = void 0; - this._secretKey = void 0; + /** + * Program Id to execute + */ - if (secretKey) { - var secretKeyBuffer = toBuffer(secretKey); + /** + * Program input + */ + function TransactionInstruction(opts) { + _classCallCheck(this, TransactionInstruction); - if (secretKey.length !== 64) { - throw new Error('bad secret key size'); - } + this.keys = void 0; + this.programId = void 0; + this.data = Buffer$1.alloc(0); + this.programId = opts.programId; + this.keys = opts.keys; - this._publicKey = secretKeyBuffer.slice(32, 64); - this._secretKey = secretKeyBuffer.slice(0, 32); - } else { - this._secretKey = toBuffer(generatePrivateKey()); - this._publicKey = toBuffer(getPublicKey(this._secretKey)); + if (opts.data) { + this.data = opts.data; } } /** - * The public key for this account + * @internal */ - _createClass(Account, [{ - key: "publicKey", - get: function get() { - return new PublicKey(this._publicKey); - } - /** - * The **unencrypted** secret key for this account. The first 32 bytes - * is the private scalar and the last 32 bytes is the public key. - * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ - */ - - }, { - key: "secretKey", - get: function get() { - return Buffer$1.concat([this._secretKey, this._publicKey], 64); + _createClass(TransactionInstruction, [{ + key: "toJSON", + value: function toJSON() { + return { + keys: this.keys.map(function (_ref17) { + var pubkey = _ref17.pubkey, + isSigner = _ref17.isSigner, + isWritable = _ref17.isWritable; + return { + pubkey: pubkey.toJSON(), + isSigner: isSigner, + isWritable: isWritable + }; + }), + programId: this.programId.toJSON(), + data: _toConsumableArray(this.data) + }; } }]); - return Account; + return TransactionInstruction; }(); - -var BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111'); /** - * Maximum over-the-wire size of a Transaction - * - * 1280 is IPv6 minimum MTU - * 40 bytes is the size of the IPv6 header - * 8 bytes is the size of the fragment header + * Pair of signature and corresponding public key */ -var PACKET_DATA_SIZE = 1280 - 40 - 8; -var VERSION_PREFIX_MASK = 0x7f; -var SIGNATURE_LENGTH_IN_BYTES = 64; - -var TransactionExpiredBlockheightExceededError = /*#__PURE__*/function (_Error) { - _inherits(TransactionExpiredBlockheightExceededError, _Error); - - var _super3 = _createSuper(TransactionExpiredBlockheightExceededError); - - function TransactionExpiredBlockheightExceededError(signature) { - var _this3; - - _classCallCheck(this, TransactionExpiredBlockheightExceededError); - - _this3 = _super3.call(this, "Signature ".concat(signature, " has expired: block height exceeded.")); - _this3.signature = void 0; - _this3.signature = signature; - return _this3; - } - - return _createClass(TransactionExpiredBlockheightExceededError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', { - value: 'TransactionExpiredBlockheightExceededError' -}); - -var TransactionExpiredTimeoutError = /*#__PURE__*/function (_Error2) { - _inherits(TransactionExpiredTimeoutError, _Error2); - - var _super4 = _createSuper(TransactionExpiredTimeoutError); +/** + * Transaction class + */ - function TransactionExpiredTimeoutError(signature, timeoutSeconds) { - var _this4; - _classCallCheck(this, TransactionExpiredTimeoutError); +var Transaction = /*#__PURE__*/function () { + /** + * The transaction fee payer + */ - _this4 = _super4.call(this, "Transaction was not confirmed in ".concat(timeoutSeconds.toFixed(2), " seconds. It is ") + 'unknown if it succeeded or failed. Check signature ' + "".concat(signature, " using the Solana Explorer or CLI tools.")); - _this4.signature = void 0; - _this4.signature = signature; - return _this4; - } + /** + * Construct an empty Transaction + */ + function Transaction(opts) { + _classCallCheck(this, Transaction); - return _createClass(TransactionExpiredTimeoutError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); + this.signatures = []; + this.feePayer = void 0; + this.instructions = []; + this.recentBlockhash = void 0; + this.lastValidBlockHeight = void 0; + this.nonceInfo = void 0; + this.minNonceContextSlot = void 0; + this._message = void 0; + this._json = void 0; -Object.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', { - value: 'TransactionExpiredTimeoutError' -}); + if (!opts) { + return; + } -var TransactionExpiredNonceInvalidError = /*#__PURE__*/function (_Error3) { - _inherits(TransactionExpiredNonceInvalidError, _Error3); + if (opts.feePayer) { + this.feePayer = opts.feePayer; + } - var _super5 = _createSuper(TransactionExpiredNonceInvalidError); + if (opts.signatures) { + this.signatures = opts.signatures; + } - function TransactionExpiredNonceInvalidError(signature) { - var _this5; + if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) { + var minContextSlot = opts.minContextSlot, + nonceInfo = opts.nonceInfo; + this.minNonceContextSlot = minContextSlot; + this.nonceInfo = nonceInfo; + } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) { + var blockhash = opts.blockhash, + lastValidBlockHeight = opts.lastValidBlockHeight; + this.recentBlockhash = blockhash; + this.lastValidBlockHeight = lastValidBlockHeight; + } else { + var recentBlockhash = opts.recentBlockhash, + _nonceInfo = opts.nonceInfo; - _classCallCheck(this, TransactionExpiredNonceInvalidError); + if (_nonceInfo) { + this.nonceInfo = _nonceInfo; + } - _this5 = _super5.call(this, "Signature ".concat(signature, " has expired: the nonce is no longer valid.")); - _this5.signature = void 0; - _this5.signature = signature; - return _this5; + this.recentBlockhash = recentBlockhash; + } } + /** + * @internal + */ - return _createClass(TransactionExpiredNonceInvalidError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -Object.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', { - value: 'TransactionExpiredNonceInvalidError' -}); - -var MessageAccountKeys = /*#__PURE__*/function () { - function MessageAccountKeys(staticAccountKeys, accountKeysFromLookups) { - _classCallCheck(this, MessageAccountKeys); - - this.staticAccountKeys = void 0; - this.accountKeysFromLookups = void 0; - this.staticAccountKeys = staticAccountKeys; - this.accountKeysFromLookups = accountKeysFromLookups; - } - _createClass(MessageAccountKeys, [{ - key: "keySegments", - value: function keySegments() { - var keySegments = [this.staticAccountKeys]; + _createClass(Transaction, [{ + key: "signature", + get: + /** + * Signatures for the transaction. Typically created by invoking the + * `sign()` method + */ - if (this.accountKeysFromLookups) { - keySegments.push(this.accountKeysFromLookups.writable); - keySegments.push(this.accountKeysFromLookups.readonly); + /** + * The first (payer) Transaction signature + */ + function get() { + if (this.signatures.length > 0) { + return this.signatures[0].signature; } - return keySegments; + return null; } }, { - key: "get", - value: function get(index) { - var _iterator = _createForOfIteratorHelper(this.keySegments()), - _step; + key: "toJSON", + value: function toJSON() { + return { + recentBlockhash: this.recentBlockhash || null, + feePayer: this.feePayer ? this.feePayer.toJSON() : null, + nonceInfo: this.nonceInfo ? { + nonce: this.nonceInfo.nonce, + nonceInstruction: this.nonceInfo.nonceInstruction.toJSON() + } : null, + instructions: this.instructions.map(function (instruction) { + return instruction.toJSON(); + }), + signers: this.signatures.map(function (_ref18) { + var publicKey = _ref18.publicKey; + return publicKey.toJSON(); + }) + }; + } + /** + * Add one or more instructions to this Transaction + */ - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var keySegment = _step.value; + }, { + key: "add", + value: function add() { + var _this9 = this; - if (index < keySegment.length) { - return keySegment[index]; - } else { - index -= keySegment.length; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) { + items[_key] = arguments[_key]; } - return; - } - }, { - key: "length", - get: function get() { - return this.keySegments().flat().length; - } - }, { - key: "compileInstructions", - value: function compileInstructions(instructions) { - // Bail early if any account indexes would overflow a u8 - var U8_MAX = 255; - - if (this.length > U8_MAX + 1) { - throw new Error('Account index overflow encountered during compilation'); + if (items.length === 0) { + throw new Error('No instructions'); } - var keyIndexMap = new Map(); - this.keySegments().flat().forEach(function (key, index) { - keyIndexMap.set(key.toBase58(), index); + items.forEach(function (item) { + if ('instructions' in item) { + _this9.instructions = _this9.instructions.concat(item.instructions); + } else if ('data' in item && 'programId' in item && 'keys' in item) { + _this9.instructions.push(item); + } else { + _this9.instructions.push(new TransactionInstruction(item)); + } }); + return this; + } + /** + * Compile transaction data + */ - var findKeyIndex = function findKeyIndex(key) { - var keyIndex = keyIndexMap.get(key.toBase58()); - if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation'); - return keyIndex; - }; + }, { + key: "compileMessage", + value: function compileMessage() { + if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) { + return this._message; + } - return instructions.map(function (instruction) { - return { - programIdIndex: findKeyIndex(instruction.programId), - accountKeyIndexes: instruction.keys.map(function (meta) { - return findKeyIndex(meta.pubkey); - }), - data: instruction.data - }; - }); - } - }]); + var recentBlockhash; + var instructions; - return MessageAccountKeys; -}(); -/** - * Layout for a public key - */ + if (this.nonceInfo) { + recentBlockhash = this.nonceInfo.nonce; + if (this.instructions[0] != this.nonceInfo.nonceInstruction) { + instructions = [this.nonceInfo.nonceInstruction].concat(_toConsumableArray(this.instructions)); + } else { + instructions = this.instructions; + } + } else { + recentBlockhash = this.recentBlockhash; + instructions = this.instructions; + } -var publicKey = function publicKey() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'publicKey'; - return blob$1(32, property); -}; -/** - * Layout for a signature - */ + if (!recentBlockhash) { + throw new Error('Transaction recentBlockhash required'); + } + if (instructions.length < 1) { + console.warn('No instructions provided'); + } -var signature = function signature() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'signature'; - return blob$1(64, property); -}; -/** - * Layout for a Rust String type - */ + var feePayer; + + if (this.feePayer) { + feePayer = this.feePayer; + } else if (this.signatures.length > 0 && this.signatures[0].publicKey) { + // Use implicit fee payer + feePayer = this.signatures[0].publicKey; + } else { + throw new Error('Transaction fee payer required'); + } + for (var i = 0; i < instructions.length; i++) { + if (instructions[i].programId === undefined) { + throw new Error("Transaction instruction index ".concat(i, " has undefined program id")); + } + } -var rustString = function rustString() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'string'; - var rsl = struct([u32('length'), u32('lengthPadding'), blob$1(offset$1(u32(), -8), 'chars')], property); + var programIds = []; + var accountMetas = []; + instructions.forEach(function (instruction) { + instruction.keys.forEach(function (accountMeta) { + accountMetas.push(_objectSpread2({}, accountMeta)); + }); + var programId = instruction.programId.toString(); - var _decode = rsl.decode.bind(rsl); + if (!programIds.includes(programId)) { + programIds.push(programId); + } + }); // Append programID account metas - var _encode = rsl.encode.bind(rsl); + programIds.forEach(function (programId) { + accountMetas.push({ + pubkey: new PublicKey(programId), + isSigner: false, + isWritable: false + }); + }); // Cull duplicate account metas - var rslShim = rsl; + var uniqueMetas = []; + accountMetas.forEach(function (accountMeta) { + var pubkeyString = accountMeta.pubkey.toString(); + var uniqueIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.toString() === pubkeyString; + }); - rslShim.decode = function (b, offset) { - var data = _decode(b, offset); + if (uniqueIndex > -1) { + uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable; + uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner; + } else { + uniqueMetas.push(accountMeta); + } + }); // Sort. Prioritizing first by signer, then by writable - return data['chars'].toString(); - }; + uniqueMetas.sort(function (x, y) { + if (x.isSigner !== y.isSigner) { + // Signers always come before non-signers + return x.isSigner ? -1 : 1; + } - rslShim.encode = function (str, b, offset) { - var data = { - chars: Buffer$1.from(str, 'utf8') - }; - return _encode(data, b, offset); - }; + if (x.isWritable !== y.isWritable) { + // Writable accounts always come before read-only accounts + return x.isWritable ? -1 : 1; + } // Otherwise, sort by pubkey, stringwise. - rslShim.alloc = function (str) { - return u32().span + u32().span + Buffer$1.from(str, 'utf8').length; - }; - return rslShim; -}; -/** - * Layout for an Authorized object - */ + return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58()); + }); // Move fee payer to the front + var feePayerIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.equals(feePayer); + }); -var authorized = function authorized() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'authorized'; - return struct([publicKey('staker'), publicKey('withdrawer')], property); -}; -/** - * Layout for a Lockup object - */ + if (feePayerIndex > -1) { + var _uniqueMetas$splice3 = uniqueMetas.splice(feePayerIndex, 1), + _uniqueMetas$splice4 = _slicedToArray(_uniqueMetas$splice3, 1), + payerMeta = _uniqueMetas$splice4[0]; + payerMeta.isSigner = true; + payerMeta.isWritable = true; + uniqueMetas.unshift(payerMeta); + } else { + uniqueMetas.unshift({ + pubkey: feePayer, + isSigner: true, + isWritable: true + }); + } // Disallow unknown signers -var lockup = function lockup() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'lockup'; - return struct([ns64('unixTimestamp'), ns64('epoch'), publicKey('custodian')], property); -}; -/** - * Layout for a VoteInit object - */ + var _iterator12 = _createForOfIteratorHelper(this.signatures), + _step12; -var voteInit = function voteInit() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteInit'; - return struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), u8('commission')], property); -}; -/** - * Layout for a VoteAuthorizeWithSeedArgs object - */ + try { + var _loop3 = function _loop3() { + var signature = _step12.value; + var uniqueIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.equals(signature.publicKey); + }); + if (uniqueIndex > -1) { + if (!uniqueMetas[uniqueIndex].isSigner) { + uniqueMetas[uniqueIndex].isSigner = true; + console.warn('Transaction references a signature that is unnecessary, ' + 'only the fee payer and instruction signer accounts should sign a transaction. ' + 'This behavior is deprecated and will throw an error in the next major version release.'); + } + } else { + throw new Error("unknown signer: ".concat(signature.publicKey.toString())); + } + }; -var voteAuthorizeWithSeedArgs = function voteAuthorizeWithSeedArgs() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteAuthorizeWithSeedArgs'; - return struct([u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property); -}; + for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { + _loop3(); + } + } catch (err) { + _iterator12.e(err); + } finally { + _iterator12.f(); + } -function getAlloc(type, fields) { - var getItemAlloc = function getItemAlloc(item) { - if (item.span >= 0) { - return item.span; - } else if (typeof item.alloc === 'function') { - return item.alloc(fields[item.property]); - } else if ('count' in item && 'elementLayout' in item) { - var field = fields[item.property]; + var numRequiredSignatures = 0; + var numReadonlySignedAccounts = 0; + var numReadonlyUnsignedAccounts = 0; // Split out signing from non-signing keys and count header values - if (Array.isArray(field)) { - return field.length * getItemAlloc(item.elementLayout); - } - } else if ('fields' in item) { - // This is a `Structure` whose size needs to be recursively measured. - return getAlloc({ - layout: item - }, fields[item.property]); - } // Couldn't determine allocated size of layout + var signedKeys = []; + var unsignedKeys = []; + uniqueMetas.forEach(function (_ref19) { + var pubkey = _ref19.pubkey, + isSigner = _ref19.isSigner, + isWritable = _ref19.isWritable; + if (isSigner) { + signedKeys.push(pubkey.toString()); + numRequiredSignatures += 1; - return 0; - }; + if (!isWritable) { + numReadonlySignedAccounts += 1; + } + } else { + unsignedKeys.push(pubkey.toString()); - var alloc = 0; - type.layout.fields.forEach(function (item) { - alloc += getItemAlloc(item); - }); - return alloc; -} + if (!isWritable) { + numReadonlyUnsignedAccounts += 1; + } + } + }); + var accountKeys = signedKeys.concat(unsignedKeys); + var compiledInstructions = instructions.map(function (instruction) { + var data = instruction.data, + programId = instruction.programId; + return { + programIdIndex: accountKeys.indexOf(programId.toString()), + accounts: instruction.keys.map(function (meta) { + return accountKeys.indexOf(meta.pubkey.toString()); + }), + data: bs58$3.encode(data) + }; + }); + compiledInstructions.forEach(function (instruction) { + assert(instruction.programIdIndex >= 0); + instruction.accounts.forEach(function (keyIndex) { + return assert(keyIndex >= 0); + }); + }); + return new Message({ + header: { + numRequiredSignatures: numRequiredSignatures, + numReadonlySignedAccounts: numReadonlySignedAccounts, + numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts + }, + accountKeys: accountKeys, + recentBlockhash: recentBlockhash, + instructions: compiledInstructions + }); + } + /** + * @internal + */ -function decodeLength(bytes) { - var len = 0; - var size = 0; + }, { + key: "_compile", + value: function _compile() { + var message = this.compileMessage(); + var signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures); - for (;;) { - var elem = bytes.shift(); - len |= (elem & 0x7f) << size * 7; - size += 1; + if (this.signatures.length === signedKeys.length) { + var valid = this.signatures.every(function (pair, index) { + return signedKeys[index].equals(pair.publicKey); + }); + if (valid) return message; + } - if ((elem & 0x80) === 0) { - break; + this.signatures = signedKeys.map(function (publicKey) { + return { + signature: null, + publicKey: publicKey + }; + }); + return message; } - } + /** + * Get a buffer of the Transaction data that need to be covered by signatures + */ - return len; -} + }, { + key: "serializeMessage", + value: function serializeMessage() { + return this._compile().serialize(); + } + /** + * Get the estimated fee associated with a transaction + */ -function encodeLength(bytes, len) { - var rem_len = len; + }, { + key: "getEstimatedFee", + value: function () { + var _getEstimatedFee = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(connection) { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return connection.getFeeForMessage(this.compileMessage()); - for (;;) { - var elem = rem_len & 0x7f; - rem_len >>= 7; + case 2: + return _context4.abrupt("return", _context4.sent.value); - if (rem_len == 0) { - bytes.push(elem); - break; - } else { - elem |= 0x80; - bytes.push(elem); - } - } -} + case 3: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); -function assert(condition, message) { - if (!condition) { - throw new Error(message || 'Assertion failed'); - } -} + function getEstimatedFee(_x8) { + return _getEstimatedFee.apply(this, arguments); + } -var CompiledKeys = /*#__PURE__*/function () { - function CompiledKeys(payer, keyMetaMap) { - _classCallCheck(this, CompiledKeys); + return getEstimatedFee; + }() + /** + * Specify the public keys which will be used to sign the Transaction. + * The first signer will be used as the transaction fee payer account. + * + * Signatures can be added with either `partialSign` or `addSignature` + * + * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be + * specified and it can be set in the Transaction constructor or with the + * `feePayer` property. + */ - this.payer = void 0; - this.keyMetaMap = void 0; - this.payer = payer; - this.keyMetaMap = keyMetaMap; - } + }, { + key: "setSigners", + value: function setSigners() { + for (var _len2 = arguments.length, signers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + signers[_key2] = arguments[_key2]; + } - _createClass(CompiledKeys, [{ - key: "getMessageComponents", - value: function getMessageComponents() { - var mapEntries = _toConsumableArray(this.keyMetaMap.entries()); + if (signers.length === 0) { + throw new Error('No signers'); + } - assert(mapEntries.length <= 256, 'Max static account keys length exceeded'); - var writableSigners = mapEntries.filter(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - meta = _ref2[1]; + var seen = new Set(); + this.signatures = signers.filter(function (publicKey) { + var key = publicKey.toString(); - return meta.isSigner && meta.isWritable; + if (seen.has(key)) { + return false; + } else { + seen.add(key); + return true; + } + }).map(function (publicKey) { + return { + signature: null, + publicKey: publicKey + }; }); - var readonlySigners = mapEntries.filter(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - meta = _ref4[1]; + } + /** + * Sign the Transaction with the specified signers. Multiple signatures may + * be applied to a Transaction. The first signature is considered "primary" + * and is used identify and confirm transactions. + * + * If the Transaction `feePayer` is not set, the first signer will be used + * as the transaction fee payer account. + * + * Transaction fields should not be modified after the first call to `sign`, + * as doing so may invalidate the signature and cause the Transaction to be + * rejected. + * + * The Transaction must be assigned a valid `recentBlockhash` before invoking this method + */ - return meta.isSigner && !meta.isWritable; - }); - var writableNonSigners = mapEntries.filter(function (_ref5) { - var _ref6 = _slicedToArray(_ref5, 2), - meta = _ref6[1]; + }, { + key: "sign", + value: function sign() { + for (var _len3 = arguments.length, signers = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + signers[_key3] = arguments[_key3]; + } - return !meta.isSigner && meta.isWritable; - }); - var readonlyNonSigners = mapEntries.filter(function (_ref7) { - var _ref8 = _slicedToArray(_ref7, 2), - meta = _ref8[1]; + if (signers.length === 0) { + throw new Error('No signers'); + } // Dedupe signers - return !meta.isSigner && !meta.isWritable; - }); - var header = { - numRequiredSignatures: writableSigners.length + readonlySigners.length, - numReadonlySignedAccounts: readonlySigners.length, - numReadonlyUnsignedAccounts: readonlyNonSigners.length - }; // sanity checks - { - assert(writableSigners.length > 0, 'Expected at least one writable signer key'); + var seen = new Set(); + var uniqueSigners = []; - var _writableSigners$2 = _slicedToArray(writableSigners[0], 1), - payerAddress = _writableSigners$2[0]; + for (var _i7 = 0, _signers = signers; _i7 < _signers.length; _i7++) { + var signer = _signers[_i7]; + var key = signer.publicKey.toString(); - assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer'); + if (seen.has(key)) { + continue; + } else { + seen.add(key); + uniqueSigners.push(signer); + } } - var staticAccountKeys = [].concat(_toConsumableArray(writableSigners.map(function (_ref9) { - var _ref10 = _slicedToArray(_ref9, 1), - address = _ref10[0]; - - return new PublicKey(address); - })), _toConsumableArray(readonlySigners.map(function (_ref11) { - var _ref12 = _slicedToArray(_ref11, 1), - address = _ref12[0]; - return new PublicKey(address); - })), _toConsumableArray(writableNonSigners.map(function (_ref13) { - var _ref14 = _slicedToArray(_ref13, 1), - address = _ref14[0]; + this.signatures = uniqueSigners.map(function (signer) { + return { + signature: null, + publicKey: signer.publicKey + }; + }); - return new PublicKey(address); - })), _toConsumableArray(readonlyNonSigners.map(function (_ref15) { - var _ref16 = _slicedToArray(_ref15, 1), - address = _ref16[0]; + var message = this._compile(); - return new PublicKey(address); - }))); - return [header, staticAccountKeys]; + this._partialSign.apply(this, [message].concat(uniqueSigners)); } + /** + * Partially sign a transaction with the specified accounts. All accounts must + * correspond to either the fee payer or a signer account in the transaction + * instructions. + * + * All the caveats from the `sign` method apply to `partialSign` + */ + }, { - key: "extractTableLookup", - value: function extractTableLookup(lookupTable) { - var _this$drainKeysFoundI = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { - return !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable; - }), - _this$drainKeysFoundI2 = _slicedToArray(_this$drainKeysFoundI, 2), - writableIndexes = _this$drainKeysFoundI2[0], - drainedWritableKeys = _this$drainKeysFoundI2[1]; + key: "partialSign", + value: function partialSign() { + for (var _len4 = arguments.length, signers = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + signers[_key4] = arguments[_key4]; + } - var _this$drainKeysFoundI3 = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { - return !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable; - }), - _this$drainKeysFoundI4 = _slicedToArray(_this$drainKeysFoundI3, 2), - readonlyIndexes = _this$drainKeysFoundI4[0], - drainedReadonlyKeys = _this$drainKeysFoundI4[1]; // Don't extract lookup if no keys were found + if (signers.length === 0) { + throw new Error('No signers'); + } // Dedupe signers - if (writableIndexes.length === 0 && readonlyIndexes.length === 0) { - return; + var seen = new Set(); + var uniqueSigners = []; + + for (var _i8 = 0, _signers2 = signers; _i8 < _signers2.length; _i8++) { + var signer = _signers2[_i8]; + var key = signer.publicKey.toString(); + + if (seen.has(key)) { + continue; + } else { + seen.add(key); + uniqueSigners.push(signer); + } } - return [{ - accountKey: lookupTable.key, - writableIndexes: writableIndexes, - readonlyIndexes: readonlyIndexes - }, { - writable: drainedWritableKeys, - readonly: drainedReadonlyKeys - }]; + var message = this._compile(); + + this._partialSign.apply(this, [message].concat(uniqueSigners)); } - /** @internal */ + /** + * @internal + */ }, { - key: "drainKeysFoundInLookupTable", - value: function drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) { - var _this6 = this; - - var lookupTableIndexes = new Array(); - var drainedKeys = new Array(); - - var _iterator2 = _createForOfIteratorHelper(this.keyMetaMap.entries()), - _step2; + key: "_partialSign", + value: function _partialSign(message) { + var _this10 = this; - try { - var _loop = function _loop() { - var _step2$value = _slicedToArray(_step2.value, 2), - address = _step2$value[0], - keyMeta = _step2$value[1]; + var signData = message.serialize(); - if (keyMetaFilter(keyMeta)) { - var key = new PublicKey(address); - var lookupTableIndex = lookupTableEntries.findIndex(function (entry) { - return entry.equals(key); - }); + for (var _len5 = arguments.length, signers = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + signers[_key5 - 1] = arguments[_key5]; + } - if (lookupTableIndex >= 0) { - assert(lookupTableIndex < 256, 'Max lookup table index exceeded'); - lookupTableIndexes.push(lookupTableIndex); - drainedKeys.push(key); + signers.forEach(function (signer) { + var signature = _sign(signData, signer.secretKey); - _this6.keyMetaMap["delete"](address); - } - } - }; + _this10._addSignature(signer.publicKey, toBuffer(signature)); + }); + } + /** + * Add an externally created signature to a transaction. The public key + * must correspond to either the fee payer or a signer account in the transaction + * instructions. + */ - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - _loop(); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } + }, { + key: "addSignature", + value: function addSignature(pubkey, signature) { + this._compile(); // Ensure signatures array is populated - return [lookupTableIndexes, drainedKeys]; + + this._addSignature(pubkey, signature); } - }], [{ - key: "compile", - value: function compile(instructions, payer) { - var keyMetaMap = new Map(); + /** + * @internal + */ - var getOrInsertDefault = function getOrInsertDefault(pubkey) { - var address = pubkey.toBase58(); - var keyMeta = keyMetaMap.get(address); + }, { + key: "_addSignature", + value: function _addSignature(pubkey, signature) { + assert(signature.length === 64); + var index = this.signatures.findIndex(function (sigpair) { + return pubkey.equals(sigpair.publicKey); + }); - if (keyMeta === undefined) { - keyMeta = { - isSigner: false, - isWritable: false, - isInvoked: false - }; - keyMetaMap.set(address, keyMeta); - } + if (index < 0) { + throw new Error("unknown signer: ".concat(pubkey.toString())); + } - return keyMeta; - }; + this.signatures[index].signature = Buffer$1.from(signature); + } + /** + * Verify signatures of a Transaction + * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one. + * If no boolean is provided, we expect a fully signed Transaction by default. + */ - var payerKeyMeta = getOrInsertDefault(payer); - payerKeyMeta.isSigner = true; - payerKeyMeta.isWritable = true; + }, { + key: "verifySignatures", + value: function verifySignatures(requireAllSignatures) { + return this._verifySignatures(this.serializeMessage(), requireAllSignatures === undefined ? true : requireAllSignatures); + } + /** + * @internal + */ - var _iterator3 = _createForOfIteratorHelper(instructions), - _step3; + }, { + key: "_verifySignatures", + value: function _verifySignatures(signData, requireAllSignatures) { + var _iterator13 = _createForOfIteratorHelper(this.signatures), + _step13; try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var ix = _step3.value; - getOrInsertDefault(ix.programId).isInvoked = true; - - var _iterator4 = _createForOfIteratorHelper(ix.keys), - _step4; + for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { + var _step13$value2 = _step13.value, + _signature = _step13$value2.signature, + _publicKey = _step13$value2.publicKey; - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var accountMeta = _step4.value; - var keyMeta = getOrInsertDefault(accountMeta.pubkey); - keyMeta.isSigner || (keyMeta.isSigner = accountMeta.isSigner); - keyMeta.isWritable || (keyMeta.isWritable = accountMeta.isWritable); + if (_signature === null) { + if (requireAllSignatures) { + return false; + } + } else { + if (!verify(_signature, signData, _publicKey.toBytes())) { + return false; } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); } } } catch (err) { - _iterator3.e(err); + _iterator13.e(err); } finally { - _iterator3.f(); + _iterator13.f(); } - return new CompiledKeys(payer, keyMetaMap); + return true; } - }]); - - return CompiledKeys; -}(); -/** - * An instruction to execute by a program - * - * @property {number} programIdIndex - * @property {number[]} accounts - * @property {string} data - */ - -/** - * List of instructions to be processed atomically - */ - + /** + * Serialize the Transaction in the wire format. + */ -var Message = /*#__PURE__*/function () { - function Message(args) { - var _this7 = this; + }, { + key: "serialize", + value: function serialize(config) { + var _Object$assign = Object.assign({ + requireAllSignatures: true, + verifySignatures: true + }, config), + requireAllSignatures = _Object$assign.requireAllSignatures, + verifySignatures = _Object$assign.verifySignatures; - _classCallCheck(this, Message); + var signData = this.serializeMessage(); - this.header = void 0; - this.accountKeys = void 0; - this.recentBlockhash = void 0; - this.instructions = void 0; - this.indexToProgramIds = new Map(); - this.header = args.header; - this.accountKeys = args.accountKeys.map(function (account) { - return new PublicKey(account); - }); - this.recentBlockhash = args.recentBlockhash; - this.instructions = args.instructions; - this.instructions.forEach(function (ix) { - return _this7.indexToProgramIds.set(ix.programIdIndex, _this7.accountKeys[ix.programIdIndex]); - }); - } + if (verifySignatures && !this._verifySignatures(signData, requireAllSignatures)) { + throw new Error('Signature verification failed'); + } - _createClass(Message, [{ - key: "version", - get: function get() { - return 'legacy'; + return this._serialize(signData); } + /** + * @internal + */ + }, { - key: "staticAccountKeys", - get: function get() { - return this.accountKeys; + key: "_serialize", + value: function _serialize(signData) { + var signatures = this.signatures; + var signatureCount = []; + encodeLength(signatureCount, signatures.length); + var transactionLength = signatureCount.length + signatures.length * 64 + signData.length; + var wireTransaction = Buffer$1.alloc(transactionLength); + assert(signatures.length < 256); + Buffer$1.from(signatureCount).copy(wireTransaction, 0); + signatures.forEach(function (_ref20, index) { + var signature = _ref20.signature; + + if (signature !== null) { + assert(signature.length === 64, "signature has invalid length"); + Buffer$1.from(signature).copy(wireTransaction, signatureCount.length + index * 64); + } + }); + signData.copy(wireTransaction, signatureCount.length + signatures.length * 64); + assert(wireTransaction.length <= PACKET_DATA_SIZE, "Transaction too large: ".concat(wireTransaction.length, " > ").concat(PACKET_DATA_SIZE)); + return wireTransaction; } + /** + * Deprecated method + * @internal + */ + }, { - key: "compiledInstructions", + key: "keys", get: function get() { - return this.instructions.map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accountKeyIndexes: ix.accounts, - data: bs58$1.decode(ix.data) - }; + assert(this.instructions.length === 1); + return this.instructions[0].keys.map(function (keyObj) { + return keyObj.pubkey; }); } + /** + * Deprecated method + * @internal + */ + }, { - key: "addressTableLookups", + key: "programId", get: function get() { - return []; - } - }, { - key: "getAccountKeys", - value: function getAccountKeys() { - return new MessageAccountKeys(this.staticAccountKeys); + assert(this.instructions.length === 1); + return this.instructions[0].programId; } + /** + * Deprecated method + * @internal + */ + }, { - key: "isAccountSigner", - value: function isAccountSigner(index) { - return index < this.header.numRequiredSignatures; + key: "data", + get: function get() { + assert(this.instructions.length === 1); + return this.instructions[0].data; } - }, { - key: "isAccountWritable", - value: function isAccountWritable(index) { - var numSignedAccounts = this.header.numRequiredSignatures; + /** + * Parse a wire transaction into a Transaction object. + */ - if (index >= this.header.numRequiredSignatures) { - var unsignedAccountIndex = index - numSignedAccounts; - var numUnsignedAccounts = this.accountKeys.length - numSignedAccounts; - var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; - return unsignedAccountIndex < numWritableUnsignedAccounts; - } else { - var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; - return index < numWritableSignedAccounts; + }], [{ + key: "from", + value: function from(buffer) { + // Slice up wire data + var byteArray = _toConsumableArray(buffer); + + var signatureCount = decodeLength(byteArray); + var signatures = []; + + for (var i = 0; i < signatureCount; i++) { + var _signature2 = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES); + + byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES); + signatures.push(bs58$3.encode(Buffer$1.from(_signature2))); } - } - }, { - key: "isProgramId", - value: function isProgramId(index) { - return this.indexToProgramIds.has(index); - } - }, { - key: "programIds", - value: function programIds() { - return _toConsumableArray(this.indexToProgramIds.values()); - } - }, { - key: "nonProgramIds", - value: function nonProgramIds() { - var _this8 = this; - return this.accountKeys.filter(function (_, index) { - return !_this8.isProgramId(index); - }); - } - }, { - key: "serialize", - value: function serialize() { - var numKeys = this.accountKeys.length; - var keyCount = []; - encodeLength(keyCount, numKeys); - var instructions = this.instructions.map(function (instruction) { - var accounts = instruction.accounts, - programIdIndex = instruction.programIdIndex; - var data = Array.from(bs58$1.decode(instruction.data)); - var keyIndicesCount = []; - encodeLength(keyIndicesCount, accounts.length); - var dataCount = []; - encodeLength(dataCount, data.length); - return { - programIdIndex: programIdIndex, - keyIndicesCount: Buffer$1.from(keyIndicesCount), - keyIndices: accounts, - dataLength: Buffer$1.from(dataCount), - data: data - }; - }); - var instructionCount = []; - encodeLength(instructionCount, instructions.length); - var instructionBuffer = Buffer$1.alloc(PACKET_DATA_SIZE); - Buffer$1.from(instructionCount).copy(instructionBuffer); - var instructionBufferLength = instructionCount.length; - instructions.forEach(function (instruction) { - var instructionLayout = struct([u8('programIdIndex'), blob$1(instruction.keyIndicesCount.length, 'keyIndicesCount'), seq$1(u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), blob$1(instruction.dataLength.length, 'dataLength'), seq$1(u8('userdatum'), instruction.data.length, 'data')]); - var length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength); - instructionBufferLength += length; - }); - instructionBuffer = instructionBuffer.slice(0, instructionBufferLength); - var signDataLayout = struct([blob$1(1, 'numRequiredSignatures'), blob$1(1, 'numReadonlySignedAccounts'), blob$1(1, 'numReadonlyUnsignedAccounts'), blob$1(keyCount.length, 'keyCount'), seq$1(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]); - var transaction = { - numRequiredSignatures: Buffer$1.from([this.header.numRequiredSignatures]), - numReadonlySignedAccounts: Buffer$1.from([this.header.numReadonlySignedAccounts]), - numReadonlyUnsignedAccounts: Buffer$1.from([this.header.numReadonlyUnsignedAccounts]), - keyCount: Buffer$1.from(keyCount), - keys: this.accountKeys.map(function (key) { - return toBuffer(key.toBytes()); - }), - recentBlockhash: bs58$1.decode(this.recentBlockhash) - }; - var signData = Buffer$1.alloc(2048); - var length = signDataLayout.encode(transaction, signData); - instructionBuffer.copy(signData, length); - return signData.slice(0, length + instructionBuffer.length); + return Transaction.populate(Message.from(byteArray), signatures); } /** - * Decode a compiled message into a Message object. + * Populate Transaction object from message and signatures */ - }], [{ - key: "compile", - value: function compile(args) { - var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); + }, { + key: "populate", + value: function populate(message) { + var signatures = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var transaction = new Transaction(); + transaction.recentBlockhash = message.recentBlockhash; - var _compiledKeys$getMess = compiledKeys.getMessageComponents(), - _compiledKeys$getMess2 = _slicedToArray(_compiledKeys$getMess, 2), - header = _compiledKeys$getMess2[0], - staticAccountKeys = _compiledKeys$getMess2[1]; + if (message.header.numRequiredSignatures > 0) { + transaction.feePayer = message.accountKeys[0]; + } - var accountKeys = new MessageAccountKeys(staticAccountKeys); - var instructions = accountKeys.compileInstructions(args.instructions).map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accounts: ix.accountKeyIndexes, - data: bs58$1.encode(ix.data) + signatures.forEach(function (signature, index) { + var sigPubkeyPair = { + signature: signature == bs58$3.encode(DEFAULT_SIGNATURE) ? null : bs58$3.decode(signature), + publicKey: message.accountKeys[index] }; + transaction.signatures.push(sigPubkeyPair); }); - return new Message({ - header: header, - accountKeys: staticAccountKeys, - recentBlockhash: args.recentBlockhash, - instructions: instructions + message.instructions.forEach(function (instruction) { + var keys = instruction.accounts.map(function (account) { + var pubkey = message.accountKeys[account]; + return { + pubkey: pubkey, + isSigner: transaction.signatures.some(function (keyObj) { + return keyObj.publicKey.toString() === pubkey.toString(); + }) || message.isAccountSigner(account), + isWritable: message.isAccountWritable(account) + }; + }); + transaction.instructions.push(new TransactionInstruction({ + keys: keys, + programId: message.accountKeys[instruction.programIdIndex], + data: bs58$3.decode(instruction.data) + })); }); + transaction._message = message; + transaction._json = transaction.toJSON(); + return transaction; } - }, { - key: "from", - value: function from(buffer) { - // Slice up wire data - var byteArray = _toConsumableArray(buffer); + }]); - var numRequiredSignatures = byteArray.shift(); + return Transaction; +}(); - if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) { - throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()'); - } +var TransactionMessage = /*#__PURE__*/function () { + function TransactionMessage(args) { + _classCallCheck(this, TransactionMessage); - var numReadonlySignedAccounts = byteArray.shift(); - var numReadonlyUnsignedAccounts = byteArray.shift(); - var accountCount = decodeLength(byteArray); - var accountKeys = []; + this.payerKey = void 0; + this.instructions = void 0; + this.recentBlockhash = void 0; + this.payerKey = args.payerKey; + this.instructions = args.instructions; + this.recentBlockhash = args.recentBlockhash; + } - for (var i = 0; i < accountCount; i++) { - var account = byteArray.slice(0, PUBLIC_KEY_LENGTH); - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - accountKeys.push(new PublicKey(Buffer$1.from(account))); + _createClass(TransactionMessage, [{ + key: "compileToLegacyMessage", + value: function compileToLegacyMessage() { + return Message.compile({ + payerKey: this.payerKey, + recentBlockhash: this.recentBlockhash, + instructions: this.instructions + }); + } + }, { + key: "compileToV0Message", + value: function compileToV0Message(addressLookupTableAccounts) { + return MessageV0.compile({ + payerKey: this.payerKey, + recentBlockhash: this.recentBlockhash, + instructions: this.instructions, + addressLookupTableAccounts: addressLookupTableAccounts + }); + } + }], [{ + key: "decompile", + value: function decompile(message, args) { + var header = message.header, + compiledInstructions = message.compiledInstructions, + recentBlockhash = message.recentBlockhash; + var numRequiredSignatures = header.numRequiredSignatures, + numReadonlySignedAccounts = header.numReadonlySignedAccounts, + numReadonlyUnsignedAccounts = header.numReadonlyUnsignedAccounts; + var numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts; + assert(numWritableSignedAccounts > 0, 'Message header is invalid'); + var numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts; + assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid'); + var accountKeys = message.getAccountKeys(args); + var payerKey = accountKeys.get(0); + + if (payerKey === undefined) { + throw new Error('Failed to decompile message because no account keys were found'); } - var recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH); - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - var instructionCount = decodeLength(byteArray); var instructions = []; - for (var _i2 = 0; _i2 < instructionCount; _i2++) { - var programIdIndex = byteArray.shift(); + var _iterator14 = _createForOfIteratorHelper(compiledInstructions), + _step14; - var _accountCount = decodeLength(byteArray); + try { + for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { + var compiledIx = _step14.value; + var keys = []; - var accounts = byteArray.slice(0, _accountCount); - byteArray = byteArray.slice(_accountCount); - var dataLength = decodeLength(byteArray); - var dataSlice = byteArray.slice(0, dataLength); - var data = bs58$1.encode(Buffer$1.from(dataSlice)); - byteArray = byteArray.slice(dataLength); - instructions.push({ - programIdIndex: programIdIndex, - accounts: accounts, - data: data - }); + var _iterator15 = _createForOfIteratorHelper(compiledIx.accountKeyIndexes), + _step15; + + try { + for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { + var keyIndex = _step15.value; + var pubkey = accountKeys.get(keyIndex); + + if (pubkey === undefined) { + throw new Error("Failed to find key for account key index ".concat(keyIndex)); + } + + var isSigner = keyIndex < numRequiredSignatures; + var isWritable = void 0; + + if (isSigner) { + isWritable = keyIndex < numWritableSignedAccounts; + } else if (keyIndex < accountKeys.staticAccountKeys.length) { + isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts; + } else { + isWritable = keyIndex - accountKeys.staticAccountKeys.length < // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above + accountKeys.accountKeysFromLookups.writable.length; + } + + keys.push({ + pubkey: pubkey, + isSigner: keyIndex < header.numRequiredSignatures, + isWritable: isWritable + }); + } + } catch (err) { + _iterator15.e(err); + } finally { + _iterator15.f(); + } + + var programId = accountKeys.get(compiledIx.programIdIndex); + + if (programId === undefined) { + throw new Error("Failed to find program id for program id index ".concat(compiledIx.programIdIndex)); + } + + instructions.push(new TransactionInstruction({ + programId: programId, + data: toBuffer(compiledIx.data), + keys: keys + })); + } + } catch (err) { + _iterator14.e(err); + } finally { + _iterator14.f(); } - var messageArgs = { - header: { - numRequiredSignatures: numRequiredSignatures, - numReadonlySignedAccounts: numReadonlySignedAccounts, - numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts - }, - recentBlockhash: bs58$1.encode(Buffer$1.from(recentBlockhash)), - accountKeys: accountKeys, - instructions: instructions - }; - return new Message(messageArgs); + return new TransactionMessage({ + payerKey: payerKey, + instructions: instructions, + recentBlockhash: recentBlockhash + }); } }]); - return Message; + return TransactionMessage; }(); /** - * Message constructor arguments + * Versioned transaction class */ -var MessageV0 = /*#__PURE__*/function () { - function MessageV0(args) { - _classCallCheck(this, MessageV0); +var VersionedTransaction = /*#__PURE__*/function () { + function VersionedTransaction(message, signatures) { + _classCallCheck(this, VersionedTransaction); - this.header = void 0; - this.staticAccountKeys = void 0; - this.recentBlockhash = void 0; - this.compiledInstructions = void 0; - this.addressTableLookups = void 0; - this.header = args.header; - this.staticAccountKeys = args.staticAccountKeys; - this.recentBlockhash = args.recentBlockhash; - this.compiledInstructions = args.compiledInstructions; - this.addressTableLookups = args.addressTableLookups; + this.signatures = void 0; + this.message = void 0; + + if (signatures !== undefined) { + assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures'); + this.signatures = signatures; + } else { + var defaultSignatures = []; + + for (var i = 0; i < message.header.numRequiredSignatures; i++) { + defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES)); + } + + this.signatures = defaultSignatures; + } + + this.message = message; } - _createClass(MessageV0, [{ + _createClass(VersionedTransaction, [{ key: "version", get: function get() { - return 0; + return this.message.version; } }, { - key: "numAccountKeysFromLookups", - get: function get() { - var count = 0; + key: "serialize", + value: function serialize() { + var serializedMessage = this.message.serialize(); + var encodedSignaturesLength = Array(); + encodeLength(encodedSignaturesLength, this.signatures.length); + var transactionLayout = struct([blob$1(encodedSignaturesLength.length, 'encodedSignaturesLength'), seq$1(signature(), this.signatures.length, 'signatures'), blob$1(serializedMessage.length, 'serializedMessage')]); + var serializedTransaction = new Uint8Array(2048); + var serializedTransactionLength = transactionLayout.encode({ + encodedSignaturesLength: new Uint8Array(encodedSignaturesLength), + signatures: this.signatures, + serializedMessage: serializedMessage + }, serializedTransaction); + return serializedTransaction.slice(0, serializedTransactionLength); + } + }, { + key: "sign", + value: function sign(signers) { + var _this11 = this; - var _iterator5 = _createForOfIteratorHelper(this.addressTableLookups), - _step5; + var messageData = this.message.serialize(); + var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + + var _iterator16 = _createForOfIteratorHelper(signers), + _step16; try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var lookup = _step5.value; - count += lookup.readonlyIndexes.length + lookup.writableIndexes.length; + var _loop4 = function _loop4() { + var signer = _step16.value; + var signerIndex = signerPubkeys.findIndex(function (pubkey) { + return pubkey.equals(signer.publicKey); + }); + assert(signerIndex >= 0, "Cannot sign with non signer key ".concat(signer.publicKey.toBase58())); + _this11.signatures[signerIndex] = _sign(messageData, signer.secretKey); + }; + + for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { + _loop4(); } } catch (err) { - _iterator5.e(err); + _iterator16.e(err); } finally { - _iterator5.f(); + _iterator16.f(); } - - return count; } }, { - key: "getAccountKeys", - value: function getAccountKeys(args) { - var accountKeysFromLookups; + key: "addSignature", + value: function addSignature(publicKey, signature) { + assert(signature.byteLength === 64, 'Signature must be 64 bytes long'); + var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + var signerIndex = signerPubkeys.findIndex(function (pubkey) { + return pubkey.equals(publicKey); + }); + assert(signerIndex >= 0, "Can not add signature; `".concat(publicKey.toBase58(), "` is not required to sign this transaction")); + this.signatures[signerIndex] = signature; + } + }], [{ + key: "deserialize", + value: function deserialize(serializedTransaction) { + var byteArray = _toConsumableArray(serializedTransaction); - if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) { - if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) { - throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups'); - } + var signatures = []; + var signaturesLength = decodeLength(byteArray); - accountKeysFromLookups = args.accountKeysFromLookups; - } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) { - accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts); - } else if (this.addressTableLookups.length > 0) { - throw new Error('Failed to get account keys because address table lookups were not resolved'); + for (var i = 0; i < signaturesLength; i++) { + signatures.push(new Uint8Array(byteArray.splice(0, SIGNATURE_LENGTH_IN_BYTES))); } - return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups); - } - }, { - key: "isAccountSigner", - value: function isAccountSigner(index) { - return index < this.header.numRequiredSignatures; + var message = VersionedMessage.deserialize(new Uint8Array(byteArray)); + return new VersionedTransaction(message, signatures); } - }, { - key: "isAccountWritable", - value: function isAccountWritable(index) { - var numSignedAccounts = this.header.numRequiredSignatures; - var numStaticAccountKeys = this.staticAccountKeys.length; + }]); - if (index >= numStaticAccountKeys) { - var lookupAccountKeysIndex = index - numStaticAccountKeys; - var numWritableLookupAccountKeys = this.addressTableLookups.reduce(function (count, lookup) { - return count + lookup.writableIndexes.length; - }, 0); - return lookupAccountKeysIndex < numWritableLookupAccountKeys; - } else if (index >= this.header.numRequiredSignatures) { - var unsignedAccountIndex = index - numSignedAccounts; - var numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts; - var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; - return unsignedAccountIndex < numWritableUnsignedAccounts; - } else { - var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; - return index < numWritableSignedAccounts; - } - } - }, { - key: "resolveAddressTableLookups", - value: function resolveAddressTableLookups(addressLookupTableAccounts) { - var accountKeysFromLookups = { - writable: [], - readonly: [] - }; + return VersionedTransaction; +}(); - var _iterator6 = _createForOfIteratorHelper(this.addressTableLookups), - _step6; +var SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111'); +var SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111'); +var SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111'); +var SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111'); +var SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111'); +var SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111'); +var SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111'); +var SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111'); +var SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111'); +/** + * Sign, send and confirm a transaction. + * + * If `commitment` option is not specified, defaults to 'max' commitment. + * + * @param {Connection} connection + * @param {Transaction} transaction + * @param {Array} signers + * @param {ConfirmOptions} [options] + * @returns {Promise} + */ - try { - var _loop2 = function _loop2() { - var tableLookup = _step6.value; - var tableAccount = addressLookupTableAccounts.find(function (account) { - return account.key.equals(tableLookup.accountKey); - }); +function sendAndConfirmTransaction(_x9, _x10, _x11, _x12) { + return _sendAndConfirmTransaction.apply(this, arguments); +} // zzz - if (!tableAccount) { - throw new Error("Failed to find address lookup table account for table key ".concat(tableLookup.accountKey.toBase58())); + +function _sendAndConfirmTransaction() { + _sendAndConfirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee108(connection, transaction, signers, options) { + var sendOptions, signature, status, nonceInstruction, nonceAccountPubkey; + return _regeneratorRuntime().wrap(function _callee108$(_context108) { + while (1) switch (_context108.prev = _context108.next) { + case 0: + sendOptions = options && { + skipPreflight: options.skipPreflight, + preflightCommitment: options.preflightCommitment || options.commitment, + maxRetries: options.maxRetries, + minContextSlot: options.minContextSlot + }; + _context108.next = 3; + return connection.sendTransaction(transaction, signers, sendOptions); + + case 3: + signature = _context108.sent; + + if (!(transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null)) { + _context108.next = 10; + break; } - var _iterator7 = _createForOfIteratorHelper(tableLookup.writableIndexes), - _step7; + _context108.next = 7; + return connection.confirmTransaction({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + signature: signature, + blockhash: transaction.recentBlockhash, + lastValidBlockHeight: transaction.lastValidBlockHeight + }, options && options.commitment); - try { - for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { - var index = _step7.value; + case 7: + status = _context108.sent.value; + _context108.next = 22; + break; - if (index < tableAccount.state.addresses.length) { - accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]); - } else { - throw new Error("Failed to find address for index ".concat(index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); - } - } - } catch (err) { - _iterator7.e(err); - } finally { - _iterator7.f(); + case 10: + if (!(transaction.minNonceContextSlot != null && transaction.nonceInfo != null)) { + _context108.next = 18; + break; } - var _iterator8 = _createForOfIteratorHelper(tableLookup.readonlyIndexes), - _step8; + nonceInstruction = transaction.nonceInfo.nonceInstruction; + nonceAccountPubkey = nonceInstruction.keys[0].pubkey; + _context108.next = 15; + return connection.confirmTransaction({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + minContextSlot: transaction.minNonceContextSlot, + nonceAccountPubkey: nonceAccountPubkey, + nonceValue: transaction.nonceInfo.nonce, + signature: signature + }, options && options.commitment); - try { - for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { - var _index = _step8.value; + case 15: + status = _context108.sent.value; + _context108.next = 22; + break; - if (_index < tableAccount.state.addresses.length) { - accountKeysFromLookups.readonly.push(tableAccount.state.addresses[_index]); - } else { - throw new Error("Failed to find address for index ".concat(_index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); - } - } - } catch (err) { - _iterator8.e(err); - } finally { - _iterator8.f(); + case 18: + if ((options === null || options === void 0 ? void 0 : options.abortSignal) != null) { + console.warn('sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' + 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' + 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.'); } - }; - for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { - _loop2(); - } - } catch (err) { - _iterator6.e(err); - } finally { - _iterator6.f(); + _context108.next = 21; + return connection.confirmTransaction(signature, options && options.commitment); + + case 21: + status = _context108.sent.value; + + case 22: + if (!status.err) { + _context108.next = 24; + break; + } + + throw new Error("Transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + + case 24: + return _context108.abrupt("return", signature); + + case 25: + case "end": + return _context108.stop(); } + }, _callee108); + })); + return _sendAndConfirmTransaction.apply(this, arguments); +} - return accountKeysFromLookups; - } - }, { - key: "serialize", - value: function serialize() { - var encodedStaticAccountKeysLength = Array(); - encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length); - var serializedInstructions = this.serializeInstructions(); - var encodedInstructionsLength = Array(); - encodeLength(encodedInstructionsLength, this.compiledInstructions.length); - var serializedAddressTableLookups = this.serializeAddressTableLookups(); - var encodedAddressTableLookupsLength = Array(); - encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length); - var messageLayout = struct([u8('prefix'), struct([u8('numRequiredSignatures'), u8('numReadonlySignedAccounts'), u8('numReadonlyUnsignedAccounts')], 'header'), blob$1(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), seq$1(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), blob$1(encodedInstructionsLength.length, 'instructionsLength'), blob$1(serializedInstructions.length, 'serializedInstructions'), blob$1(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), blob$1(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]); - var serializedMessage = new Uint8Array(PACKET_DATA_SIZE); - var MESSAGE_VERSION_0_PREFIX = 1 << 7; - var serializedMessageLength = messageLayout.encode({ - prefix: MESSAGE_VERSION_0_PREFIX, - header: this.header, - staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength), - staticAccountKeys: this.staticAccountKeys.map(function (key) { - return key.toBytes(); - }), - recentBlockhash: bs58$1.decode(this.recentBlockhash), - instructionsLength: new Uint8Array(encodedInstructionsLength), - serializedInstructions: serializedInstructions, - addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength), - serializedAddressTableLookups: serializedAddressTableLookups - }, serializedMessage); - return serializedMessage.slice(0, serializedMessageLength); +function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); +} +/** + * Populate a buffer of instruction data using an InstructionType + * @internal + */ + + +function encodeData(type, fields) { + var allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields); + var data = Buffer$1.alloc(allocLength); + var layoutFields = Object.assign({ + instruction: type.index + }, fields); + type.layout.encode(layoutFields, data); + return data; +} +/** + * Decode instruction data buffer using an InstructionType + * @internal + */ + + +function decodeData$1(type, buffer) { + var data; + + try { + data = type.layout.decode(buffer); + } catch (err) { + throw new Error('invalid instruction; ' + err); + } + + if (data.instruction !== type.index) { + throw new Error("invalid instruction; instruction index mismatch ".concat(data.instruction, " != ").concat(type.index)); + } + + return data; +} +/** + * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11 + * + * @internal + */ + + +var FeeCalculatorLayout = nu64$1('lamportsPerSignature'); +/** + * Calculator for transaction fees. + * + * @deprecated Deprecated since Solana v1.8.0. + */ + +/** + * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32 + * + * @internal + */ + +var NonceAccountLayout = struct([u32('version'), u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), struct([FeeCalculatorLayout], 'feeCalculator')]); +var NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span; +/** + * A durable nonce is a 32 byte value encoded as a base58 string. + */ + +/** + * NonceAccount class + */ + +var NonceAccount = /*#__PURE__*/function () { + /** + * @internal + */ + function NonceAccount(args) { + _classCallCheck(this, NonceAccount); + + this.authorizedPubkey = void 0; + this.nonce = void 0; + this.feeCalculator = void 0; + this.authorizedPubkey = args.authorizedPubkey; + this.nonce = args.nonce; + this.feeCalculator = args.feeCalculator; + } + /** + * Deserialize NonceAccount from the account data. + * + * @param buffer account data + * @return NonceAccount + */ + + + _createClass(NonceAccount, null, [{ + key: "fromAccountData", + value: function fromAccountData(buffer) { + var nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0); + return new NonceAccount({ + authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey), + nonce: new PublicKey(nonceAccount.nonce).toString(), + feeCalculator: nonceAccount.feeCalculator + }); } - }, { - key: "serializeInstructions", - value: function serializeInstructions() { - var serializedLength = 0; - var serializedInstructions = new Uint8Array(PACKET_DATA_SIZE); + }]); + + return NonceAccount; +}(); + +var encodeDecode = function encodeDecode(layout) { + var decode = layout.decode.bind(layout); + var encode = layout.encode.bind(layout); + return { + decode: decode, + encode: encode + }; +}; + +var bigInt = function bigInt(length) { + return function (property) { + var layout = blob$1(length, property); + + var _encodeDecode = encodeDecode(layout), + encode = _encodeDecode.encode, + decode = _encodeDecode.decode; + + var bigIntLayout = layout; + + bigIntLayout.decode = function (buffer, offset) { + var src = decode(buffer, offset); + return toBigIntLE_1(Buffer$1.from(src)); + }; + + bigIntLayout.encode = function (bigInt, buffer, offset) { + var src = toBufferLE_1(bigInt, length); + return encode(src, buffer, offset); + }; + + return bigIntLayout; + }; +}; + +var u64 = bigInt(8); +/** + * Create account system transaction params + */ + +/** + * System Instruction class + */ + +var SystemInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function SystemInstruction() { + _classCallCheck(this, SystemInstruction); + } + /** + * Decode a system instruction and retrieve the instruction type. + */ - var _iterator9 = _createForOfIteratorHelper(this.compiledInstructions), - _step9; - try { - for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { - var instruction = _step9.value; - var encodedAccountKeyIndexesLength = Array(); - encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length); - var encodedDataLength = Array(); - encodeLength(encodedDataLength, instruction.data.length); - var instructionLayout = struct([u8('programIdIndex'), blob$1(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), seq$1(u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), blob$1(encodedDataLength.length, 'encodedDataLength'), blob$1(instruction.data.length, 'data')]); - serializedLength += instructionLayout.encode({ - programIdIndex: instruction.programIdIndex, - encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength), - accountKeyIndexes: instruction.accountKeyIndexes, - encodedDataLength: new Uint8Array(encodedDataLength), - data: instruction.data - }, serializedInstructions, serializedLength); + _createClass(SystemInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; + + for (var _i9 = 0, _Object$entries = Object.entries(SYSTEM_INSTRUCTION_LAYOUTS); _i9 < _Object$entries.length; _i9++) { + var _Object$entries$_i2 = _slicedToArray(_Object$entries[_i9], 2), + ixType = _Object$entries$_i2[0], + layout = _Object$entries$_i2[1]; + + if (layout.index == typeIndex) { + type = ixType; + break; } - } catch (err) { - _iterator9.e(err); - } finally { - _iterator9.f(); } - return serializedInstructions.slice(0, serializedLength); + if (!type) { + throw new Error('Instruction type incorrect; not a SystemInstruction'); + } + + return type; } - }, { - key: "serializeAddressTableLookups", - value: function serializeAddressTableLookups() { - var serializedLength = 0; - var serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE); + /** + * Decode a create account system instruction and retrieve the instruction params. + */ - var _iterator10 = _createForOfIteratorHelper(this.addressTableLookups), - _step10; + }, { + key: "decodeCreateAccount", + value: function decodeCreateAccount(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - try { - for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { - var lookup = _step10.value; - var encodedWritableIndexesLength = Array(); - encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length); - var encodedReadonlyIndexesLength = Array(); - encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length); - var addressTableLookupLayout = struct([publicKey('accountKey'), blob$1(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), seq$1(u8(), lookup.writableIndexes.length, 'writableIndexes'), blob$1(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), seq$1(u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]); - serializedLength += addressTableLookupLayout.encode({ - accountKey: lookup.accountKey.toBytes(), - encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength), - writableIndexes: lookup.writableIndexes, - encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength), - readonlyIndexes: lookup.readonlyIndexes - }, serializedAddressTableLookups, serializedLength); - } - } catch (err) { - _iterator10.e(err); - } finally { - _iterator10.f(); - } + var _decodeData$ = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data), + lamports = _decodeData$.lamports, + space = _decodeData$.space, + programId = _decodeData$.programId; - return serializedAddressTableLookups.slice(0, serializedLength); + return { + fromPubkey: instruction.keys[0].pubkey, + newAccountPubkey: instruction.keys[1].pubkey, + lamports: lamports, + space: space, + programId: new PublicKey(programId) + }; } - }], [{ - key: "compile", - value: function compile(args) { - var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); - var addressTableLookups = new Array(); - var accountKeysFromLookups = { - writable: new Array(), - readonly: new Array() + /** + * Decode a transfer system instruction and retrieve the instruction params. + */ + + }, { + key: "decodeTransfer", + value: function decodeTransfer(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); + + var _decodeData$2 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data), + lamports = _decodeData$2.lamports; + + return { + fromPubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + lamports: lamports }; - var lookupTableAccounts = args.addressLookupTableAccounts || []; + } + /** + * Decode a transfer with seed system instruction and retrieve the instruction params. + */ - var _iterator11 = _createForOfIteratorHelper(lookupTableAccounts), - _step11; + }, { + key: "decodeTransferWithSeed", + value: function decodeTransferWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - try { - for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { - var lookupTable = _step11.value; - var extractResult = compiledKeys.extractTableLookup(lookupTable); + var _decodeData$3 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data), + lamports = _decodeData$3.lamports, + seed = _decodeData$3.seed, + programId = _decodeData$3.programId; - if (extractResult !== undefined) { - var _accountKeysFromLooku, _accountKeysFromLooku2; + return { + fromPubkey: instruction.keys[0].pubkey, + basePubkey: instruction.keys[1].pubkey, + toPubkey: instruction.keys[2].pubkey, + lamports: lamports, + seed: seed, + programId: new PublicKey(programId) + }; + } + /** + * Decode an allocate system instruction and retrieve the instruction params. + */ - var _extractResult2 = _slicedToArray(extractResult, 2), - addressTableLookup = _extractResult2[0], - _extractResult$2 = _extractResult2[1], - writable = _extractResult$2.writable, - readonly = _extractResult$2.readonly; + }, { + key: "decodeAllocate", + value: function decodeAllocate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - addressTableLookups.push(addressTableLookup); + var _decodeData$4 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data), + space = _decodeData$4.space; - (_accountKeysFromLooku = accountKeysFromLookups.writable).push.apply(_accountKeysFromLooku, _toConsumableArray(writable)); + return { + accountPubkey: instruction.keys[0].pubkey, + space: space + }; + } + /** + * Decode an allocate with seed system instruction and retrieve the instruction params. + */ - (_accountKeysFromLooku2 = accountKeysFromLookups.readonly).push.apply(_accountKeysFromLooku2, _toConsumableArray(readonly)); - } - } - } catch (err) { - _iterator11.e(err); - } finally { - _iterator11.f(); - } + }, { + key: "decodeAllocateWithSeed", + value: function decodeAllocateWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var _compiledKeys$getMess3 = compiledKeys.getMessageComponents(), - _compiledKeys$getMess4 = _slicedToArray(_compiledKeys$getMess3, 2), - header = _compiledKeys$getMess4[0], - staticAccountKeys = _compiledKeys$getMess4[1]; + var _decodeData$5 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data), + base = _decodeData$5.base, + seed = _decodeData$5.seed, + space = _decodeData$5.space, + programId = _decodeData$5.programId; - var accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups); - var compiledInstructions = accountKeys.compileInstructions(args.instructions); - return new MessageV0({ - header: header, - staticAccountKeys: staticAccountKeys, - recentBlockhash: args.recentBlockhash, - compiledInstructions: compiledInstructions, - addressTableLookups: addressTableLookups - }); + return { + accountPubkey: instruction.keys[0].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + space: space, + programId: new PublicKey(programId) + }; } + /** + * Decode an assign system instruction and retrieve the instruction params. + */ + }, { - key: "deserialize", - value: function deserialize(serializedMessage) { - var byteArray = _toConsumableArray(serializedMessage); + key: "decodeAssign", + value: function decodeAssign(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var prefix = byteArray.shift(); - var maskedPrefix = prefix & VERSION_PREFIX_MASK; - assert(prefix !== maskedPrefix, "Expected versioned message but received legacy message"); - var version = maskedPrefix; - assert(version === 0, "Expected versioned message with version 0 but found version ".concat(version)); - var header = { - numRequiredSignatures: byteArray.shift(), - numReadonlySignedAccounts: byteArray.shift(), - numReadonlyUnsignedAccounts: byteArray.shift() + var _decodeData$6 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data), + programId = _decodeData$6.programId; + + return { + accountPubkey: instruction.keys[0].pubkey, + programId: new PublicKey(programId) }; - var staticAccountKeys = []; - var staticAccountKeysLength = decodeLength(byteArray); + } + /** + * Decode an assign with seed system instruction and retrieve the instruction params. + */ - for (var i = 0; i < staticAccountKeysLength; i++) { - staticAccountKeys.push(new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH))); - } + }, { + key: "decodeAssignWithSeed", + value: function decodeAssignWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var recentBlockhash = bs58$1.encode(byteArray.splice(0, PUBLIC_KEY_LENGTH)); - var instructionCount = decodeLength(byteArray); - var compiledInstructions = []; + var _decodeData$7 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data), + base = _decodeData$7.base, + seed = _decodeData$7.seed, + programId = _decodeData$7.programId; - for (var _i4 = 0; _i4 < instructionCount; _i4++) { - var programIdIndex = byteArray.shift(); - var accountKeyIndexesLength = decodeLength(byteArray); - var accountKeyIndexes = byteArray.splice(0, accountKeyIndexesLength); - var dataLength = decodeLength(byteArray); - var data = new Uint8Array(byteArray.splice(0, dataLength)); - compiledInstructions.push({ - programIdIndex: programIdIndex, - accountKeyIndexes: accountKeyIndexes, - data: data - }); - } + return { + accountPubkey: instruction.keys[0].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + programId: new PublicKey(programId) + }; + } + /** + * Decode a create account with seed system instruction and retrieve the instruction params. + */ - var addressTableLookupsCount = decodeLength(byteArray); - var addressTableLookups = []; + }, { + key: "decodeCreateWithSeed", + value: function decodeCreateWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - for (var _i6 = 0; _i6 < addressTableLookupsCount; _i6++) { - var accountKey = new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH)); - var writableIndexesLength = decodeLength(byteArray); - var writableIndexes = byteArray.splice(0, writableIndexesLength); - var readonlyIndexesLength = decodeLength(byteArray); - var readonlyIndexes = byteArray.splice(0, readonlyIndexesLength); - addressTableLookups.push({ - accountKey: accountKey, - writableIndexes: writableIndexes, - readonlyIndexes: readonlyIndexes - }); - } + var _decodeData$8 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data), + base = _decodeData$8.base, + seed = _decodeData$8.seed, + lamports = _decodeData$8.lamports, + space = _decodeData$8.space, + programId = _decodeData$8.programId; - return new MessageV0({ - header: header, - staticAccountKeys: staticAccountKeys, - recentBlockhash: recentBlockhash, - compiledInstructions: compiledInstructions, - addressTableLookups: addressTableLookups - }); + return { + fromPubkey: instruction.keys[0].pubkey, + newAccountPubkey: instruction.keys[1].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + lamports: lamports, + space: space, + programId: new PublicKey(programId) + }; } - }]); + /** + * Decode a nonce initialize system instruction and retrieve the instruction params. + */ - return MessageV0; -}(); // eslint-disable-next-line no-redeclare + }, { + key: "decodeNonceInitialize", + value: function decodeNonceInitialize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + var _decodeData$9 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data), + authorized = _decodeData$9.authorized; -var VersionedMessage = { - deserializeMessageVersion: function deserializeMessageVersion(serializedMessage) { - var prefix = serializedMessage[0]; - var maskedPrefix = prefix & VERSION_PREFIX_MASK; // if the highest bit of the prefix is not set, the message is not versioned + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: new PublicKey(authorized) + }; + } + /** + * Decode a nonce advance system instruction and retrieve the instruction params. + */ - if (maskedPrefix === prefix) { - return 'legacy'; - } // the lower 7 bits of the prefix indicate the message version + }, { + key: "decodeNonceAdvance", + value: function decodeNonceAdvance(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data); + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey + }; + } + /** + * Decode a nonce withdraw system instruction and retrieve the instruction params. + */ + }, { + key: "decodeNonceWithdraw", + value: function decodeNonceWithdraw(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 5); - return maskedPrefix; - }, - deserialize: function deserialize(serializedMessage) { - var version = VersionedMessage.deserializeMessageVersion(serializedMessage); + var _decodeData$10 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data), + lamports = _decodeData$10.lamports; - if (version === 'legacy') { - return Message.from(serializedMessage); + return { + noncePubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey, + lamports: lamports + }; } + /** + * Decode a nonce authorize system instruction and retrieve the instruction params. + */ - if (version === 0) { - return MessageV0.deserialize(serializedMessage); - } else { - throw new Error("Transaction message version ".concat(version, " deserialization is not supported")); + }, { + key: "decodeNonceAuthorize", + value: function decodeNonceAuthorize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); + + var _decodeData$11 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data), + authorized = _decodeData$11.authorized; + + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[1].pubkey, + newAuthorizedPubkey: new PublicKey(authorized) + }; } - } -}; -/** - * Transaction signature as base-58 encoded string - */ + /** + * @internal + */ -var TransactionStatus; -/** - * Default (empty) signature - */ + }, { + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(SystemProgram.programId)) { + throw new Error('invalid instruction; programId is not SystemProgram'); + } + } + /** + * @internal + */ -(function (TransactionStatus) { - TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"] = 0] = "BLOCKHEIGHT_EXCEEDED"; - TransactionStatus[TransactionStatus["PROCESSED"] = 1] = "PROCESSED"; - TransactionStatus[TransactionStatus["TIMED_OUT"] = 2] = "TIMED_OUT"; - TransactionStatus[TransactionStatus["NONCE_INVALID"] = 3] = "NONCE_INVALID"; -})(TransactionStatus || (TransactionStatus = {})); + }, { + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); + } + } + }]); -var DEFAULT_SIGNATURE = Buffer$1.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0); + return SystemInstruction; +}(); /** - * Account metadata used to define instructions + * An enumeration of valid SystemInstructionType's */ /** - * Transaction Instruction class + * An enumeration of valid system InstructionType's + * @internal */ -var TransactionInstruction = /*#__PURE__*/function () { - /** - * Public keys to include in this transaction - * Boolean represents whether this pubkey needs to sign the transaction - */ +var SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({ + Create: { + index: 0, + layout: struct([u32('instruction'), ns64('lamports'), ns64('space'), publicKey('programId')]) + }, + Assign: { + index: 1, + layout: struct([u32('instruction'), publicKey('programId')]) + }, + Transfer: { + index: 2, + layout: struct([u32('instruction'), u64('lamports')]) + }, + CreateWithSeed: { + index: 3, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('lamports'), ns64('space'), publicKey('programId')]) + }, + AdvanceNonceAccount: { + index: 4, + layout: struct([u32('instruction')]) + }, + WithdrawNonceAccount: { + index: 5, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + InitializeNonceAccount: { + index: 6, + layout: struct([u32('instruction'), publicKey('authorized')]) + }, + AuthorizeNonceAccount: { + index: 7, + layout: struct([u32('instruction'), publicKey('authorized')]) + }, + Allocate: { + index: 8, + layout: struct([u32('instruction'), ns64('space')]) + }, + AllocateWithSeed: { + index: 9, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('space'), publicKey('programId')]) + }, + AssignWithSeed: { + index: 10, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')]) + }, + TransferWithSeed: { + index: 11, + layout: struct([u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')]) + }, + UpgradeNonceAccount: { + index: 12, + layout: struct([u32('instruction')]) + } +}); +/** + * Factory class for transactions to interact with the System program + */ + +var SystemProgram = /*#__PURE__*/function () { /** - * Program Id to execute + * @internal */ - + function SystemProgram() { + _classCallCheck(this, SystemProgram); + } /** - * Program input + * Public key that identifies the System program */ - function TransactionInstruction(opts) { - _classCallCheck(this, TransactionInstruction); - - this.keys = void 0; - this.programId = void 0; - this.data = Buffer$1.alloc(0); - this.programId = opts.programId; - this.keys = opts.keys; - if (opts.data) { - this.data = opts.data; - } - } /** - * @internal + * Generate a transaction instruction that creates a new account */ - _createClass(TransactionInstruction, [{ - key: "toJSON", - value: function toJSON() { - return { - keys: this.keys.map(function (_ref17) { - var pubkey = _ref17.pubkey, - isSigner = _ref17.isSigner, - isWritable = _ref17.isWritable; - return { - pubkey: pubkey.toJSON(), - isSigner: isSigner, - isWritable: isWritable - }; - }), - programId: this.programId.toJSON(), - data: _toConsumableArray(this.data) - }; + _createClass(SystemProgram, null, [{ + key: "createAccount", + value: function createAccount(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.Create; + var data = encodeData(type, { + lamports: params.lamports, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.newAccountPubkey, + isSigner: true, + isWritable: true + }], + programId: this.programId, + data: data + }); } - }]); - - return TransactionInstruction; -}(); -/** - * Pair of signature and corresponding public key - */ + /** + * Generate a transaction instruction that transfers lamports from one account to another + */ -/** - * Transaction class - */ + }, { + key: "transfer", + value: function transfer(params) { + var data; + var keys; + if ('basePubkey' in params) { + var _type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed; + data = encodeData(_type, { + lamports: BigInt(params.lamports), + seed: params.seed, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.fromPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }]; + } else { + var _type2 = SYSTEM_INSTRUCTION_LAYOUTS.Transfer; + data = encodeData(_type2, { + lamports: BigInt(params.lamports) + }); + keys = [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }]; + } -var Transaction = /*#__PURE__*/function () { - /** - * The transaction fee payer - */ + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that assigns an account to a program + */ - /** - * Construct an empty Transaction - */ - function Transaction(opts) { - _classCallCheck(this, Transaction); + }, { + key: "assign", + value: function assign(params) { + var data; + var keys; - this.signatures = []; - this.feePayer = void 0; - this.instructions = []; - this.recentBlockhash = void 0; - this.lastValidBlockHeight = void 0; - this.nonceInfo = void 0; - this.minNonceContextSlot = void 0; - this._message = void 0; - this._json = void 0; + if ('basePubkey' in params) { + var _type3 = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed; + data = encodeData(_type3, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }]; + } else { + var _type4 = SYSTEM_INSTRUCTION_LAYOUTS.Assign; + data = encodeData(_type4, { + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: true, + isWritable: true + }]; + } - if (!opts) { - return; + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); } + /** + * Generate a transaction instruction that creates a new account at + * an address generated with `from`, a seed, and programId + */ - if (opts.feePayer) { - this.feePayer = opts.feePayer; - } + }, { + key: "createAccountWithSeed", + value: function createAccountWithSeed(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed; + var data = encodeData(type, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + lamports: params.lamports, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + var keys = [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.newAccountPubkey, + isSigner: false, + isWritable: true + }]; - if (opts.signatures) { - this.signatures = opts.signatures; + if (params.basePubkey != params.fromPubkey) { + keys.push({ + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }); + } + + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); } + /** + * Generate a transaction that creates a new Nonce account + */ - if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) { - var minContextSlot = opts.minContextSlot, - nonceInfo = opts.nonceInfo; - this.minNonceContextSlot = minContextSlot; - this.nonceInfo = nonceInfo; - } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) { - var blockhash = opts.blockhash, - lastValidBlockHeight = opts.lastValidBlockHeight; - this.recentBlockhash = blockhash; - this.lastValidBlockHeight = lastValidBlockHeight; - } else { - var recentBlockhash = opts.recentBlockhash, - _nonceInfo = opts.nonceInfo; + }, { + key: "createNonceAccount", + value: function createNonceAccount(params) { + var transaction = new Transaction(); - if (_nonceInfo) { - this.nonceInfo = _nonceInfo; + if ('basePubkey' in params && 'seed' in params) { + transaction.add(SystemProgram.createAccountWithSeed({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.noncePubkey, + basePubkey: params.basePubkey, + seed: params.seed, + lamports: params.lamports, + space: NONCE_ACCOUNT_LENGTH, + programId: this.programId + })); + } else { + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.noncePubkey, + lamports: params.lamports, + space: NONCE_ACCOUNT_LENGTH, + programId: this.programId + })); } - this.recentBlockhash = recentBlockhash; + var initParams = { + noncePubkey: params.noncePubkey, + authorizedPubkey: params.authorizedPubkey + }; + transaction.add(this.nonceInitialize(initParams)); + return transaction; } - } - /** - * @internal - */ - - - _createClass(Transaction, [{ - key: "signature", - get: /** - * Signatures for the transaction. Typically created by invoking the - * `sign()` method + * Generate an instruction to initialize a Nonce account */ + }, { + key: "nonceInitialize", + value: function nonceInitialize(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount; + var data = encodeData(type, { + authorized: toBuffer(params.authorizedPubkey.toBuffer()) + }); + var instructionData = { + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); + } /** - * The first (payer) Transaction signature + * Generate an instruction to advance the nonce in a Nonce account */ - function get() { - if (this.signatures.length > 0) { - return this.signatures[0].signature; - } - return null; - } }, { - key: "toJSON", - value: function toJSON() { - return { - recentBlockhash: this.recentBlockhash || null, - feePayer: this.feePayer ? this.feePayer.toJSON() : null, - nonceInfo: this.nonceInfo ? { - nonce: this.nonceInfo.nonce, - nonceInstruction: this.nonceInfo.nonceInstruction.toJSON() - } : null, - instructions: this.instructions.map(function (instruction) { - return instruction.toJSON(); - }), - signers: this.signatures.map(function (_ref18) { - var publicKey = _ref18.publicKey; - return publicKey.toJSON(); - }) + key: "nonceAdvance", + value: function nonceAdvance(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount; + var data = encodeData(type); + var instructionData = { + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data }; + return new TransactionInstruction(instructionData); } /** - * Add one or more instructions to this Transaction + * Generate a transaction instruction that withdraws lamports from a Nonce account */ }, { - key: "add", - value: function add() { - var _this9 = this; + key: "nonceWithdraw", + value: function nonceWithdraw(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount; + var data = encodeData(type, { + lamports: params.lamports + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that authorizes a new PublicKey as the authority + * on a Nonce account. + */ - for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) { - items[_key] = arguments[_key]; - } + }, { + key: "nonceAuthorize", + value: function nonceAuthorize(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount; + var data = encodeData(type, { + authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()) + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that allocates space in an account without funding + */ - if (items.length === 0) { - throw new Error('No instructions'); + }, { + key: "allocate", + value: function allocate(params) { + var data; + var keys; + + if ('basePubkey' in params) { + var _type5 = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed; + data = encodeData(_type5, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }]; + } else { + var _type6 = SYSTEM_INSTRUCTION_LAYOUTS.Allocate; + data = encodeData(_type6, { + space: params.space + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: true, + isWritable: true + }]; } - items.forEach(function (item) { - if ('instructions' in item) { - _this9.instructions = _this9.instructions.concat(item.instructions); - } else if ('data' in item && 'programId' in item && 'keys' in item) { - _this9.instructions.push(item); - } else { - _this9.instructions.push(new TransactionInstruction(item)); - } + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data }); - return this; + } + }]); + + return SystemProgram; +}(); + +SystemProgram.programId = new PublicKey('11111111111111111111111111111111'); // Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the +// rest of the Transaction fields +// +// TODO: replace 300 with a proper constant for the size of the other +// Transaction fields + +var CHUNK_SIZE = PACKET_DATA_SIZE - 300; +/** + * Program loader interface + */ + +var Loader = /*#__PURE__*/function () { + /** + * @internal + */ + function Loader() { + _classCallCheck(this, Loader); + } + /** + * Amount of program data placed in each load Transaction + */ + + /** + * Minimum number of signatures required to load a program not including + * retries + * + * Can be used to calculate transaction fees + */ + + + _createClass(Loader, null, [{ + key: "getMinNumSignatures", + value: function getMinNumSignatures(dataLength) { + return 2 * ( // Every transaction requires two signatures (payer + program) + Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction + 1) // Add one for Finalize transaction + ; } /** - * Compile transaction data + * Loads a generic program + * + * @param connection The connection to use + * @param payer System account that pays to load the program + * @param program Account to load the program into + * @param programId Public key that identifies the loader + * @param data Program octets + * @return true if program was loaded successfully, false if program was already loaded */ }, { - key: "compileMessage", - value: function compileMessage() { - if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) { - return this._message; - } + key: "load", + value: function () { + var _load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(connection, payer, program, programId, data) { + var balanceNeeded, programInfo, transaction, dataLayout, chunkSize, offset, array, transactions, bytes, _data, _transaction, REQUESTS_PER_SECOND, _dataLayout, _data2, _transaction2; - var recentBlockhash; - var instructions; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return connection.getMinimumBalanceForRentExemption(data.length); - if (this.nonceInfo) { - recentBlockhash = this.nonceInfo.nonce; + case 2: + balanceNeeded = _context5.sent; + _context5.next = 5; + return connection.getAccountInfo(program.publicKey, 'confirmed'); - if (this.instructions[0] != this.nonceInfo.nonceInstruction) { - instructions = [this.nonceInfo.nonceInstruction].concat(_toConsumableArray(this.instructions)); - } else { - instructions = this.instructions; - } - } else { - recentBlockhash = this.recentBlockhash; - instructions = this.instructions; - } + case 5: + programInfo = _context5.sent; + transaction = null; - if (!recentBlockhash) { - throw new Error('Transaction recentBlockhash required'); - } + if (!(programInfo !== null)) { + _context5.next = 16; + break; + } - if (instructions.length < 1) { - console.warn('No instructions provided'); - } + if (!programInfo.executable) { + _context5.next = 11; + break; + } - var feePayer; + console.error('Program load failed, account is already executable'); + return _context5.abrupt("return", false); - if (this.feePayer) { - feePayer = this.feePayer; - } else if (this.signatures.length > 0 && this.signatures[0].publicKey) { - // Use implicit fee payer - feePayer = this.signatures[0].publicKey; - } else { - throw new Error('Transaction fee payer required'); - } + case 11: + if (programInfo.data.length !== data.length) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.allocate({ + accountPubkey: program.publicKey, + space: data.length + })); + } - for (var i = 0; i < instructions.length; i++) { - if (instructions[i].programId === undefined) { - throw new Error("Transaction instruction index ".concat(i, " has undefined program id")); - } - } + if (!programInfo.owner.equals(programId)) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.assign({ + accountPubkey: program.publicKey, + programId: programId + })); + } - var programIds = []; - var accountMetas = []; - instructions.forEach(function (instruction) { - instruction.keys.forEach(function (accountMeta) { - accountMetas.push(_objectSpread2({}, accountMeta)); - }); - var programId = instruction.programId.toString(); + if (programInfo.lamports < balanceNeeded) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: program.publicKey, + lamports: balanceNeeded - programInfo.lamports + })); + } - if (!programIds.includes(programId)) { - programIds.push(programId); - } - }); // Append programID account metas + _context5.next = 17; + break; - programIds.forEach(function (programId) { - accountMetas.push({ - pubkey: new PublicKey(programId), - isSigner: false, - isWritable: false - }); - }); // Cull duplicate account metas + case 16: + transaction = new Transaction().add(SystemProgram.createAccount({ + fromPubkey: payer.publicKey, + newAccountPubkey: program.publicKey, + lamports: balanceNeeded > 0 ? balanceNeeded : 1, + space: data.length, + programId: programId + })); - var uniqueMetas = []; - accountMetas.forEach(function (accountMeta) { - var pubkeyString = accountMeta.pubkey.toString(); - var uniqueIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.toString() === pubkeyString; - }); + case 17: + if (!(transaction !== null)) { + _context5.next = 20; + break; + } - if (uniqueIndex > -1) { - uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable; - uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner; - } else { - uniqueMetas.push(accountMeta); - } - }); // Sort. Prioritizing first by signer, then by writable + _context5.next = 20; + return sendAndConfirmTransaction(connection, transaction, [payer, program], { + commitment: 'confirmed' + }); - uniqueMetas.sort(function (x, y) { - if (x.isSigner !== y.isSigner) { - // Signers always come before non-signers - return x.isSigner ? -1 : 1; - } + case 20: + dataLayout = struct([u32('instruction'), u32('offset'), u32('bytesLength'), u32('bytesLengthPadding'), seq$1(u8('byte'), offset$1(u32(), -8), 'bytes')]); + chunkSize = Loader.chunkSize; + offset = 0; + array = data; + transactions = []; - if (x.isWritable !== y.isWritable) { - // Writable accounts always come before read-only accounts - return x.isWritable ? -1 : 1; - } // Otherwise, sort by pubkey, stringwise. + case 25: + if (!(array.length > 0)) { + _context5.next = 39; + break; + } + bytes = array.slice(0, chunkSize); + _data = Buffer$1.alloc(chunkSize + 16); + dataLayout.encode({ + instruction: 0, + // Load instruction + offset: offset, + bytes: bytes, + bytesLength: 0, + bytesLengthPadding: 0 + }, _data); + _transaction = new Transaction().add({ + keys: [{ + pubkey: program.publicKey, + isSigner: true, + isWritable: true + }], + programId: programId, + data: _data + }); + transactions.push(sendAndConfirmTransaction(connection, _transaction, [payer, program], { + commitment: 'confirmed' + })); // Delay between sends in an attempt to reduce rate limit errors - return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58()); - }); // Move fee payer to the front + if (!connection._rpcEndpoint.includes('solana.com')) { + _context5.next = 35; + break; + } - var feePayerIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.equals(feePayer); - }); + REQUESTS_PER_SECOND = 4; + _context5.next = 35; + return sleep(1000 / REQUESTS_PER_SECOND); - if (feePayerIndex > -1) { - var _uniqueMetas$splice3 = uniqueMetas.splice(feePayerIndex, 1), - _uniqueMetas$splice4 = _slicedToArray(_uniqueMetas$splice3, 1), - payerMeta = _uniqueMetas$splice4[0]; + case 35: + offset += chunkSize; + array = array.slice(chunkSize); + _context5.next = 25; + break; - payerMeta.isSigner = true; - payerMeta.isWritable = true; - uniqueMetas.unshift(payerMeta); - } else { - uniqueMetas.unshift({ - pubkey: feePayer, - isSigner: true, - isWritable: true - }); - } // Disallow unknown signers + case 39: + _context5.next = 41; + return Promise.all(transactions); + case 41: + _dataLayout = struct([u32('instruction')]); + _data2 = Buffer$1.alloc(_dataLayout.span); - var _iterator12 = _createForOfIteratorHelper(this.signatures), - _step12; + _dataLayout.encode({ + instruction: 1 // Finalize instruction - try { - var _loop3 = function _loop3() { - var signature = _step12.value; - var uniqueIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.equals(signature.publicKey); - }); + }, _data2); - if (uniqueIndex > -1) { - if (!uniqueMetas[uniqueIndex].isSigner) { - uniqueMetas[uniqueIndex].isSigner = true; - console.warn('Transaction references a signature that is unnecessary, ' + 'only the fee payer and instruction signer accounts should sign a transaction. ' + 'This behavior is deprecated and will throw an error in the next major version release.'); - } - } else { - throw new Error("unknown signer: ".concat(signature.publicKey.toString())); + _transaction2 = new Transaction().add({ + keys: [{ + pubkey: program.publicKey, + isSigner: true, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: programId, + data: _data2 + }); + _context5.next = 47; + return sendAndConfirmTransaction(connection, _transaction2, [payer, program], { + commitment: 'confirmed' + }); + + case 47: + return _context5.abrupt("return", true); + + case 48: + case "end": + return _context5.stop(); } - }; + }, _callee5); + })); - for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { - _loop3(); - } - } catch (err) { - _iterator12.e(err); - } finally { - _iterator12.f(); + function load(_x13, _x14, _x15, _x16, _x17) { + return _load.apply(this, arguments); } - var numRequiredSignatures = 0; - var numReadonlySignedAccounts = 0; - var numReadonlyUnsignedAccounts = 0; // Split out signing from non-signing keys and count header values + return load; + }() + }]); - var signedKeys = []; - var unsignedKeys = []; - uniqueMetas.forEach(function (_ref19) { - var pubkey = _ref19.pubkey, - isSigner = _ref19.isSigner, - isWritable = _ref19.isWritable; + return Loader; +}(); - if (isSigner) { - signedKeys.push(pubkey.toString()); - numRequiredSignatures += 1; +Loader.chunkSize = CHUNK_SIZE; +var BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111'); +/** + * Factory class for transactions to interact with a program loader + */ - if (!isWritable) { - numReadonlySignedAccounts += 1; - } - } else { - unsignedKeys.push(pubkey.toString()); +var BpfLoader = /*#__PURE__*/function () { + function BpfLoader() { + _classCallCheck(this, BpfLoader); + } - if (!isWritable) { - numReadonlyUnsignedAccounts += 1; - } - } - }); - var accountKeys = signedKeys.concat(unsignedKeys); - var compiledInstructions = instructions.map(function (instruction) { - var data = instruction.data, - programId = instruction.programId; - return { - programIdIndex: accountKeys.indexOf(programId.toString()), - accounts: instruction.keys.map(function (meta) { - return accountKeys.indexOf(meta.pubkey.toString()); - }), - data: bs58$1.encode(data) - }; - }); - compiledInstructions.forEach(function (instruction) { - assert(instruction.programIdIndex >= 0); - instruction.accounts.forEach(function (keyIndex) { - return assert(keyIndex >= 0); - }); - }); - return new Message({ - header: { - numRequiredSignatures: numRequiredSignatures, - numReadonlySignedAccounts: numReadonlySignedAccounts, - numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts - }, - accountKeys: accountKeys, - recentBlockhash: recentBlockhash, - instructions: compiledInstructions - }); - } + _createClass(BpfLoader, null, [{ + key: "getMinNumSignatures", + value: /** - * @internal + * Minimum number of signatures required to load a program not including + * retries + * + * Can be used to calculate transaction fees */ - - }, { - key: "_compile", - value: function _compile() { - var message = this.compileMessage(); - var signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures); - - if (this.signatures.length === signedKeys.length) { - var valid = this.signatures.every(function (pair, index) { - return signedKeys[index].equals(pair.publicKey); - }); - if (valid) return message; - } - - this.signatures = signedKeys.map(function (publicKey) { - return { - signature: null, - publicKey: publicKey - }; - }); - return message; + function getMinNumSignatures(dataLength) { + return Loader.getMinNumSignatures(dataLength); } /** - * Get a buffer of the Transaction data that need to be covered by signatures + * Load a SBF program + * + * @param connection The connection to use + * @param payer Account that will pay program loading fees + * @param program Account to load the program into + * @param elf The entire ELF containing the SBF program + * @param loaderProgramId The program id of the BPF loader to use + * @return true if program was loaded successfully, false if program was already loaded */ }, { - key: "serializeMessage", - value: function serializeMessage() { - return this._compile().serialize(); + key: "load", + value: function load(connection, payer, program, elf, loaderProgramId) { + return Loader.load(connection, payer, program, loaderProgramId, elf); } - /** - * Get the estimated fee associated with a transaction - */ + }]); - }, { - key: "getEstimatedFee", - value: function () { - var _getEstimatedFee = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(connection) { - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return connection.getFeeForMessage(this.compileMessage()); + return BpfLoader; +}(); - case 2: - return _context4.abrupt("return", _context4.sent.value); +var objToString = Object.prototype.toString; - case 3: - case "end": - return _context4.stop(); - } - }, _callee4, this); - })); +var objKeys = Object.keys || function (obj) { + var keys = []; - function getEstimatedFee(_x8) { - return _getEstimatedFee.apply(this, arguments); - } + for (var name in obj) { + keys.push(name); + } - return getEstimatedFee; - }() - /** - * Specify the public keys which will be used to sign the Transaction. - * The first signer will be used as the transaction fee payer account. - * - * Signatures can be added with either `partialSign` or `addSignature` - * - * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be - * specified and it can be set in the Transaction constructor or with the - * `feePayer` property. - */ + return keys; +}; - }, { - key: "setSigners", - value: function setSigners() { - for (var _len2 = arguments.length, signers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - signers[_key2] = arguments[_key2]; - } +function stringify(val, isArrayProp) { + var i, max, str, keys, key, propVal, toStr; - if (signers.length === 0) { - throw new Error('No signers'); - } + if (val === true) { + return "true"; + } - var seen = new Set(); - this.signatures = signers.filter(function (publicKey) { - var key = publicKey.toString(); + if (val === false) { + return "false"; + } - if (seen.has(key)) { - return false; - } else { - seen.add(key); - return true; - } - }).map(function (publicKey) { - return { - signature: null, - publicKey: publicKey - }; - }); - } - /** - * Sign the Transaction with the specified signers. Multiple signatures may - * be applied to a Transaction. The first signature is considered "primary" - * and is used identify and confirm transactions. - * - * If the Transaction `feePayer` is not set, the first signer will be used - * as the transaction fee payer account. - * - * Transaction fields should not be modified after the first call to `sign`, - * as doing so may invalidate the signature and cause the Transaction to be - * rejected. - * - * The Transaction must be assigned a valid `recentBlockhash` before invoking this method - */ + switch (_typeof$1(val)) { + case "object": + if (val === null) { + return null; + } else if (val.toJSON && typeof val.toJSON === "function") { + return stringify(val.toJSON(), isArrayProp); + } else { + toStr = objToString.call(val); - }, { - key: "sign", - value: function sign() { - for (var _len3 = arguments.length, signers = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - signers[_key3] = arguments[_key3]; - } + if (toStr === "[object Array]") { + str = '['; + max = val.length - 1; + + for (i = 0; i < max; i++) { + str += stringify(val[i], true) + ','; + } + + if (max > -1) { + str += stringify(val[i], true); + } + + return str + ']'; + } else if (toStr === "[object Object]") { + // only object is left + keys = objKeys(val).sort(); + max = keys.length; + str = ""; + i = 0; - if (signers.length === 0) { - throw new Error('No signers'); - } // Dedupe signers + while (i < max) { + key = keys[i]; + propVal = stringify(val[key], false); + if (propVal !== undefined) { + if (str) { + str += ','; + } - var seen = new Set(); - var uniqueSigners = []; + str += JSON.stringify(key) + ':' + propVal; + } - for (var _i7 = 0, _signers = signers; _i7 < _signers.length; _i7++) { - var signer = _signers[_i7]; - var key = signer.publicKey.toString(); + i++; + } - if (seen.has(key)) { - continue; + return '{' + str + '}'; } else { - seen.add(key); - uniqueSigners.push(signer); + return JSON.stringify(val); } } - this.signatures = uniqueSigners.map(function (signer) { - return { - signature: null, - publicKey: signer.publicKey - }; - }); + case "function": + case "undefined": + return isArrayProp ? null : undefined; - var message = this._compile(); + case "string": + return JSON.stringify(val); - this._partialSign.apply(this, [message].concat(uniqueSigners)); - } - /** - * Partially sign a transaction with the specified accounts. All accounts must - * correspond to either the fee payer or a signer account in the transaction - * instructions. - * - * All the caveats from the `sign` method apply to `partialSign` - */ + default: + return isFinite(val) ? val : null; + } +} - }, { - key: "partialSign", - value: function partialSign() { - for (var _len4 = arguments.length, signers = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - signers[_key4] = arguments[_key4]; - } +var fastStableStringify = function fastStableStringify(val) { + var returnVal = stringify(val, false); - if (signers.length === 0) { - throw new Error('No signers'); - } // Dedupe signers + if (returnVal !== undefined) { + return '' + returnVal; + } +}; +var fastStableStringify$1 = fastStableStringify; +var MINIMUM_SLOT_PER_EPOCH = 32; // Returns the number of trailing zeros in the binary representation of self. - var seen = new Set(); - var uniqueSigners = []; +function trailingZeros(n) { + var trailingZeros = 0; - for (var _i8 = 0, _signers2 = signers; _i8 < _signers2.length; _i8++) { - var signer = _signers2[_i8]; - var key = signer.publicKey.toString(); + while (n > 1) { + n /= 2; + trailingZeros++; + } - if (seen.has(key)) { - continue; - } else { - seen.add(key); - uniqueSigners.push(signer); - } - } + return trailingZeros; +} // Returns the smallest power of two greater than or equal to n - var message = this._compile(); - this._partialSign.apply(this, [message].concat(uniqueSigners)); - } - /** - * @internal - */ +function nextPowerOfTwo(n) { + if (n === 0) return 1; + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; + n |= n >> 32; + return n + 1; +} +/** + * Epoch schedule + * (see https://docs.solana.com/terminology#epoch) + * Can be retrieved with the {@link Connection.getEpochSchedule} method + */ - }, { - key: "_partialSign", - value: function _partialSign(message) { - var _this10 = this; - var signData = message.serialize(); +var EpochSchedule = /*#__PURE__*/function () { + /** The maximum number of slots in each epoch */ - for (var _len5 = arguments.length, signers = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - signers[_key5 - 1] = arguments[_key5]; - } + /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */ - signers.forEach(function (signer) { - var signature = _sign(signData, signer.secretKey); + /** Indicates whether epochs start short and grow */ - _this10._addSignature(signer.publicKey, toBuffer(signature)); - }); - } - /** - * Add an externally created signature to a transaction. The public key - * must correspond to either the fee payer or a signer account in the transaction - * instructions. - */ + /** The first epoch with `slotsPerEpoch` slots */ - }, { - key: "addSignature", - value: function addSignature(pubkey, signature) { - this._compile(); // Ensure signatures array is populated + /** The first slot of `firstNormalEpoch` */ + function EpochSchedule(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) { + _classCallCheck(this, EpochSchedule); + this.slotsPerEpoch = void 0; + this.leaderScheduleSlotOffset = void 0; + this.warmup = void 0; + this.firstNormalEpoch = void 0; + this.firstNormalSlot = void 0; + this.slotsPerEpoch = slotsPerEpoch; + this.leaderScheduleSlotOffset = leaderScheduleSlotOffset; + this.warmup = warmup; + this.firstNormalEpoch = firstNormalEpoch; + this.firstNormalSlot = firstNormalSlot; + } - this._addSignature(pubkey, signature); + _createClass(EpochSchedule, [{ + key: "getEpoch", + value: function getEpoch(slot) { + return this.getEpochAndSlotIndex(slot)[0]; } - /** - * @internal - */ - }, { - key: "_addSignature", - value: function _addSignature(pubkey, signature) { - assert(signature.length === 64); - var index = this.signatures.findIndex(function (sigpair) { - return pubkey.equals(sigpair.publicKey); - }); + key: "getEpochAndSlotIndex", + value: function getEpochAndSlotIndex(slot) { + if (slot < this.firstNormalSlot) { + var epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1; + var epochLen = this.getSlotsInEpoch(epoch); + var slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH); + return [epoch, slotIndex]; + } else { + var normalSlotIndex = slot - this.firstNormalSlot; + var normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch); - if (index < 0) { - throw new Error("unknown signer: ".concat(pubkey.toString())); - } + var _epoch = this.firstNormalEpoch + normalEpochIndex; - this.signatures[index].signature = Buffer$1.from(signature); - } - /** - * Verify signatures of a Transaction - * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one. - * If no boolean is provided, we expect a fully signed Transaction by default. - */ + var _slotIndex = normalSlotIndex % this.slotsPerEpoch; + return [_epoch, _slotIndex]; + } + } }, { - key: "verifySignatures", - value: function verifySignatures(requireAllSignatures) { - return this._verifySignatures(this.serializeMessage(), requireAllSignatures === undefined ? true : requireAllSignatures); + key: "getFirstSlotInEpoch", + value: function getFirstSlotInEpoch(epoch) { + if (epoch <= this.firstNormalEpoch) { + return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH; + } else { + return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot; + } } - /** - * @internal - */ - }, { - key: "_verifySignatures", - value: function _verifySignatures(signData, requireAllSignatures) { - var _iterator13 = _createForOfIteratorHelper(this.signatures), - _step13; - - try { - for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { - var _step13$value2 = _step13.value, - _signature = _step13$value2.signature, - _publicKey = _step13$value2.publicKey; - - if (_signature === null) { - if (requireAllSignatures) { - return false; - } - } else { - if (!verify(_signature, signData, _publicKey.toBytes())) { - return false; - } - } - } - } catch (err) { - _iterator13.e(err); - } finally { - _iterator13.f(); + key: "getLastSlotInEpoch", + value: function getLastSlotInEpoch(epoch) { + return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1; + } + }, { + key: "getSlotsInEpoch", + value: function getSlotsInEpoch(epoch) { + if (epoch < this.firstNormalEpoch) { + return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH)); + } else { + return this.slotsPerEpoch; } - - return true; } - /** - * Serialize the Transaction in the wire format. - */ + }]); - }, { - key: "serialize", - value: function serialize(config) { - var _Object$assign = Object.assign({ - requireAllSignatures: true, - verifySignatures: true - }, config), - requireAllSignatures = _Object$assign.requireAllSignatures, - verifySignatures = _Object$assign.verifySignatures; + return EpochSchedule; +}(); - var signData = this.serializeMessage(); +var SendTransactionError = /*#__PURE__*/function (_Error4) { + _inherits(SendTransactionError, _Error4); - if (verifySignatures && !this._verifySignatures(signData, requireAllSignatures)) { - throw new Error('Signature verification failed'); - } + var _super6 = _createSuper(SendTransactionError); - return this._serialize(signData); - } - /** - * @internal - */ + function SendTransactionError(message, logs) { + var _this12; - }, { - key: "_serialize", - value: function _serialize(signData) { - var signatures = this.signatures; - var signatureCount = []; - encodeLength(signatureCount, signatures.length); - var transactionLength = signatureCount.length + signatures.length * 64 + signData.length; - var wireTransaction = Buffer$1.alloc(transactionLength); - assert(signatures.length < 256); - Buffer$1.from(signatureCount).copy(wireTransaction, 0); - signatures.forEach(function (_ref20, index) { - var signature = _ref20.signature; + _classCallCheck(this, SendTransactionError); - if (signature !== null) { - assert(signature.length === 64, "signature has invalid length"); - Buffer$1.from(signature).copy(wireTransaction, signatureCount.length + index * 64); - } - }); - signData.copy(wireTransaction, signatureCount.length + signatures.length * 64); - assert(wireTransaction.length <= PACKET_DATA_SIZE, "Transaction too large: ".concat(wireTransaction.length, " > ").concat(PACKET_DATA_SIZE)); - return wireTransaction; - } - /** - * Deprecated method - * @internal - */ + _this12 = _super6.call(this, message); + _this12.logs = void 0; + _this12.logs = logs; + return _this12; + } - }, { - key: "keys", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].keys.map(function (keyObj) { - return keyObj.pubkey; - }); - } - /** - * Deprecated method - * @internal - */ + return _createClass(SendTransactionError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); // Keep in sync with client/src/rpc_custom_errors.rs +// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - }, { - key: "programId", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].programId; - } - /** - * Deprecated method - * @internal - */ - }, { - key: "data", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].data; - } - /** - * Parse a wire transaction into a Transaction object. - */ +var SolanaJSONRPCErrorCode = { + JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001, + JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002, + JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003, + JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004, + JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005, + JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006, + JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007, + JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008, + JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009, + JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010, + JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011, + JSON_RPC_SCAN_ERROR: -32012, + JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013, + JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014, + JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015, + JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016 +}; - }], [{ - key: "from", - value: function from(buffer) { - // Slice up wire data - var byteArray = _toConsumableArray(buffer); +var SolanaJSONRPCError = /*#__PURE__*/function (_Error5) { + _inherits(SolanaJSONRPCError, _Error5); - var signatureCount = decodeLength(byteArray); - var signatures = []; + var _super7 = _createSuper(SolanaJSONRPCError); - for (var i = 0; i < signatureCount; i++) { - var _signature2 = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES); + function SolanaJSONRPCError(_ref21, customMessage) { + var _this13; - byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES); - signatures.push(bs58$1.encode(Buffer$1.from(_signature2))); - } + var code = _ref21.code, + message = _ref21.message, + data = _ref21.data; - return Transaction.populate(Message.from(byteArray), signatures); - } - /** - * Populate Transaction object from message and signatures - */ + _classCallCheck(this, SolanaJSONRPCError); - }, { - key: "populate", - value: function populate(message) { - var signatures = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var transaction = new Transaction(); - transaction.recentBlockhash = message.recentBlockhash; + _this13 = _super7.call(this, customMessage != null ? "".concat(customMessage, ": ").concat(message) : message); + _this13.code = void 0; + _this13.data = void 0; + _this13.code = code; + _this13.data = data; + _this13.name = 'SolanaJSONRPCError'; + return _this13; + } - if (message.header.numRequiredSignatures > 0) { - transaction.feePayer = message.accountKeys[0]; - } + return _createClass(SolanaJSONRPCError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); - signatures.forEach(function (signature, index) { - var sigPubkeyPair = { - signature: signature == bs58$1.encode(DEFAULT_SIGNATURE) ? null : bs58$1.decode(signature), - publicKey: message.accountKeys[index] - }; - transaction.signatures.push(sigPubkeyPair); - }); - message.instructions.forEach(function (instruction) { - var keys = instruction.accounts.map(function (account) { - var pubkey = message.accountKeys[account]; - return { - pubkey: pubkey, - isSigner: transaction.signatures.some(function (keyObj) { - return keyObj.publicKey.toString() === pubkey.toString(); - }) || message.isAccountSigner(account), - isWritable: message.isAccountWritable(account) - }; - }); - transaction.instructions.push(new TransactionInstruction({ - keys: keys, - programId: message.accountKeys[instruction.programIdIndex], - data: bs58$1.decode(instruction.data) - })); - }); - transaction._message = message; - transaction._json = transaction.toJSON(); - return transaction; - } - }]); +var fetchImpl = globalThis.fetch; - return Transaction; -}(); +var RpcWebSocketClient = /*#__PURE__*/function (_RpcWebSocketCommonCl) { + _inherits(RpcWebSocketClient, _RpcWebSocketCommonCl); -var TransactionMessage = /*#__PURE__*/function () { - function TransactionMessage(args) { - _classCallCheck(this, TransactionMessage); + var _super8 = _createSuper(RpcWebSocketClient); - this.payerKey = void 0; - this.instructions = void 0; - this.recentBlockhash = void 0; - this.payerKey = args.payerKey; - this.instructions = args.instructions; - this.recentBlockhash = args.recentBlockhash; - } + function RpcWebSocketClient(address, options, generate_request_id) { + var _this14; - _createClass(TransactionMessage, [{ - key: "compileToLegacyMessage", - value: function compileToLegacyMessage() { - return Message.compile({ - payerKey: this.payerKey, - recentBlockhash: this.recentBlockhash, - instructions: this.instructions - }); - } - }, { - key: "compileToV0Message", - value: function compileToV0Message(addressLookupTableAccounts) { - return MessageV0.compile({ - payerKey: this.payerKey, - recentBlockhash: this.recentBlockhash, - instructions: this.instructions, - addressLookupTableAccounts: addressLookupTableAccounts - }); - } - }], [{ - key: "decompile", - value: function decompile(message, args) { - var header = message.header, - compiledInstructions = message.compiledInstructions, - recentBlockhash = message.recentBlockhash; - var numRequiredSignatures = header.numRequiredSignatures, - numReadonlySignedAccounts = header.numReadonlySignedAccounts, - numReadonlyUnsignedAccounts = header.numReadonlyUnsignedAccounts; - var numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts; - assert(numWritableSignedAccounts > 0, 'Message header is invalid'); - var numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts; - assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid'); - var accountKeys = message.getAccountKeys(args); - var payerKey = accountKeys.get(0); + _classCallCheck(this, RpcWebSocketClient); - if (payerKey === undefined) { - throw new Error('Failed to decompile message because no account keys were found'); - } + var webSocketFactory = function webSocketFactory(url) { + var rpc = createRpc(url, _objectSpread2({ + autoconnect: true, + max_reconnects: 5, + reconnect: true, + reconnect_interval: 1000 + }, options)); - var instructions = []; + if ('socket' in rpc) { + _this14.underlyingSocket = rpc.socket; + } else { + _this14.underlyingSocket = rpc; + } - var _iterator14 = _createForOfIteratorHelper(compiledInstructions), - _step14; + return rpc; + }; - try { - for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { - var compiledIx = _step14.value; - var keys = []; + _this14 = _super8.call(this, webSocketFactory, address, options, generate_request_id); + _this14.underlyingSocket = void 0; + return _this14; + } - var _iterator15 = _createForOfIteratorHelper(compiledIx.accountKeyIndexes), - _step15; + _createClass(RpcWebSocketClient, [{ + key: "call", + value: function call() { + var _this$underlyingSocke; - try { - for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { - var keyIndex = _step15.value; - var pubkey = accountKeys.get(keyIndex); + var readyState = (_this$underlyingSocke = this.underlyingSocket) === null || _this$underlyingSocke === void 0 ? void 0 : _this$underlyingSocke.readyState; - if (pubkey === undefined) { - throw new Error("Failed to find key for account key index ".concat(keyIndex)); - } + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } - var isSigner = keyIndex < numRequiredSignatures; - var isWritable = void 0; + if (readyState === 1 + /* WebSocket.OPEN */ + ) { + var _get2; - if (isSigner) { - isWritable = keyIndex < numWritableSignedAccounts; - } else if (keyIndex < accountKeys.staticAccountKeys.length) { - isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts; - } else { - isWritable = keyIndex - accountKeys.staticAccountKeys.length < // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above - accountKeys.accountKeysFromLookups.writable.length; - } + return (_get2 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "call", this)).call.apply(_get2, [this].concat(args)); + } - keys.push({ - pubkey: pubkey, - isSigner: keyIndex < header.numRequiredSignatures, - isWritable: isWritable - }); - } - } catch (err) { - _iterator15.e(err); - } finally { - _iterator15.f(); - } + return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); + } + }, { + key: "notify", + value: function notify() { + var _this$underlyingSocke2; - var programId = accountKeys.get(compiledIx.programIdIndex); + var readyState = (_this$underlyingSocke2 = this.underlyingSocket) === null || _this$underlyingSocke2 === void 0 ? void 0 : _this$underlyingSocke2.readyState; - if (programId === undefined) { - throw new Error("Failed to find program id for program id index ".concat(compiledIx.programIdIndex)); - } + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } - instructions.push(new TransactionInstruction({ - programId: programId, - data: toBuffer(compiledIx.data), - keys: keys - })); - } - } catch (err) { - _iterator14.e(err); - } finally { - _iterator14.f(); + if (readyState === 1 + /* WebSocket.OPEN */ + ) { + var _get3; + + return (_get3 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "notify", this)).call.apply(_get3, [this].concat(args)); } - return new TransactionMessage({ - payerKey: payerKey, - instructions: instructions, - recentBlockhash: recentBlockhash - }); + return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); } }]); - return TransactionMessage; -}(); + return RpcWebSocketClient; +}(RpcWebSocketCommonClient); // TODO: These constants should be removed in favor of reading them out of a +// Syscall account + /** - * Versioned transaction class + * @internal */ -var VersionedTransaction = /*#__PURE__*/function () { - function VersionedTransaction(message, signatures) { - _classCallCheck(this, VersionedTransaction); +var NUM_TICKS_PER_SECOND = 160; +/** + * @internal + */ - this.signatures = void 0; - this.message = void 0; +var DEFAULT_TICKS_PER_SLOT = 64; +/** + * @internal + */ - if (signatures !== undefined) { - assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures'); - this.signatures = signatures; - } else { - var defaultSignatures = []; +var NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT; +/** + * @internal + */ - for (var i = 0; i < message.header.numRequiredSignatures; i++) { - defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES)); - } +var MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND; +/** + * @internal + */ - this.signatures = defaultSignatures; - } +/** + * Decode account data buffer using an AccountType + * @internal + */ - this.message = message; +function decodeData(type, data) { + var decoded; + + try { + decoded = type.layout.decode(data); + } catch (err) { + throw new Error('invalid instruction; ' + err); } - _createClass(VersionedTransaction, [{ - key: "version", - get: function get() { - return this.message.version; - } - }, { - key: "serialize", - value: function serialize() { - var serializedMessage = this.message.serialize(); - var encodedSignaturesLength = Array(); - encodeLength(encodedSignaturesLength, this.signatures.length); - var transactionLayout = struct([blob$1(encodedSignaturesLength.length, 'encodedSignaturesLength'), seq$1(signature(), this.signatures.length, 'signatures'), blob$1(serializedMessage.length, 'serializedMessage')]); - var serializedTransaction = new Uint8Array(2048); - var serializedTransactionLength = transactionLayout.encode({ - encodedSignaturesLength: new Uint8Array(encodedSignaturesLength), - signatures: this.signatures, - serializedMessage: serializedMessage - }, serializedTransaction); - return serializedTransaction.slice(0, serializedTransactionLength); - } - }, { - key: "sign", - value: function sign(signers) { - var _this11 = this; + if (decoded.typeIndex !== type.index) { + throw new Error("invalid account data; account type mismatch ".concat(decoded.typeIndex, " != ").concat(type.index)); + } - var messageData = this.message.serialize(); - var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + return decoded; +} /// The serialized size of lookup table metadata - var _iterator16 = _createForOfIteratorHelper(signers), - _step16; - try { - var _loop4 = function _loop4() { - var signer = _step16.value; - var signerIndex = signerPubkeys.findIndex(function (pubkey) { - return pubkey.equals(signer.publicKey); - }); - assert(signerIndex >= 0, "Cannot sign with non signer key ".concat(signer.publicKey.toBase58())); - _this11.signatures[signerIndex] = _sign(messageData, signer.secretKey); - }; +var LOOKUP_TABLE_META_SIZE = 56; - for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { - _loop4(); - } - } catch (err) { - _iterator16.e(err); - } finally { - _iterator16.f(); - } - } - }, { - key: "addSignature", - value: function addSignature(publicKey, signature) { - assert(signature.byteLength === 64, 'Signature must be 64 bytes long'); - var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); - var signerIndex = signerPubkeys.findIndex(function (pubkey) { - return pubkey.equals(publicKey); - }); - assert(signerIndex >= 0, "Can not add signature; `".concat(publicKey.toBase58(), "` is not required to sign this transaction")); - this.signatures[signerIndex] = signature; +var AddressLookupTableAccount = /*#__PURE__*/function () { + function AddressLookupTableAccount(args) { + _classCallCheck(this, AddressLookupTableAccount); + + this.key = void 0; + this.state = void 0; + this.key = args.key; + this.state = args.state; + } + + _createClass(AddressLookupTableAccount, [{ + key: "isActive", + value: function isActive() { + var U64_MAX = BigInt('0xffffffffffffffff'); + return this.state.deactivationSlot === U64_MAX; } }], [{ key: "deserialize", - value: function deserialize(serializedTransaction) { - var byteArray = _toConsumableArray(serializedTransaction); - - var signatures = []; - var signaturesLength = decodeLength(byteArray); + value: function deserialize(accountData) { + var meta = decodeData(LookupTableMetaLayout, accountData); + var serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE; + assert(serializedAddressesLen >= 0, 'lookup table is invalid'); + assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid'); + var numSerializedAddresses = serializedAddressesLen / 32; - for (var i = 0; i < signaturesLength; i++) { - signatures.push(new Uint8Array(byteArray.splice(0, SIGNATURE_LENGTH_IN_BYTES))); - } + var _BufferLayout$struct$ = struct([seq$1(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE)), + addresses = _BufferLayout$struct$.addresses; - var message = VersionedMessage.deserialize(new Uint8Array(byteArray)); - return new VersionedTransaction(message, signatures); + return { + deactivationSlot: meta.deactivationSlot, + lastExtendedSlot: meta.lastExtendedSlot, + lastExtendedSlotStartIndex: meta.lastExtendedStartIndex, + authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined, + addresses: addresses.map(function (address) { + return new PublicKey(address); + }) + }; } }]); - return VersionedTransaction; + return AddressLookupTableAccount; }(); -var SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111'); -var SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111'); -var SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111'); -var SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111'); -var SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111'); -var SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111'); -var SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111'); -var SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111'); -var SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111'); -/** - * Sign, send and confirm a transaction. - * - * If `commitment` option is not specified, defaults to 'max' commitment. - * - * @param {Connection} connection - * @param {Transaction} transaction - * @param {Array} signers - * @param {ConfirmOptions} [options] - * @returns {Promise} - */ - -function sendAndConfirmTransaction(_x9, _x10, _x11, _x12) { - return _sendAndConfirmTransaction.apply(this, arguments); -} // zzz +var LookupTableMetaLayout = { + index: 1, + layout: struct([u32('typeIndex'), u64('deactivationSlot'), nu64$1('lastExtendedSlot'), u8('lastExtendedStartIndex'), u8(), // option + seq$1(publicKey(), offset$1(u8(), -1), 'authority')]) +}; +var URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i; +function makeWebsocketUrl(endpoint) { + var matches = endpoint.match(URL_RE); -function _sendAndConfirmTransaction() { - _sendAndConfirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee108(connection, transaction, signers, options) { - var sendOptions, signature, status, nonceInstruction, nonceAccountPubkey; - return _regeneratorRuntime().wrap(function _callee108$(_context108) { - while (1) switch (_context108.prev = _context108.next) { - case 0: - sendOptions = options && { - skipPreflight: options.skipPreflight, - preflightCommitment: options.preflightCommitment || options.commitment, - maxRetries: options.maxRetries, - minContextSlot: options.minContextSlot - }; - _context108.next = 3; - return connection.sendTransaction(transaction, signers, sendOptions); + if (matches == null) { + throw TypeError("Failed to validate endpoint URL `".concat(endpoint, "`")); + } - case 3: - signature = _context108.sent; + var _matches = _slicedToArray(matches, 4); + _matches[0]; + var // eslint-disable-line @typescript-eslint/no-unused-vars + hostish = _matches[1], + portWithColon = _matches[2], + rest = _matches[3]; - if (!(transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null)) { - _context108.next = 10; - break; - } + var protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:'; + var startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10); + var websocketPort = // Only shift the port by +1 as a convention for ws(s) only if given endpoint + // is explictly specifying the endpoint port (HTTP-based RPC), assuming + // we're directly trying to connect to solana-validator's ws listening port. + // When the endpoint omits the port, we're connecting to the protocol + // default ports: http(80) or https(443) and it's assumed we're behind a reverse + // proxy which manages WebSocket upgrade and backend port redirection. + startPort == null ? '' : ":".concat(startPort + 1); + return "".concat(protocol, "//").concat(hostish).concat(websocketPort).concat(rest); +} - _context108.next = 7; - return connection.confirmTransaction({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - signature: signature, - blockhash: transaction.recentBlockhash, - lastValidBlockHeight: transaction.lastValidBlockHeight - }, options && options.commitment); +var PublicKeyFromString = coerce(instance(PublicKey), string(), function (value) { + return new PublicKey(value); +}); +var RawAccountDataResult = tuple([string(), literal('base64')]); +var BufferFromRawAccountData = coerce(instance(Buffer$1), RawAccountDataResult, function (value) { + return Buffer$1.from(value[0], 'base64'); +}); +/** + * Attempt to use a recent blockhash for up to 30 seconds + * @internal + */ - case 7: - status = _context108.sent.value; - _context108.next = 22; - break; +var BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; +/** + * HACK. + * Copied from rpc-websockets/dist/lib/client. + * Otherwise, `yarn build` fails with: + * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d + */ - case 10: - if (!(transaction.minNonceContextSlot != null && transaction.nonceInfo != null)) { - _context108.next = 18; - break; - } +/* @internal */ - nonceInstruction = transaction.nonceInfo.nonceInstruction; - nonceAccountPubkey = nonceInstruction.keys[0].pubkey; - _context108.next = 15; - return connection.confirmTransaction({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - minContextSlot: transaction.minNonceContextSlot, - nonceAccountPubkey: nonceAccountPubkey, - nonceValue: transaction.nonceInfo.nonce, - signature: signature - }, options && options.commitment); +function assertEndpointUrl(putativeUrl) { + if (/^https?:/.test(putativeUrl) === false) { + throw new TypeError('Endpoint URL must start with `http:` or `https:`.'); + } - case 15: - status = _context108.sent.value; - _context108.next = 22; - break; + return putativeUrl; +} +/** @internal */ - case 18: - if ((options === null || options === void 0 ? void 0 : options.abortSignal) != null) { - console.warn('sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' + 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' + 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.'); - } - _context108.next = 21; - return connection.confirmTransaction(signature, options && options.commitment); +function extractCommitmentFromConfig(commitmentOrConfig) { + var commitment; + var config; - case 21: - status = _context108.sent.value; + if (typeof commitmentOrConfig === 'string') { + commitment = commitmentOrConfig; + } else if (commitmentOrConfig) { + var specifiedCommitment = commitmentOrConfig.commitment, + specifiedConfig = _objectWithoutProperties(commitmentOrConfig, _excluded); - case 22: - if (!status.err) { - _context108.next = 24; - break; - } + commitment = specifiedCommitment; + config = specifiedConfig; + } - throw new Error("Transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + return { + commitment: commitment, + config: config + }; +} +/** + * @internal + */ - case 24: - return _context108.abrupt("return", signature); - case 25: - case "end": - return _context108.stop(); - } - }, _callee108); - })); - return _sendAndConfirmTransaction.apply(this, arguments); +function createRpcResult(result) { + return union([type({ + jsonrpc: literal('2.0'), + id: string(), + result: result + }), type({ + jsonrpc: literal('2.0'), + id: string(), + error: type({ + code: unknown(), + message: string(), + data: optional(any()) + }) + })]); } -function sleep(ms) { - return new Promise(function (resolve) { - return setTimeout(resolve, ms); +var UnknownRpcResult = createRpcResult(unknown()); +/** + * @internal + */ + +function jsonRpcResult(schema) { + return coerce(createRpcResult(schema), UnknownRpcResult, function (value) { + if ('error' in value) { + return value; + } else { + return _objectSpread2(_objectSpread2({}, value), {}, { + result: _create(value.result, schema) + }); + } }); } /** - * Populate a buffer of instruction data using an InstructionType * @internal */ -function encodeData(type, fields) { - var allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields); - var data = Buffer$1.alloc(allocLength); - var layoutFields = Object.assign({ - instruction: type.index - }, fields); - type.layout.encode(layoutFields, data); - return data; +function jsonRpcResultAndContext(value) { + return jsonRpcResult(type({ + context: type({ + slot: number() + }), + value: value + })); } /** - * Decode instruction data buffer using an InstructionType * @internal */ -function decodeData$1(type, buffer) { - var data; +function notificationResultAndContext(value) { + return type({ + context: type({ + slot: number() + }), + value: value + }); +} +/** + * @internal + */ - try { - data = type.layout.decode(buffer); - } catch (err) { - throw new Error('invalid instruction; ' + err); - } - if (data.instruction !== type.index) { - throw new Error("invalid instruction; instruction index mismatch ".concat(data.instruction, " != ").concat(type.index)); +function versionedMessageFromResponse(version, response) { + if (version === 0) { + return new MessageV0({ + header: response.header, + staticAccountKeys: response.accountKeys.map(function (accountKey) { + return new PublicKey(accountKey); + }), + recentBlockhash: response.recentBlockhash, + compiledInstructions: response.instructions.map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accounts, + data: bs58$3.decode(ix.data) + }; + }), + addressTableLookups: response.addressTableLookups + }); + } else { + return new Message(response); } - - return data; } /** - * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11 - * - * @internal + * The level of commitment desired when querying state + *
+ *   'processed': Query the most recent block which has reached 1 confirmation by the connected node
+ *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
+ *   'finalized': Query the most recent block which has been finalized by the cluster
+ * 
+ */ + + +var GetInflationGovernorResult = type({ + foundation: number(), + foundationTerm: number(), + initial: number(), + taper: number(), + terminal: number() +}); +/** + * The inflation reward for an epoch */ - -var FeeCalculatorLayout = nu64$1('lamportsPerSignature'); /** - * Calculator for transaction fees. - * - * @deprecated Deprecated since Solana v1.8.0. + * Expected JSON RPC response for the "getInflationReward" message */ +var GetInflationRewardResult = jsonRpcResult(array(nullable(type({ + epoch: number(), + effectiveSlot: number(), + amount: number(), + postBalance: number(), + commission: optional(nullable(number())) +})))); /** - * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32 - * - * @internal + * Expected JSON RPC response for the "getRecentPrioritizationFees" message */ -var NonceAccountLayout = struct([u32('version'), u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), struct([FeeCalculatorLayout], 'feeCalculator')]); -var NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span; +var GetRecentPrioritizationFeesResult = array(type({ + slot: number(), + prioritizationFee: number() +})); /** - * A durable nonce is a 32 byte value encoded as a base58 string. + * Expected JSON RPC response for the "getInflationRate" message */ +var GetInflationRateResult = type({ + total: number(), + validator: number(), + foundation: number(), + epoch: number() +}); /** - * NonceAccount class + * Information about the current epoch */ -var NonceAccount = /*#__PURE__*/function () { - /** - * @internal - */ - function NonceAccount(args) { - _classCallCheck(this, NonceAccount); - - this.authorizedPubkey = void 0; - this.nonce = void 0; - this.feeCalculator = void 0; - this.authorizedPubkey = args.authorizedPubkey; - this.nonce = args.nonce; - this.feeCalculator = args.feeCalculator; - } - /** - * Deserialize NonceAccount from the account data. - * - * @param buffer account data - * @return NonceAccount - */ - - - _createClass(NonceAccount, null, [{ - key: "fromAccountData", - value: function fromAccountData(buffer) { - var nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0); - return new NonceAccount({ - authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey), - nonce: new PublicKey(nonceAccount.nonce).toString(), - feeCalculator: nonceAccount.feeCalculator - }); - } - }]); - - return NonceAccount; -}(); - -var encodeDecode = function encodeDecode(layout) { - var decode = layout.decode.bind(layout); - var encode = layout.encode.bind(layout); - return { - decode: decode, - encode: encode - }; -}; - -var bigInt = function bigInt(length) { - return function (property) { - var layout = blob$1(length, property); - - var _encodeDecode = encodeDecode(layout), - encode = _encodeDecode.encode, - decode = _encodeDecode.decode; - - var bigIntLayout = layout; - - bigIntLayout.decode = function (buffer, offset) { - var src = decode(buffer, offset); - return toBigIntLE_1(Buffer$1.from(src)); - }; - - bigIntLayout.encode = function (bigInt, buffer, offset) { - var src = toBufferLE_1(bigInt, length); - return encode(src, buffer, offset); - }; - - return bigIntLayout; - }; -}; - -var u64 = bigInt(8); +var GetEpochInfoResult = type({ + epoch: number(), + slotIndex: number(), + slotsInEpoch: number(), + absoluteSlot: number(), + blockHeight: optional(number()), + transactionCount: optional(number()) +}); +var GetEpochScheduleResult = type({ + slotsPerEpoch: number(), + leaderScheduleSlotOffset: number(), + warmup: _boolean(), + firstNormalEpoch: number(), + firstNormalSlot: number() +}); /** - * Create account system transaction params + * Leader schedule + * (see https://docs.solana.com/terminology#leader-schedule) */ +var GetLeaderScheduleResult = record(string(), array(number())); /** - * System Instruction class + * Transaction error or null */ -var SystemInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function SystemInstruction() { - _classCallCheck(this, SystemInstruction); - } - /** - * Decode a system instruction and retrieve the instruction type. - */ - - - _createClass(SystemInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; - - for (var _i9 = 0, _Object$entries = Object.entries(SYSTEM_INSTRUCTION_LAYOUTS); _i9 < _Object$entries.length; _i9++) { - var _Object$entries$_i2 = _slicedToArray(_Object$entries[_i9], 2), - ixType = _Object$entries$_i2[0], - layout = _Object$entries$_i2[1]; - - if (layout.index == typeIndex) { - type = ixType; - break; - } - } +var TransactionErrorResult = nullable(union([type({}), string()])); +/** + * Signature status for a transaction + */ - if (!type) { - throw new Error('Instruction type incorrect; not a SystemInstruction'); - } +var SignatureStatusResult = type({ + err: TransactionErrorResult +}); +/** + * Transaction signature received notification + */ - return type; - } - /** - * Decode a create account system instruction and retrieve the instruction params. - */ +var SignatureReceivedResult = literal('receivedSignature'); +/** + * Version info for a node + */ - }, { - key: "decodeCreateAccount", - value: function decodeCreateAccount(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); +var VersionResult = type({ + 'solana-core': string(), + 'feature-set': optional(number()) +}); +var SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({ + err: nullable(union([type({}), string()])), + logs: nullable(array(string())), + accounts: optional(nullable(array(nullable(type({ + executable: _boolean(), + owner: string(), + lamports: number(), + data: array(string()), + rentEpoch: optional(number()) + }))))), + unitsConsumed: optional(number()), + returnData: optional(nullable(type({ + programId: string(), + data: tuple([string(), literal('base64')]) + }))) +})); +/** + * Expected JSON RPC response for the "getBlockProduction" message + */ - var _decodeData$ = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data), - lamports = _decodeData$.lamports, - space = _decodeData$.space, - programId = _decodeData$.programId; +var BlockProductionResponseStruct = jsonRpcResultAndContext(type({ + byIdentity: record(string(), array(number())), + range: type({ + firstSlot: number(), + lastSlot: number() + }) +})); +/** + * A performance sample + */ - return { - fromPubkey: instruction.keys[0].pubkey, - newAccountPubkey: instruction.keys[1].pubkey, - lamports: lamports, - space: space, - programId: new PublicKey(programId) - }; +function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) { + var fetch = customFetch ? customFetch : fetchImpl; + var agent; + { + if (httpAgent != null) { + console.warn('You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' + 'It has been ignored; `httpAgent` is only used in Node environments.'); } - /** - * Decode a transfer system instruction and retrieve the instruction params. - */ - - }, { - key: "decodeTransfer", - value: function decodeTransfer(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + } + var fetchWithMiddleware; - var _decodeData$2 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data), - lamports = _decodeData$2.lamports; + if (fetchMiddleware) { + fetchWithMiddleware = /*#__PURE__*/function () { + var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(info, init) { + var modifiedFetchArgs; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return new Promise(function (resolve, reject) { + try { + fetchMiddleware(info, init, function (modifiedInfo, modifiedInit) { + return resolve([modifiedInfo, modifiedInit]); + }); + } catch (error) { + reject(error); + } + }); - return { - fromPubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - lamports: lamports - }; - } - /** - * Decode a transfer with seed system instruction and retrieve the instruction params. - */ + case 2: + modifiedFetchArgs = _context6.sent; + _context6.next = 5; + return fetch.apply(void 0, _toConsumableArray(modifiedFetchArgs)); - }, { - key: "decodeTransferWithSeed", - value: function decodeTransferWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 5: + return _context6.abrupt("return", _context6.sent); - var _decodeData$3 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data), - lamports = _decodeData$3.lamports, - seed = _decodeData$3.seed, - programId = _decodeData$3.programId; + case 6: + case "end": + return _context6.stop(); + } + }, _callee6); + })); - return { - fromPubkey: instruction.keys[0].pubkey, - basePubkey: instruction.keys[1].pubkey, - toPubkey: instruction.keys[2].pubkey, - lamports: lamports, - seed: seed, - programId: new PublicKey(programId) + return function fetchWithMiddleware(_x18, _x19) { + return _ref22.apply(this, arguments); }; - } - /** - * Decode an allocate system instruction and retrieve the instruction params. - */ - - }, { - key: "decodeAllocate", - value: function decodeAllocate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + }(); + } - var _decodeData$4 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data), - space = _decodeData$4.space; + var clientBrowser = new RpcClient( /*#__PURE__*/function () { + var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(request, callback) { + var options, too_many_requests_retries, res, waitTime, text; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + options = { + method: 'POST', + body: request, + agent: agent, + headers: Object.assign({ + 'Content-Type': 'application/json' + }, httpHeaders || {}, COMMON_HTTP_HEADERS) + }; + _context7.prev = 1; + too_many_requests_retries = 5; + waitTime = 500; - return { - accountPubkey: instruction.keys[0].pubkey, - space: space - }; - } - /** - * Decode an allocate with seed system instruction and retrieve the instruction params. - */ + case 4: + if (!fetchWithMiddleware) { + _context7.next = 10; + break; + } - }, { - key: "decodeAllocateWithSeed", - value: function decodeAllocateWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + _context7.next = 7; + return fetchWithMiddleware(url, options); - var _decodeData$5 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data), - base = _decodeData$5.base, - seed = _decodeData$5.seed, - space = _decodeData$5.space, - programId = _decodeData$5.programId; + case 7: + res = _context7.sent; + _context7.next = 13; + break; - return { - accountPubkey: instruction.keys[0].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - space: space, - programId: new PublicKey(programId) - }; - } - /** - * Decode an assign system instruction and retrieve the instruction params. - */ + case 10: + _context7.next = 12; + return fetch(url, options); - }, { - key: "decodeAssign", - value: function decodeAssign(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + case 12: + res = _context7.sent; - var _decodeData$6 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data), - programId = _decodeData$6.programId; + case 13: + if (!(res.status !== 429 + /* Too many requests */ + )) { + _context7.next = 15; + break; + } - return { - accountPubkey: instruction.keys[0].pubkey, - programId: new PublicKey(programId) - }; - } - /** - * Decode an assign with seed system instruction and retrieve the instruction params. - */ + return _context7.abrupt("break", 26); - }, { - key: "decodeAssignWithSeed", - value: function decodeAssignWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + case 15: + if (!(disableRetryOnRateLimit === true)) { + _context7.next = 17; + break; + } - var _decodeData$7 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data), - base = _decodeData$7.base, - seed = _decodeData$7.seed, - programId = _decodeData$7.programId; + return _context7.abrupt("break", 26); - return { - accountPubkey: instruction.keys[0].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - programId: new PublicKey(programId) - }; - } - /** - * Decode a create account with seed system instruction and retrieve the instruction params. - */ + case 17: + too_many_requests_retries -= 1; - }, { - key: "decodeCreateWithSeed", - value: function decodeCreateWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + if (!(too_many_requests_retries === 0)) { + _context7.next = 20; + break; + } - var _decodeData$8 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data), - base = _decodeData$8.base, - seed = _decodeData$8.seed, - lamports = _decodeData$8.lamports, - space = _decodeData$8.space, - programId = _decodeData$8.programId; + return _context7.abrupt("break", 26); - return { - fromPubkey: instruction.keys[0].pubkey, - newAccountPubkey: instruction.keys[1].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - lamports: lamports, - space: space, - programId: new PublicKey(programId) - }; - } - /** - * Decode a nonce initialize system instruction and retrieve the instruction params. - */ + case 20: + console.log("Server responded with ".concat(res.status, " ").concat(res.statusText, ". Retrying after ").concat(waitTime, "ms delay...")); + _context7.next = 23; + return sleep(waitTime); - }, { - key: "decodeNonceInitialize", - value: function decodeNonceInitialize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 23: + waitTime *= 2; - var _decodeData$9 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data), - authorized = _decodeData$9.authorized; + case 24: + _context7.next = 4; + break; - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: new PublicKey(authorized) - }; - } - /** - * Decode a nonce advance system instruction and retrieve the instruction params. - */ + case 26: + _context7.next = 28; + return res.text(); - }, { - key: "decodeNonceAdvance", - value: function decodeNonceAdvance(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data); - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey - }; - } - /** - * Decode a nonce withdraw system instruction and retrieve the instruction params. - */ + case 28: + text = _context7.sent; - }, { - key: "decodeNonceWithdraw", - value: function decodeNonceWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 5); + if (res.ok) { + callback(null, text); + } else { + callback(new Error("".concat(res.status, " ").concat(res.statusText, ": ").concat(text))); + } - var _decodeData$10 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data), - lamports = _decodeData$10.lamports; + _context7.next = 35; + break; - return { - noncePubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey, - lamports: lamports - }; - } - /** - * Decode a nonce authorize system instruction and retrieve the instruction params. - */ + case 32: + _context7.prev = 32; + _context7.t0 = _context7["catch"](1); + if (_context7.t0 instanceof Error) callback(_context7.t0); - }, { - key: "decodeNonceAuthorize", - value: function decodeNonceAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + case 35: + case "end": + return _context7.stop(); + } + }, _callee7, null, [[1, 32]]); + })); - var _decodeData$11 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data), - authorized = _decodeData$11.authorized; + return function (_x20, _x21) { + return _ref23.apply(this, arguments); + }; + }(), {}); + return clientBrowser; +} - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[1].pubkey, - newAuthorizedPubkey: new PublicKey(authorized) - }; - } - /** - * @internal - */ +function createRpcRequest(client) { + return function (method, args) { + return new Promise(function (resolve, reject) { + client.request(method, args, function (err, response) { + if (err) { + reject(err); + return; + } - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(SystemProgram.programId)) { - throw new Error('invalid instruction; programId is not SystemProgram'); - } - } - /** - * @internal - */ + resolve(response); + }); + }); + }; +} - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } - } - }]); +function createRpcBatchRequest(client) { + return function (requests) { + return new Promise(function (resolve, reject) { + // Do nothing if requests is empty + if (requests.length === 0) resolve([]); + var batch = requests.map(function (params) { + return client.request(params.methodName, params.args); + }); + client.request(batch, function (err, response) { + if (err) { + reject(err); + return; + } - return SystemInstruction; -}(); + resolve(response); + }); + }); + }; +} /** - * An enumeration of valid SystemInstructionType's + * Expected JSON RPC response for the "getInflationGovernor" message */ + +var GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult); /** - * An enumeration of valid system InstructionType's - * @internal + * Expected JSON RPC response for the "getInflationRate" message */ - -var SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({ - Create: { - index: 0, - layout: struct([u32('instruction'), ns64('lamports'), ns64('space'), publicKey('programId')]) - }, - Assign: { - index: 1, - layout: struct([u32('instruction'), publicKey('programId')]) - }, - Transfer: { - index: 2, - layout: struct([u32('instruction'), u64('lamports')]) - }, - CreateWithSeed: { - index: 3, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('lamports'), ns64('space'), publicKey('programId')]) - }, - AdvanceNonceAccount: { - index: 4, - layout: struct([u32('instruction')]) - }, - WithdrawNonceAccount: { - index: 5, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - InitializeNonceAccount: { - index: 6, - layout: struct([u32('instruction'), publicKey('authorized')]) - }, - AuthorizeNonceAccount: { - index: 7, - layout: struct([u32('instruction'), publicKey('authorized')]) - }, - Allocate: { - index: 8, - layout: struct([u32('instruction'), ns64('space')]) - }, - AllocateWithSeed: { - index: 9, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('space'), publicKey('programId')]) - }, - AssignWithSeed: { - index: 10, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')]) - }, - TransferWithSeed: { - index: 11, - layout: struct([u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')]) - }, - UpgradeNonceAccount: { - index: 12, - layout: struct([u32('instruction')]) - } -}); +var GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult); /** - * Factory class for transactions to interact with the System program + * Expected JSON RPC response for the "getRecentPrioritizationFees" message */ -var SystemProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function SystemProgram() { - _classCallCheck(this, SystemProgram); - } - /** - * Public key that identifies the System program - */ - - /** - * Generate a transaction instruction that creates a new account - */ - - - _createClass(SystemProgram, null, [{ - key: "createAccount", - value: function createAccount(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.Create; - var data = encodeData(type, { - lamports: params.lamports, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.newAccountPubkey, - isSigner: true, - isWritable: true - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that transfers lamports from one account to another - */ - - }, { - key: "transfer", - value: function transfer(params) { - var data; - var keys; - - if ('basePubkey' in params) { - var _type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed; - data = encodeData(_type, { - lamports: BigInt(params.lamports), - seed: params.seed, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.fromPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }]; - } else { - var _type2 = SYSTEM_INSTRUCTION_LAYOUTS.Transfer; - data = encodeData(_type2, { - lamports: BigInt(params.lamports) - }); - keys = [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }]; - } +var GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult); +/** + * Expected JSON RPC response for the "getEpochInfo" message + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that assigns an account to a program - */ +var GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult); +/** + * Expected JSON RPC response for the "getEpochSchedule" message + */ - }, { - key: "assign", - value: function assign(params) { - var data; - var keys; +var GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult); +/** + * Expected JSON RPC response for the "getLeaderSchedule" message + */ - if ('basePubkey' in params) { - var _type3 = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed; - data = encodeData(_type3, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }]; - } else { - var _type4 = SYSTEM_INSTRUCTION_LAYOUTS.Assign; - data = encodeData(_type4, { - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: true, - isWritable: true - }]; - } +var GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult); +/** + * Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that creates a new account at - * an address generated with `from`, a seed, and programId - */ +var SlotRpcResult = jsonRpcResult(number()); +/** + * Supply + */ - }, { - key: "createAccountWithSeed", - value: function createAccountWithSeed(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed; - var data = encodeData(type, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - lamports: params.lamports, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - var keys = [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.newAccountPubkey, - isSigner: false, - isWritable: true - }]; +/** + * Expected JSON RPC response for the "getSupply" message + */ - if (params.basePubkey != params.fromPubkey) { - keys.push({ - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }); - } +var GetSupplyRpcResult = jsonRpcResultAndContext(type({ + total: number(), + circulating: number(), + nonCirculating: number(), + nonCirculatingAccounts: array(PublicKeyFromString) +})); +/** + * Token amount object which returns a token amount in different formats + * for various client use cases. + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction that creates a new Nonce account - */ +/** + * Expected JSON RPC structure for token amounts + */ - }, { - key: "createNonceAccount", - value: function createNonceAccount(params) { - var transaction = new Transaction(); +var TokenAmountResult = type({ + amount: string(), + uiAmount: nullable(number()), + decimals: number(), + uiAmountString: optional(string()) +}); +/** + * Token address and balance. + */ - if ('basePubkey' in params && 'seed' in params) { - transaction.add(SystemProgram.createAccountWithSeed({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.noncePubkey, - basePubkey: params.basePubkey, - seed: params.seed, - lamports: params.lamports, - space: NONCE_ACCOUNT_LENGTH, - programId: this.programId - })); - } else { - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.noncePubkey, - lamports: params.lamports, - space: NONCE_ACCOUNT_LENGTH, - programId: this.programId - })); - } +/** + * Expected JSON RPC response for the "getTokenLargestAccounts" message + */ - var initParams = { - noncePubkey: params.noncePubkey, - authorizedPubkey: params.authorizedPubkey - }; - transaction.add(this.nonceInitialize(initParams)); - return transaction; - } - /** - * Generate an instruction to initialize a Nonce account - */ +var GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({ + address: PublicKeyFromString, + amount: string(), + uiAmount: nullable(number()), + decimals: number(), + uiAmountString: optional(string()) +}))); +/** + * Expected JSON RPC response for the "getTokenAccountsByOwner" message + */ - }, { - key: "nonceInitialize", - value: function nonceInitialize(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount; - var data = encodeData(type, { - authorized: toBuffer(params.authorizedPubkey.toBuffer()) - }); - var instructionData = { - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate an instruction to advance the nonce in a Nonce account - */ +var GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ + pubkey: PublicKeyFromString, + account: type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: BufferFromRawAccountData, + rentEpoch: number() + }) +}))); +var ParsedAccountDataResult = type({ + program: string(), + parsed: unknown(), + space: number() +}); +/** + * Expected JSON RPC response for the "getTokenAccountsByOwner" message with parsed data + */ - }, { - key: "nonceAdvance", - value: function nonceAdvance(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount; - var data = encodeData(type); - var instructionData = { - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a transaction instruction that withdraws lamports from a Nonce account - */ +var GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ + pubkey: PublicKeyFromString, + account: type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: ParsedAccountDataResult, + rentEpoch: number() + }) +}))); +/** + * Pair of an account address and its balance + */ - }, { - key: "nonceWithdraw", - value: function nonceWithdraw(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount; - var data = encodeData(type, { - lamports: params.lamports - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that authorizes a new PublicKey as the authority - * on a Nonce account. - */ +/** + * Expected JSON RPC response for the "getLargestAccounts" message + */ - }, { - key: "nonceAuthorize", - value: function nonceAuthorize(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount; - var data = encodeData(type, { - authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()) - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that allocates space in an account without funding - */ +var GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({ + lamports: number(), + address: PublicKeyFromString +}))); +/** + * @internal + */ - }, { - key: "allocate", - value: function allocate(params) { - var data; - var keys; +var AccountInfoResult = type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: BufferFromRawAccountData, + rentEpoch: number() +}); +/** + * @internal + */ - if ('basePubkey' in params) { - var _type5 = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed; - data = encodeData(_type5, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }]; - } else { - var _type6 = SYSTEM_INSTRUCTION_LAYOUTS.Allocate; - data = encodeData(_type6, { - space: params.space - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: true, - isWritable: true - }]; - } +var KeyedAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: AccountInfoResult +}); +var ParsedOrRawAccountData = coerce(union([instance(Buffer$1), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), function (value) { + if (Array.isArray(value)) { + return _create(value, BufferFromRawAccountData); + } else { + return value; + } +}); +/** + * @internal + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - }]); +var ParsedAccountInfoResult = type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: ParsedOrRawAccountData, + rentEpoch: number() +}); +var KeyedParsedAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: ParsedAccountInfoResult +}); +/** + * @internal + */ - return SystemProgram; -}(); +var StakeActivationResult = type({ + state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]), + active: number(), + inactive: number() +}); +/** + * Expected JSON RPC response for the "getConfirmedSignaturesForAddress2" message + */ -SystemProgram.programId = new PublicKey('11111111111111111111111111111111'); // Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the -// rest of the Transaction fields -// -// TODO: replace 300 with a proper constant for the size of the other -// Transaction fields +var GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({ + signature: string(), + slot: number(), + err: TransactionErrorResult, + memo: nullable(string()), + blockTime: optional(nullable(number())) +}))); +/** + * Expected JSON RPC response for the "getSignaturesForAddress" message + */ -var CHUNK_SIZE = PACKET_DATA_SIZE - 300; +var GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({ + signature: string(), + slot: number(), + err: TransactionErrorResult, + memo: nullable(string()), + blockTime: optional(nullable(number())) +}))); +/*** + * Expected JSON RPC response for the "accountNotification" message + */ + +var AccountNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(AccountInfoResult) +}); /** - * Program loader interface + * @internal */ -var Loader = /*#__PURE__*/function () { - /** - * @internal - */ - function Loader() { - _classCallCheck(this, Loader); - } - /** - * Amount of program data placed in each load Transaction - */ +var ProgramAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: AccountInfoResult +}); +/*** + * Expected JSON RPC response for the "programNotification" message + */ - /** - * Minimum number of signatures required to load a program not including - * retries - * - * Can be used to calculate transaction fees - */ +var ProgramAccountNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(ProgramAccountInfoResult) +}); +/** + * @internal + */ +var SlotInfoResult = type({ + parent: number(), + slot: number(), + root: number() +}); +/** + * Expected JSON RPC response for the "slotNotification" message + */ - _createClass(Loader, null, [{ - key: "getMinNumSignatures", - value: function getMinNumSignatures(dataLength) { - return 2 * ( // Every transaction requires two signatures (payer + program) - Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction - 1) // Add one for Finalize transaction - ; - } - /** - * Loads a generic program - * - * @param connection The connection to use - * @param payer System account that pays to load the program - * @param program Account to load the program into - * @param programId Public key that identifies the loader - * @param data Program octets - * @return true if program was loaded successfully, false if program was already loaded - */ +var SlotNotificationResult = type({ + subscription: number(), + result: SlotInfoResult +}); +/** + * Slot updates which can be used for tracking the live progress of a cluster. + * - `"firstShredReceived"`: connected node received the first shred of a block. + * Indicates that a new block that is being produced. + * - `"completed"`: connected node has received all shreds of a block. Indicates + * a block was recently produced. + * - `"optimisticConfirmation"`: block was optimistically confirmed by the + * cluster. It is not guaranteed that an optimistic confirmation notification + * will be sent for every finalized blocks. + * - `"root"`: the connected node rooted this block. + * - `"createdBank"`: the connected node has started validating this block. + * - `"frozen"`: the connected node has validated this block. + * - `"dead"`: the connected node failed to validate this block. + */ - }, { - key: "load", - value: function () { - var _load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(connection, payer, program, programId, data) { - var balanceNeeded, programInfo, transaction, dataLayout, chunkSize, offset, array, transactions, bytes, _data, _transaction, REQUESTS_PER_SECOND, _dataLayout, _data2, _transaction2; +/** + * @internal + */ - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - _context5.next = 2; - return connection.getMinimumBalanceForRentExemption(data.length); +var SlotUpdateResult = union([type({ + type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]), + slot: number(), + timestamp: number() +}), type({ + type: literal('createdBank'), + parent: number(), + slot: number(), + timestamp: number() +}), type({ + type: literal('frozen'), + slot: number(), + timestamp: number(), + stats: type({ + numTransactionEntries: number(), + numSuccessfulTransactions: number(), + numFailedTransactions: number(), + maxTransactionsPerEntry: number() + }) +}), type({ + type: literal('dead'), + slot: number(), + timestamp: number(), + err: string() +})]); +/** + * Expected JSON RPC response for the "slotsUpdatesNotification" message + */ - case 2: - balanceNeeded = _context5.sent; - _context5.next = 5; - return connection.getAccountInfo(program.publicKey, 'confirmed'); +var SlotUpdateNotificationResult = type({ + subscription: number(), + result: SlotUpdateResult +}); +/** + * Expected JSON RPC response for the "signatureNotification" message + */ - case 5: - programInfo = _context5.sent; - transaction = null; +var SignatureNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult])) +}); +/** + * Expected JSON RPC response for the "rootNotification" message + */ - if (!(programInfo !== null)) { - _context5.next = 16; - break; - } +var RootNotificationResult = type({ + subscription: number(), + result: number() +}); +var ContactInfoResult = type({ + pubkey: string(), + gossip: nullable(string()), + tpu: nullable(string()), + rpc: nullable(string()), + version: nullable(string()) +}); +var VoteAccountInfoResult = type({ + votePubkey: string(), + nodePubkey: string(), + activatedStake: number(), + epochVoteAccount: _boolean(), + epochCredits: array(tuple([number(), number(), number()])), + commission: number(), + lastVote: number(), + rootSlot: nullable(number()) +}); +/** + * Expected JSON RPC response for the "getVoteAccounts" message + */ - if (!programInfo.executable) { - _context5.next = 11; - break; - } +var GetVoteAccounts = jsonRpcResult(type({ + current: array(VoteAccountInfoResult), + delinquent: array(VoteAccountInfoResult) +})); +var ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]); +var SignatureStatusResponse = type({ + slot: number(), + confirmations: nullable(number()), + err: TransactionErrorResult, + confirmationStatus: optional(ConfirmationStatus) +}); +/** + * Expected JSON RPC response for the "getSignatureStatuses" message + */ - console.error('Program load failed, account is already executable'); - return _context5.abrupt("return", false); +var GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse))); +/** + * Expected JSON RPC response for the "getMinimumBalanceForRentExemption" message + */ - case 11: - if (programInfo.data.length !== data.length) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.allocate({ - accountPubkey: program.publicKey, - space: data.length - })); - } +var GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number()); +var AddressTableLookupStruct = type({ + accountKey: PublicKeyFromString, + writableIndexes: array(number()), + readonlyIndexes: array(number()) +}); +var ConfirmedTransactionResult = type({ + signatures: array(string()), + message: type({ + accountKeys: array(string()), + header: type({ + numRequiredSignatures: number(), + numReadonlySignedAccounts: number(), + numReadonlyUnsignedAccounts: number() + }), + instructions: array(type({ + accounts: array(number()), + data: string(), + programIdIndex: number() + })), + recentBlockhash: string(), + addressTableLookups: optional(array(AddressTableLookupStruct)) + }) +}); +var AnnotatedAccountKey = type({ + pubkey: PublicKeyFromString, + signer: _boolean(), + writable: _boolean(), + source: optional(union([literal('transaction'), literal('lookupTable')])) +}); +var ConfirmedTransactionAccountsModeResult = type({ + accountKeys: array(AnnotatedAccountKey), + signatures: array(string()) +}); +var ParsedInstructionResult = type({ + parsed: unknown(), + program: string(), + programId: PublicKeyFromString +}); +var RawInstructionResult = type({ + accounts: array(PublicKeyFromString), + data: string(), + programId: PublicKeyFromString +}); +var InstructionResult = union([RawInstructionResult, ParsedInstructionResult]); +var UnknownInstructionResult = union([type({ + parsed: unknown(), + program: string(), + programId: string() +}), type({ + accounts: array(string()), + data: string(), + programId: string() +})]); +var ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, function (value) { + if ('accounts' in value) { + return _create(value, RawInstructionResult); + } else { + return _create(value, ParsedInstructionResult); + } +}); +/** + * @internal + */ + +var ParsedConfirmedTransactionResult = type({ + signatures: array(string()), + message: type({ + accountKeys: array(AnnotatedAccountKey), + instructions: array(ParsedOrRawInstruction), + recentBlockhash: string(), + addressTableLookups: optional(nullable(array(AddressTableLookupStruct))) + }) +}); +var TokenBalanceResult = type({ + accountIndex: number(), + mint: string(), + owner: optional(string()), + uiTokenAmount: TokenAmountResult +}); +var LoadedAddressesResult = type({ + writable: array(PublicKeyFromString), + readonly: array(PublicKeyFromString) +}); +/** + * @internal + */ + +var ConfirmedTransactionMetaResult = type({ + err: TransactionErrorResult, + fee: number(), + innerInstructions: optional(nullable(array(type({ + index: number(), + instructions: array(type({ + accounts: array(number()), + data: string(), + programIdIndex: number() + })) + })))), + preBalances: array(number()), + postBalances: array(number()), + logMessages: optional(nullable(array(string()))), + preTokenBalances: optional(nullable(array(TokenBalanceResult))), + postTokenBalances: optional(nullable(array(TokenBalanceResult))), + loadedAddresses: optional(LoadedAddressesResult), + computeUnitsConsumed: optional(number()) +}); +/** + * @internal + */ + +var ParsedConfirmedTransactionMetaResult = type({ + err: TransactionErrorResult, + fee: number(), + innerInstructions: optional(nullable(array(type({ + index: number(), + instructions: array(ParsedOrRawInstruction) + })))), + preBalances: array(number()), + postBalances: array(number()), + logMessages: optional(nullable(array(string()))), + preTokenBalances: optional(nullable(array(TokenBalanceResult))), + postTokenBalances: optional(nullable(array(TokenBalanceResult))), + loadedAddresses: optional(LoadedAddressesResult), + computeUnitsConsumed: optional(number()) +}); +var TransactionVersionStruct = union([literal(0), literal('legacy')]); +/** @internal */ - if (!programInfo.owner.equals(programId)) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.assign({ - accountPubkey: program.publicKey, - programId: programId - })); - } +var RewardsResult = type({ + pubkey: string(), + lamports: number(), + postBalance: nullable(number()), + rewardType: nullable(string()), + commission: optional(nullable(number())) +}); +/** + * Expected JSON RPC response for the "getBlock" message + */ - if (programInfo.lamports < balanceNeeded) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.transfer({ - fromPubkey: payer.publicKey, - toPubkey: program.publicKey, - lamports: balanceNeeded - programInfo.lamports - })); - } +var GetBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionResult, + meta: nullable(ConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `none` + */ - _context5.next = 17; - break; +var GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` + */ - case 16: - transaction = new Transaction().add(SystemProgram.createAccount({ - fromPubkey: payer.publicKey, - newAccountPubkey: program.publicKey, - lamports: balanceNeeded > 0 ? balanceNeeded : 1, - space: data.length, - programId: programId - })); +var GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionAccountsModeResult, + meta: nullable(ConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected parsed JSON RPC response for the "getBlock" message + */ - case 17: - if (!(transaction !== null)) { - _context5.next = 20; - break; - } +var GetParsedBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ParsedConfirmedTransactionResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` + */ - _context5.next = 20; - return sendAndConfirmTransaction(connection, transaction, [payer, program], { - commitment: 'confirmed' - }); +var GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionAccountsModeResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `none` + */ - case 20: - dataLayout = struct([u32('instruction'), u32('offset'), u32('bytesLength'), u32('bytesLengthPadding'), seq$1(u8('byte'), offset$1(u32(), -8), 'bytes')]); - chunkSize = Loader.chunkSize; - offset = 0; - array = data; - transactions = []; +var GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) +}))); +/** + * Expected JSON RPC response for the "getConfirmedBlock" message + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead. + */ - case 25: - if (!(array.length > 0)) { - _context5.next = 39; - break; - } +var GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionResult, + meta: nullable(ConfirmedTransactionMetaResult) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()) +}))); +/** + * Expected JSON RPC response for the "getBlock" message + */ - bytes = array.slice(0, chunkSize); - _data = Buffer$1.alloc(chunkSize + 16); - dataLayout.encode({ - instruction: 0, - // Load instruction - offset: offset, - bytes: bytes, - bytesLength: 0, - bytesLengthPadding: 0 - }, _data); - _transaction = new Transaction().add({ - keys: [{ - pubkey: program.publicKey, - isSigner: true, - isWritable: true - }], - programId: programId, - data: _data - }); - transactions.push(sendAndConfirmTransaction(connection, _transaction, [payer, program], { - commitment: 'confirmed' - })); // Delay between sends in an attempt to reduce rate limit errors +var GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + signatures: array(string()), + blockTime: nullable(number()) +}))); +/** + * Expected JSON RPC response for the "getTransaction" message + */ - if (!connection._rpcEndpoint.includes('solana.com')) { - _context5.next = 35; - break; - } +var GetTransactionRpcResult = jsonRpcResult(nullable(type({ + slot: number(), + meta: ConfirmedTransactionMetaResult, + blockTime: optional(nullable(number())), + transaction: ConfirmedTransactionResult, + version: optional(TransactionVersionStruct) +}))); +/** + * Expected parsed JSON RPC response for the "getTransaction" message + */ - REQUESTS_PER_SECOND = 4; - _context5.next = 35; - return sleep(1000 / REQUESTS_PER_SECOND); +var GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({ + slot: number(), + transaction: ParsedConfirmedTransactionResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + blockTime: optional(nullable(number())), + version: optional(TransactionVersionStruct) +}))); +/** + * Expected JSON RPC response for the "getRecentBlockhash" message + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead. + */ - case 35: - offset += chunkSize; - array = array.slice(chunkSize); - _context5.next = 25; - break; +var GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(type({ + blockhash: string(), + feeCalculator: type({ + lamportsPerSignature: number() + }) +})); +/** + * Expected JSON RPC response for the "getLatestBlockhash" message + */ - case 39: - _context5.next = 41; - return Promise.all(transactions); +var GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({ + blockhash: string(), + lastValidBlockHeight: number() +})); +var PerfSampleResult = type({ + slot: number(), + numTransactions: number(), + numSlots: number(), + samplePeriodSecs: number() +}); +/* + * Expected JSON RPC response for "getRecentPerformanceSamples" message + */ - case 41: - _dataLayout = struct([u32('instruction')]); - _data2 = Buffer$1.alloc(_dataLayout.span); +var GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult)); +/** + * Expected JSON RPC response for the "getFeeCalculatorForBlockhash" message + */ - _dataLayout.encode({ - instruction: 1 // Finalize instruction +var GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({ + feeCalculator: type({ + lamportsPerSignature: number() + }) +}))); +/** + * Expected JSON RPC response for the "requestAirdrop" message + */ - }, _data2); +var RequestAirdropRpcResult = jsonRpcResult(string()); +/** + * Expected JSON RPC response for the "sendTransaction" message + */ - _transaction2 = new Transaction().add({ - keys: [{ - pubkey: program.publicKey, - isSigner: true, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: programId, - data: _data2 - }); - _context5.next = 47; - return sendAndConfirmTransaction(connection, _transaction2, [payer, program], { - commitment: 'confirmed' - }); +var SendTransactionRpcResult = jsonRpcResult(string()); +/** + * Information about the latest slot being processed by a node + */ - case 47: - return _context5.abrupt("return", true); +/** + * @internal + */ - case 48: - case "end": - return _context5.stop(); - } - }, _callee5); - })); +var LogsResult = type({ + err: TransactionErrorResult, + logs: array(string()), + signature: string() +}); +/** + * Logs result. + */ - function load(_x13, _x14, _x15, _x16, _x17) { - return _load.apply(this, arguments); - } +/** + * Expected JSON RPC response for the "logsNotification" message. + */ - return load; - }() - }]); +var LogsNotificationResult = type({ + result: notificationResultAndContext(LogsResult), + subscription: number() +}); +/** + * Filter for log subscriptions. + */ - return Loader; -}(); +/** @internal */ -Loader.chunkSize = CHUNK_SIZE; -var BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111'); +var COMMON_HTTP_HEADERS = { + 'solana-client': "js/".concat("0.0.0-development") +}; /** - * Factory class for transactions to interact with a program loader + * A connection to a fullnode JSON RPC endpoint */ -var BpfLoader = /*#__PURE__*/function () { - function BpfLoader() { - _classCallCheck(this, BpfLoader); - } +var Connection = /*#__PURE__*/function () { + /** @internal */ - _createClass(BpfLoader, null, [{ - key: "getMinNumSignatures", - value: - /** - * Minimum number of signatures required to load a program not including - * retries - * - * Can be used to calculate transaction fees - */ - function getMinNumSignatures(dataLength) { - return Loader.getMinNumSignatures(dataLength); - } - /** - * Load a SBF program - * - * @param connection The connection to use - * @param payer Account that will pay program loading fees - * @param program Account to load the program into - * @param elf The entire ELF containing the SBF program - * @param loaderProgramId The program id of the BPF loader to use - * @return true if program was loaded successfully, false if program was already loaded - */ + /** @internal */ - }, { - key: "load", - value: function load(connection, payer, program, elf, loaderProgramId) { - return Loader.load(connection, payer, program, loaderProgramId, elf); - } - }]); + /** @internal */ - return BpfLoader; -}(); + /** @internal */ -var objToString = Object.prototype.toString; + /** @internal */ -var objKeys = Object.keys || function (obj) { - var keys = []; + /** @internal */ - for (var name in obj) { - keys.push(name); - } + /** @internal */ - return keys; -}; + /** @internal */ -function stringify(val, isArrayProp) { - var i, max, str, keys, key, propVal, toStr; + /** @internal */ - if (val === true) { - return "true"; - } + /** @internal */ - if (val === false) { - return "false"; - } + /** @internal */ - switch (_typeof$1(val)) { - case "object": - if (val === null) { - return null; - } else if (val.toJSON && typeof val.toJSON === "function") { - return stringify(val.toJSON(), isArrayProp); - } else { - toStr = objToString.call(val); + /** @internal + * A number that we increment every time an active connection closes. + * Used to determine whether the same socket connection that was open + * when an async operation started is the same one that's active when + * its continuation fires. + * + */ - if (toStr === "[object Array]") { - str = '['; - max = val.length - 1; + /** @internal */ - for (i = 0; i < max; i++) { - str += stringify(val[i], true) + ','; - } + /** @internal */ - if (max > -1) { - str += stringify(val[i], true); - } + /** @internal */ - return str + ']'; - } else if (toStr === "[object Object]") { - // only object is left - keys = objKeys(val).sort(); - max = keys.length; - str = ""; - i = 0; + /** @internal */ - while (i < max) { - key = keys[i]; - propVal = stringify(val[key], false); + /** @internal */ - if (propVal !== undefined) { - if (str) { - str += ','; - } + /** @internal */ - str += JSON.stringify(key) + ':' + propVal; - } + /** @internal */ - i++; - } + /** @internal */ - return '{' + str + '}'; - } else { - return JSON.stringify(val); - } - } + /** @internal */ - case "function": - case "undefined": - return isArrayProp ? null : undefined; + /** + * Special case. + * After a signature is processed, RPCs automatically dispose of the + * subscription on the server side. We need to track which of these + * subscriptions have been disposed in such a way, so that we know + * whether the client is dealing with a not-yet-processed signature + * (in which case we must tear down the server subscription) or an + * already-processed signature (in which case the client can simply + * clear out the subscription locally without telling the server). + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ - case "string": - return JSON.stringify(val); + /** @internal */ - default: - return isFinite(val) ? val : null; - } -} + /** + * Establish a JSON RPC connection + * + * @param endpoint URL to the fullnode JSON RPC endpoint + * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object + */ + function Connection(endpoint, _commitmentOrConfig) { + var _this15 = this; + + _classCallCheck(this, Connection); + + this._commitment = void 0; + this._confirmTransactionInitialTimeout = void 0; + this._rpcEndpoint = void 0; + this._rpcWsEndpoint = void 0; + this._rpcClient = void 0; + this._rpcRequest = void 0; + this._rpcBatchRequest = void 0; + this._rpcWebSocket = void 0; + this._rpcWebSocketConnected = false; + this._rpcWebSocketHeartbeat = null; + this._rpcWebSocketIdleTimeout = null; + this._rpcWebSocketGeneration = 0; + this._disableBlockhashCaching = false; + this._pollingBlockhash = false; + this._blockhashInfo = { + latestBlockhash: null, + lastFetch: 0, + transactionSignatures: [], + simulatedSignatures: [] + }; + this._nextClientSubscriptionId = 0; + this._subscriptionDisposeFunctionsByClientSubscriptionId = {}; + this._subscriptionHashByClientSubscriptionId = {}; + this._subscriptionStateChangeCallbacksByHash = {}; + this._subscriptionCallbacksByServerSubscriptionId = {}; + this._subscriptionsByHash = {}; + this._subscriptionsAutoDisposedByRpc = new Set(); -var fastStableStringify = function fastStableStringify(val) { - var returnVal = stringify(val, false); + this.getBlockHeight = function () { + var requestPromises = {}; + return /*#__PURE__*/function () { + var _ref24 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(commitmentOrConfig) { + var _requestPromises$requ; - if (returnVal !== undefined) { - return '' + returnVal; - } -}; + var _extractCommitmentFro, commitment, config, args, requestHash; -var fastStableStringify$1 = fastStableStringify; -var MINIMUM_SLOT_PER_EPOCH = 32; // Returns the number of trailing zeros in the binary representation of self. + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _extractCommitmentFro = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro.commitment, config = _extractCommitmentFro.config; + args = _this15._buildArgs([], commitment, undefined + /* encoding */ + , config); + requestHash = fastStableStringify$1(args); + requestPromises[requestHash] = (_requestPromises$requ = requestPromises[requestHash]) !== null && _requestPromises$requ !== void 0 ? _requestPromises$requ : _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.prev = 0; + _context8.next = 3; + return _this15._rpcRequest('getBlockHeight', args); -function trailingZeros(n) { - var trailingZeros = 0; + case 3: + unsafeRes = _context8.sent; + res = _create(unsafeRes, jsonRpcResult(number())); - while (n > 1) { - n /= 2; - trailingZeros++; - } + if (!('error' in res)) { + _context8.next = 7; + break; + } - return trailingZeros; -} // Returns the smallest power of two greater than or equal to n + throw new SolanaJSONRPCError(res.error, 'failed to get block height information'); + case 7: + return _context8.abrupt("return", res.result); -function nextPowerOfTwo(n) { - if (n === 0) return 1; - n--; - n |= n >> 1; - n |= n >> 2; - n |= n >> 4; - n |= n >> 8; - n |= n >> 16; - n |= n >> 32; - return n + 1; -} -/** - * Epoch schedule - * (see https://docs.solana.com/terminology#epoch) - * Can be retrieved with the {@link Connection.getEpochSchedule} method - */ + case 8: + _context8.prev = 8; + delete requestPromises[requestHash]; + return _context8.finish(8); + case 11: + case "end": + return _context8.stop(); + } + }, _callee8, null, [[0,, 8, 11]]); + }))(); + _context9.next = 6; + return requestPromises[requestHash]; -var EpochSchedule = /*#__PURE__*/function () { - /** The maximum number of slots in each epoch */ + case 6: + return _context9.abrupt("return", _context9.sent); - /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */ + case 7: + case "end": + return _context9.stop(); + } + }, _callee9); + })); - /** Indicates whether epochs start short and grow */ + return function (_x22) { + return _ref24.apply(this, arguments); + }; + }(); + }(); - /** The first epoch with `slotsPerEpoch` slots */ + var wsEndpoint; + var httpHeaders; + var fetch; + var fetchMiddleware; + var disableRetryOnRateLimit; + var httpAgent; - /** The first slot of `firstNormalEpoch` */ - function EpochSchedule(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) { - _classCallCheck(this, EpochSchedule); + if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') { + this._commitment = _commitmentOrConfig; + } else if (_commitmentOrConfig) { + this._commitment = _commitmentOrConfig.commitment; + this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout; + wsEndpoint = _commitmentOrConfig.wsEndpoint; + httpHeaders = _commitmentOrConfig.httpHeaders; + fetch = _commitmentOrConfig.fetch; + fetchMiddleware = _commitmentOrConfig.fetchMiddleware; + disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit; + httpAgent = _commitmentOrConfig.httpAgent; + } - this.slotsPerEpoch = void 0; - this.leaderScheduleSlotOffset = void 0; - this.warmup = void 0; - this.firstNormalEpoch = void 0; - this.firstNormalSlot = void 0; - this.slotsPerEpoch = slotsPerEpoch; - this.leaderScheduleSlotOffset = leaderScheduleSlotOffset; - this.warmup = warmup; - this.firstNormalEpoch = firstNormalEpoch; - this.firstNormalSlot = firstNormalSlot; - } + this._rpcEndpoint = assertEndpointUrl(endpoint); + this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint); + this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent); + this._rpcRequest = createRpcRequest(this._rpcClient); + this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient); + this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, { + autoconnect: false, + max_reconnects: Infinity + }); - _createClass(EpochSchedule, [{ - key: "getEpoch", - value: function getEpoch(slot) { - return this.getEpochAndSlotIndex(slot)[0]; - } - }, { - key: "getEpochAndSlotIndex", - value: function getEpochAndSlotIndex(slot) { - if (slot < this.firstNormalSlot) { - var epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1; - var epochLen = this.getSlotsInEpoch(epoch); - var slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH); - return [epoch, slotIndex]; - } else { - var normalSlotIndex = slot - this.firstNormalSlot; - var normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch); + this._rpcWebSocket.on('open', this._wsOnOpen.bind(this)); - var _epoch = this.firstNormalEpoch + normalEpochIndex; + this._rpcWebSocket.on('error', this._wsOnError.bind(this)); - var _slotIndex = normalSlotIndex % this.slotsPerEpoch; + this._rpcWebSocket.on('close', this._wsOnClose.bind(this)); - return [_epoch, _slotIndex]; - } - } - }, { - key: "getFirstSlotInEpoch", - value: function getFirstSlotInEpoch(epoch) { - if (epoch <= this.firstNormalEpoch) { - return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH; - } else { - return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot; - } - } - }, { - key: "getLastSlotInEpoch", - value: function getLastSlotInEpoch(epoch) { - return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1; - } - }, { - key: "getSlotsInEpoch", - value: function getSlotsInEpoch(epoch) { - if (epoch < this.firstNormalEpoch) { - return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH)); - } else { - return this.slotsPerEpoch; - } - } - }]); + this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this)); - return EpochSchedule; -}(); + this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this)); -var SendTransactionError = /*#__PURE__*/function (_Error4) { - _inherits(SendTransactionError, _Error4); + this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this)); - var _super6 = _createSuper(SendTransactionError); + this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this)); - function SendTransactionError(message, logs) { - var _this12; + this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this)); - _classCallCheck(this, SendTransactionError); + this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this)); - _this12 = _super6.call(this, message); - _this12.logs = void 0; - _this12.logs = logs; - return _this12; + this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this)); } - - return _createClass(SendTransactionError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); // Keep in sync with client/src/rpc_custom_errors.rs -// Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ + /** + * The default commitment used for requests + */ -var SolanaJSONRPCErrorCode = { - JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001, - JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002, - JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003, - JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004, - JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005, - JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006, - JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007, - JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008, - JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009, - JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010, - JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011, - JSON_RPC_SCAN_ERROR: -32012, - JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013, - JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014, - JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015, - JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016 -}; + _createClass(Connection, [{ + key: "commitment", + get: function get() { + return this._commitment; + } + /** + * The RPC endpoint + */ -var SolanaJSONRPCError = /*#__PURE__*/function (_Error5) { - _inherits(SolanaJSONRPCError, _Error5); + }, { + key: "rpcEndpoint", + get: function get() { + return this._rpcEndpoint; + } + /** + * Fetch the balance for the specified public key, return with context + */ - var _super7 = _createSuper(SolanaJSONRPCError); + }, { + key: "getBalanceAndContext", + value: function () { + var _getBalanceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(publicKey, commitmentOrConfig) { + var _extractCommitmentFro2, commitment, config, args, unsafeRes, res; - function SolanaJSONRPCError(_ref21, customMessage) { - var _this13; + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + /** @internal */ + _extractCommitmentFro2 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro2.commitment, config = _extractCommitmentFro2.config; + args = this._buildArgs([publicKey.toBase58()], commitment, undefined + /* encoding */ + , config); + _context10.next = 4; + return this._rpcRequest('getBalance', args); - var code = _ref21.code, - message = _ref21.message, - data = _ref21.data; + case 4: + unsafeRes = _context10.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(number())); - _classCallCheck(this, SolanaJSONRPCError); + if (!('error' in res)) { + _context10.next = 8; + break; + } - _this13 = _super7.call(this, customMessage != null ? "".concat(customMessage, ": ").concat(message) : message); - _this13.code = void 0; - _this13.data = void 0; - _this13.code = code; - _this13.data = data; - _this13.name = 'SolanaJSONRPCError'; - return _this13; - } + throw new SolanaJSONRPCError(res.error, "failed to get balance for ".concat(publicKey.toBase58())); - return _createClass(SolanaJSONRPCError); -}( /*#__PURE__*/_wrapNativeSuper(Error)); + case 8: + return _context10.abrupt("return", res.result); -var fetchImpl = globalThis.fetch; + case 9: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); -var RpcWebSocketClient = /*#__PURE__*/function (_RpcWebSocketCommonCl) { - _inherits(RpcWebSocketClient, _RpcWebSocketCommonCl); + function getBalanceAndContext(_x23, _x24) { + return _getBalanceAndContext.apply(this, arguments); + } - var _super8 = _createSuper(RpcWebSocketClient); + return getBalanceAndContext; + }() + /** + * Fetch the balance for the specified public key + */ - function RpcWebSocketClient(address, options, generate_request_id) { - var _this14; + }, { + key: "getBalance", + value: function () { + var _getBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(publicKey, commitmentOrConfig) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return this.getBalanceAndContext(publicKey, commitmentOrConfig).then(function (x) { + return x.value; + })["catch"](function (e) { + throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e); + }); - _classCallCheck(this, RpcWebSocketClient); + case 2: + return _context11.abrupt("return", _context11.sent); - var webSocketFactory = function webSocketFactory(url) { - var rpc = createRpc(url, _objectSpread2({ - autoconnect: true, - max_reconnects: 5, - reconnect: true, - reconnect_interval: 1000 - }, options)); + case 3: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); - if ('socket' in rpc) { - _this14.underlyingSocket = rpc.socket; - } else { - _this14.underlyingSocket = rpc; + function getBalance(_x25, _x26) { + return _getBalance.apply(this, arguments); } - return rpc; - }; - - _this14 = _super8.call(this, webSocketFactory, address, options, generate_request_id); - _this14.underlyingSocket = void 0; - return _this14; - } - - _createClass(RpcWebSocketClient, [{ - key: "call", - value: function call() { - var _this$underlyingSocke; + return getBalance; + }() + /** + * Fetch the estimated production time of a block + */ - var readyState = (_this$underlyingSocke = this.underlyingSocket) === null || _this$underlyingSocke === void 0 ? void 0 : _this$underlyingSocke.readyState; + }, { + key: "getBlockTime", + value: function () { + var _getBlockTime = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(slot) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return this._rpcRequest('getBlockTime', [slot]); - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } + case 2: + unsafeRes = _context12.sent; + res = _create(unsafeRes, jsonRpcResult(nullable(number()))); - if (readyState === 1 - /* WebSocket.OPEN */ - ) { - var _get2; + if (!('error' in res)) { + _context12.next = 6; + break; + } - return (_get2 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "call", this)).call.apply(_get2, [this].concat(args)); - } + throw new SolanaJSONRPCError(res.error, "failed to get block time for slot ".concat(slot)); - return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); - } - }, { - key: "notify", - value: function notify() { - var _this$underlyingSocke2; + case 6: + return _context12.abrupt("return", res.result); - var readyState = (_this$underlyingSocke2 = this.underlyingSocket) === null || _this$underlyingSocke2 === void 0 ? void 0 : _this$underlyingSocke2.readyState; + case 7: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); - for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; + function getBlockTime(_x27) { + return _getBlockTime.apply(this, arguments); } - if (readyState === 1 - /* WebSocket.OPEN */ - ) { - var _get3; + return getBlockTime; + }() + /** + * Fetch the lowest slot that the node has information about in its ledger. + * This value may increase over time if the node is configured to purge older ledger data + */ - return (_get3 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "notify", this)).call.apply(_get3, [this].concat(args)); - } + }, { + key: "getMinimumLedgerSlot", + value: function () { + var _getMinimumLedgerSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return this._rpcRequest('minimumLedgerSlot', []); - return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); - } - }]); + case 2: + unsafeRes = _context13.sent; + res = _create(unsafeRes, jsonRpcResult(number())); - return RpcWebSocketClient; -}(RpcWebSocketCommonClient); // TODO: These constants should be removed in favor of reading them out of a -// Syscall account + if (!('error' in res)) { + _context13.next = 6; + break; + } -/** - * @internal - */ + throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot'); + case 6: + return _context13.abrupt("return", res.result); -var NUM_TICKS_PER_SECOND = 160; -/** - * @internal - */ + case 7: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); -var DEFAULT_TICKS_PER_SLOT = 64; -/** - * @internal - */ + function getMinimumLedgerSlot() { + return _getMinimumLedgerSlot.apply(this, arguments); + } -var NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT; -/** - * @internal - */ + return getMinimumLedgerSlot; + }() + /** + * Fetch the slot of the lowest confirmed block that has not been purged from the ledger + */ -var MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND; -/** - * @internal - */ + }, { + key: "getFirstAvailableBlock", + value: function () { + var _getFirstAvailableBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return this._rpcRequest('getFirstAvailableBlock', []); -/** - * Decode account data buffer using an AccountType - * @internal - */ + case 2: + unsafeRes = _context14.sent; + res = _create(unsafeRes, SlotRpcResult); -function decodeData(type, data) { - var decoded; + if (!('error' in res)) { + _context14.next = 6; + break; + } - try { - decoded = type.layout.decode(data); - } catch (err) { - throw new Error('invalid instruction; ' + err); - } + throw new SolanaJSONRPCError(res.error, 'failed to get first available block'); - if (decoded.typeIndex !== type.index) { - throw new Error("invalid account data; account type mismatch ".concat(decoded.typeIndex, " != ").concat(type.index)); - } + case 6: + return _context14.abrupt("return", res.result); - return decoded; -} /// The serialized size of lookup table metadata + case 7: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function getFirstAvailableBlock() { + return _getFirstAvailableBlock.apply(this, arguments); + } -var LOOKUP_TABLE_META_SIZE = 56; + return getFirstAvailableBlock; + }() + /** + * Fetch information about the current supply + */ -var AddressLookupTableAccount = /*#__PURE__*/function () { - function AddressLookupTableAccount(args) { - _classCallCheck(this, AddressLookupTableAccount); + }, { + key: "getSupply", + value: function () { + var _getSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(config) { + var configArg, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + configArg = {}; - this.key = void 0; - this.state = void 0; - this.key = args.key; - this.state = args.state; - } + if (typeof config === 'string') { + configArg = { + commitment: config + }; + } else if (config) { + configArg = _objectSpread2(_objectSpread2({}, config), {}, { + commitment: config && config.commitment || this.commitment + }); + } else { + configArg = { + commitment: this.commitment + }; + } - _createClass(AddressLookupTableAccount, [{ - key: "isActive", - value: function isActive() { - var U64_MAX = BigInt('0xffffffffffffffff'); - return this.state.deactivationSlot === U64_MAX; - } - }], [{ - key: "deserialize", - value: function deserialize(accountData) { - var meta = decodeData(LookupTableMetaLayout, accountData); - var serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE; - assert(serializedAddressesLen >= 0, 'lookup table is invalid'); - assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid'); - var numSerializedAddresses = serializedAddressesLen / 32; + _context15.next = 4; + return this._rpcRequest('getSupply', [configArg]); - var _BufferLayout$struct$ = struct([seq$1(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE)), - addresses = _BufferLayout$struct$.addresses; + case 4: + unsafeRes = _context15.sent; + res = _create(unsafeRes, GetSupplyRpcResult); - return { - deactivationSlot: meta.deactivationSlot, - lastExtendedSlot: meta.lastExtendedSlot, - lastExtendedSlotStartIndex: meta.lastExtendedStartIndex, - authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined, - addresses: addresses.map(function (address) { - return new PublicKey(address); - }) - }; - } - }]); + if (!('error' in res)) { + _context15.next = 8; + break; + } - return AddressLookupTableAccount; -}(); + throw new SolanaJSONRPCError(res.error, 'failed to get supply'); -var LookupTableMetaLayout = { - index: 1, - layout: struct([u32('typeIndex'), u64('deactivationSlot'), nu64$1('lastExtendedSlot'), u8('lastExtendedStartIndex'), u8(), // option - seq$1(publicKey(), offset$1(u8(), -1), 'authority')]) -}; -var URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i; + case 8: + return _context15.abrupt("return", res.result); -function makeWebsocketUrl(endpoint) { - var matches = endpoint.match(URL_RE); + case 9: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); - if (matches == null) { - throw TypeError("Failed to validate endpoint URL `".concat(endpoint, "`")); - } + function getSupply(_x28) { + return _getSupply.apply(this, arguments); + } - var _matches = _slicedToArray(matches, 4); - _matches[0]; - var // eslint-disable-line @typescript-eslint/no-unused-vars - hostish = _matches[1], - portWithColon = _matches[2], - rest = _matches[3]; + return getSupply; + }() + /** + * Fetch the current supply of a token mint + */ - var protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:'; - var startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10); - var websocketPort = // Only shift the port by +1 as a convention for ws(s) only if given endpoint - // is explictly specifying the endpoint port (HTTP-based RPC), assuming - // we're directly trying to connect to solana-validator's ws listening port. - // When the endpoint omits the port, we're connecting to the protocol - // default ports: http(80) or https(443) and it's assumed we're behind a reverse - // proxy which manages WebSocket upgrade and backend port redirection. - startPort == null ? '' : ":".concat(startPort + 1); - return "".concat(protocol, "//").concat(hostish).concat(websocketPort).concat(rest); -} + }, { + key: "getTokenSupply", + value: function () { + var _getTokenSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(tokenMintAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + args = this._buildArgs([tokenMintAddress.toBase58()], commitment); + _context16.next = 3; + return this._rpcRequest('getTokenSupply', args); -var PublicKeyFromString = coerce(instance(PublicKey), string(), function (value) { - return new PublicKey(value); -}); -var RawAccountDataResult = tuple([string(), literal('base64')]); -var BufferFromRawAccountData = coerce(instance(Buffer$1), RawAccountDataResult, function (value) { - return Buffer$1.from(value[0], 'base64'); -}); -/** - * Attempt to use a recent blockhash for up to 30 seconds - * @internal - */ + case 3: + unsafeRes = _context16.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); -var BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; -/** - * HACK. - * Copied from rpc-websockets/dist/lib/client. - * Otherwise, `yarn build` fails with: - * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d - */ + if (!('error' in res)) { + _context16.next = 7; + break; + } -/* @internal */ + throw new SolanaJSONRPCError(res.error, 'failed to get token supply'); -function assertEndpointUrl(putativeUrl) { - if (/^https?:/.test(putativeUrl) === false) { - throw new TypeError('Endpoint URL must start with `http:` or `https:`.'); - } + case 7: + return _context16.abrupt("return", res.result); - return putativeUrl; -} -/** @internal */ + case 8: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getTokenSupply(_x29, _x30) { + return _getTokenSupply.apply(this, arguments); + } -function extractCommitmentFromConfig(commitmentOrConfig) { - var commitment; - var config; + return getTokenSupply; + }() + /** + * Fetch the current balance of a token account + */ - if (typeof commitmentOrConfig === 'string') { - commitment = commitmentOrConfig; - } else if (commitmentOrConfig) { - var specifiedCommitment = commitmentOrConfig.commitment, - specifiedConfig = _objectWithoutProperties(commitmentOrConfig, _excluded); + }, { + key: "getTokenAccountBalance", + value: function () { + var _getTokenAccountBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(tokenAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + args = this._buildArgs([tokenAddress.toBase58()], commitment); + _context17.next = 3; + return this._rpcRequest('getTokenAccountBalance', args); - commitment = specifiedCommitment; - config = specifiedConfig; - } + case 3: + unsafeRes = _context17.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); - return { - commitment: commitment, - config: config - }; -} -/** - * @internal - */ + if (!('error' in res)) { + _context17.next = 7; + break; + } + throw new SolanaJSONRPCError(res.error, 'failed to get token account balance'); -function createRpcResult(result) { - return union([type({ - jsonrpc: literal('2.0'), - id: string(), - result: result - }), type({ - jsonrpc: literal('2.0'), - id: string(), - error: type({ - code: unknown(), - message: string(), - data: optional(any()) - }) - })]); -} + case 7: + return _context17.abrupt("return", res.result); -var UnknownRpcResult = createRpcResult(unknown()); -/** - * @internal - */ + case 8: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); -function jsonRpcResult(schema) { - return coerce(createRpcResult(schema), UnknownRpcResult, function (value) { - if ('error' in value) { - return value; - } else { - return _objectSpread2(_objectSpread2({}, value), {}, { - result: _create(value.result, schema) - }); - } - }); -} -/** - * @internal - */ + function getTokenAccountBalance(_x31, _x32) { + return _getTokenAccountBalance.apply(this, arguments); + } + return getTokenAccountBalance; + }() + /** + * Fetch all the token accounts owned by the specified account + * + * @return {Promise}>>>} + */ -function jsonRpcResultAndContext(value) { - return jsonRpcResult(type({ - context: type({ - slot: number() - }), - value: value - })); -} -/** - * @internal - */ + }, { + key: "getTokenAccountsByOwner", + value: function () { + var _getTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(ownerAddress, filter, commitmentOrConfig) { + var _extractCommitmentFro3, commitment, config, _args, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + _extractCommitmentFro3 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro3.commitment, config = _extractCommitmentFro3.config; + _args = [ownerAddress.toBase58()]; -function notificationResultAndContext(value) { - return type({ - context: type({ - slot: number() - }), - value: value - }); -} -/** - * @internal - */ + if ('mint' in filter) { + _args.push({ + mint: filter.mint.toBase58() + }); + } else { + _args.push({ + programId: filter.programId.toBase58() + }); + } + args = this._buildArgs(_args, commitment, 'base64', config); + _context18.next = 6; + return this._rpcRequest('getTokenAccountsByOwner', args); -function versionedMessageFromResponse(version, response) { - if (version === 0) { - return new MessageV0({ - header: response.header, - staticAccountKeys: response.accountKeys.map(function (accountKey) { - return new PublicKey(accountKey); - }), - recentBlockhash: response.recentBlockhash, - compiledInstructions: response.instructions.map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accountKeyIndexes: ix.accounts, - data: bs58$1.decode(ix.data) - }; - }), - addressTableLookups: response.addressTableLookups - }); - } else { - return new Message(response); - } -} -/** - * The level of commitment desired when querying state - *
- *   'processed': Query the most recent block which has reached 1 confirmation by the connected node
- *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
- *   'finalized': Query the most recent block which has been finalized by the cluster
- * 
- */ + case 6: + unsafeRes = _context18.sent; + res = _create(unsafeRes, GetTokenAccountsByOwner); + if (!('error' in res)) { + _context18.next = 10; + break; + } -var GetInflationGovernorResult = type({ - foundation: number(), - foundationTerm: number(), - initial: number(), - taper: number(), - terminal: number() -}); -/** - * The inflation reward for an epoch - */ + throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); -/** - * Expected JSON RPC response for the "getInflationReward" message - */ + case 10: + return _context18.abrupt("return", res.result); -var GetInflationRewardResult = jsonRpcResult(array(nullable(type({ - epoch: number(), - effectiveSlot: number(), - amount: number(), - postBalance: number(), - commission: optional(nullable(number())) -})))); -/** - * Expected JSON RPC response for the "getRecentPrioritizationFees" message - */ + case 11: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); -var GetRecentPrioritizationFeesResult = array(type({ - slot: number(), - prioritizationFee: number() -})); -/** - * Expected JSON RPC response for the "getInflationRate" message - */ + function getTokenAccountsByOwner(_x33, _x34, _x35) { + return _getTokenAccountsByOwner.apply(this, arguments); + } -var GetInflationRateResult = type({ - total: number(), - validator: number(), - foundation: number(), - epoch: number() -}); -/** - * Information about the current epoch - */ + return getTokenAccountsByOwner; + }() + /** + * Fetch parsed token accounts owned by the specified account + * + * @return {Promise}>>>} + */ -var GetEpochInfoResult = type({ - epoch: number(), - slotIndex: number(), - slotsInEpoch: number(), - absoluteSlot: number(), - blockHeight: optional(number()), - transactionCount: optional(number()) -}); -var GetEpochScheduleResult = type({ - slotsPerEpoch: number(), - leaderScheduleSlotOffset: number(), - warmup: _boolean(), - firstNormalEpoch: number(), - firstNormalSlot: number() -}); -/** - * Leader schedule - * (see https://docs.solana.com/terminology#leader-schedule) - */ + }, { + key: "getParsedTokenAccountsByOwner", + value: function () { + var _getParsedTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(ownerAddress, filter, commitment) { + var _args, args, unsafeRes, res; -var GetLeaderScheduleResult = record(string(), array(number())); -/** - * Transaction error or null - */ + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _args = [ownerAddress.toBase58()]; -var TransactionErrorResult = nullable(union([type({}), string()])); -/** - * Signature status for a transaction - */ + if ('mint' in filter) { + _args.push({ + mint: filter.mint.toBase58() + }); + } else { + _args.push({ + programId: filter.programId.toBase58() + }); + } -var SignatureStatusResult = type({ - err: TransactionErrorResult -}); -/** - * Transaction signature received notification - */ + args = this._buildArgs(_args, commitment, 'jsonParsed'); + _context19.next = 5; + return this._rpcRequest('getTokenAccountsByOwner', args); -var SignatureReceivedResult = literal('receivedSignature'); -/** - * Version info for a node - */ + case 5: + unsafeRes = _context19.sent; + res = _create(unsafeRes, GetParsedTokenAccountsByOwner); -var VersionResult = type({ - 'solana-core': string(), - 'feature-set': optional(number()) -}); -var SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({ - err: nullable(union([type({}), string()])), - logs: nullable(array(string())), - accounts: optional(nullable(array(nullable(type({ - executable: _boolean(), - owner: string(), - lamports: number(), - data: array(string()), - rentEpoch: optional(number()) - }))))), - unitsConsumed: optional(number()), - returnData: optional(nullable(type({ - programId: string(), - data: tuple([string(), literal('base64')]) - }))) -})); -/** - * Expected JSON RPC response for the "getBlockProduction" message - */ + if (!('error' in res)) { + _context19.next = 9; + break; + } + + throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); -var BlockProductionResponseStruct = jsonRpcResultAndContext(type({ - byIdentity: record(string(), array(number())), - range: type({ - firstSlot: number(), - lastSlot: number() - }) -})); -/** - * A performance sample - */ + case 9: + return _context19.abrupt("return", res.result); -function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) { - var fetch = customFetch ? customFetch : fetchImpl; - var agent; - { - if (httpAgent != null) { - console.warn('You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' + 'It has been ignored; `httpAgent` is only used in Node environments.'); - } - } - var fetchWithMiddleware; + case 10: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); - if (fetchMiddleware) { - fetchWithMiddleware = /*#__PURE__*/function () { - var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(info, init) { - var modifiedFetchArgs; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { + function getParsedTokenAccountsByOwner(_x36, _x37, _x38) { + return _getParsedTokenAccountsByOwner.apply(this, arguments); + } + + return getParsedTokenAccountsByOwner; + }() + /** + * Fetch the 20 largest accounts with their current balances + */ + + }, { + key: "getLargestAccounts", + value: function () { + var _getLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(config) { + var arg, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { case 0: - _context6.next = 2; - return new Promise(function (resolve, reject) { - try { - fetchMiddleware(info, init, function (modifiedInfo, modifiedInit) { - return resolve([modifiedInfo, modifiedInit]); - }); - } catch (error) { - reject(error); - } + arg = _objectSpread2(_objectSpread2({}, config), {}, { + commitment: config && config.commitment || this.commitment }); + args = arg.filter || arg.commitment ? [arg] : []; + _context20.next = 4; + return this._rpcRequest('getLargestAccounts', args); - case 2: - modifiedFetchArgs = _context6.sent; - _context6.next = 5; - return fetch.apply(void 0, _toConsumableArray(modifiedFetchArgs)); + case 4: + unsafeRes = _context20.sent; + res = _create(unsafeRes, GetLargestAccountsRpcResult); - case 5: - return _context6.abrupt("return", _context6.sent); + if (!('error' in res)) { + _context20.next = 8; + break; + } - case 6: + throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts'); + + case 8: + return _context20.abrupt("return", res.result); + + case 9: case "end": - return _context6.stop(); + return _context20.stop(); } - }, _callee6); + }, _callee20, this); })); - return function fetchWithMiddleware(_x18, _x19) { - return _ref22.apply(this, arguments); - }; - }(); - } + function getLargestAccounts(_x39) { + return _getLargestAccounts.apply(this, arguments); + } - var clientBrowser = new RpcClient( /*#__PURE__*/function () { - var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(request, callback) { - var options, too_many_requests_retries, res, waitTime, text; - return _regeneratorRuntime().wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - options = { - method: 'POST', - body: request, - agent: agent, - headers: Object.assign({ - 'Content-Type': 'application/json' - }, httpHeaders || {}, COMMON_HTTP_HEADERS) - }; - _context7.prev = 1; - too_many_requests_retries = 5; - waitTime = 500; + return getLargestAccounts; + }() + /** + * Fetch the 20 largest token accounts with their current balances + * for a given mint. + */ - case 4: - if (!fetchWithMiddleware) { - _context7.next = 10; - break; - } + }, { + key: "getTokenLargestAccounts", + value: function () { + var _getTokenLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(mintAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + args = this._buildArgs([mintAddress.toBase58()], commitment); + _context21.next = 3; + return this._rpcRequest('getTokenLargestAccounts', args); - _context7.next = 7; - return fetchWithMiddleware(url, options); + case 3: + unsafeRes = _context21.sent; + res = _create(unsafeRes, GetTokenLargestAccountsResult); - case 7: - res = _context7.sent; - _context7.next = 13; - break; + if (!('error' in res)) { + _context21.next = 7; + break; + } - case 10: - _context7.next = 12; - return fetch(url, options); + throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts'); - case 12: - res = _context7.sent; + case 7: + return _context21.abrupt("return", res.result); - case 13: - if (!(res.status !== 429 - /* Too many requests */ - )) { - _context7.next = 15; - break; - } + case 8: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); - return _context7.abrupt("break", 26); + function getTokenLargestAccounts(_x40, _x41) { + return _getTokenLargestAccounts.apply(this, arguments); + } - case 15: - if (!(disableRetryOnRateLimit === true)) { - _context7.next = 17; - break; - } + return getTokenLargestAccounts; + }() + /** + * Fetch all the account info for the specified public key, return with context + */ - return _context7.abrupt("break", 26); + }, { + key: "getAccountInfoAndContext", + value: function () { + var _getAccountInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(publicKey, commitmentOrConfig) { + var _extractCommitmentFro4, commitment, config, args, unsafeRes, res; - case 17: - too_many_requests_retries -= 1; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + _extractCommitmentFro4 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro4.commitment, config = _extractCommitmentFro4.config; + args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config); + _context22.next = 4; + return this._rpcRequest('getAccountInfo', args); - if (!(too_many_requests_retries === 0)) { - _context7.next = 20; - break; - } + case 4: + unsafeRes = _context22.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult))); - return _context7.abrupt("break", 26); + if (!('error' in res)) { + _context22.next = 8; + break; + } - case 20: - console.log("Server responded with ".concat(res.status, " ").concat(res.statusText, ". Retrying after ").concat(waitTime, "ms delay...")); - _context7.next = 23; - return sleep(waitTime); + throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); - case 23: - waitTime *= 2; + case 8: + return _context22.abrupt("return", res.result); - case 24: - _context7.next = 4; - break; + case 9: + case "end": + return _context22.stop(); + } + }, _callee22, this); + })); - case 26: - _context7.next = 28; - return res.text(); + function getAccountInfoAndContext(_x42, _x43) { + return _getAccountInfoAndContext.apply(this, arguments); + } - case 28: - text = _context7.sent; + return getAccountInfoAndContext; + }() + /** + * Fetch parsed account info for the specified public key + */ - if (res.ok) { - callback(null, text); - } else { - callback(new Error("".concat(res.status, " ").concat(res.statusText, ": ").concat(text))); - } + }, { + key: "getParsedAccountInfo", + value: function () { + var _getParsedAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(publicKey, commitmentOrConfig) { + var _extractCommitmentFro5, commitment, config, args, unsafeRes, res; - _context7.next = 35; - break; + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + _extractCommitmentFro5 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro5.commitment, config = _extractCommitmentFro5.config; + args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config); + _context23.next = 4; + return this._rpcRequest('getAccountInfo', args); - case 32: - _context7.prev = 32; - _context7.t0 = _context7["catch"](1); - if (_context7.t0 instanceof Error) callback(_context7.t0); + case 4: + unsafeRes = _context23.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult))); - case 35: - case "end": - return _context7.stop(); - } - }, _callee7, null, [[1, 32]]); - })); + if (!('error' in res)) { + _context23.next = 8; + break; + } - return function (_x20, _x21) { - return _ref23.apply(this, arguments); - }; - }(), {}); - return clientBrowser; -} + throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); -function createRpcRequest(client) { - return function (method, args) { - return new Promise(function (resolve, reject) { - client.request(method, args, function (err, response) { - if (err) { - reject(err); - return; - } + case 8: + return _context23.abrupt("return", res.result); - resolve(response); - }); - }); - }; -} + case 9: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); -function createRpcBatchRequest(client) { - return function (requests) { - return new Promise(function (resolve, reject) { - // Do nothing if requests is empty - if (requests.length === 0) resolve([]); - var batch = requests.map(function (params) { - return client.request(params.methodName, params.args); - }); - client.request(batch, function (err, response) { - if (err) { - reject(err); - return; - } + function getParsedAccountInfo(_x44, _x45) { + return _getParsedAccountInfo.apply(this, arguments); + } - resolve(response); - }); - }); - }; -} -/** - * Expected JSON RPC response for the "getInflationGovernor" message - */ + return getParsedAccountInfo; + }() + /** + * Fetch all the account info for the specified public key + */ + }, { + key: "getAccountInfo", + value: function () { + var _getAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(publicKey, commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + _context24.prev = 0; + _context24.next = 3; + return this.getAccountInfoAndContext(publicKey, commitmentOrConfig); -var GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult); -/** - * Expected JSON RPC response for the "getInflationRate" message - */ + case 3: + res = _context24.sent; + return _context24.abrupt("return", res.value); -var GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult); -/** - * Expected JSON RPC response for the "getRecentPrioritizationFees" message - */ + case 7: + _context24.prev = 7; + _context24.t0 = _context24["catch"](0); + throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + _context24.t0); -var GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult); -/** - * Expected JSON RPC response for the "getEpochInfo" message - */ + case 10: + case "end": + return _context24.stop(); + } + }, _callee24, this, [[0, 7]]); + })); -var GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult); -/** - * Expected JSON RPC response for the "getEpochSchedule" message - */ + function getAccountInfo(_x46, _x47) { + return _getAccountInfo.apply(this, arguments); + } -var GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult); -/** - * Expected JSON RPC response for the "getLeaderSchedule" message - */ + return getAccountInfo; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + */ -var GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult); -/** - * Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages - */ + }, { + key: "getMultipleParsedAccounts", + value: function () { + var _getMultipleParsedAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(publicKeys, rawConfig) { + var _extractCommitmentFro6, commitment, config, keys, args, unsafeRes, res; -var SlotRpcResult = jsonRpcResult(number()); -/** - * Supply - */ + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + _extractCommitmentFro6 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro6.commitment, config = _extractCommitmentFro6.config; + keys = publicKeys.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs([keys], commitment, 'jsonParsed', config); + _context25.next = 5; + return this._rpcRequest('getMultipleAccounts', args); -/** - * Expected JSON RPC response for the "getSupply" message - */ + case 5: + unsafeRes = _context25.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult)))); -var GetSupplyRpcResult = jsonRpcResultAndContext(type({ - total: number(), - circulating: number(), - nonCirculating: number(), - nonCirculatingAccounts: array(PublicKeyFromString) -})); -/** - * Token amount object which returns a token amount in different formats - * for various client use cases. - */ + if (!('error' in res)) { + _context25.next = 9; + break; + } -/** - * Expected JSON RPC structure for token amounts - */ + throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); -var TokenAmountResult = type({ - amount: string(), - uiAmount: nullable(number()), - decimals: number(), - uiAmountString: optional(string()) -}); -/** - * Token address and balance. - */ + case 9: + return _context25.abrupt("return", res.result); -/** - * Expected JSON RPC response for the "getTokenLargestAccounts" message - */ + case 10: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); -var GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({ - address: PublicKeyFromString, - amount: string(), - uiAmount: nullable(number()), - decimals: number(), - uiAmountString: optional(string()) -}))); -/** - * Expected JSON RPC response for the "getTokenAccountsByOwner" message - */ + function getMultipleParsedAccounts(_x48, _x49) { + return _getMultipleParsedAccounts.apply(this, arguments); + } -var GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ - pubkey: PublicKeyFromString, - account: type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: BufferFromRawAccountData, - rentEpoch: number() - }) -}))); -var ParsedAccountDataResult = type({ - program: string(), - parsed: unknown(), - space: number() -}); -/** - * Expected JSON RPC response for the "getTokenAccountsByOwner" message with parsed data - */ + return getMultipleParsedAccounts; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + */ -var GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ - pubkey: PublicKeyFromString, - account: type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: ParsedAccountDataResult, - rentEpoch: number() - }) -}))); -/** - * Pair of an account address and its balance - */ + }, { + key: "getMultipleAccountsInfoAndContext", + value: function () { + var _getMultipleAccountsInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(publicKeys, commitmentOrConfig) { + var _extractCommitmentFro7, commitment, config, keys, args, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee26$(_context26) { + while (1) switch (_context26.prev = _context26.next) { + case 0: + _extractCommitmentFro7 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro7.commitment, config = _extractCommitmentFro7.config; + keys = publicKeys.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs([keys], commitment, 'base64', config); + _context26.next = 5; + return this._rpcRequest('getMultipleAccounts', args); -/** - * Expected JSON RPC response for the "getLargestAccounts" message - */ + case 5: + unsafeRes = _context26.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult)))); -var GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({ - lamports: number(), - address: PublicKeyFromString -}))); -/** - * @internal - */ + if (!('error' in res)) { + _context26.next = 9; + break; + } -var AccountInfoResult = type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: BufferFromRawAccountData, - rentEpoch: number() -}); -/** - * @internal - */ + throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); -var KeyedAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: AccountInfoResult -}); -var ParsedOrRawAccountData = coerce(union([instance(Buffer$1), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), function (value) { - if (Array.isArray(value)) { - return _create(value, BufferFromRawAccountData); - } else { - return value; - } -}); -/** - * @internal - */ + case 9: + return _context26.abrupt("return", res.result); -var ParsedAccountInfoResult = type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: ParsedOrRawAccountData, - rentEpoch: number() -}); -var KeyedParsedAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: ParsedAccountInfoResult -}); -/** - * @internal - */ + case 10: + case "end": + return _context26.stop(); + } + }, _callee26, this); + })); -var StakeActivationResult = type({ - state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]), - active: number(), - inactive: number() -}); -/** - * Expected JSON RPC response for the "getConfirmedSignaturesForAddress2" message - */ + function getMultipleAccountsInfoAndContext(_x50, _x51) { + return _getMultipleAccountsInfoAndContext.apply(this, arguments); + } -var GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({ - signature: string(), - slot: number(), - err: TransactionErrorResult, - memo: nullable(string()), - blockTime: optional(nullable(number())) -}))); -/** - * Expected JSON RPC response for the "getSignaturesForAddress" message - */ + return getMultipleAccountsInfoAndContext; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys + */ -var GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({ - signature: string(), - slot: number(), - err: TransactionErrorResult, - memo: nullable(string()), - blockTime: optional(nullable(number())) -}))); -/*** - * Expected JSON RPC response for the "accountNotification" message - */ + }, { + key: "getMultipleAccountsInfo", + value: function () { + var _getMultipleAccountsInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27(publicKeys, commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee27$(_context27) { + while (1) switch (_context27.prev = _context27.next) { + case 0: + _context27.next = 2; + return this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig); -var AccountNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(AccountInfoResult) -}); -/** - * @internal - */ + case 2: + res = _context27.sent; + return _context27.abrupt("return", res.value); -var ProgramAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: AccountInfoResult -}); -/*** - * Expected JSON RPC response for the "programNotification" message - */ + case 4: + case "end": + return _context27.stop(); + } + }, _callee27, this); + })); -var ProgramAccountNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(ProgramAccountInfoResult) -}); -/** - * @internal - */ + function getMultipleAccountsInfo(_x52, _x53) { + return _getMultipleAccountsInfo.apply(this, arguments); + } -var SlotInfoResult = type({ - parent: number(), - slot: number(), - root: number() -}); -/** - * Expected JSON RPC response for the "slotNotification" message - */ + return getMultipleAccountsInfo; + }() + /** + * Returns epoch activation information for a stake account that has been delegated + */ -var SlotNotificationResult = type({ - subscription: number(), - result: SlotInfoResult -}); -/** - * Slot updates which can be used for tracking the live progress of a cluster. - * - `"firstShredReceived"`: connected node received the first shred of a block. - * Indicates that a new block that is being produced. - * - `"completed"`: connected node has received all shreds of a block. Indicates - * a block was recently produced. - * - `"optimisticConfirmation"`: block was optimistically confirmed by the - * cluster. It is not guaranteed that an optimistic confirmation notification - * will be sent for every finalized blocks. - * - `"root"`: the connected node rooted this block. - * - `"createdBank"`: the connected node has started validating this block. - * - `"frozen"`: the connected node has validated this block. - * - `"dead"`: the connected node failed to validate this block. - */ + }, { + key: "getStakeActivation", + value: function () { + var _getStakeActivation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28(publicKey, commitmentOrConfig, epoch) { + var _extractCommitmentFro8, commitment, config, args, unsafeRes, res; -/** - * @internal - */ + return _regeneratorRuntime().wrap(function _callee28$(_context28) { + while (1) switch (_context28.prev = _context28.next) { + case 0: + _extractCommitmentFro8 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro8.commitment, config = _extractCommitmentFro8.config; + args = this._buildArgs([publicKey.toBase58()], commitment, undefined + /* encoding */ + , _objectSpread2(_objectSpread2({}, config), {}, { + epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch + })); + _context28.next = 4; + return this._rpcRequest('getStakeActivation', args); -var SlotUpdateResult = union([type({ - type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]), - slot: number(), - timestamp: number() -}), type({ - type: literal('createdBank'), - parent: number(), - slot: number(), - timestamp: number() -}), type({ - type: literal('frozen'), - slot: number(), - timestamp: number(), - stats: type({ - numTransactionEntries: number(), - numSuccessfulTransactions: number(), - numFailedTransactions: number(), - maxTransactionsPerEntry: number() - }) -}), type({ - type: literal('dead'), - slot: number(), - timestamp: number(), - err: string() -})]); -/** - * Expected JSON RPC response for the "slotsUpdatesNotification" message - */ + case 4: + unsafeRes = _context28.sent; + res = _create(unsafeRes, jsonRpcResult(StakeActivationResult)); -var SlotUpdateNotificationResult = type({ - subscription: number(), - result: SlotUpdateResult -}); -/** - * Expected JSON RPC response for the "signatureNotification" message - */ + if (!('error' in res)) { + _context28.next = 8; + break; + } -var SignatureNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult])) -}); -/** - * Expected JSON RPC response for the "rootNotification" message - */ + throw new SolanaJSONRPCError(res.error, "failed to get Stake Activation ".concat(publicKey.toBase58())); -var RootNotificationResult = type({ - subscription: number(), - result: number() -}); -var ContactInfoResult = type({ - pubkey: string(), - gossip: nullable(string()), - tpu: nullable(string()), - rpc: nullable(string()), - version: nullable(string()) -}); -var VoteAccountInfoResult = type({ - votePubkey: string(), - nodePubkey: string(), - activatedStake: number(), - epochVoteAccount: _boolean(), - epochCredits: array(tuple([number(), number(), number()])), - commission: number(), - lastVote: number(), - rootSlot: nullable(number()) -}); -/** - * Expected JSON RPC response for the "getVoteAccounts" message - */ + case 8: + return _context28.abrupt("return", res.result); -var GetVoteAccounts = jsonRpcResult(type({ - current: array(VoteAccountInfoResult), - delinquent: array(VoteAccountInfoResult) -})); -var ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]); -var SignatureStatusResponse = type({ - slot: number(), - confirmations: nullable(number()), - err: TransactionErrorResult, - confirmationStatus: optional(ConfirmationStatus) -}); -/** - * Expected JSON RPC response for the "getSignatureStatuses" message - */ + case 9: + case "end": + return _context28.stop(); + } + }, _callee28, this); + })); -var GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse))); -/** - * Expected JSON RPC response for the "getMinimumBalanceForRentExemption" message - */ + function getStakeActivation(_x54, _x55, _x56) { + return _getStakeActivation.apply(this, arguments); + } -var GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number()); -var AddressTableLookupStruct = type({ - accountKey: PublicKeyFromString, - writableIndexes: array(number()), - readonlyIndexes: array(number()) -}); -var ConfirmedTransactionResult = type({ - signatures: array(string()), - message: type({ - accountKeys: array(string()), - header: type({ - numRequiredSignatures: number(), - numReadonlySignedAccounts: number(), - numReadonlyUnsignedAccounts: number() - }), - instructions: array(type({ - accounts: array(number()), - data: string(), - programIdIndex: number() - })), - recentBlockhash: string(), - addressTableLookups: optional(array(AddressTableLookupStruct)) - }) -}); -var AnnotatedAccountKey = type({ - pubkey: PublicKeyFromString, - signer: _boolean(), - writable: _boolean(), - source: optional(union([literal('transaction'), literal('lookupTable')])) -}); -var ConfirmedTransactionAccountsModeResult = type({ - accountKeys: array(AnnotatedAccountKey), - signatures: array(string()) -}); -var ParsedInstructionResult = type({ - parsed: unknown(), - program: string(), - programId: PublicKeyFromString -}); -var RawInstructionResult = type({ - accounts: array(PublicKeyFromString), - data: string(), - programId: PublicKeyFromString -}); -var InstructionResult = union([RawInstructionResult, ParsedInstructionResult]); -var UnknownInstructionResult = union([type({ - parsed: unknown(), - program: string(), - programId: string() -}), type({ - accounts: array(string()), - data: string(), - programId: string() -})]); -var ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, function (value) { - if ('accounts' in value) { - return _create(value, RawInstructionResult); - } else { - return _create(value, ParsedInstructionResult); - } -}); -/** - * @internal - */ + return getStakeActivation; + }() + /** + * Fetch all the accounts owned by the specified program id + * + * @return {Promise}>>} + */ -var ParsedConfirmedTransactionResult = type({ - signatures: array(string()), - message: type({ - accountKeys: array(AnnotatedAccountKey), - instructions: array(ParsedOrRawInstruction), - recentBlockhash: string(), - addressTableLookups: optional(nullable(array(AddressTableLookupStruct))) - }) -}); -var TokenBalanceResult = type({ - accountIndex: number(), - mint: string(), - owner: optional(string()), - uiTokenAmount: TokenAmountResult -}); -var LoadedAddressesResult = type({ - writable: array(PublicKeyFromString), - readonly: array(PublicKeyFromString) -}); -/** - * @internal - */ + }, { + key: "getProgramAccounts", + value: function () { + var _getProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee29(programId, configOrCommitment) { + var _extractCommitmentFro9, commitment, config, _ref26, encoding, configWithoutEncoding, args, unsafeRes, res; -var ConfirmedTransactionMetaResult = type({ - err: TransactionErrorResult, - fee: number(), - innerInstructions: optional(nullable(array(type({ - index: number(), - instructions: array(type({ - accounts: array(number()), - data: string(), - programIdIndex: number() - })) - })))), - preBalances: array(number()), - postBalances: array(number()), - logMessages: optional(nullable(array(string()))), - preTokenBalances: optional(nullable(array(TokenBalanceResult))), - postTokenBalances: optional(nullable(array(TokenBalanceResult))), - loadedAddresses: optional(LoadedAddressesResult), - computeUnitsConsumed: optional(number()) -}); -/** - * @internal - */ + return _regeneratorRuntime().wrap(function _callee29$(_context29) { + while (1) switch (_context29.prev = _context29.next) { + case 0: + _extractCommitmentFro9 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro9.commitment, config = _extractCommitmentFro9.config; + _ref26 = config || {}, encoding = _ref26.encoding, configWithoutEncoding = _objectWithoutProperties(_ref26, _excluded2); + args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', configWithoutEncoding); + _context29.next = 5; + return this._rpcRequest('getProgramAccounts', args); -var ParsedConfirmedTransactionMetaResult = type({ - err: TransactionErrorResult, - fee: number(), - innerInstructions: optional(nullable(array(type({ - index: number(), - instructions: array(ParsedOrRawInstruction) - })))), - preBalances: array(number()), - postBalances: array(number()), - logMessages: optional(nullable(array(string()))), - preTokenBalances: optional(nullable(array(TokenBalanceResult))), - postTokenBalances: optional(nullable(array(TokenBalanceResult))), - loadedAddresses: optional(LoadedAddressesResult), - computeUnitsConsumed: optional(number()) -}); -var TransactionVersionStruct = union([literal(0), literal('legacy')]); -/** @internal */ + case 5: + unsafeRes = _context29.sent; + res = _create(unsafeRes, jsonRpcResult(array(KeyedAccountInfoResult))); -var RewardsResult = type({ - pubkey: string(), - lamports: number(), - postBalance: nullable(number()), - rewardType: nullable(string()), - commission: optional(nullable(number())) -}); -/** - * Expected JSON RPC response for the "getBlock" message - */ + if (!('error' in res)) { + _context29.next = 9; + break; + } -var GetBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionResult, - meta: nullable(ConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `none` - */ + throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); -var GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` - */ + case 9: + return _context29.abrupt("return", res.result); -var GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionAccountsModeResult, - meta: nullable(ConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected parsed JSON RPC response for the "getBlock" message - */ + case 10: + case "end": + return _context29.stop(); + } + }, _callee29, this); + })); -var GetParsedBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ParsedConfirmedTransactionResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` - */ + function getProgramAccounts(_x57, _x58) { + return _getProgramAccounts.apply(this, arguments); + } -var GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionAccountsModeResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `none` - */ + return getProgramAccounts; + }() + /** + * Fetch and parse all the accounts owned by the specified program id + * + * @return {Promise}>>} + */ -var GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) -}))); -/** - * Expected JSON RPC response for the "getConfirmedBlock" message - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead. - */ + }, { + key: "getParsedProgramAccounts", + value: function () { + var _getParsedProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee30(programId, configOrCommitment) { + var _extractCommitmentFro10, commitment, config, args, unsafeRes, res; -var GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionResult, - meta: nullable(ConfirmedTransactionMetaResult) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()) -}))); -/** - * Expected JSON RPC response for the "getBlock" message - */ + return _regeneratorRuntime().wrap(function _callee30$(_context30) { + while (1) switch (_context30.prev = _context30.next) { + case 0: + _extractCommitmentFro10 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro10.commitment, config = _extractCommitmentFro10.config; + args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config); + _context30.next = 4; + return this._rpcRequest('getProgramAccounts', args); -var GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - signatures: array(string()), - blockTime: nullable(number()) -}))); -/** - * Expected JSON RPC response for the "getTransaction" message - */ + case 4: + unsafeRes = _context30.sent; + res = _create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult))); -var GetTransactionRpcResult = jsonRpcResult(nullable(type({ - slot: number(), - meta: ConfirmedTransactionMetaResult, - blockTime: optional(nullable(number())), - transaction: ConfirmedTransactionResult, - version: optional(TransactionVersionStruct) -}))); -/** - * Expected parsed JSON RPC response for the "getTransaction" message - */ + if (!('error' in res)) { + _context30.next = 8; + break; + } -var GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({ - slot: number(), - transaction: ParsedConfirmedTransactionResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - blockTime: optional(nullable(number())), - version: optional(TransactionVersionStruct) -}))); -/** - * Expected JSON RPC response for the "getRecentBlockhash" message - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead. - */ + throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); -var GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(type({ - blockhash: string(), - feeCalculator: type({ - lamportsPerSignature: number() - }) -})); -/** - * Expected JSON RPC response for the "getLatestBlockhash" message - */ + case 8: + return _context30.abrupt("return", res.result); -var GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({ - blockhash: string(), - lastValidBlockHeight: number() -})); -var PerfSampleResult = type({ - slot: number(), - numTransactions: number(), - numSlots: number(), - samplePeriodSecs: number() -}); -/* - * Expected JSON RPC response for "getRecentPerformanceSamples" message - */ + case 9: + case "end": + return _context30.stop(); + } + }, _callee30, this); + })); -var GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult)); -/** - * Expected JSON RPC response for the "getFeeCalculatorForBlockhash" message - */ + function getParsedProgramAccounts(_x59, _x60) { + return _getParsedProgramAccounts.apply(this, arguments); + } -var GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({ - feeCalculator: type({ - lamportsPerSignature: number() - }) -}))); -/** - * Expected JSON RPC response for the "requestAirdrop" message - */ + return getParsedProgramAccounts; + }() // eslint-disable-next-line no-dupe-class-members -var RequestAirdropRpcResult = jsonRpcResult(string()); -/** - * Expected JSON RPC response for the "sendTransaction" message - */ + }, { + key: "confirmTransaction", + value: function () { + var _confirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee31(strategy, commitment) { + var rawSignature, _config$abortSignal, config, decodedSignature; -var SendTransactionRpcResult = jsonRpcResult(string()); -/** - * Information about the latest slot being processed by a node - */ + return _regeneratorRuntime().wrap(function _callee31$(_context31) { + while (1) switch (_context31.prev = _context31.next) { + case 0: + if (!(typeof strategy == 'string')) { + _context31.next = 4; + break; + } -/** - * @internal - */ + rawSignature = strategy; + _context31.next = 8; + break; -var LogsResult = type({ - err: TransactionErrorResult, - logs: array(string()), - signature: string() -}); -/** - * Logs result. - */ + case 4: + config = strategy; -/** - * Expected JSON RPC response for the "logsNotification" message. - */ + if (!((_config$abortSignal = config.abortSignal) !== null && _config$abortSignal !== void 0 && _config$abortSignal.aborted)) { + _context31.next = 7; + break; + } -var LogsNotificationResult = type({ - result: notificationResultAndContext(LogsResult), - subscription: number() -}); -/** - * Filter for log subscriptions. - */ + return _context31.abrupt("return", Promise.reject(config.abortSignal.reason)); -/** @internal */ + case 7: + rawSignature = config.signature; -var COMMON_HTTP_HEADERS = { - 'solana-client': "js/".concat("0.0.0-development") -}; -/** - * A connection to a fullnode JSON RPC endpoint - */ + case 8: + _context31.prev = 8; + decodedSignature = bs58$3.decode(rawSignature); + _context31.next = 15; + break; -var Connection = /*#__PURE__*/function () { - /** @internal */ + case 12: + _context31.prev = 12; + _context31.t0 = _context31["catch"](8); + throw new Error('signature must be base58 encoded: ' + rawSignature); - /** @internal */ + case 15: + assert(decodedSignature.length === 64, 'signature has invalid length'); - /** @internal */ + if (!(typeof strategy === 'string')) { + _context31.next = 22; + break; + } - /** @internal */ + _context31.next = 19; + return this.confirmTransactionUsingLegacyTimeoutStrategy({ + commitment: commitment || this.commitment, + signature: rawSignature + }); - /** @internal */ + case 19: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 22: + if (!('lastValidBlockHeight' in strategy)) { + _context31.next = 28; + break; + } - /** @internal */ + _context31.next = 25; + return this.confirmTransactionUsingBlockHeightExceedanceStrategy({ + commitment: commitment || this.commitment, + strategy: strategy + }); - /** @internal */ + case 25: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 28: + _context31.next = 30; + return this.confirmTransactionUsingDurableNonceStrategy({ + commitment: commitment || this.commitment, + strategy: strategy + }); - /** @internal */ + case 30: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 31: + case "end": + return _context31.stop(); + } + }, _callee31, this, [[8, 12]]); + })); - /** @internal - * A number that we increment every time an active connection closes. - * Used to determine whether the same socket connection that was open - * when an async operation started is the same one that's active when - * its continuation fires. - * - */ + function confirmTransaction(_x61, _x62) { + return _confirmTransaction.apply(this, arguments); + } - /** @internal */ + return confirmTransaction; + }() + }, { + key: "getCancellationPromise", + value: function getCancellationPromise(signal) { + return new Promise(function (_, reject) { + if (signal == null) { + return; + } - /** @internal */ + if (signal.aborted) { + reject(signal.reason); + } else { + signal.addEventListener('abort', function () { + reject(signal.reason); + }); + } + }); + } + }, { + key: "getTransactionConfirmationPromise", + value: function getTransactionConfirmationPromise(_ref27) { + var _this16 = this; - /** @internal */ + var commitment = _ref27.commitment, + signature = _ref27.signature; + var signatureSubscriptionId; + var disposeSignatureSubscriptionStateChangeObserver; + var done = false; + var confirmationPromise = new Promise(function (resolve, reject) { + try { + signatureSubscriptionId = _this16.onSignature(signature, function (result, context) { + signatureSubscriptionId = undefined; + var response = { + context: context, + value: result + }; + resolve({ + __type: TransactionStatus.PROCESSED, + response: response + }); + }, commitment); + var subscriptionSetupPromise = new Promise(function (resolveSubscriptionSetup) { + if (signatureSubscriptionId == null) { + resolveSubscriptionSetup(); + } else { + disposeSignatureSubscriptionStateChangeObserver = _this16._onSubscriptionStateChange(signatureSubscriptionId, function (nextState) { + if (nextState === 'subscribed') { + resolveSubscriptionSetup(); + } + }); + } + }); - /** @internal */ + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee32() { + var response, context, value; + return _regeneratorRuntime().wrap(function _callee32$(_context32) { + while (1) switch (_context32.prev = _context32.next) { + case 0: + _context32.next = 2; + return subscriptionSetupPromise; - /** @internal */ + case 2: + if (!done) { + _context32.next = 4; + break; + } - /** @internal */ + return _context32.abrupt("return"); - /** @internal */ + case 4: + _context32.next = 6; + return _this16.getSignatureStatus(signature); - /** @internal */ + case 6: + response = _context32.sent; - /** @internal */ + if (!done) { + _context32.next = 9; + break; + } - /** - * Special case. - * After a signature is processed, RPCs automatically dispose of the - * subscription on the server side. We need to track which of these - * subscriptions have been disposed in such a way, so that we know - * whether the client is dealing with a not-yet-processed signature - * (in which case we must tear down the server subscription) or an - * already-processed signature (in which case the client can simply - * clear out the subscription locally without telling the server). - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ + return _context32.abrupt("return"); - /** @internal */ + case 9: + if (!(response == null)) { + _context32.next = 11; + break; + } - /** - * Establish a JSON RPC connection - * - * @param endpoint URL to the fullnode JSON RPC endpoint - * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object - */ - function Connection(endpoint, _commitmentOrConfig) { - var _this15 = this; + return _context32.abrupt("return"); - _classCallCheck(this, Connection); + case 11: + context = response.context, value = response.value; - this._commitment = void 0; - this._confirmTransactionInitialTimeout = void 0; - this._rpcEndpoint = void 0; - this._rpcWsEndpoint = void 0; - this._rpcClient = void 0; - this._rpcRequest = void 0; - this._rpcBatchRequest = void 0; - this._rpcWebSocket = void 0; - this._rpcWebSocketConnected = false; - this._rpcWebSocketHeartbeat = null; - this._rpcWebSocketIdleTimeout = null; - this._rpcWebSocketGeneration = 0; - this._disableBlockhashCaching = false; - this._pollingBlockhash = false; - this._blockhashInfo = { - latestBlockhash: null, - lastFetch: 0, - transactionSignatures: [], - simulatedSignatures: [] - }; - this._nextClientSubscriptionId = 0; - this._subscriptionDisposeFunctionsByClientSubscriptionId = {}; - this._subscriptionHashByClientSubscriptionId = {}; - this._subscriptionStateChangeCallbacksByHash = {}; - this._subscriptionCallbacksByServerSubscriptionId = {}; - this._subscriptionsByHash = {}; - this._subscriptionsAutoDisposedByRpc = new Set(); + if (!(value == null)) { + _context32.next = 14; + break; + } - this.getBlockHeight = function () { - var requestPromises = {}; - return /*#__PURE__*/function () { - var _ref24 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(commitmentOrConfig) { - var _requestPromises$requ; + return _context32.abrupt("return"); - var _extractCommitmentFro, commitment, config, args, requestHash; + case 14: + if (!(value !== null && value !== void 0 && value.err)) { + _context32.next = 18; + break; + } - return _regeneratorRuntime().wrap(function _callee9$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - _extractCommitmentFro = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro.commitment, config = _extractCommitmentFro.config; - args = _this15._buildArgs([], commitment, undefined - /* encoding */ - , config); - requestHash = fastStableStringify$1(args); - requestPromises[requestHash] = (_requestPromises$requ = requestPromises[requestHash]) !== null && _requestPromises$requ !== void 0 ? _requestPromises$requ : _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _context8.prev = 0; - _context8.next = 3; - return _this15._rpcRequest('getBlockHeight', args); + reject(value.err); + _context32.next = 29; + break; - case 3: - unsafeRes = _context8.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + case 18: + _context32.t0 = commitment; + _context32.next = _context32.t0 === 'confirmed' ? 21 : _context32.t0 === 'single' ? 21 : _context32.t0 === 'singleGossip' ? 21 : _context32.t0 === 'finalized' ? 24 : _context32.t0 === 'max' ? 24 : _context32.t0 === 'root' ? 24 : _context32.t0 === 'processed' ? 27 : _context32.t0 === 'recent' ? 27 : 27; + break; - if (!('error' in res)) { - _context8.next = 7; - break; - } + case 21: + if (!(value.confirmationStatus === 'processed')) { + _context32.next = 23; + break; + } - throw new SolanaJSONRPCError(res.error, 'failed to get block height information'); + return _context32.abrupt("return"); - case 7: - return _context8.abrupt("return", res.result); + case 23: + return _context32.abrupt("break", 27); - case 8: - _context8.prev = 8; - delete requestPromises[requestHash]; - return _context8.finish(8); + case 24: + if (!(value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed')) { + _context32.next = 26; + break; + } + + return _context32.abrupt("return"); + + case 26: + return _context32.abrupt("break", 27); - case 11: - case "end": - return _context8.stop(); + case 27: + done = true; + resolve({ + __type: TransactionStatus.PROCESSED, + response: { + context: context, + value: value } - }, _callee8, null, [[0,, 8, 11]]); - }))(); - _context9.next = 6; - return requestPromises[requestHash]; + }); - case 6: - return _context9.abrupt("return", _context9.sent); + case 29: + case "end": + return _context32.stop(); + } + }, _callee32); + }))(); + } catch (err) { + reject(err); + } + }); - case 7: - case "end": - return _context9.stop(); - } - }, _callee9); - })); + var abortConfirmation = function abortConfirmation() { + if (disposeSignatureSubscriptionStateChangeObserver) { + disposeSignatureSubscriptionStateChangeObserver(); + disposeSignatureSubscriptionStateChangeObserver = undefined; + } - return function (_x22) { - return _ref24.apply(this, arguments); - }; - }(); - }(); + if (signatureSubscriptionId != null) { + _this16.removeSignatureListener(signatureSubscriptionId); - var wsEndpoint; - var httpHeaders; - var fetch; - var fetchMiddleware; - var disableRetryOnRateLimit; - var httpAgent; + signatureSubscriptionId = undefined; + } + }; - if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') { - this._commitment = _commitmentOrConfig; - } else if (_commitmentOrConfig) { - this._commitment = _commitmentOrConfig.commitment; - this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout; - wsEndpoint = _commitmentOrConfig.wsEndpoint; - httpHeaders = _commitmentOrConfig.httpHeaders; - fetch = _commitmentOrConfig.fetch; - fetchMiddleware = _commitmentOrConfig.fetchMiddleware; - disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit; - httpAgent = _commitmentOrConfig.httpAgent; + return { + abortConfirmation: abortConfirmation, + confirmationPromise: confirmationPromise + }; } + }, { + key: "confirmTransactionUsingBlockHeightExceedanceStrategy", + value: function () { + var _confirmTransactionUsingBlockHeightExceedanceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee35(_ref29) { + var _this17 = this; - this._rpcEndpoint = assertEndpointUrl(endpoint); - this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint); - this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent); - this._rpcRequest = createRpcRequest(this._rpcClient); - this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient); - this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, { - autoconnect: false, - max_reconnects: Infinity - }); + var commitment, _ref29$strategy, abortSignal, lastValidBlockHeight, signature, done, expiryPromise, _this$getTransactionC, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome; - this._rpcWebSocket.on('open', this._wsOnOpen.bind(this)); + return _regeneratorRuntime().wrap(function _callee35$(_context35) { + while (1) switch (_context35.prev = _context35.next) { + case 0: + commitment = _ref29.commitment, _ref29$strategy = _ref29.strategy, abortSignal = _ref29$strategy.abortSignal, lastValidBlockHeight = _ref29$strategy.lastValidBlockHeight, signature = _ref29$strategy.signature; + done = false; + expiryPromise = new Promise(function (resolve) { + var checkBlockHeight = /*#__PURE__*/function () { + var _ref30 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee33() { + var blockHeight; + return _regeneratorRuntime().wrap(function _callee33$(_context33) { + while (1) switch (_context33.prev = _context33.next) { + case 0: + _context33.prev = 0; + _context33.next = 3; + return _this17.getBlockHeight(commitment); - this._rpcWebSocket.on('error', this._wsOnError.bind(this)); + case 3: + blockHeight = _context33.sent; + return _context33.abrupt("return", blockHeight); - this._rpcWebSocket.on('close', this._wsOnClose.bind(this)); + case 7: + _context33.prev = 7; + _context33.t0 = _context33["catch"](0); + return _context33.abrupt("return", -1); - this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this)); + case 10: + case "end": + return _context33.stop(); + } + }, _callee33, null, [[0, 7]]); + })); - this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this)); + return function checkBlockHeight() { + return _ref30.apply(this, arguments); + }; + }(); - this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this)); + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee34() { + var currentBlockHeight; + return _regeneratorRuntime().wrap(function _callee34$(_context34) { + while (1) switch (_context34.prev = _context34.next) { + case 0: + _context34.next = 2; + return checkBlockHeight(); - this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this)); + case 2: + currentBlockHeight = _context34.sent; - this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this)); + if (!done) { + _context34.next = 5; + break; + } - this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this)); + return _context34.abrupt("return"); - this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this)); - } - /** - * The default commitment used for requests - */ + case 5: + if (!(currentBlockHeight <= lastValidBlockHeight)) { + _context34.next = 17; + break; + } + _context34.next = 8; + return sleep(1000); - _createClass(Connection, [{ - key: "commitment", - get: function get() { - return this._commitment; - } - /** - * The RPC endpoint - */ + case 8: + if (!done) { + _context34.next = 10; + break; + } - }, { - key: "rpcEndpoint", - get: function get() { - return this._rpcEndpoint; - } - /** - * Fetch the balance for the specified public key, return with context - */ + return _context34.abrupt("return"); - }, { - key: "getBalanceAndContext", - value: function () { - var _getBalanceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(publicKey, commitmentOrConfig) { - var _extractCommitmentFro2, commitment, config, args, unsafeRes, res; + case 10: + _context34.next = 12; + return checkBlockHeight(); - return _regeneratorRuntime().wrap(function _callee10$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - /** @internal */ - _extractCommitmentFro2 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro2.commitment, config = _extractCommitmentFro2.config; - args = this._buildArgs([publicKey.toBase58()], commitment, undefined - /* encoding */ - , config); - _context10.next = 4; - return this._rpcRequest('getBalance', args); + case 12: + currentBlockHeight = _context34.sent; - case 4: - unsafeRes = _context10.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(number())); + if (!done) { + _context34.next = 15; + break; + } - if (!('error' in res)) { - _context10.next = 8; - break; - } + return _context34.abrupt("return"); - throw new SolanaJSONRPCError(res.error, "failed to get balance for ".concat(publicKey.toBase58())); + case 15: + _context34.next = 5; + break; + + case 17: + resolve({ + __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED + }); + + case 18: + case "end": + return _context34.stop(); + } + }, _callee34); + }))(); + }); + _this$getTransactionC = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC.abortConfirmation, confirmationPromise = _this$getTransactionC.confirmationPromise; + cancellationPromise = this.getCancellationPromise(abortSignal); + _context35.prev = 5; + _context35.next = 8; + return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); case 8: - return _context10.abrupt("return", res.result); + outcome = _context35.sent; - case 9: - case "end": - return _context10.stop(); - } - }, _callee10, this); - })); + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context35.next = 13; + break; + } - function getBalanceAndContext(_x23, _x24) { - return _getBalanceAndContext.apply(this, arguments); - } + result = outcome.response; + _context35.next = 14; + break; - return getBalanceAndContext; - }() - /** - * Fetch the balance for the specified public key - */ + case 13: + throw new TransactionExpiredBlockheightExceededError(signature); - }, { - key: "getBalance", - value: function () { - var _getBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(publicKey, commitmentOrConfig) { - return _regeneratorRuntime().wrap(function _callee11$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return this.getBalanceAndContext(publicKey, commitmentOrConfig).then(function (x) { - return x.value; - })["catch"](function (e) { - throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e); - }); + case 14: + _context35.prev = 14; + done = true; + abortConfirmation(); + return _context35.finish(14); - case 2: - return _context11.abrupt("return", _context11.sent); + case 18: + return _context35.abrupt("return", result); - case 3: + case 19: case "end": - return _context11.stop(); + return _context35.stop(); } - }, _callee11, this); + }, _callee35, this, [[5,, 14, 18]]); })); - function getBalance(_x25, _x26) { - return _getBalance.apply(this, arguments); + function confirmTransactionUsingBlockHeightExceedanceStrategy(_x63) { + return _confirmTransactionUsingBlockHeightExceedanceStrategy.apply(this, arguments); } - return getBalance; + return confirmTransactionUsingBlockHeightExceedanceStrategy; }() - /** - * Fetch the estimated production time of a block - */ - }, { - key: "getBlockTime", + key: "confirmTransactionUsingDurableNonceStrategy", value: function () { - var _getBlockTime = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(slot) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee12$(_context12) { - while (1) switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return this._rpcRequest('getBlockTime', [slot]); + var _confirmTransactionUsingDurableNonceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee38(_ref32) { + var _this18 = this; - case 2: - unsafeRes = _context12.sent; - res = _create(unsafeRes, jsonRpcResult(nullable(number()))); + var commitment, _ref32$strategy, abortSignal, minContextSlot, nonceAccountPubkey, nonceValue, signature, done, expiryPromise, _this$getTransactionC2, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome, _signatureStatus, signatureStatus, _outcome$slotInWhichN, status, commitmentForStatus, confirmationStatus; - if (!('error' in res)) { - _context12.next = 6; - break; - } + return _regeneratorRuntime().wrap(function _callee38$(_context38) { + while (1) switch (_context38.prev = _context38.next) { + case 0: + commitment = _ref32.commitment, _ref32$strategy = _ref32.strategy, abortSignal = _ref32$strategy.abortSignal, minContextSlot = _ref32$strategy.minContextSlot, nonceAccountPubkey = _ref32$strategy.nonceAccountPubkey, nonceValue = _ref32$strategy.nonceValue, signature = _ref32$strategy.signature; + done = false; + expiryPromise = new Promise(function (resolve) { + var currentNonceValue = nonceValue; + var lastCheckedSlot = null; - throw new SolanaJSONRPCError(res.error, "failed to get block time for slot ".concat(slot)); + var getCurrentNonceValue = /*#__PURE__*/function () { + var _ref33 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36() { + var _yield$_this18$getNon2, context, nonceAccount; - case 6: - return _context12.abrupt("return", res.result); + return _regeneratorRuntime().wrap(function _callee36$(_context36) { + while (1) switch (_context36.prev = _context36.next) { + case 0: + _context36.prev = 0; + _context36.next = 3; + return _this18.getNonceAndContext(nonceAccountPubkey, { + commitment: commitment, + minContextSlot: minContextSlot + }); - case 7: - case "end": - return _context12.stop(); - } - }, _callee12, this); - })); + case 3: + _yield$_this18$getNon2 = _context36.sent; + context = _yield$_this18$getNon2.context; + nonceAccount = _yield$_this18$getNon2.value; + lastCheckedSlot = context.slot; + return _context36.abrupt("return", nonceAccount === null || nonceAccount === void 0 ? void 0 : nonceAccount.nonce); - function getBlockTime(_x27) { - return _getBlockTime.apply(this, arguments); - } + case 10: + _context36.prev = 10; + _context36.t0 = _context36["catch"](0); + return _context36.abrupt("return", currentNonceValue); - return getBlockTime; - }() - /** - * Fetch the lowest slot that the node has information about in its ledger. - * This value may increase over time if the node is configured to purge older ledger data - */ + case 13: + case "end": + return _context36.stop(); + } + }, _callee36, null, [[0, 10]]); + })); - }, { - key: "getMinimumLedgerSlot", - value: function () { - var _getMinimumLedgerSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee13$(_context13) { - while (1) switch (_context13.prev = _context13.next) { - case 0: - _context13.next = 2; - return this._rpcRequest('minimumLedgerSlot', []); + return function getCurrentNonceValue() { + return _ref33.apply(this, arguments); + }; + }(); - case 2: - unsafeRes = _context13.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee37() { + return _regeneratorRuntime().wrap(function _callee37$(_context37) { + while (1) switch (_context37.prev = _context37.next) { + case 0: + _context37.next = 2; + return getCurrentNonceValue(); - if (!('error' in res)) { - _context13.next = 6; - break; - } + case 2: + currentNonceValue = _context37.sent; - throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot'); + if (!done) { + _context37.next = 5; + break; + } - case 6: - return _context13.abrupt("return", res.result); + return _context37.abrupt("return"); - case 7: - case "end": - return _context13.stop(); - } - }, _callee13, this); - })); + case 5: - function getMinimumLedgerSlot() { - return _getMinimumLedgerSlot.apply(this, arguments); - } + if (!(nonceValue !== currentNonceValue)) { + _context37.next = 9; + break; + } - return getMinimumLedgerSlot; - }() - /** - * Fetch the slot of the lowest confirmed block that has not been purged from the ledger - */ + resolve({ + __type: TransactionStatus.NONCE_INVALID, + slotInWhichNonceDidAdvance: lastCheckedSlot + }); + return _context37.abrupt("return"); - }, { - key: "getFirstAvailableBlock", - value: function () { - var _getFirstAvailableBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee14$(_context14) { - while (1) switch (_context14.prev = _context14.next) { - case 0: - _context14.next = 2; - return this._rpcRequest('getFirstAvailableBlock', []); + case 9: + _context37.next = 11; + return sleep(2000); - case 2: - unsafeRes = _context14.sent; - res = _create(unsafeRes, SlotRpcResult); + case 11: + if (!done) { + _context37.next = 13; + break; + } - if (!('error' in res)) { - _context14.next = 6; - break; - } + return _context37.abrupt("return"); - throw new SolanaJSONRPCError(res.error, 'failed to get first available block'); + case 13: + _context37.next = 15; + return getCurrentNonceValue(); - case 6: - return _context14.abrupt("return", res.result); + case 15: + currentNonceValue = _context37.sent; - case 7: - case "end": - return _context14.stop(); - } - }, _callee14, this); - })); + if (!done) { + _context37.next = 18; + break; + } - function getFirstAvailableBlock() { - return _getFirstAvailableBlock.apply(this, arguments); - } + return _context37.abrupt("return"); - return getFirstAvailableBlock; - }() - /** - * Fetch information about the current supply - */ + case 18: + _context37.next = 5; + break; - }, { - key: "getSupply", - value: function () { - var _getSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(config) { - var configArg, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee15$(_context15) { - while (1) switch (_context15.prev = _context15.next) { - case 0: - configArg = {}; + case 20: + case "end": + return _context37.stop(); + } + }, _callee37); + }))(); + }); + _this$getTransactionC2 = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC2.abortConfirmation, confirmationPromise = _this$getTransactionC2.confirmationPromise; + cancellationPromise = this.getCancellationPromise(abortSignal); + _context38.prev = 5; + _context38.next = 8; + return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + + case 8: + outcome = _context38.sent; - if (typeof config === 'string') { - configArg = { - commitment: config - }; - } else if (config) { - configArg = _objectSpread2(_objectSpread2({}, config), {}, { - commitment: config && config.commitment || this.commitment - }); - } else { - configArg = { - commitment: this.commitment - }; + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context38.next = 13; + break; } - _context15.next = 4; - return this._rpcRequest('getSupply', [configArg]); + result = outcome.response; + _context38.next = 47; + break; - case 4: - unsafeRes = _context15.sent; - res = _create(unsafeRes, GetSupplyRpcResult); + case 13: - if (!('error' in res)) { - _context15.next = 8; - break; - } + _context38.next = 16; + return this.getSignatureStatus(signature); - throw new SolanaJSONRPCError(res.error, 'failed to get supply'); + case 16: + status = _context38.sent; - case 8: - return _context15.abrupt("return", res.result); + if (!(status == null)) { + _context38.next = 19; + break; + } - case 9: - case "end": - return _context15.stop(); - } - }, _callee15, this); - })); + return _context38.abrupt("break", 27); - function getSupply(_x28) { - return _getSupply.apply(this, arguments); - } + case 19: + if (!(status.context.slot < ((_outcome$slotInWhichN = outcome.slotInWhichNonceDidAdvance) !== null && _outcome$slotInWhichN !== void 0 ? _outcome$slotInWhichN : minContextSlot))) { + _context38.next = 23; + break; + } - return getSupply; - }() - /** - * Fetch the current supply of a token mint - */ + _context38.next = 22; + return sleep(400); - }, { - key: "getTokenSupply", - value: function () { - var _getTokenSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(tokenMintAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee16$(_context16) { - while (1) switch (_context16.prev = _context16.next) { - case 0: - args = this._buildArgs([tokenMintAddress.toBase58()], commitment); - _context16.next = 3; - return this._rpcRequest('getTokenSupply', args); + case 22: + return _context38.abrupt("continue", 13); - case 3: - unsafeRes = _context16.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); + case 23: + signatureStatus = status; + return _context38.abrupt("break", 27); - if (!('error' in res)) { - _context16.next = 7; + case 27: + if (!((_signatureStatus = signatureStatus) !== null && _signatureStatus !== void 0 && _signatureStatus.value)) { + _context38.next = 46; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token supply'); + commitmentForStatus = commitment || 'finalized'; + confirmationStatus = signatureStatus.value.confirmationStatus; + _context38.t0 = commitmentForStatus; + _context38.next = _context38.t0 === 'processed' ? 33 : _context38.t0 === 'recent' ? 33 : _context38.t0 === 'confirmed' ? 36 : _context38.t0 === 'single' ? 36 : _context38.t0 === 'singleGossip' ? 36 : _context38.t0 === 'finalized' ? 39 : _context38.t0 === 'max' ? 39 : _context38.t0 === 'root' ? 39 : 42; + break; - case 7: - return _context16.abrupt("return", res.result); + case 33: + if (!(confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { + _context38.next = 35; + break; + } - case 8: - case "end": - return _context16.stop(); - } - }, _callee16, this); - })); + throw new TransactionExpiredNonceInvalidError(signature); - function getTokenSupply(_x29, _x30) { - return _getTokenSupply.apply(this, arguments); - } + case 35: + return _context38.abrupt("break", 43); - return getTokenSupply; - }() - /** - * Fetch the current balance of a token account - */ + case 36: + if (!(confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { + _context38.next = 38; + break; + } - }, { - key: "getTokenAccountBalance", - value: function () { - var _getTokenAccountBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(tokenAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee17$(_context17) { - while (1) switch (_context17.prev = _context17.next) { - case 0: - args = this._buildArgs([tokenAddress.toBase58()], commitment); - _context17.next = 3; - return this._rpcRequest('getTokenAccountBalance', args); + throw new TransactionExpiredNonceInvalidError(signature); - case 3: - unsafeRes = _context17.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); + case 38: + return _context38.abrupt("break", 43); - if (!('error' in res)) { - _context17.next = 7; + case 39: + if (!(confirmationStatus !== 'finalized')) { + _context38.next = 41; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token account balance'); + throw new TransactionExpiredNonceInvalidError(signature); - case 7: - return _context17.abrupt("return", res.result); + case 41: + return _context38.abrupt("break", 43); - case 8: + case 42: + + case 43: + result = { + context: signatureStatus.context, + value: { + err: signatureStatus.value.err + } + }; + _context38.next = 47; + break; + + case 46: + throw new TransactionExpiredNonceInvalidError(signature); + + case 47: + _context38.prev = 47; + done = true; + abortConfirmation(); + return _context38.finish(47); + + case 51: + return _context38.abrupt("return", result); + + case 52: case "end": - return _context17.stop(); + return _context38.stop(); } - }, _callee17, this); + }, _callee38, this, [[5,, 47, 51]]); })); - function getTokenAccountBalance(_x31, _x32) { - return _getTokenAccountBalance.apply(this, arguments); + function confirmTransactionUsingDurableNonceStrategy(_x64) { + return _confirmTransactionUsingDurableNonceStrategy.apply(this, arguments); } - return getTokenAccountBalance; + return confirmTransactionUsingDurableNonceStrategy; }() - /** - * Fetch all the token accounts owned by the specified account - * - * @return {Promise}>>>} - */ - }, { - key: "getTokenAccountsByOwner", + key: "confirmTransactionUsingLegacyTimeoutStrategy", value: function () { - var _getTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(ownerAddress, filter, commitmentOrConfig) { - var _extractCommitmentFro3, commitment, config, _args, args, unsafeRes, res; + var _confirmTransactionUsingLegacyTimeoutStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee39(_ref35) { + var _this19 = this; - return _regeneratorRuntime().wrap(function _callee18$(_context18) { - while (1) switch (_context18.prev = _context18.next) { + var commitment, signature, timeoutId, expiryPromise, _this$getTransactionC3, abortConfirmation, confirmationPromise, result, outcome; + + return _regeneratorRuntime().wrap(function _callee39$(_context39) { + while (1) switch (_context39.prev = _context39.next) { case 0: - _extractCommitmentFro3 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro3.commitment, config = _extractCommitmentFro3.config; - _args = [ownerAddress.toBase58()]; + commitment = _ref35.commitment, signature = _ref35.signature; + expiryPromise = new Promise(function (resolve) { + var timeoutMs = _this19._confirmTransactionInitialTimeout || 60 * 1000; - if ('mint' in filter) { - _args.push({ - mint: filter.mint.toBase58() - }); - } else { - _args.push({ - programId: filter.programId.toBase58() - }); - } + switch (commitment) { + case 'processed': + case 'recent': + case 'single': + case 'confirmed': + case 'singleGossip': + { + timeoutMs = _this19._confirmTransactionInitialTimeout || 30 * 1000; + break; + } + } - args = this._buildArgs(_args, commitment, 'base64', config); - _context18.next = 6; - return this._rpcRequest('getTokenAccountsByOwner', args); + timeoutId = setTimeout(function () { + return resolve({ + __type: TransactionStatus.TIMED_OUT, + timeoutMs: timeoutMs + }); + }, timeoutMs); + }); + _this$getTransactionC3 = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC3.abortConfirmation, confirmationPromise = _this$getTransactionC3.confirmationPromise; + _context39.prev = 3; + _context39.next = 6; + return Promise.race([confirmationPromise, expiryPromise]); case 6: - unsafeRes = _context18.sent; - res = _create(unsafeRes, GetTokenAccountsByOwner); + outcome = _context39.sent; - if (!('error' in res)) { - _context18.next = 10; + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context39.next = 11; break; } - throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); - - case 10: - return _context18.abrupt("return", res.result); + result = outcome.response; + _context39.next = 12; + break; case 11: + throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000); + + case 12: + _context39.prev = 12; + clearTimeout(timeoutId); + abortConfirmation(); + return _context39.finish(12); + + case 16: + return _context39.abrupt("return", result); + + case 17: case "end": - return _context18.stop(); + return _context39.stop(); } - }, _callee18, this); + }, _callee39, this, [[3,, 12, 16]]); })); - function getTokenAccountsByOwner(_x33, _x34, _x35) { - return _getTokenAccountsByOwner.apply(this, arguments); + function confirmTransactionUsingLegacyTimeoutStrategy(_x65) { + return _confirmTransactionUsingLegacyTimeoutStrategy.apply(this, arguments); } - return getTokenAccountsByOwner; + return confirmTransactionUsingLegacyTimeoutStrategy; }() /** - * Fetch parsed token accounts owned by the specified account - * - * @return {Promise}>>>} + * Return the list of nodes that are currently participating in the cluster */ }, { - key: "getParsedTokenAccountsByOwner", + key: "getClusterNodes", value: function () { - var _getParsedTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(ownerAddress, filter, commitment) { - var _args, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee19$(_context19) { - while (1) switch (_context19.prev = _context19.next) { + var _getClusterNodes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee40() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee40$(_context40) { + while (1) switch (_context40.prev = _context40.next) { case 0: - _args = [ownerAddress.toBase58()]; - - if ('mint' in filter) { - _args.push({ - mint: filter.mint.toBase58() - }); - } else { - _args.push({ - programId: filter.programId.toBase58() - }); - } - - args = this._buildArgs(_args, commitment, 'jsonParsed'); - _context19.next = 5; - return this._rpcRequest('getTokenAccountsByOwner', args); + _context40.next = 2; + return this._rpcRequest('getClusterNodes', []); - case 5: - unsafeRes = _context19.sent; - res = _create(unsafeRes, GetParsedTokenAccountsByOwner); + case 2: + unsafeRes = _context40.sent; + res = _create(unsafeRes, jsonRpcResult(array(ContactInfoResult))); if (!('error' in res)) { - _context19.next = 9; + _context40.next = 6; break; } - throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes'); - case 9: - return _context19.abrupt("return", res.result); + case 6: + return _context40.abrupt("return", res.result); - case 10: + case 7: case "end": - return _context19.stop(); + return _context40.stop(); } - }, _callee19, this); + }, _callee40, this); })); - function getParsedTokenAccountsByOwner(_x36, _x37, _x38) { - return _getParsedTokenAccountsByOwner.apply(this, arguments); + function getClusterNodes() { + return _getClusterNodes.apply(this, arguments); } - return getParsedTokenAccountsByOwner; + return getClusterNodes; }() /** - * Fetch the 20 largest accounts with their current balances + * Return the list of nodes that are currently participating in the cluster */ }, { - key: "getLargestAccounts", + key: "getVoteAccounts", value: function () { - var _getLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(config) { - var arg, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee20$(_context20) { - while (1) switch (_context20.prev = _context20.next) { + var _getVoteAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee41(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee41$(_context41) { + while (1) switch (_context41.prev = _context41.next) { case 0: - arg = _objectSpread2(_objectSpread2({}, config), {}, { - commitment: config && config.commitment || this.commitment - }); - args = arg.filter || arg.commitment ? [arg] : []; - _context20.next = 4; - return this._rpcRequest('getLargestAccounts', args); + args = this._buildArgs([], commitment); + _context41.next = 3; + return this._rpcRequest('getVoteAccounts', args); - case 4: - unsafeRes = _context20.sent; - res = _create(unsafeRes, GetLargestAccountsRpcResult); + case 3: + unsafeRes = _context41.sent; + res = _create(unsafeRes, GetVoteAccounts); if (!('error' in res)) { - _context20.next = 8; + _context41.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts'); + throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts'); - case 8: - return _context20.abrupt("return", res.result); + case 7: + return _context41.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context20.stop(); + return _context41.stop(); } - }, _callee20, this); + }, _callee41, this); })); - function getLargestAccounts(_x39) { - return _getLargestAccounts.apply(this, arguments); + function getVoteAccounts(_x66) { + return _getVoteAccounts.apply(this, arguments); } - return getLargestAccounts; + return getVoteAccounts; }() /** - * Fetch the 20 largest token accounts with their current balances - * for a given mint. + * Fetch the current slot that the node is processing */ }, { - key: "getTokenLargestAccounts", + key: "getSlot", value: function () { - var _getTokenLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(mintAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee21$(_context21) { - while (1) switch (_context21.prev = _context21.next) { + var _getSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee42(commitmentOrConfig) { + var _extractCommitmentFro11, commitment, config, args, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee42$(_context42) { + while (1) switch (_context42.prev = _context42.next) { case 0: - args = this._buildArgs([mintAddress.toBase58()], commitment); - _context21.next = 3; - return this._rpcRequest('getTokenLargestAccounts', args); + _extractCommitmentFro11 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro11.commitment, config = _extractCommitmentFro11.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context42.next = 4; + return this._rpcRequest('getSlot', args); - case 3: - unsafeRes = _context21.sent; - res = _create(unsafeRes, GetTokenLargestAccountsResult); + case 4: + unsafeRes = _context42.sent; + res = _create(unsafeRes, jsonRpcResult(number())); if (!('error' in res)) { - _context21.next = 7; + _context42.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts'); - - case 7: - return _context21.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get slot'); case 8: + return _context42.abrupt("return", res.result); + + case 9: case "end": - return _context21.stop(); + return _context42.stop(); } - }, _callee21, this); + }, _callee42, this); })); - function getTokenLargestAccounts(_x40, _x41) { - return _getTokenLargestAccounts.apply(this, arguments); + function getSlot(_x67) { + return _getSlot.apply(this, arguments); } - return getTokenLargestAccounts; + return getSlot; }() /** - * Fetch all the account info for the specified public key, return with context + * Fetch the current slot leader of the cluster */ }, { - key: "getAccountInfoAndContext", + key: "getSlotLeader", value: function () { - var _getAccountInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(publicKey, commitmentOrConfig) { - var _extractCommitmentFro4, commitment, config, args, unsafeRes, res; + var _getSlotLeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee43(commitmentOrConfig) { + var _extractCommitmentFro12, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee22$(_context22) { - while (1) switch (_context22.prev = _context22.next) { + return _regeneratorRuntime().wrap(function _callee43$(_context43) { + while (1) switch (_context43.prev = _context43.next) { case 0: - _extractCommitmentFro4 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro4.commitment, config = _extractCommitmentFro4.config; - args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config); - _context22.next = 4; - return this._rpcRequest('getAccountInfo', args); + _extractCommitmentFro12 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro12.commitment, config = _extractCommitmentFro12.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context43.next = 4; + return this._rpcRequest('getSlotLeader', args); case 4: - unsafeRes = _context22.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult))); + unsafeRes = _context43.sent; + res = _create(unsafeRes, jsonRpcResult(string())); if (!('error' in res)) { - _context22.next = 8; + _context43.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get slot leader'); case 8: - return _context22.abrupt("return", res.result); + return _context43.abrupt("return", res.result); case 9: case "end": - return _context22.stop(); + return _context43.stop(); } - }, _callee22, this); + }, _callee43, this); })); - function getAccountInfoAndContext(_x42, _x43) { - return _getAccountInfoAndContext.apply(this, arguments); + function getSlotLeader(_x68) { + return _getSlotLeader.apply(this, arguments); } - return getAccountInfoAndContext; + return getSlotLeader; }() /** - * Fetch parsed account info for the specified public key + * Fetch `limit` number of slot leaders starting from `startSlot` + * + * @param startSlot fetch slot leaders starting from this slot + * @param limit number of slot leaders to return */ }, { - key: "getParsedAccountInfo", + key: "getSlotLeaders", value: function () { - var _getParsedAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(publicKey, commitmentOrConfig) { - var _extractCommitmentFro5, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee23$(_context23) { - while (1) switch (_context23.prev = _context23.next) { + var _getSlotLeaders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee44(startSlot, limit) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee44$(_context44) { + while (1) switch (_context44.prev = _context44.next) { case 0: - _extractCommitmentFro5 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro5.commitment, config = _extractCommitmentFro5.config; - args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config); - _context23.next = 4; - return this._rpcRequest('getAccountInfo', args); + args = [startSlot, limit]; + _context44.next = 3; + return this._rpcRequest('getSlotLeaders', args); - case 4: - unsafeRes = _context23.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult))); + case 3: + unsafeRes = _context44.sent; + res = _create(unsafeRes, jsonRpcResult(array(PublicKeyFromString))); if (!('error' in res)) { - _context23.next = 8; + _context44.next = 7; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders'); + + case 7: + return _context44.abrupt("return", res.result); case 8: - return _context23.abrupt("return", res.result); - - case 9: case "end": - return _context23.stop(); + return _context44.stop(); } - }, _callee23, this); + }, _callee44, this); })); - function getParsedAccountInfo(_x44, _x45) { - return _getParsedAccountInfo.apply(this, arguments); + function getSlotLeaders(_x69, _x70) { + return _getSlotLeaders.apply(this, arguments); } - return getParsedAccountInfo; + return getSlotLeaders; }() /** - * Fetch all the account info for the specified public key + * Fetch the current status of a signature */ }, { - key: "getAccountInfo", + key: "getSignatureStatus", value: function () { - var _getAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(publicKey, commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee24$(_context24) { - while (1) switch (_context24.prev = _context24.next) { - case 0: - _context24.prev = 0; - _context24.next = 3; - return this.getAccountInfoAndContext(publicKey, commitmentOrConfig); + var _getSignatureStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee45(signature, config) { + var _yield$this$getSignat, context, values, value; - case 3: - res = _context24.sent; - return _context24.abrupt("return", res.value); + return _regeneratorRuntime().wrap(function _callee45$(_context45) { + while (1) switch (_context45.prev = _context45.next) { + case 0: + _context45.next = 2; + return this.getSignatureStatuses([signature], config); - case 7: - _context24.prev = 7; - _context24.t0 = _context24["catch"](0); - throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + _context24.t0); + case 2: + _yield$this$getSignat = _context45.sent; + context = _yield$this$getSignat.context; + values = _yield$this$getSignat.value; + assert(values.length === 1); + value = values[0]; + return _context45.abrupt("return", { + context: context, + value: value + }); - case 10: + case 8: case "end": - return _context24.stop(); + return _context45.stop(); } - }, _callee24, this, [[0, 7]]); + }, _callee45, this); })); - function getAccountInfo(_x46, _x47) { - return _getAccountInfo.apply(this, arguments); + function getSignatureStatus(_x71, _x72) { + return _getSignatureStatus.apply(this, arguments); } - return getAccountInfo; + return getSignatureStatus; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + * Fetch the current statuses of a batch of signatures */ }, { - key: "getMultipleParsedAccounts", + key: "getSignatureStatuses", value: function () { - var _getMultipleParsedAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(publicKeys, rawConfig) { - var _extractCommitmentFro6, commitment, config, keys, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee25$(_context25) { - while (1) switch (_context25.prev = _context25.next) { + var _getSignatureStatuses = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee46(signatures, config) { + var params, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee46$(_context46) { + while (1) switch (_context46.prev = _context46.next) { case 0: - _extractCommitmentFro6 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro6.commitment, config = _extractCommitmentFro6.config; - keys = publicKeys.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs([keys], commitment, 'jsonParsed', config); - _context25.next = 5; - return this._rpcRequest('getMultipleAccounts', args); + params = [signatures]; - case 5: - unsafeRes = _context25.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult)))); + if (config) { + params.push(config); + } + + _context46.next = 4; + return this._rpcRequest('getSignatureStatuses', params); + + case 4: + unsafeRes = _context46.sent; + res = _create(unsafeRes, GetSignatureStatusesRpcResult); if (!('error' in res)) { - _context25.next = 9; + _context46.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); + throw new SolanaJSONRPCError(res.error, 'failed to get signature status'); - case 9: - return _context25.abrupt("return", res.result); + case 8: + return _context46.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context25.stop(); + return _context46.stop(); } - }, _callee25, this); + }, _callee46, this); })); - function getMultipleParsedAccounts(_x48, _x49) { - return _getMultipleParsedAccounts.apply(this, arguments); + function getSignatureStatuses(_x73, _x74) { + return _getSignatureStatuses.apply(this, arguments); } - return getMultipleParsedAccounts; + return getSignatureStatuses; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + * Fetch the current transaction count of the cluster */ }, { - key: "getMultipleAccountsInfoAndContext", + key: "getTransactionCount", value: function () { - var _getMultipleAccountsInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(publicKeys, commitmentOrConfig) { - var _extractCommitmentFro7, commitment, config, keys, args, unsafeRes, res; + var _getTransactionCount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee47(commitmentOrConfig) { + var _extractCommitmentFro13, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee26$(_context26) { - while (1) switch (_context26.prev = _context26.next) { + return _regeneratorRuntime().wrap(function _callee47$(_context47) { + while (1) switch (_context47.prev = _context47.next) { case 0: - _extractCommitmentFro7 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro7.commitment, config = _extractCommitmentFro7.config; - keys = publicKeys.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs([keys], commitment, 'base64', config); - _context26.next = 5; - return this._rpcRequest('getMultipleAccounts', args); + _extractCommitmentFro13 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro13.commitment, config = _extractCommitmentFro13.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context47.next = 4; + return this._rpcRequest('getTransactionCount', args); - case 5: - unsafeRes = _context26.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult)))); + case 4: + unsafeRes = _context47.sent; + res = _create(unsafeRes, jsonRpcResult(number())); if (!('error' in res)) { - _context26.next = 9; + _context47.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction count'); - case 9: - return _context26.abrupt("return", res.result); + case 8: + return _context47.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context26.stop(); + return _context47.stop(); } - }, _callee26, this); + }, _callee47, this); })); - function getMultipleAccountsInfoAndContext(_x50, _x51) { - return _getMultipleAccountsInfoAndContext.apply(this, arguments); + function getTransactionCount(_x75) { + return _getTransactionCount.apply(this, arguments); } - return getMultipleAccountsInfoAndContext; + return getTransactionCount; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys + * Fetch the current total currency supply of the cluster in lamports + * + * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead. */ }, { - key: "getMultipleAccountsInfo", + key: "getTotalSupply", value: function () { - var _getMultipleAccountsInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27(publicKeys, commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee27$(_context27) { - while (1) switch (_context27.prev = _context27.next) { + var _getTotalSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee48(commitment) { + var result; + return _regeneratorRuntime().wrap(function _callee48$(_context48) { + while (1) switch (_context48.prev = _context48.next) { case 0: - _context27.next = 2; - return this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig); + _context48.next = 2; + return this.getSupply({ + commitment: commitment, + excludeNonCirculatingAccountsList: true + }); case 2: - res = _context27.sent; - return _context27.abrupt("return", res.value); + result = _context48.sent; + return _context48.abrupt("return", result.value.total); case 4: case "end": - return _context27.stop(); + return _context48.stop(); } - }, _callee27, this); + }, _callee48, this); })); - function getMultipleAccountsInfo(_x52, _x53) { - return _getMultipleAccountsInfo.apply(this, arguments); + function getTotalSupply(_x76) { + return _getTotalSupply.apply(this, arguments); } - return getMultipleAccountsInfo; + return getTotalSupply; }() /** - * Returns epoch activation information for a stake account that has been delegated + * Fetch the cluster InflationGovernor parameters */ }, { - key: "getStakeActivation", + key: "getInflationGovernor", value: function () { - var _getStakeActivation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28(publicKey, commitmentOrConfig, epoch) { - var _extractCommitmentFro8, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee28$(_context28) { - while (1) switch (_context28.prev = _context28.next) { + var _getInflationGovernor = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee49(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee49$(_context49) { + while (1) switch (_context49.prev = _context49.next) { case 0: - _extractCommitmentFro8 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro8.commitment, config = _extractCommitmentFro8.config; - args = this._buildArgs([publicKey.toBase58()], commitment, undefined - /* encoding */ - , _objectSpread2(_objectSpread2({}, config), {}, { - epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch - })); - _context28.next = 4; - return this._rpcRequest('getStakeActivation', args); + args = this._buildArgs([], commitment); + _context49.next = 3; + return this._rpcRequest('getInflationGovernor', args); - case 4: - unsafeRes = _context28.sent; - res = _create(unsafeRes, jsonRpcResult(StakeActivationResult)); + case 3: + unsafeRes = _context49.sent; + res = _create(unsafeRes, GetInflationGovernorRpcResult); if (!('error' in res)) { - _context28.next = 8; + _context49.next = 7; break; } - throw new SolanaJSONRPCError(res.error, "failed to get Stake Activation ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation'); - case 8: - return _context28.abrupt("return", res.result); + case 7: + return _context49.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context28.stop(); + return _context49.stop(); } - }, _callee28, this); + }, _callee49, this); })); - function getStakeActivation(_x54, _x55, _x56) { - return _getStakeActivation.apply(this, arguments); + function getInflationGovernor(_x77) { + return _getInflationGovernor.apply(this, arguments); } - return getStakeActivation; + return getInflationGovernor; }() /** - * Fetch all the accounts owned by the specified program id - * - * @return {Promise}>>} + * Fetch the inflation reward for a list of addresses for an epoch */ }, { - key: "getProgramAccounts", + key: "getInflationReward", value: function () { - var _getProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee29(programId, configOrCommitment) { - var _extractCommitmentFro9, commitment, config, _ref26, encoding, configWithoutEncoding, args, unsafeRes, res; + var _getInflationReward = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee50(addresses, epoch, commitmentOrConfig) { + var _extractCommitmentFro14, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee29$(_context29) { - while (1) switch (_context29.prev = _context29.next) { + return _regeneratorRuntime().wrap(function _callee50$(_context50) { + while (1) switch (_context50.prev = _context50.next) { case 0: - _extractCommitmentFro9 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro9.commitment, config = _extractCommitmentFro9.config; - _ref26 = config || {}, encoding = _ref26.encoding, configWithoutEncoding = _objectWithoutProperties(_ref26, _excluded2); - args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', configWithoutEncoding); - _context29.next = 5; - return this._rpcRequest('getProgramAccounts', args); + _extractCommitmentFro14 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro14.commitment, config = _extractCommitmentFro14.config; + args = this._buildArgs([addresses.map(function (pubkey) { + return pubkey.toBase58(); + })], commitment, undefined + /* encoding */ + , _objectSpread2(_objectSpread2({}, config), {}, { + epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch + })); + _context50.next = 4; + return this._rpcRequest('getInflationReward', args); - case 5: - unsafeRes = _context29.sent; - res = _create(unsafeRes, jsonRpcResult(array(KeyedAccountInfoResult))); + case 4: + unsafeRes = _context50.sent; + res = _create(unsafeRes, GetInflationRewardResult); if (!('error' in res)) { - _context29.next = 9; + _context50.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward'); - case 9: - return _context29.abrupt("return", res.result); + case 8: + return _context50.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context29.stop(); + return _context50.stop(); } - }, _callee29, this); + }, _callee50, this); })); - function getProgramAccounts(_x57, _x58) { - return _getProgramAccounts.apply(this, arguments); + function getInflationReward(_x78, _x79, _x80) { + return _getInflationReward.apply(this, arguments); } - return getProgramAccounts; + return getInflationReward; }() /** - * Fetch and parse all the accounts owned by the specified program id - * - * @return {Promise}>>} + * Fetch the specific inflation values for the current epoch */ }, { - key: "getParsedProgramAccounts", + key: "getInflationRate", value: function () { - var _getParsedProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee30(programId, configOrCommitment) { - var _extractCommitmentFro10, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee30$(_context30) { - while (1) switch (_context30.prev = _context30.next) { + var _getInflationRate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee51() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee51$(_context51) { + while (1) switch (_context51.prev = _context51.next) { case 0: - _extractCommitmentFro10 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro10.commitment, config = _extractCommitmentFro10.config; - args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config); - _context30.next = 4; - return this._rpcRequest('getProgramAccounts', args); + _context51.next = 2; + return this._rpcRequest('getInflationRate', []); - case 4: - unsafeRes = _context30.sent; - res = _create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult))); + case 2: + unsafeRes = _context51.sent; + res = _create(unsafeRes, GetInflationRateRpcResult); if (!('error' in res)) { - _context30.next = 8; + _context51.next = 6; break; } - throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate'); - case 8: - return _context30.abrupt("return", res.result); + case 6: + return _context51.abrupt("return", res.result); - case 9: + case 7: case "end": - return _context30.stop(); + return _context51.stop(); } - }, _callee30, this); + }, _callee51, this); })); - function getParsedProgramAccounts(_x59, _x60) { - return _getParsedProgramAccounts.apply(this, arguments); + function getInflationRate() { + return _getInflationRate.apply(this, arguments); } - return getParsedProgramAccounts; - }() // eslint-disable-next-line no-dupe-class-members + return getInflationRate; + }() + /** + * Fetch the Epoch Info parameters + */ }, { - key: "confirmTransaction", + key: "getEpochInfo", value: function () { - var _confirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee31(strategy, commitment) { - var rawSignature, _config$abortSignal, config, decodedSignature; + var _getEpochInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee52(commitmentOrConfig) { + var _extractCommitmentFro15, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee31$(_context31) { - while (1) switch (_context31.prev = _context31.next) { + return _regeneratorRuntime().wrap(function _callee52$(_context52) { + while (1) switch (_context52.prev = _context52.next) { case 0: - if (!(typeof strategy == 'string')) { - _context31.next = 4; - break; - } - - rawSignature = strategy; - _context31.next = 8; - break; + _extractCommitmentFro15 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro15.commitment, config = _extractCommitmentFro15.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context52.next = 4; + return this._rpcRequest('getEpochInfo', args); case 4: - config = strategy; - - if (!((_config$abortSignal = config.abortSignal) !== null && _config$abortSignal !== void 0 && _config$abortSignal.aborted)) { - _context31.next = 7; - break; - } - - return _context31.abrupt("return", Promise.reject(config.abortSignal.reason)); - - case 7: - rawSignature = config.signature; - - case 8: - _context31.prev = 8; - decodedSignature = bs58$1.decode(rawSignature); - _context31.next = 15; - break; - - case 12: - _context31.prev = 12; - _context31.t0 = _context31["catch"](8); - throw new Error('signature must be base58 encoded: ' + rawSignature); - - case 15: - assert(decodedSignature.length === 64, 'signature has invalid length'); - - if (!(typeof strategy === 'string')) { - _context31.next = 22; - break; - } - - _context31.next = 19; - return this.confirmTransactionUsingLegacyTimeoutStrategy({ - commitment: commitment || this.commitment, - signature: rawSignature - }); - - case 19: - return _context31.abrupt("return", _context31.sent); + unsafeRes = _context52.sent; + res = _create(unsafeRes, GetEpochInfoRpcResult); - case 22: - if (!('lastValidBlockHeight' in strategy)) { - _context31.next = 28; + if (!('error' in res)) { + _context52.next = 8; break; - } - - _context31.next = 25; - return this.confirmTransactionUsingBlockHeightExceedanceStrategy({ - commitment: commitment || this.commitment, - strategy: strategy - }); - - case 25: - return _context31.abrupt("return", _context31.sent); - - case 28: - _context31.next = 30; - return this.confirmTransactionUsingDurableNonceStrategy({ - commitment: commitment || this.commitment, - strategy: strategy - }); - - case 30: - return _context31.abrupt("return", _context31.sent); - - case 31: - case "end": - return _context31.stop(); - } - }, _callee31, this, [[8, 12]]); - })); - - function confirmTransaction(_x61, _x62) { - return _confirmTransaction.apply(this, arguments); - } - - return confirmTransaction; - }() - }, { - key: "getCancellationPromise", - value: function getCancellationPromise(signal) { - return new Promise(function (_, reject) { - if (signal == null) { - return; - } - - if (signal.aborted) { - reject(signal.reason); - } else { - signal.addEventListener('abort', function () { - reject(signal.reason); - }); - } - }); - } - }, { - key: "getTransactionConfirmationPromise", - value: function getTransactionConfirmationPromise(_ref27) { - var _this16 = this; - - var commitment = _ref27.commitment, - signature = _ref27.signature; - var signatureSubscriptionId; - var disposeSignatureSubscriptionStateChangeObserver; - var done = false; - var confirmationPromise = new Promise(function (resolve, reject) { - try { - signatureSubscriptionId = _this16.onSignature(signature, function (result, context) { - signatureSubscriptionId = undefined; - var response = { - context: context, - value: result - }; - resolve({ - __type: TransactionStatus.PROCESSED, - response: response - }); - }, commitment); - var subscriptionSetupPromise = new Promise(function (resolveSubscriptionSetup) { - if (signatureSubscriptionId == null) { - resolveSubscriptionSetup(); - } else { - disposeSignatureSubscriptionStateChangeObserver = _this16._onSubscriptionStateChange(signatureSubscriptionId, function (nextState) { - if (nextState === 'subscribed') { - resolveSubscriptionSetup(); - } - }); - } - }); + } - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee32() { - var response, context, value; - return _regeneratorRuntime().wrap(function _callee32$(_context32) { - while (1) switch (_context32.prev = _context32.next) { - case 0: - _context32.next = 2; - return subscriptionSetupPromise; + throw new SolanaJSONRPCError(res.error, 'failed to get epoch info'); - case 2: - if (!done) { - _context32.next = 4; - break; - } + case 8: + return _context52.abrupt("return", res.result); - return _context32.abrupt("return"); + case 9: + case "end": + return _context52.stop(); + } + }, _callee52, this); + })); - case 4: - _context32.next = 6; - return _this16.getSignatureStatus(signature); + function getEpochInfo(_x81) { + return _getEpochInfo.apply(this, arguments); + } - case 6: - response = _context32.sent; + return getEpochInfo; + }() + /** + * Fetch the Epoch Schedule parameters + */ - if (!done) { - _context32.next = 9; - break; - } + }, { + key: "getEpochSchedule", + value: function () { + var _getEpochSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee53() { + var unsafeRes, res, epochSchedule; + return _regeneratorRuntime().wrap(function _callee53$(_context53) { + while (1) switch (_context53.prev = _context53.next) { + case 0: + _context53.next = 2; + return this._rpcRequest('getEpochSchedule', []); - return _context32.abrupt("return"); + case 2: + unsafeRes = _context53.sent; + res = _create(unsafeRes, GetEpochScheduleRpcResult); - case 9: - if (!(response == null)) { - _context32.next = 11; - break; - } + if (!('error' in res)) { + _context53.next = 6; + break; + } - return _context32.abrupt("return"); + throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule'); - case 11: - context = response.context, value = response.value; + case 6: + epochSchedule = res.result; + return _context53.abrupt("return", new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot)); - if (!(value == null)) { - _context32.next = 14; - break; - } + case 8: + case "end": + return _context53.stop(); + } + }, _callee53, this); + })); - return _context32.abrupt("return"); + function getEpochSchedule() { + return _getEpochSchedule.apply(this, arguments); + } - case 14: - if (!(value !== null && value !== void 0 && value.err)) { - _context32.next = 18; - break; - } + return getEpochSchedule; + }() + /** + * Fetch the leader schedule for the current epoch + * @return {Promise>} + */ - reject(value.err); - _context32.next = 29; - break; + }, { + key: "getLeaderSchedule", + value: function () { + var _getLeaderSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee54() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee54$(_context54) { + while (1) switch (_context54.prev = _context54.next) { + case 0: + _context54.next = 2; + return this._rpcRequest('getLeaderSchedule', []); - case 18: - _context32.t0 = commitment; - _context32.next = _context32.t0 === 'confirmed' ? 21 : _context32.t0 === 'single' ? 21 : _context32.t0 === 'singleGossip' ? 21 : _context32.t0 === 'finalized' ? 24 : _context32.t0 === 'max' ? 24 : _context32.t0 === 'root' ? 24 : _context32.t0 === 'processed' ? 27 : _context32.t0 === 'recent' ? 27 : 27; - break; + case 2: + unsafeRes = _context54.sent; + res = _create(unsafeRes, GetLeaderScheduleRpcResult); - case 21: - if (!(value.confirmationStatus === 'processed')) { - _context32.next = 23; - break; - } + if (!('error' in res)) { + _context54.next = 6; + break; + } - return _context32.abrupt("return"); + throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule'); - case 23: - return _context32.abrupt("break", 27); + case 6: + return _context54.abrupt("return", res.result); - case 24: - if (!(value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed')) { - _context32.next = 26; - break; - } + case 7: + case "end": + return _context54.stop(); + } + }, _callee54, this); + })); - return _context32.abrupt("return"); + function getLeaderSchedule() { + return _getLeaderSchedule.apply(this, arguments); + } - case 26: - return _context32.abrupt("break", 27); + return getLeaderSchedule; + }() + /** + * Fetch the minimum balance needed to exempt an account of `dataLength` + * size from rent + */ - case 27: - done = true; - resolve({ - __type: TransactionStatus.PROCESSED, - response: { - context: context, - value: value - } - }); + }, { + key: "getMinimumBalanceForRentExemption", + value: function () { + var _getMinimumBalanceForRentExemption = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee55(dataLength, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee55$(_context55) { + while (1) switch (_context55.prev = _context55.next) { + case 0: + args = this._buildArgs([dataLength], commitment); + _context55.next = 3; + return this._rpcRequest('getMinimumBalanceForRentExemption', args); - case 29: - case "end": - return _context32.stop(); + case 3: + unsafeRes = _context55.sent; + res = _create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult); + + if (!('error' in res)) { + _context55.next = 8; + break; } - }, _callee32); - }))(); - } catch (err) { - reject(err); - } - }); - var abortConfirmation = function abortConfirmation() { - if (disposeSignatureSubscriptionStateChangeObserver) { - disposeSignatureSubscriptionStateChangeObserver(); - disposeSignatureSubscriptionStateChangeObserver = undefined; - } + console.warn('Unable to fetch minimum balance for rent exemption'); + return _context55.abrupt("return", 0); - if (signatureSubscriptionId != null) { - _this16.removeSignatureListener(signatureSubscriptionId); + case 8: + return _context55.abrupt("return", res.result); - signatureSubscriptionId = undefined; - } - }; + case 9: + case "end": + return _context55.stop(); + } + }, _callee55, this); + })); - return { - abortConfirmation: abortConfirmation, - confirmationPromise: confirmationPromise - }; - } - }, { - key: "confirmTransactionUsingBlockHeightExceedanceStrategy", - value: function () { - var _confirmTransactionUsingBlockHeightExceedanceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee35(_ref29) { - var _this17 = this; + function getMinimumBalanceForRentExemption(_x82, _x83) { + return _getMinimumBalanceForRentExemption.apply(this, arguments); + } - var commitment, _ref29$strategy, abortSignal, lastValidBlockHeight, signature, done, expiryPromise, _this$getTransactionC, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome; + return getMinimumBalanceForRentExemption; + }() + /** + * Fetch a recent blockhash from the cluster, return with context + * @return {Promise>} + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + */ - return _regeneratorRuntime().wrap(function _callee35$(_context35) { - while (1) switch (_context35.prev = _context35.next) { + }, { + key: "getRecentBlockhashAndContext", + value: function () { + var _getRecentBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee56(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee56$(_context56) { + while (1) switch (_context56.prev = _context56.next) { case 0: - commitment = _ref29.commitment, _ref29$strategy = _ref29.strategy, abortSignal = _ref29$strategy.abortSignal, lastValidBlockHeight = _ref29$strategy.lastValidBlockHeight, signature = _ref29$strategy.signature; - done = false; - expiryPromise = new Promise(function (resolve) { - var checkBlockHeight = /*#__PURE__*/function () { - var _ref30 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee33() { - var blockHeight; - return _regeneratorRuntime().wrap(function _callee33$(_context33) { - while (1) switch (_context33.prev = _context33.next) { - case 0: - _context33.prev = 0; - _context33.next = 3; - return _this17.getBlockHeight(commitment); - - case 3: - blockHeight = _context33.sent; - return _context33.abrupt("return", blockHeight); - - case 7: - _context33.prev = 7; - _context33.t0 = _context33["catch"](0); - return _context33.abrupt("return", -1); + args = this._buildArgs([], commitment); + _context56.next = 3; + return this._rpcRequest('getRecentBlockhash', args); - case 10: - case "end": - return _context33.stop(); - } - }, _callee33, null, [[0, 7]]); - })); + case 3: + unsafeRes = _context56.sent; + res = _create(unsafeRes, GetRecentBlockhashAndContextRpcResult); - return function checkBlockHeight() { - return _ref30.apply(this, arguments); - }; - }(); + if (!('error' in res)) { + _context56.next = 7; + break; + } - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee34() { - var currentBlockHeight; - return _regeneratorRuntime().wrap(function _callee34$(_context34) { - while (1) switch (_context34.prev = _context34.next) { - case 0: - _context34.next = 2; - return checkBlockHeight(); + throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash'); - case 2: - currentBlockHeight = _context34.sent; + case 7: + return _context56.abrupt("return", res.result); - if (!done) { - _context34.next = 5; - break; - } + case 8: + case "end": + return _context56.stop(); + } + }, _callee56, this); + })); - return _context34.abrupt("return"); + function getRecentBlockhashAndContext(_x84) { + return _getRecentBlockhashAndContext.apply(this, arguments); + } - case 5: - if (!(currentBlockHeight <= lastValidBlockHeight)) { - _context34.next = 17; - break; - } + return getRecentBlockhashAndContext; + }() + /** + * Fetch recent performance samples + * @return {Promise>} + */ - _context34.next = 8; - return sleep(1000); + }, { + key: "getRecentPerformanceSamples", + value: function () { + var _getRecentPerformanceSamples = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee57(limit) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee57$(_context57) { + while (1) switch (_context57.prev = _context57.next) { + case 0: + _context57.next = 2; + return this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []); - case 8: - if (!done) { - _context34.next = 10; - break; - } + case 2: + unsafeRes = _context57.sent; + res = _create(unsafeRes, GetRecentPerformanceSamplesRpcResult); - return _context34.abrupt("return"); + if (!('error' in res)) { + _context57.next = 6; + break; + } - case 10: - _context34.next = 12; - return checkBlockHeight(); + throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples'); - case 12: - currentBlockHeight = _context34.sent; + case 6: + return _context57.abrupt("return", res.result); - if (!done) { - _context34.next = 15; - break; - } + case 7: + case "end": + return _context57.stop(); + } + }, _callee57, this); + })); - return _context34.abrupt("return"); + function getRecentPerformanceSamples(_x85) { + return _getRecentPerformanceSamples.apply(this, arguments); + } - case 15: - _context34.next = 5; - break; + return getRecentPerformanceSamples; + }() + /** + * Fetch the fee calculator for a recent blockhash from the cluster, return with context + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead. + */ - case 17: - resolve({ - __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED - }); + }, { + key: "getFeeCalculatorForBlockhash", + value: function () { + var _getFeeCalculatorForBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee58(blockhash, commitment) { + var args, unsafeRes, res, _res$result, context, value; - case 18: - case "end": - return _context34.stop(); - } - }, _callee34); - }))(); - }); - _this$getTransactionC = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC.abortConfirmation, confirmationPromise = _this$getTransactionC.confirmationPromise; - cancellationPromise = this.getCancellationPromise(abortSignal); - _context35.prev = 5; - _context35.next = 8; - return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + return _regeneratorRuntime().wrap(function _callee58$(_context58) { + while (1) switch (_context58.prev = _context58.next) { + case 0: + args = this._buildArgs([blockhash], commitment); + _context58.next = 3; + return this._rpcRequest('getFeeCalculatorForBlockhash', args); - case 8: - outcome = _context35.sent; + case 3: + unsafeRes = _context58.sent; + res = _create(unsafeRes, GetFeeCalculatorRpcResult); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context35.next = 13; + if (!('error' in res)) { + _context58.next = 7; break; } - result = outcome.response; - _context35.next = 14; - break; - - case 13: - throw new TransactionExpiredBlockheightExceededError(signature); - - case 14: - _context35.prev = 14; - done = true; - abortConfirmation(); - return _context35.finish(14); + throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator'); - case 18: - return _context35.abrupt("return", result); + case 7: + _res$result = res.result, context = _res$result.context, value = _res$result.value; + return _context58.abrupt("return", { + context: context, + value: value !== null ? value.feeCalculator : null + }); - case 19: + case 9: case "end": - return _context35.stop(); + return _context58.stop(); } - }, _callee35, this, [[5,, 14, 18]]); + }, _callee58, this); })); - function confirmTransactionUsingBlockHeightExceedanceStrategy(_x63) { - return _confirmTransactionUsingBlockHeightExceedanceStrategy.apply(this, arguments); + function getFeeCalculatorForBlockhash(_x86, _x87) { + return _getFeeCalculatorForBlockhash.apply(this, arguments); } - return confirmTransactionUsingBlockHeightExceedanceStrategy; + return getFeeCalculatorForBlockhash; }() + /** + * Fetch the fee for a message from the cluster, return with context + */ + }, { - key: "confirmTransactionUsingDurableNonceStrategy", + key: "getFeeForMessage", value: function () { - var _confirmTransactionUsingDurableNonceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee38(_ref32) { - var _this18 = this; - - var commitment, _ref32$strategy, abortSignal, minContextSlot, nonceAccountPubkey, nonceValue, signature, done, expiryPromise, _this$getTransactionC2, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome, _signatureStatus, signatureStatus, _outcome$slotInWhichN, status, commitmentForStatus, confirmationStatus; - - return _regeneratorRuntime().wrap(function _callee38$(_context38) { - while (1) switch (_context38.prev = _context38.next) { + var _getFeeForMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee59(message, commitment) { + var wireMessage, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee59$(_context59) { + while (1) switch (_context59.prev = _context59.next) { case 0: - commitment = _ref32.commitment, _ref32$strategy = _ref32.strategy, abortSignal = _ref32$strategy.abortSignal, minContextSlot = _ref32$strategy.minContextSlot, nonceAccountPubkey = _ref32$strategy.nonceAccountPubkey, nonceValue = _ref32$strategy.nonceValue, signature = _ref32$strategy.signature; - done = false; - expiryPromise = new Promise(function (resolve) { - var currentNonceValue = nonceValue; - var lastCheckedSlot = null; - - var getCurrentNonceValue = /*#__PURE__*/function () { - var _ref33 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36() { - var _yield$_this18$getNon2, context, nonceAccount; + wireMessage = toBuffer(message.serialize()).toString('base64'); + args = this._buildArgs([wireMessage], commitment); + _context59.next = 4; + return this._rpcRequest('getFeeForMessage', args); - return _regeneratorRuntime().wrap(function _callee36$(_context36) { - while (1) switch (_context36.prev = _context36.next) { - case 0: - _context36.prev = 0; - _context36.next = 3; - return _this18.getNonceAndContext(nonceAccountPubkey, { - commitment: commitment, - minContextSlot: minContextSlot - }); + case 4: + unsafeRes = _context59.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(number()))); - case 3: - _yield$_this18$getNon2 = _context36.sent; - context = _yield$_this18$getNon2.context; - nonceAccount = _yield$_this18$getNon2.value; - lastCheckedSlot = context.slot; - return _context36.abrupt("return", nonceAccount === null || nonceAccount === void 0 ? void 0 : nonceAccount.nonce); + if (!('error' in res)) { + _context59.next = 8; + break; + } - case 10: - _context36.prev = 10; - _context36.t0 = _context36["catch"](0); - return _context36.abrupt("return", currentNonceValue); + throw new SolanaJSONRPCError(res.error, 'failed to get fee for message'); - case 13: - case "end": - return _context36.stop(); - } - }, _callee36, null, [[0, 10]]); - })); + case 8: + if (!(res.result === null)) { + _context59.next = 10; + break; + } - return function getCurrentNonceValue() { - return _ref33.apply(this, arguments); - }; - }(); + throw new Error('invalid blockhash'); - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee37() { - return _regeneratorRuntime().wrap(function _callee37$(_context37) { - while (1) switch (_context37.prev = _context37.next) { - case 0: - _context37.next = 2; - return getCurrentNonceValue(); + case 10: + return _context59.abrupt("return", res.result); - case 2: - currentNonceValue = _context37.sent; + case 11: + case "end": + return _context59.stop(); + } + }, _callee59, this); + })); - if (!done) { - _context37.next = 5; - break; - } + function getFeeForMessage(_x88, _x89) { + return _getFeeForMessage.apply(this, arguments); + } - return _context37.abrupt("return"); + return getFeeForMessage; + }() + /** + * Fetch a list of prioritization fees from recent blocks. + */ - case 5: + }, { + key: "getRecentPrioritizationFees", + value: function () { + var _getRecentPrioritizationFees = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee60(config) { + var _config$lockedWritabl; - if (!(nonceValue !== currentNonceValue)) { - _context37.next = 9; - break; - } + var accounts, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee60$(_context60) { + while (1) switch (_context60.prev = _context60.next) { + case 0: + accounts = config === null || config === void 0 ? void 0 : (_config$lockedWritabl = config.lockedWritableAccounts) === null || _config$lockedWritabl === void 0 ? void 0 : _config$lockedWritabl.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs(accounts !== null && accounts !== void 0 && accounts.length ? [accounts] : []); + _context60.next = 4; + return this._rpcRequest('getRecentPrioritizationFees', args); - resolve({ - __type: TransactionStatus.NONCE_INVALID, - slotInWhichNonceDidAdvance: lastCheckedSlot - }); - return _context37.abrupt("return"); + case 4: + unsafeRes = _context60.sent; + res = _create(unsafeRes, GetRecentPrioritizationFeesRpcResult); - case 9: - _context37.next = 11; - return sleep(2000); + if (!('error' in res)) { + _context60.next = 8; + break; + } - case 11: - if (!done) { - _context37.next = 13; - break; - } + throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees'); - return _context37.abrupt("return"); + case 8: + return _context60.abrupt("return", res.result); - case 13: - _context37.next = 15; - return getCurrentNonceValue(); + case 9: + case "end": + return _context60.stop(); + } + }, _callee60, this); + })); - case 15: - currentNonceValue = _context37.sent; + function getRecentPrioritizationFees(_x90) { + return _getRecentPrioritizationFees.apply(this, arguments); + } - if (!done) { - _context37.next = 18; - break; - } + return getRecentPrioritizationFees; + }() + /** + * Fetch a recent blockhash from the cluster + * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + */ - return _context37.abrupt("return"); + }, { + key: "getRecentBlockhash", + value: function () { + var _getRecentBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee61(commitment) { + var res; + return _regeneratorRuntime().wrap(function _callee61$(_context61) { + while (1) switch (_context61.prev = _context61.next) { + case 0: + _context61.prev = 0; + _context61.next = 3; + return this.getRecentBlockhashAndContext(commitment); - case 18: - _context37.next = 5; - break; + case 3: + res = _context61.sent; + return _context61.abrupt("return", res.value); - case 20: - case "end": - return _context37.stop(); - } - }, _callee37); - }))(); - }); - _this$getTransactionC2 = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC2.abortConfirmation, confirmationPromise = _this$getTransactionC2.confirmationPromise; - cancellationPromise = this.getCancellationPromise(abortSignal); - _context38.prev = 5; - _context38.next = 8; - return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + case 7: + _context61.prev = 7; + _context61.t0 = _context61["catch"](0); + throw new Error('failed to get recent blockhash: ' + _context61.t0); - case 8: - outcome = _context38.sent; + case 10: + case "end": + return _context61.stop(); + } + }, _callee61, this, [[0, 7]]); + })); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context38.next = 13; - break; - } + function getRecentBlockhash(_x91) { + return _getRecentBlockhash.apply(this, arguments); + } - result = outcome.response; - _context38.next = 47; - break; + return getRecentBlockhash; + }() + /** + * Fetch the latest blockhash from the cluster + * @return {Promise} + */ - case 13: + }, { + key: "getLatestBlockhash", + value: function () { + var _getLatestBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee62(commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee62$(_context62) { + while (1) switch (_context62.prev = _context62.next) { + case 0: + _context62.prev = 0; + _context62.next = 3; + return this.getLatestBlockhashAndContext(commitmentOrConfig); - _context38.next = 16; - return this.getSignatureStatus(signature); + case 3: + res = _context62.sent; + return _context62.abrupt("return", res.value); - case 16: - status = _context38.sent; + case 7: + _context62.prev = 7; + _context62.t0 = _context62["catch"](0); + throw new Error('failed to get recent blockhash: ' + _context62.t0); - if (!(status == null)) { - _context38.next = 19; - break; - } + case 10: + case "end": + return _context62.stop(); + } + }, _callee62, this, [[0, 7]]); + })); - return _context38.abrupt("break", 27); + function getLatestBlockhash(_x92) { + return _getLatestBlockhash.apply(this, arguments); + } - case 19: - if (!(status.context.slot < ((_outcome$slotInWhichN = outcome.slotInWhichNonceDidAdvance) !== null && _outcome$slotInWhichN !== void 0 ? _outcome$slotInWhichN : minContextSlot))) { - _context38.next = 23; - break; - } + return getLatestBlockhash; + }() + /** + * Fetch the latest blockhash from the cluster + * @return {Promise} + */ - _context38.next = 22; - return sleep(400); + }, { + key: "getLatestBlockhashAndContext", + value: function () { + var _getLatestBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee63(commitmentOrConfig) { + var _extractCommitmentFro16, commitment, config, args, unsafeRes, res; - case 22: - return _context38.abrupt("continue", 13); + return _regeneratorRuntime().wrap(function _callee63$(_context63) { + while (1) switch (_context63.prev = _context63.next) { + case 0: + _extractCommitmentFro16 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro16.commitment, config = _extractCommitmentFro16.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context63.next = 4; + return this._rpcRequest('getLatestBlockhash', args); - case 23: - signatureStatus = status; - return _context38.abrupt("break", 27); + case 4: + unsafeRes = _context63.sent; + res = _create(unsafeRes, GetLatestBlockhashRpcResult); - case 27: - if (!((_signatureStatus = signatureStatus) !== null && _signatureStatus !== void 0 && _signatureStatus.value)) { - _context38.next = 46; + if (!('error' in res)) { + _context63.next = 8; break; } - commitmentForStatus = commitment || 'finalized'; - confirmationStatus = signatureStatus.value.confirmationStatus; - _context38.t0 = commitmentForStatus; - _context38.next = _context38.t0 === 'processed' ? 33 : _context38.t0 === 'recent' ? 33 : _context38.t0 === 'confirmed' ? 36 : _context38.t0 === 'single' ? 36 : _context38.t0 === 'singleGossip' ? 36 : _context38.t0 === 'finalized' ? 39 : _context38.t0 === 'max' ? 39 : _context38.t0 === 'root' ? 39 : 42; - break; + throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash'); - case 33: - if (!(confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { - _context38.next = 35; - break; - } + case 8: + return _context63.abrupt("return", res.result); - throw new TransactionExpiredNonceInvalidError(signature); + case 9: + case "end": + return _context63.stop(); + } + }, _callee63, this); + })); - case 35: - return _context38.abrupt("break", 43); + function getLatestBlockhashAndContext(_x93) { + return _getLatestBlockhashAndContext.apply(this, arguments); + } - case 36: - if (!(confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { - _context38.next = 38; - break; - } + return getLatestBlockhashAndContext; + }() + /** + * Fetch the node version + */ - throw new TransactionExpiredNonceInvalidError(signature); + }, { + key: "getVersion", + value: function () { + var _getVersion = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee64() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee64$(_context64) { + while (1) switch (_context64.prev = _context64.next) { + case 0: + _context64.next = 2; + return this._rpcRequest('getVersion', []); - case 38: - return _context38.abrupt("break", 43); + case 2: + unsafeRes = _context64.sent; + res = _create(unsafeRes, jsonRpcResult(VersionResult)); - case 39: - if (!(confirmationStatus !== 'finalized')) { - _context38.next = 41; + if (!('error' in res)) { + _context64.next = 6; break; } - throw new TransactionExpiredNonceInvalidError(signature); + throw new SolanaJSONRPCError(res.error, 'failed to get version'); - case 41: - return _context38.abrupt("break", 43); + case 6: + return _context64.abrupt("return", res.result); - case 42: + case 7: + case "end": + return _context64.stop(); + } + }, _callee64, this); + })); - case 43: - result = { - context: signatureStatus.context, - value: { - err: signatureStatus.value.err - } - }; - _context38.next = 47; - break; + function getVersion() { + return _getVersion.apply(this, arguments); + } - case 46: - throw new TransactionExpiredNonceInvalidError(signature); + return getVersion; + }() + /** + * Fetch the genesis hash + */ - case 47: - _context38.prev = 47; - done = true; - abortConfirmation(); - return _context38.finish(47); + }, { + key: "getGenesisHash", + value: function () { + var _getGenesisHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee65() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee65$(_context65) { + while (1) switch (_context65.prev = _context65.next) { + case 0: + _context65.next = 2; + return this._rpcRequest('getGenesisHash', []); - case 51: - return _context38.abrupt("return", result); + case 2: + unsafeRes = _context65.sent; + res = _create(unsafeRes, jsonRpcResult(string())); - case 52: + if (!('error' in res)) { + _context65.next = 6; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash'); + + case 6: + return _context65.abrupt("return", res.result); + + case 7: case "end": - return _context38.stop(); + return _context65.stop(); } - }, _callee38, this, [[5,, 47, 51]]); + }, _callee65, this); })); - function confirmTransactionUsingDurableNonceStrategy(_x64) { - return _confirmTransactionUsingDurableNonceStrategy.apply(this, arguments); + function getGenesisHash() { + return _getGenesisHash.apply(this, arguments); } - return confirmTransactionUsingDurableNonceStrategy; + return getGenesisHash; }() + /** + * Fetch a processed block from the cluster. + * + * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by + * setting the `maxSupportedTransactionVersion` property. + */ + + /** + * Fetch a processed block from the cluster. + */ + // eslint-disable-next-line no-dupe-class-members + }, { - key: "confirmTransactionUsingLegacyTimeoutStrategy", + key: "getBlock", value: function () { - var _confirmTransactionUsingLegacyTimeoutStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee39(_ref35) { - var _this19 = this; - - var commitment, signature, timeoutId, expiryPromise, _this$getTransactionC3, abortConfirmation, confirmationPromise, result, outcome; + var _getBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee66(slot, rawConfig) { + var _extractCommitmentFro17, commitment, config, args, unsafeRes, res, _res, _res2, result; - return _regeneratorRuntime().wrap(function _callee39$(_context39) { - while (1) switch (_context39.prev = _context39.next) { + return _regeneratorRuntime().wrap(function _callee66$(_context66) { + while (1) switch (_context66.prev = _context66.next) { case 0: - commitment = _ref35.commitment, signature = _ref35.signature; - expiryPromise = new Promise(function (resolve) { - var timeoutMs = _this19._confirmTransactionInitialTimeout || 60 * 1000; - - switch (commitment) { - case 'processed': - case 'recent': - case 'single': - case 'confirmed': - case 'singleGossip': - { - timeoutMs = _this19._confirmTransactionInitialTimeout || 30 * 1000; - break; - } - } + _extractCommitmentFro17 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro17.commitment, config = _extractCommitmentFro17.config; + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined + /* encoding */ + , config); + _context66.next = 4; + return this._rpcRequest('getBlock', args); - timeoutId = setTimeout(function () { - return resolve({ - __type: TransactionStatus.TIMED_OUT, - timeoutMs: timeoutMs - }); - }, timeoutMs); - }); - _this$getTransactionC3 = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC3.abortConfirmation, confirmationPromise = _this$getTransactionC3.confirmationPromise; - _context39.prev = 3; - _context39.next = 6; - return Promise.race([confirmationPromise, expiryPromise]); + case 4: + unsafeRes = _context66.sent; + _context66.prev = 5; + _context66.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; + _context66.next = _context66.t0 === 'accounts' ? 9 : _context66.t0 === 'none' ? 13 : 17; + break; - case 6: - outcome = _context39.sent; + case 9: + res = _create(unsafeRes, GetAccountsModeBlockRpcResult); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context39.next = 11; + if (!('error' in res)) { + _context66.next = 12; break; } - result = outcome.response; - _context39.next = 12; - break; - - case 11: - throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000); + throw res.error; case 12: - _context39.prev = 12; - clearTimeout(timeoutId); - abortConfirmation(); - return _context39.finish(12); + return _context66.abrupt("return", res.result); + + case 13: + _res = _create(unsafeRes, GetNoneModeBlockRpcResult); + + if (!('error' in _res)) { + _context66.next = 16; + break; + } + + throw _res.error; case 16: - return _context39.abrupt("return", result); + return _context66.abrupt("return", _res.result); case 17: + _res2 = _create(unsafeRes, GetBlockRpcResult); + + if (!('error' in _res2)) { + _context66.next = 20; + break; + } + + throw _res2.error; + + case 20: + result = _res2.result; + return _context66.abrupt("return", result ? _objectSpread2(_objectSpread2({}, result), {}, { + transactions: result.transactions.map(function (_ref36) { + var transaction = _ref36.transaction, + meta = _ref36.meta, + version = _ref36.version; + return { + meta: meta, + transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { + message: versionedMessageFromResponse(version, transaction.message) + }), + version: version + }; + }) + }) : null); + + case 22: + _context66.next = 27; + break; + + case 24: + _context66.prev = 24; + _context66.t1 = _context66["catch"](5); + throw new SolanaJSONRPCError(_context66.t1, 'failed to get confirmed block'); + + case 27: case "end": - return _context39.stop(); + return _context66.stop(); } - }, _callee39, this, [[3,, 12, 16]]); + }, _callee66, this, [[5, 24]]); })); - function confirmTransactionUsingLegacyTimeoutStrategy(_x65) { - return _confirmTransactionUsingLegacyTimeoutStrategy.apply(this, arguments); + function getBlock(_x94, _x95) { + return _getBlock.apply(this, arguments); } - return confirmTransactionUsingLegacyTimeoutStrategy; + return getBlock; }() /** - * Return the list of nodes that are currently participating in the cluster + * Fetch parsed transaction details for a confirmed or finalized block */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getClusterNodes", + key: "getParsedBlock", value: function () { - var _getClusterNodes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee40() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee40$(_context40) { - while (1) switch (_context40.prev = _context40.next) { + var _getParsedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee67(slot, rawConfig) { + var _extractCommitmentFro18, commitment, config, args, unsafeRes, res, _res3, _res4; + + return _regeneratorRuntime().wrap(function _callee67$(_context67) { + while (1) switch (_context67.prev = _context67.next) { case 0: - _context40.next = 2; - return this._rpcRequest('getClusterNodes', []); + _extractCommitmentFro18 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro18.commitment, config = _extractCommitmentFro18.config; + args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config); + _context67.next = 4; + return this._rpcRequest('getBlock', args); - case 2: - unsafeRes = _context40.sent; - res = _create(unsafeRes, jsonRpcResult(array(ContactInfoResult))); + case 4: + unsafeRes = _context67.sent; + _context67.prev = 5; + _context67.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; + _context67.next = _context67.t0 === 'accounts' ? 9 : _context67.t0 === 'none' ? 13 : 17; + break; + + case 9: + res = _create(unsafeRes, GetParsedAccountsModeBlockRpcResult); if (!('error' in res)) { - _context40.next = 6; + _context67.next = 12; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes'); + throw res.error; - case 6: - return _context40.abrupt("return", res.result); + case 12: + return _context67.abrupt("return", res.result); - case 7: - case "end": - return _context40.stop(); - } - }, _callee40, this); - })); + case 13: + _res3 = _create(unsafeRes, GetParsedNoneModeBlockRpcResult); - function getClusterNodes() { - return _getClusterNodes.apply(this, arguments); - } + if (!('error' in _res3)) { + _context67.next = 16; + break; + } - return getClusterNodes; - }() - /** - * Return the list of nodes that are currently participating in the cluster - */ + throw _res3.error; - }, { - key: "getVoteAccounts", - value: function () { - var _getVoteAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee41(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee41$(_context41) { - while (1) switch (_context41.prev = _context41.next) { - case 0: - args = this._buildArgs([], commitment); - _context41.next = 3; - return this._rpcRequest('getVoteAccounts', args); + case 16: + return _context67.abrupt("return", _res3.result); - case 3: - unsafeRes = _context41.sent; - res = _create(unsafeRes, GetVoteAccounts); + case 17: + _res4 = _create(unsafeRes, GetParsedBlockRpcResult); - if (!('error' in res)) { - _context41.next = 7; + if (!('error' in _res4)) { + _context67.next = 20; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts'); + throw _res4.error; - case 7: - return _context41.abrupt("return", res.result); + case 20: + return _context67.abrupt("return", _res4.result); - case 8: + case 21: + _context67.next = 26; + break; + + case 23: + _context67.prev = 23; + _context67.t1 = _context67["catch"](5); + throw new SolanaJSONRPCError(_context67.t1, 'failed to get block'); + + case 26: case "end": - return _context41.stop(); + return _context67.stop(); } - }, _callee41, this); + }, _callee67, this, [[5, 23]]); })); - function getVoteAccounts(_x66) { - return _getVoteAccounts.apply(this, arguments); + function getParsedBlock(_x96, _x97) { + return _getParsedBlock.apply(this, arguments); } - return getVoteAccounts; + return getParsedBlock; }() - /** - * Fetch the current slot that the node is processing + /* + * Returns the current block height of the node + */ + + /* + * Returns recent block production information from the current or previous epoch */ }, { - key: "getSlot", + key: "getBlockProduction", value: function () { - var _getSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee42(commitmentOrConfig) { - var _extractCommitmentFro11, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee42$(_context42) { - while (1) switch (_context42.prev = _context42.next) { + var _getBlockProduction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee68(configOrCommitment) { + var extra, commitment, c, rest, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee68$(_context68) { + while (1) switch (_context68.prev = _context68.next) { case 0: - _extractCommitmentFro11 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro11.commitment, config = _extractCommitmentFro11.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context42.next = 4; - return this._rpcRequest('getSlot', args); + if (typeof configOrCommitment === 'string') { + commitment = configOrCommitment; + } else if (configOrCommitment) { + c = configOrCommitment.commitment, rest = _objectWithoutProperties(configOrCommitment, _excluded3); + commitment = c; + extra = rest; + } + + args = this._buildArgs([], commitment, 'base64', extra); + _context68.next = 4; + return this._rpcRequest('getBlockProduction', args); case 4: - unsafeRes = _context42.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + unsafeRes = _context68.sent; + res = _create(unsafeRes, BlockProductionResponseStruct); if (!('error' in res)) { - _context42.next = 8; + _context68.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot'); + throw new SolanaJSONRPCError(res.error, 'failed to get block production information'); case 8: - return _context42.abrupt("return", res.result); + return _context68.abrupt("return", res.result); case 9: case "end": - return _context42.stop(); + return _context68.stop(); } - }, _callee42, this); + }, _callee68, this); })); - function getSlot(_x67) { - return _getSlot.apply(this, arguments); + function getBlockProduction(_x98) { + return _getBlockProduction.apply(this, arguments); } - return getSlot; + return getBlockProduction; }() /** - * Fetch the current slot leader of the cluster + * Fetch a confirmed or finalized transaction from the cluster. + * + * @deprecated Instead, call `getTransaction` using a + * `GetVersionedTransactionConfig` by setting the + * `maxSupportedTransactionVersion` property. + */ + + /** + * Fetch a confirmed or finalized transaction from the cluster. */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getSlotLeader", + key: "getTransaction", value: function () { - var _getSlotLeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee43(commitmentOrConfig) { - var _extractCommitmentFro12, commitment, config, args, unsafeRes, res; + var _getTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee69(signature, rawConfig) { + var _extractCommitmentFro19, commitment, config, args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee43$(_context43) { - while (1) switch (_context43.prev = _context43.next) { + return _regeneratorRuntime().wrap(function _callee69$(_context69) { + while (1) switch (_context69.prev = _context69.next) { case 0: - _extractCommitmentFro12 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro12.commitment, config = _extractCommitmentFro12.config; - args = this._buildArgs([], commitment, undefined + _extractCommitmentFro19 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro19.commitment, config = _extractCommitmentFro19.config; + args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */ , config); - _context43.next = 4; - return this._rpcRequest('getSlotLeader', args); + _context69.next = 4; + return this._rpcRequest('getTransaction', args); case 4: - unsafeRes = _context43.sent; - res = _create(unsafeRes, jsonRpcResult(string())); + unsafeRes = _context69.sent; + res = _create(unsafeRes, GetTransactionRpcResult); if (!('error' in res)) { - _context43.next = 8; + _context69.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot leader'); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 8: - return _context43.abrupt("return", res.result); - - case 9: - case "end": - return _context43.stop(); - } - }, _callee43, this); - })); - - function getSlotLeader(_x68) { - return _getSlotLeader.apply(this, arguments); - } - - return getSlotLeader; - }() - /** - * Fetch `limit` number of slot leaders starting from `startSlot` - * - * @param startSlot fetch slot leaders starting from this slot - * @param limit number of slot leaders to return - */ - - }, { - key: "getSlotLeaders", - value: function () { - var _getSlotLeaders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee44(startSlot, limit) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee44$(_context44) { - while (1) switch (_context44.prev = _context44.next) { - case 0: - args = [startSlot, limit]; - _context44.next = 3; - return this._rpcRequest('getSlotLeaders', args); - - case 3: - unsafeRes = _context44.sent; - res = _create(unsafeRes, jsonRpcResult(array(PublicKeyFromString))); + result = res.result; - if (!('error' in res)) { - _context44.next = 7; + if (result) { + _context69.next = 11; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders'); + return _context69.abrupt("return", result); - case 7: - return _context44.abrupt("return", res.result); + case 11: + return _context69.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { + transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { + message: versionedMessageFromResponse(result.version, result.transaction.message) + }) + })); - case 8: + case 12: case "end": - return _context44.stop(); + return _context69.stop(); } - }, _callee44, this); + }, _callee69, this); })); - function getSlotLeaders(_x69, _x70) { - return _getSlotLeaders.apply(this, arguments); + function getTransaction(_x99, _x100) { + return _getTransaction.apply(this, arguments); } - return getSlotLeaders; + return getTransaction; }() /** - * Fetch the current status of a signature + * Fetch parsed transaction details for a confirmed or finalized transaction */ }, { - key: "getSignatureStatus", + key: "getParsedTransaction", value: function () { - var _getSignatureStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee45(signature, config) { - var _yield$this$getSignat, context, values, value; - - return _regeneratorRuntime().wrap(function _callee45$(_context45) { - while (1) switch (_context45.prev = _context45.next) { - case 0: - _context45.next = 2; - return this.getSignatureStatuses([signature], config); - - case 2: - _yield$this$getSignat = _context45.sent; - context = _yield$this$getSignat.context; - values = _yield$this$getSignat.value; - assert(values.length === 1); - value = values[0]; - return _context45.abrupt("return", { - context: context, - value: value - }); - - case 8: - case "end": - return _context45.stop(); - } - }, _callee45, this); - })); - - function getSignatureStatus(_x71, _x72) { - return _getSignatureStatus.apply(this, arguments); - } - - return getSignatureStatus; - }() - /** - * Fetch the current statuses of a batch of signatures - */ + var _getParsedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee70(signature, commitmentOrConfig) { + var _extractCommitmentFro20, commitment, config, args, unsafeRes, res; - }, { - key: "getSignatureStatuses", - value: function () { - var _getSignatureStatuses = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee46(signatures, config) { - var params, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee46$(_context46) { - while (1) switch (_context46.prev = _context46.next) { + return _regeneratorRuntime().wrap(function _callee70$(_context70) { + while (1) switch (_context70.prev = _context70.next) { case 0: - params = [signatures]; - - if (config) { - params.push(config); - } - - _context46.next = 4; - return this._rpcRequest('getSignatureStatuses', params); + _extractCommitmentFro20 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro20.commitment, config = _extractCommitmentFro20.config; + args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); + _context70.next = 4; + return this._rpcRequest('getTransaction', args); case 4: - unsafeRes = _context46.sent; - res = _create(unsafeRes, GetSignatureStatusesRpcResult); + unsafeRes = _context70.sent; + res = _create(unsafeRes, GetParsedTransactionRpcResult); if (!('error' in res)) { - _context46.next = 8; + _context70.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get signature status'); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 8: - return _context46.abrupt("return", res.result); + return _context70.abrupt("return", res.result); case 9: case "end": - return _context46.stop(); + return _context70.stop(); } - }, _callee46, this); + }, _callee70, this); })); - function getSignatureStatuses(_x73, _x74) { - return _getSignatureStatuses.apply(this, arguments); + function getParsedTransaction(_x101, _x102) { + return _getParsedTransaction.apply(this, arguments); } - return getSignatureStatuses; + return getParsedTransaction; }() /** - * Fetch the current transaction count of the cluster + * Fetch parsed transaction details for a batch of confirmed transactions */ }, { - key: "getTransactionCount", + key: "getParsedTransactions", value: function () { - var _getTransactionCount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee47(commitmentOrConfig) { - var _extractCommitmentFro13, commitment, config, args, unsafeRes, res; + var _getParsedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee71(signatures, commitmentOrConfig) { + var _this20 = this; - return _regeneratorRuntime().wrap(function _callee47$(_context47) { - while (1) switch (_context47.prev = _context47.next) { + var _extractCommitmentFro21, commitment, config, batch, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee71$(_context71) { + while (1) switch (_context71.prev = _context71.next) { case 0: - _extractCommitmentFro13 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro13.commitment, config = _extractCommitmentFro13.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context47.next = 4; - return this._rpcRequest('getTransactionCount', args); + _extractCommitmentFro21 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro21.commitment, config = _extractCommitmentFro21.config; + batch = signatures.map(function (signature) { + var args = _this20._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); - case 4: - unsafeRes = _context47.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + return { + methodName: 'getTransaction', + args: args + }; + }); + _context71.next = 4; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context47.next = 8; - break; - } + case 4: + unsafeRes = _context71.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetParsedTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get transaction count'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + } - case 8: - return _context47.abrupt("return", res.result); + return res.result; + }); + return _context71.abrupt("return", res); - case 9: + case 7: case "end": - return _context47.stop(); + return _context71.stop(); } - }, _callee47, this); + }, _callee71, this); })); - function getTransactionCount(_x75) { - return _getTransactionCount.apply(this, arguments); + function getParsedTransactions(_x103, _x104) { + return _getParsedTransactions.apply(this, arguments); } - return getTransactionCount; + return getParsedTransactions; }() /** - * Fetch the current total currency supply of the cluster in lamports + * Fetch transaction details for a batch of confirmed transactions. + * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}. * - * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead. + * @deprecated Instead, call `getTransactions` using a + * `GetVersionedTransactionConfig` by setting the + * `maxSupportedTransactionVersion` property. */ - }, { - key: "getTotalSupply", - value: function () { - var _getTotalSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee48(commitment) { - var result; - return _regeneratorRuntime().wrap(function _callee48$(_context48) { - while (1) switch (_context48.prev = _context48.next) { - case 0: - _context48.next = 2; - return this.getSupply({ - commitment: commitment, - excludeNonCirculatingAccountsList: true - }); - - case 2: - result = _context48.sent; - return _context48.abrupt("return", result.value.total); - - case 4: - case "end": - return _context48.stop(); - } - }, _callee48, this); - })); - - function getTotalSupply(_x76) { - return _getTotalSupply.apply(this, arguments); - } - - return getTotalSupply; - }() /** - * Fetch the cluster InflationGovernor parameters + * Fetch transaction details for a batch of confirmed transactions. + * Similar to {@link getParsedTransactions} but returns a {@link + * VersionedTransactionResponse}. */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getInflationGovernor", + key: "getTransactions", value: function () { - var _getInflationGovernor = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee49(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee49$(_context49) { - while (1) switch (_context49.prev = _context49.next) { + var _getTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee72(signatures, commitmentOrConfig) { + var _this21 = this; + + var _extractCommitmentFro22, commitment, config, batch, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee72$(_context72) { + while (1) switch (_context72.prev = _context72.next) { case 0: - args = this._buildArgs([], commitment); - _context49.next = 3; - return this._rpcRequest('getInflationGovernor', args); + _extractCommitmentFro22 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro22.commitment, config = _extractCommitmentFro22.config; + batch = signatures.map(function (signature) { + var args = _this21._buildArgsAtLeastConfirmed([signature], commitment, undefined + /* encoding */ + , config); - case 3: - unsafeRes = _context49.sent; - res = _create(unsafeRes, GetInflationGovernorRpcResult); + return { + methodName: 'getTransaction', + args: args + }; + }); + _context72.next = 4; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context49.next = 7; - break; - } + case 4: + unsafeRes = _context72.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get inflation'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + } + + var result = res.result; + if (!result) return result; + return _objectSpread2(_objectSpread2({}, result), {}, { + transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { + message: versionedMessageFromResponse(result.version, result.transaction.message) + }) + }); + }); + return _context72.abrupt("return", res); case 7: - return _context49.abrupt("return", res.result); - - case 8: case "end": - return _context49.stop(); + return _context72.stop(); } - }, _callee49, this); + }, _callee72, this); })); - function getInflationGovernor(_x77) { - return _getInflationGovernor.apply(this, arguments); + function getTransactions(_x105, _x106) { + return _getTransactions.apply(this, arguments); } - return getInflationGovernor; + return getTransactions; }() /** - * Fetch the inflation reward for a list of addresses for an epoch + * Fetch a list of Transactions and transaction statuses from the cluster + * for a confirmed block. + * + * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead. */ }, { - key: "getInflationReward", + key: "getConfirmedBlock", value: function () { - var _getInflationReward = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee50(addresses, epoch, commitmentOrConfig) { - var _extractCommitmentFro14, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee50$(_context50) { - while (1) switch (_context50.prev = _context50.next) { + var _getConfirmedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee73(slot, commitment) { + var args, unsafeRes, res, result, block; + return _regeneratorRuntime().wrap(function _callee73$(_context73) { + while (1) switch (_context73.prev = _context73.next) { case 0: - _extractCommitmentFro14 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro14.commitment, config = _extractCommitmentFro14.config; - args = this._buildArgs([addresses.map(function (pubkey) { - return pubkey.toBase58(); - })], commitment, undefined - /* encoding */ - , _objectSpread2(_objectSpread2({}, config), {}, { - epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch - })); - _context50.next = 4; - return this._rpcRequest('getInflationReward', args); + args = this._buildArgsAtLeastConfirmed([slot], commitment); + _context73.next = 3; + return this._rpcRequest('getConfirmedBlock', args); - case 4: - unsafeRes = _context50.sent; - res = _create(unsafeRes, GetInflationRewardResult); + case 3: + unsafeRes = _context73.sent; + res = _create(unsafeRes, GetConfirmedBlockRpcResult); if (!('error' in res)) { - _context50.next = 8; + _context73.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward'); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); - case 8: - return _context50.abrupt("return", res.result); + case 7: + result = res.result; - case 9: + if (result) { + _context73.next = 10; + break; + } + + throw new Error('Confirmed block ' + slot + ' not found'); + + case 10: + block = _objectSpread2(_objectSpread2({}, result), {}, { + transactions: result.transactions.map(function (_ref37) { + var transaction = _ref37.transaction, + meta = _ref37.meta; + var message = new Message(transaction.message); + return { + meta: meta, + transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { + message: message + }) + }; + }) + }); + return _context73.abrupt("return", _objectSpread2(_objectSpread2({}, block), {}, { + transactions: block.transactions.map(function (_ref38) { + var transaction = _ref38.transaction, + meta = _ref38.meta; + return { + meta: meta, + transaction: Transaction.populate(transaction.message, transaction.signatures) + }; + }) + })); + + case 12: case "end": - return _context50.stop(); + return _context73.stop(); } - }, _callee50, this); + }, _callee73, this); })); - function getInflationReward(_x78, _x79, _x80) { - return _getInflationReward.apply(this, arguments); + function getConfirmedBlock(_x107, _x108) { + return _getConfirmedBlock.apply(this, arguments); } - return getInflationReward; + return getConfirmedBlock; }() /** - * Fetch the specific inflation values for the current epoch + * Fetch confirmed blocks between two slots */ }, { - key: "getInflationRate", + key: "getBlocks", value: function () { - var _getInflationRate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee51() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee51$(_context51) { - while (1) switch (_context51.prev = _context51.next) { + var _getBlocks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee74(startSlot, endSlot, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee74$(_context74) { + while (1) switch (_context74.prev = _context74.next) { case 0: - _context51.next = 2; - return this._rpcRequest('getInflationRate', []); + args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment); + _context74.next = 3; + return this._rpcRequest('getBlocks', args); - case 2: - unsafeRes = _context51.sent; - res = _create(unsafeRes, GetInflationRateRpcResult); + case 3: + unsafeRes = _context74.sent; + res = _create(unsafeRes, jsonRpcResult(array(number()))); if (!('error' in res)) { - _context51.next = 6; + _context74.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate'); - - case 6: - return _context51.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get blocks'); case 7: + return _context74.abrupt("return", res.result); + + case 8: case "end": - return _context51.stop(); + return _context74.stop(); } - }, _callee51, this); + }, _callee74, this); })); - function getInflationRate() { - return _getInflationRate.apply(this, arguments); + function getBlocks(_x109, _x110, _x111) { + return _getBlocks.apply(this, arguments); } - return getInflationRate; + return getBlocks; }() /** - * Fetch the Epoch Info parameters + * Fetch a list of Signatures from the cluster for a block, excluding rewards */ }, { - key: "getEpochInfo", + key: "getBlockSignatures", value: function () { - var _getEpochInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee52(commitmentOrConfig) { - var _extractCommitmentFro15, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee52$(_context52) { - while (1) switch (_context52.prev = _context52.next) { + var _getBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee75(slot, commitment) { + var args, unsafeRes, res, result; + return _regeneratorRuntime().wrap(function _callee75$(_context75) { + while (1) switch (_context75.prev = _context75.next) { case 0: - _extractCommitmentFro15 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro15.commitment, config = _extractCommitmentFro15.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context52.next = 4; - return this._rpcRequest('getEpochInfo', args); + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { + transactionDetails: 'signatures', + rewards: false + }); + _context75.next = 3; + return this._rpcRequest('getBlock', args); - case 4: - unsafeRes = _context52.sent; - res = _create(unsafeRes, GetEpochInfoRpcResult); + case 3: + unsafeRes = _context75.sent; + res = _create(unsafeRes, GetBlockSignaturesRpcResult); if (!('error' in res)) { - _context52.next = 8; + _context75.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get epoch info'); + throw new SolanaJSONRPCError(res.error, 'failed to get block'); - case 8: - return _context52.abrupt("return", res.result); + case 7: + result = res.result; - case 9: + if (result) { + _context75.next = 10; + break; + } + + throw new Error('Block ' + slot + ' not found'); + + case 10: + return _context75.abrupt("return", result); + + case 11: case "end": - return _context52.stop(); + return _context75.stop(); } - }, _callee52, this); + }, _callee75, this); })); - function getEpochInfo(_x81) { - return _getEpochInfo.apply(this, arguments); + function getBlockSignatures(_x112, _x113) { + return _getBlockSignatures.apply(this, arguments); } - return getEpochInfo; + return getBlockSignatures; }() /** - * Fetch the Epoch Schedule parameters + * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead. */ }, { - key: "getEpochSchedule", + key: "getConfirmedBlockSignatures", value: function () { - var _getEpochSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee53() { - var unsafeRes, res, epochSchedule; - return _regeneratorRuntime().wrap(function _callee53$(_context53) { - while (1) switch (_context53.prev = _context53.next) { + var _getConfirmedBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee76(slot, commitment) { + var args, unsafeRes, res, result; + return _regeneratorRuntime().wrap(function _callee76$(_context76) { + while (1) switch (_context76.prev = _context76.next) { case 0: - _context53.next = 2; - return this._rpcRequest('getEpochSchedule', []); + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { + transactionDetails: 'signatures', + rewards: false + }); + _context76.next = 3; + return this._rpcRequest('getConfirmedBlock', args); - case 2: - unsafeRes = _context53.sent; - res = _create(unsafeRes, GetEpochScheduleRpcResult); + case 3: + unsafeRes = _context76.sent; + res = _create(unsafeRes, GetBlockSignaturesRpcResult); if (!('error' in res)) { - _context53.next = 6; + _context76.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule'); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); - case 6: - epochSchedule = res.result; - return _context53.abrupt("return", new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot)); + case 7: + result = res.result; - case 8: + if (result) { + _context76.next = 10; + break; + } + + throw new Error('Confirmed block ' + slot + ' not found'); + + case 10: + return _context76.abrupt("return", result); + + case 11: case "end": - return _context53.stop(); + return _context76.stop(); } - }, _callee53, this); + }, _callee76, this); })); - function getEpochSchedule() { - return _getEpochSchedule.apply(this, arguments); + function getConfirmedBlockSignatures(_x114, _x115) { + return _getConfirmedBlockSignatures.apply(this, arguments); } - return getEpochSchedule; + return getConfirmedBlockSignatures; }() /** - * Fetch the leader schedule for the current epoch - * @return {Promise>} + * Fetch a transaction details for a confirmed transaction + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead. */ }, { - key: "getLeaderSchedule", + key: "getConfirmedTransaction", value: function () { - var _getLeaderSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee54() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee54$(_context54) { - while (1) switch (_context54.prev = _context54.next) { + var _getConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee77(signature, commitment) { + var args, unsafeRes, res, result, message, signatures; + return _regeneratorRuntime().wrap(function _callee77$(_context77) { + while (1) switch (_context77.prev = _context77.next) { case 0: - _context54.next = 2; - return this._rpcRequest('getLeaderSchedule', []); + args = this._buildArgsAtLeastConfirmed([signature], commitment); + _context77.next = 3; + return this._rpcRequest('getConfirmedTransaction', args); - case 2: - unsafeRes = _context54.sent; - res = _create(unsafeRes, GetLeaderScheduleRpcResult); + case 3: + unsafeRes = _context77.sent; + res = _create(unsafeRes, GetTransactionRpcResult); if (!('error' in res)) { - _context54.next = 6; + _context77.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule'); - - case 6: - return _context54.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 7: + result = res.result; + + if (result) { + _context77.next = 10; + break; + } + + return _context77.abrupt("return", result); + + case 10: + message = new Message(result.transaction.message); + signatures = result.transaction.signatures; + return _context77.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { + transaction: Transaction.populate(message, signatures) + })); + + case 13: case "end": - return _context54.stop(); + return _context77.stop(); } - }, _callee54, this); + }, _callee77, this); })); - function getLeaderSchedule() { - return _getLeaderSchedule.apply(this, arguments); + function getConfirmedTransaction(_x116, _x117) { + return _getConfirmedTransaction.apply(this, arguments); } - return getLeaderSchedule; + return getConfirmedTransaction; }() /** - * Fetch the minimum balance needed to exempt an account of `dataLength` - * size from rent + * Fetch parsed transaction details for a confirmed transaction + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead. */ }, { - key: "getMinimumBalanceForRentExemption", + key: "getParsedConfirmedTransaction", value: function () { - var _getMinimumBalanceForRentExemption = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee55(dataLength, commitment) { + var _getParsedConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee78(signature, commitment) { var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee55$(_context55) { - while (1) switch (_context55.prev = _context55.next) { + return _regeneratorRuntime().wrap(function _callee78$(_context78) { + while (1) switch (_context78.prev = _context78.next) { case 0: - args = this._buildArgs([dataLength], commitment); - _context55.next = 3; - return this._rpcRequest('getMinimumBalanceForRentExemption', args); + args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); + _context78.next = 3; + return this._rpcRequest('getConfirmedTransaction', args); case 3: - unsafeRes = _context55.sent; - res = _create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult); + unsafeRes = _context78.sent; + res = _create(unsafeRes, GetParsedTransactionRpcResult); if (!('error' in res)) { - _context55.next = 8; + _context78.next = 7; break; } - console.warn('Unable to fetch minimum balance for rent exemption'); - return _context55.abrupt("return", 0); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction'); - case 8: - return _context55.abrupt("return", res.result); + case 7: + return _context78.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context55.stop(); + return _context78.stop(); } - }, _callee55, this); + }, _callee78, this); })); - function getMinimumBalanceForRentExemption(_x82, _x83) { - return _getMinimumBalanceForRentExemption.apply(this, arguments); + function getParsedConfirmedTransaction(_x118, _x119) { + return _getParsedConfirmedTransaction.apply(this, arguments); } - return getMinimumBalanceForRentExemption; + return getParsedConfirmedTransaction; }() /** - * Fetch a recent blockhash from the cluster, return with context - * @return {Promise>} + * Fetch parsed transaction details for a batch of confirmed transactions * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead. */ }, { - key: "getRecentBlockhashAndContext", + key: "getParsedConfirmedTransactions", value: function () { - var _getRecentBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee56(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee56$(_context56) { - while (1) switch (_context56.prev = _context56.next) { + var _getParsedConfirmedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee79(signatures, commitment) { + var _this22 = this; + + var batch, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee79$(_context79) { + while (1) switch (_context79.prev = _context79.next) { case 0: - args = this._buildArgs([], commitment); - _context56.next = 3; - return this._rpcRequest('getRecentBlockhash', args); + batch = signatures.map(function (signature) { + var args = _this22._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); - case 3: - unsafeRes = _context56.sent; - res = _create(unsafeRes, GetRecentBlockhashAndContextRpcResult); + return { + methodName: 'getConfirmedTransaction', + args: args + }; + }); + _context79.next = 3; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context56.next = 7; - break; - } + case 3: + unsafeRes = _context79.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetParsedTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions'); + } - case 7: - return _context56.abrupt("return", res.result); + return res.result; + }); + return _context79.abrupt("return", res); - case 8: + case 6: case "end": - return _context56.stop(); + return _context79.stop(); } - }, _callee56, this); + }, _callee79, this); })); - function getRecentBlockhashAndContext(_x84) { - return _getRecentBlockhashAndContext.apply(this, arguments); + function getParsedConfirmedTransactions(_x120, _x121) { + return _getParsedConfirmedTransactions.apply(this, arguments); } - return getRecentBlockhashAndContext; + return getParsedConfirmedTransactions; }() /** - * Fetch recent performance samples - * @return {Promise>} + * Fetch a list of all the confirmed signatures for transactions involving an address + * within a specified slot range. Max range allowed is 10,000 slots. + * + * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead. + * + * @param address queried address + * @param startSlot start slot, inclusive + * @param endSlot end slot, inclusive */ }, { - key: "getRecentPerformanceSamples", + key: "getConfirmedSignaturesForAddress", value: function () { - var _getRecentPerformanceSamples = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee57(limit) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee57$(_context57) { - while (1) switch (_context57.prev = _context57.next) { + var _getConfirmedSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee80(address, startSlot, endSlot) { + var options, firstAvailableBlock, block, highestConfirmedRoot, _block, confirmedSignatureInfo; + + return _regeneratorRuntime().wrap(function _callee80$(_context80) { + while (1) switch (_context80.prev = _context80.next) { case 0: - _context57.next = 2; - return this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []); + options = {}; + _context80.next = 3; + return this.getFirstAvailableBlock(); - case 2: - unsafeRes = _context57.sent; - res = _create(unsafeRes, GetRecentPerformanceSamplesRpcResult); + case 3: + firstAvailableBlock = _context80.sent; - if (!('error' in res)) { - _context57.next = 6; + case 4: + if ('until' in options) { + _context80.next = 24; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples'); + startSlot--; - case 6: - return _context57.abrupt("return", res.result); + if (!(startSlot <= 0 || startSlot < firstAvailableBlock)) { + _context80.next = 8; + break; + } - case 7: - case "end": - return _context57.stop(); - } - }, _callee57, this); - })); + return _context80.abrupt("break", 24); - function getRecentPerformanceSamples(_x85) { - return _getRecentPerformanceSamples.apply(this, arguments); - } + case 8: + _context80.prev = 8; + _context80.next = 11; + return this.getConfirmedBlockSignatures(startSlot, 'finalized'); - return getRecentPerformanceSamples; - }() - /** - * Fetch the fee calculator for a recent blockhash from the cluster, return with context - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead. - */ + case 11: + block = _context80.sent; - }, { - key: "getFeeCalculatorForBlockhash", - value: function () { - var _getFeeCalculatorForBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee58(blockhash, commitment) { - var args, unsafeRes, res, _res$result, context, value; + if (block.signatures.length > 0) { + options.until = block.signatures[block.signatures.length - 1].toString(); + } - return _regeneratorRuntime().wrap(function _callee58$(_context58) { - while (1) switch (_context58.prev = _context58.next) { - case 0: - args = this._buildArgs([blockhash], commitment); - _context58.next = 3; - return this._rpcRequest('getFeeCalculatorForBlockhash', args); + _context80.next = 22; + break; - case 3: - unsafeRes = _context58.sent; - res = _create(unsafeRes, GetFeeCalculatorRpcResult); + case 15: + _context80.prev = 15; + _context80.t0 = _context80["catch"](8); - if (!('error' in res)) { - _context58.next = 7; + if (!(_context80.t0 instanceof Error && _context80.t0.message.includes('skipped'))) { + _context80.next = 21; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator'); - - case 7: - _res$result = res.result, context = _res$result.context, value = _res$result.value; - return _context58.abrupt("return", { - context: context, - value: value !== null ? value.feeCalculator : null - }); - - case 9: - case "end": - return _context58.stop(); - } - }, _callee58, this); - })); + return _context80.abrupt("continue", 4); - function getFeeCalculatorForBlockhash(_x86, _x87) { - return _getFeeCalculatorForBlockhash.apply(this, arguments); - } + case 21: + throw _context80.t0; - return getFeeCalculatorForBlockhash; - }() - /** - * Fetch the fee for a message from the cluster, return with context - */ + case 22: + _context80.next = 4; + break; - }, { - key: "getFeeForMessage", - value: function () { - var _getFeeForMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee59(message, commitment) { - var wireMessage, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee59$(_context59) { - while (1) switch (_context59.prev = _context59.next) { - case 0: - wireMessage = toBuffer(message.serialize()).toString('base64'); - args = this._buildArgs([wireMessage], commitment); - _context59.next = 4; - return this._rpcRequest('getFeeForMessage', args); + case 24: + _context80.next = 26; + return this.getSlot('finalized'); - case 4: - unsafeRes = _context59.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(number()))); + case 26: + highestConfirmedRoot = _context80.sent; - if (!('error' in res)) { - _context59.next = 8; + case 27: + if ('before' in options) { + _context80.next = 47; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get fee for message'); + endSlot++; - case 8: - if (!(res.result === null)) { - _context59.next = 10; + if (!(endSlot > highestConfirmedRoot)) { + _context80.next = 31; break; } - throw new Error('invalid blockhash'); - - case 10: - return _context59.abrupt("return", res.result); - - case 11: - case "end": - return _context59.stop(); - } - }, _callee59, this); - })); + return _context80.abrupt("break", 47); - function getFeeForMessage(_x88, _x89) { - return _getFeeForMessage.apply(this, arguments); - } + case 31: + _context80.prev = 31; + _context80.next = 34; + return this.getConfirmedBlockSignatures(endSlot); - return getFeeForMessage; - }() - /** - * Fetch a list of prioritization fees from recent blocks. - */ + case 34: + _block = _context80.sent; - }, { - key: "getRecentPrioritizationFees", - value: function () { - var _getRecentPrioritizationFees = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee60(config) { - var _config$lockedWritabl; + if (_block.signatures.length > 0) { + options.before = _block.signatures[_block.signatures.length - 1].toString(); + } - var accounts, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee60$(_context60) { - while (1) switch (_context60.prev = _context60.next) { - case 0: - accounts = config === null || config === void 0 ? void 0 : (_config$lockedWritabl = config.lockedWritableAccounts) === null || _config$lockedWritabl === void 0 ? void 0 : _config$lockedWritabl.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs(accounts !== null && accounts !== void 0 && accounts.length ? [accounts] : []); - _context60.next = 4; - return this._rpcRequest('getRecentPrioritizationFees', args); + _context80.next = 45; + break; - case 4: - unsafeRes = _context60.sent; - res = _create(unsafeRes, GetRecentPrioritizationFeesRpcResult); + case 38: + _context80.prev = 38; + _context80.t1 = _context80["catch"](31); - if (!('error' in res)) { - _context60.next = 8; + if (!(_context80.t1 instanceof Error && _context80.t1.message.includes('skipped'))) { + _context80.next = 44; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees'); + return _context80.abrupt("continue", 27); - case 8: - return _context60.abrupt("return", res.result); + case 44: + throw _context80.t1; - case 9: + case 45: + _context80.next = 27; + break; + + case 47: + _context80.next = 49; + return this.getConfirmedSignaturesForAddress2(address, options); + + case 49: + confirmedSignatureInfo = _context80.sent; + return _context80.abrupt("return", confirmedSignatureInfo.map(function (info) { + return info.signature; + })); + + case 51: case "end": - return _context60.stop(); + return _context80.stop(); } - }, _callee60, this); + }, _callee80, this, [[8, 15], [31, 38]]); })); - function getRecentPrioritizationFees(_x90) { - return _getRecentPrioritizationFees.apply(this, arguments); + function getConfirmedSignaturesForAddress(_x122, _x123, _x124) { + return _getConfirmedSignaturesForAddress.apply(this, arguments); } - return getRecentPrioritizationFees; + return getConfirmedSignaturesForAddress; }() /** - * Fetch a recent blockhash from the cluster - * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} + * Returns confirmed signatures for transactions involving an + * address backwards in time from the provided signature or most recent confirmed block * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + * + * @param address queried address + * @param options */ }, { - key: "getRecentBlockhash", + key: "getConfirmedSignaturesForAddress2", value: function () { - var _getRecentBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee61(commitment) { - var res; - return _regeneratorRuntime().wrap(function _callee61$(_context61) { - while (1) switch (_context61.prev = _context61.next) { + var _getConfirmedSignaturesForAddress2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee81(address, options, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee81$(_context81) { + while (1) switch (_context81.prev = _context81.next) { case 0: - _context61.prev = 0; - _context61.next = 3; - return this.getRecentBlockhashAndContext(commitment); + args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); + _context81.next = 3; + return this._rpcRequest('getConfirmedSignaturesForAddress2', args); case 3: - res = _context61.sent; - return _context61.abrupt("return", res.value); + unsafeRes = _context81.sent; + res = _create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult); + + if (!('error' in res)) { + _context81.next = 7; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address'); case 7: - _context61.prev = 7; - _context61.t0 = _context61["catch"](0); - throw new Error('failed to get recent blockhash: ' + _context61.t0); + return _context81.abrupt("return", res.result); - case 10: + case 8: case "end": - return _context61.stop(); + return _context81.stop(); } - }, _callee61, this, [[0, 7]]); + }, _callee81, this); })); - function getRecentBlockhash(_x91) { - return _getRecentBlockhash.apply(this, arguments); + function getConfirmedSignaturesForAddress2(_x125, _x126, _x127) { + return _getConfirmedSignaturesForAddress2.apply(this, arguments); } - return getRecentBlockhash; + return getConfirmedSignaturesForAddress2; }() /** - * Fetch the latest blockhash from the cluster - * @return {Promise} + * Returns confirmed signatures for transactions involving an + * address backwards in time from the provided signature or most recent confirmed block + * + * + * @param address queried address + * @param options */ }, { - key: "getLatestBlockhash", + key: "getSignaturesForAddress", value: function () { - var _getLatestBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee62(commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee62$(_context62) { - while (1) switch (_context62.prev = _context62.next) { + var _getSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee82(address, options, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee82$(_context82) { + while (1) switch (_context82.prev = _context82.next) { case 0: - _context62.prev = 0; - _context62.next = 3; - return this.getLatestBlockhashAndContext(commitmentOrConfig); + args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); + _context82.next = 3; + return this._rpcRequest('getSignaturesForAddress', args); case 3: - res = _context62.sent; - return _context62.abrupt("return", res.value); + unsafeRes = _context82.sent; + res = _create(unsafeRes, GetSignaturesForAddressRpcResult); + + if (!('error' in res)) { + _context82.next = 7; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address'); case 7: - _context62.prev = 7; - _context62.t0 = _context62["catch"](0); - throw new Error('failed to get recent blockhash: ' + _context62.t0); + return _context82.abrupt("return", res.result); - case 10: + case 8: case "end": - return _context62.stop(); + return _context82.stop(); } - }, _callee62, this, [[0, 7]]); + }, _callee82, this); })); - function getLatestBlockhash(_x92) { - return _getLatestBlockhash.apply(this, arguments); + function getSignaturesForAddress(_x128, _x129, _x130) { + return _getSignaturesForAddress.apply(this, arguments); } - return getLatestBlockhash; + return getSignaturesForAddress; }() - /** - * Fetch the latest blockhash from the cluster - * @return {Promise} - */ - }, { - key: "getLatestBlockhashAndContext", + key: "getAddressLookupTable", value: function () { - var _getLatestBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee63(commitmentOrConfig) { - var _extractCommitmentFro16, commitment, config, args, unsafeRes, res; + var _getAddressLookupTable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee83(accountKey, config) { + var _yield$this$getAccoun, context, accountInfo, value; - return _regeneratorRuntime().wrap(function _callee63$(_context63) { - while (1) switch (_context63.prev = _context63.next) { + return _regeneratorRuntime().wrap(function _callee83$(_context83) { + while (1) switch (_context83.prev = _context83.next) { case 0: - _extractCommitmentFro16 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro16.commitment, config = _extractCommitmentFro16.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context63.next = 4; - return this._rpcRequest('getLatestBlockhash', args); + _context83.next = 2; + return this.getAccountInfoAndContext(accountKey, config); - case 4: - unsafeRes = _context63.sent; - res = _create(unsafeRes, GetLatestBlockhashRpcResult); + case 2: + _yield$this$getAccoun = _context83.sent; + context = _yield$this$getAccoun.context; + accountInfo = _yield$this$getAccoun.value; + value = null; - if (!('error' in res)) { - _context63.next = 8; - break; + if (accountInfo !== null) { + value = new AddressLookupTableAccount({ + key: accountKey, + state: AddressLookupTableAccount.deserialize(accountInfo.data) + }); } - throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash'); + return _context83.abrupt("return", { + context: context, + value: value + }); case 8: - return _context63.abrupt("return", res.result); - - case 9: case "end": - return _context63.stop(); + return _context83.stop(); } - }, _callee63, this); + }, _callee83, this); })); - function getLatestBlockhashAndContext(_x93) { - return _getLatestBlockhashAndContext.apply(this, arguments); + function getAddressLookupTable(_x131, _x132) { + return _getAddressLookupTable.apply(this, arguments); } - return getLatestBlockhashAndContext; + return getAddressLookupTable; }() /** - * Fetch the node version + * Fetch the contents of a Nonce account from the cluster, return with context */ }, { - key: "getVersion", + key: "getNonceAndContext", value: function () { - var _getVersion = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee64() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee64$(_context64) { - while (1) switch (_context64.prev = _context64.next) { + var _getNonceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee84(nonceAccount, commitmentOrConfig) { + var _yield$this$getAccoun2, context, accountInfo, value; + + return _regeneratorRuntime().wrap(function _callee84$(_context84) { + while (1) switch (_context84.prev = _context84.next) { case 0: - _context64.next = 2; - return this._rpcRequest('getVersion', []); + _context84.next = 2; + return this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig); case 2: - unsafeRes = _context64.sent; - res = _create(unsafeRes, jsonRpcResult(VersionResult)); + _yield$this$getAccoun2 = _context84.sent; + context = _yield$this$getAccoun2.context; + accountInfo = _yield$this$getAccoun2.value; + value = null; - if (!('error' in res)) { - _context64.next = 6; - break; + if (accountInfo !== null) { + value = NonceAccount.fromAccountData(accountInfo.data); } - throw new SolanaJSONRPCError(res.error, 'failed to get version'); - - case 6: - return _context64.abrupt("return", res.result); + return _context84.abrupt("return", { + context: context, + value: value + }); - case 7: + case 8: case "end": - return _context64.stop(); + return _context84.stop(); } - }, _callee64, this); + }, _callee84, this); })); - function getVersion() { - return _getVersion.apply(this, arguments); + function getNonceAndContext(_x133, _x134) { + return _getNonceAndContext.apply(this, arguments); } - return getVersion; + return getNonceAndContext; }() /** - * Fetch the genesis hash + * Fetch the contents of a Nonce account from the cluster */ }, { - key: "getGenesisHash", + key: "getNonce", value: function () { - var _getGenesisHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee65() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee65$(_context65) { - while (1) switch (_context65.prev = _context65.next) { + var _getNonce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee85(nonceAccount, commitmentOrConfig) { + return _regeneratorRuntime().wrap(function _callee85$(_context85) { + while (1) switch (_context85.prev = _context85.next) { case 0: - _context65.next = 2; - return this._rpcRequest('getGenesisHash', []); + _context85.next = 2; + return this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(function (x) { + return x.value; + })["catch"](function (e) { + throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e); + }); case 2: - unsafeRes = _context65.sent; - res = _create(unsafeRes, jsonRpcResult(string())); - - if (!('error' in res)) { - _context65.next = 6; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash'); - - case 6: - return _context65.abrupt("return", res.result); + return _context85.abrupt("return", _context85.sent); - case 7: + case 3: case "end": - return _context65.stop(); + return _context85.stop(); } - }, _callee65, this); + }, _callee85, this); })); - function getGenesisHash() { - return _getGenesisHash.apply(this, arguments); + function getNonce(_x135, _x136) { + return _getNonce.apply(this, arguments); } - return getGenesisHash; + return getNonce; }() /** - * Fetch a processed block from the cluster. + * Request an allocation of lamports to the specified address * - * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by - * setting the `maxSupportedTransactionVersion` property. - */ - - /** - * Fetch a processed block from the cluster. + * ```typescript + * import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js"; + * + * (async () => { + * const connection = new Connection("https://api.testnet.solana.com", "confirmed"); + * const myAddress = new PublicKey("2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM"); + * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL); + * await connection.confirmTransaction(signature); + * })(); + * ``` */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "getBlock", + key: "requestAirdrop", value: function () { - var _getBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee66(slot, rawConfig) { - var _extractCommitmentFro17, commitment, config, args, unsafeRes, res, _res, _res2, result; - - return _regeneratorRuntime().wrap(function _callee66$(_context66) { - while (1) switch (_context66.prev = _context66.next) { + var _requestAirdrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee86(to, lamports) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee86$(_context86) { + while (1) switch (_context86.prev = _context86.next) { case 0: - _extractCommitmentFro17 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro17.commitment, config = _extractCommitmentFro17.config; - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined - /* encoding */ - , config); - _context66.next = 4; - return this._rpcRequest('getBlock', args); - - case 4: - unsafeRes = _context66.sent; - _context66.prev = 5; - _context66.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; - _context66.next = _context66.t0 === 'accounts' ? 9 : _context66.t0 === 'none' ? 13 : 17; - break; + _context86.next = 2; + return this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]); - case 9: - res = _create(unsafeRes, GetAccountsModeBlockRpcResult); + case 2: + unsafeRes = _context86.sent; + res = _create(unsafeRes, RequestAirdropRpcResult); if (!('error' in res)) { - _context66.next = 12; - break; - } - - throw res.error; - - case 12: - return _context66.abrupt("return", res.result); - - case 13: - _res = _create(unsafeRes, GetNoneModeBlockRpcResult); - - if (!('error' in _res)) { - _context66.next = 16; - break; - } - - throw _res.error; - - case 16: - return _context66.abrupt("return", _res.result); - - case 17: - _res2 = _create(unsafeRes, GetBlockRpcResult); - - if (!('error' in _res2)) { - _context66.next = 20; + _context86.next = 6; break; } - throw _res2.error; - - case 20: - result = _res2.result; - return _context66.abrupt("return", result ? _objectSpread2(_objectSpread2({}, result), {}, { - transactions: result.transactions.map(function (_ref36) { - var transaction = _ref36.transaction, - meta = _ref36.meta, - version = _ref36.version; - return { - meta: meta, - transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { - message: versionedMessageFromResponse(version, transaction.message) - }), - version: version - }; - }) - }) : null); - - case 22: - _context66.next = 27; - break; - - case 24: - _context66.prev = 24; - _context66.t1 = _context66["catch"](5); - throw new SolanaJSONRPCError(_context66.t1, 'failed to get confirmed block'); + throw new SolanaJSONRPCError(res.error, "airdrop to ".concat(to.toBase58(), " failed")); - case 27: + case 6: + return _context86.abrupt("return", res.result); + + case 7: case "end": - return _context66.stop(); + return _context86.stop(); } - }, _callee66, this, [[5, 24]]); + }, _callee86, this); })); - function getBlock(_x94, _x95) { - return _getBlock.apply(this, arguments); + function requestAirdrop(_x137, _x138) { + return _requestAirdrop.apply(this, arguments); } - return getBlock; + return requestAirdrop; }() /** - * Fetch parsed transaction details for a confirmed or finalized block + * @internal */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "getParsedBlock", + key: "_blockhashWithExpiryBlockHeight", value: function () { - var _getParsedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee67(slot, rawConfig) { - var _extractCommitmentFro18, commitment, config, args, unsafeRes, res, _res3, _res4; - - return _regeneratorRuntime().wrap(function _callee67$(_context67) { - while (1) switch (_context67.prev = _context67.next) { + var _blockhashWithExpiryBlockHeight2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee87(disableCache) { + var timeSinceFetch, expired; + return _regeneratorRuntime().wrap(function _callee87$(_context87) { + while (1) switch (_context87.prev = _context87.next) { case 0: - _extractCommitmentFro18 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro18.commitment, config = _extractCommitmentFro18.config; - args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config); - _context67.next = 4; - return this._rpcRequest('getBlock', args); + if (disableCache) { + _context87.next = 10; + break; + } + + case 1: + if (!this._pollingBlockhash) { + _context87.next = 6; + break; + } + + _context87.next = 4; + return sleep(100); case 4: - unsafeRes = _context67.sent; - _context67.prev = 5; - _context67.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; - _context67.next = _context67.t0 === 'accounts' ? 9 : _context67.t0 === 'none' ? 13 : 17; + _context87.next = 1; break; - case 9: - res = _create(unsafeRes, GetParsedAccountsModeBlockRpcResult); + case 6: + timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch; + expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS; - if (!('error' in res)) { - _context67.next = 12; + if (!(this._blockhashInfo.latestBlockhash !== null && !expired)) { + _context87.next = 10; break; } - throw res.error; + return _context87.abrupt("return", this._blockhashInfo.latestBlockhash); + + case 10: + _context87.next = 12; + return this._pollNewBlockhash(); case 12: - return _context67.abrupt("return", res.result); + return _context87.abrupt("return", _context87.sent); case 13: - _res3 = _create(unsafeRes, GetParsedNoneModeBlockRpcResult); + case "end": + return _context87.stop(); + } + }, _callee87, this); + })); - if (!('error' in _res3)) { - _context67.next = 16; + function _blockhashWithExpiryBlockHeight(_x139) { + return _blockhashWithExpiryBlockHeight2.apply(this, arguments); + } + + return _blockhashWithExpiryBlockHeight; + }() + /** + * @internal + */ + + }, { + key: "_pollNewBlockhash", + value: function () { + var _pollNewBlockhash2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee88() { + var startTime, cachedLatestBlockhash, cachedBlockhash, i, latestBlockhash; + return _regeneratorRuntime().wrap(function _callee88$(_context88) { + while (1) switch (_context88.prev = _context88.next) { + case 0: + this._pollingBlockhash = true; + _context88.prev = 1; + startTime = Date.now(); + cachedLatestBlockhash = this._blockhashInfo.latestBlockhash; + cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null; + i = 0; + + case 6: + if (!(i < 50)) { + _context88.next = 18; break; } - throw _res3.error; - - case 16: - return _context67.abrupt("return", _res3.result); + _context88.next = 9; + return this.getLatestBlockhash('finalized'); - case 17: - _res4 = _create(unsafeRes, GetParsedBlockRpcResult); + case 9: + latestBlockhash = _context88.sent; - if (!('error' in _res4)) { - _context67.next = 20; + if (!(cachedBlockhash !== latestBlockhash.blockhash)) { + _context88.next = 13; break; } - throw _res4.error; + this._blockhashInfo = { + latestBlockhash: latestBlockhash, + lastFetch: Date.now(), + transactionSignatures: [], + simulatedSignatures: [] + }; + return _context88.abrupt("return", latestBlockhash); - case 20: - return _context67.abrupt("return", _res4.result); + case 13: + _context88.next = 15; + return sleep(MS_PER_SLOT / 2); - case 21: - _context67.next = 26; + case 15: + i++; + _context88.next = 6; break; - case 23: - _context67.prev = 23; - _context67.t1 = _context67["catch"](5); - throw new SolanaJSONRPCError(_context67.t1, 'failed to get block'); + case 18: + throw new Error("Unable to obtain a new blockhash after ".concat(Date.now() - startTime, "ms")); - case 26: + case 19: + _context88.prev = 19; + this._pollingBlockhash = false; + return _context88.finish(19); + + case 22: case "end": - return _context67.stop(); + return _context88.stop(); } - }, _callee67, this, [[5, 23]]); + }, _callee88, this, [[1,, 19, 22]]); })); - function getParsedBlock(_x96, _x97) { - return _getParsedBlock.apply(this, arguments); + function _pollNewBlockhash() { + return _pollNewBlockhash2.apply(this, arguments); } - return getParsedBlock; + return _pollNewBlockhash; }() - /* - * Returns the current block height of the node - */ - - /* - * Returns recent block production information from the current or previous epoch + /** + * get the stake minimum delegation */ }, { - key: "getBlockProduction", + key: "getStakeMinimumDelegation", value: function () { - var _getBlockProduction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee68(configOrCommitment) { - var extra, commitment, c, rest, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee68$(_context68) { - while (1) switch (_context68.prev = _context68.next) { - case 0: - if (typeof configOrCommitment === 'string') { - commitment = configOrCommitment; - } else if (configOrCommitment) { - c = configOrCommitment.commitment, rest = _objectWithoutProperties(configOrCommitment, _excluded3); - commitment = c; - extra = rest; - } + var _getStakeMinimumDelegation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee89(config) { + var _extractCommitmentFro23, commitment, configArg, args, unsafeRes, res; - args = this._buildArgs([], commitment, 'base64', extra); - _context68.next = 4; - return this._rpcRequest('getBlockProduction', args); + return _regeneratorRuntime().wrap(function _callee89$(_context89) { + while (1) switch (_context89.prev = _context89.next) { + case 0: + _extractCommitmentFro23 = extractCommitmentFromConfig(config), commitment = _extractCommitmentFro23.commitment, configArg = _extractCommitmentFro23.config; + args = this._buildArgs([], commitment, 'base64', configArg); + _context89.next = 4; + return this._rpcRequest('getStakeMinimumDelegation', args); case 4: - unsafeRes = _context68.sent; - res = _create(unsafeRes, BlockProductionResponseStruct); + unsafeRes = _context89.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(number())); if (!('error' in res)) { - _context68.next = 8; + _context89.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get block production information'); + throw new SolanaJSONRPCError(res.error, "failed to get stake minimum delegation"); case 8: - return _context68.abrupt("return", res.result); + return _context89.abrupt("return", res.result); case 9: case "end": - return _context68.stop(); + return _context89.stop(); } - }, _callee68, this); + }, _callee89, this); })); - function getBlockProduction(_x98) { - return _getBlockProduction.apply(this, arguments); + function getStakeMinimumDelegation(_x140) { + return _getStakeMinimumDelegation.apply(this, arguments); } - return getBlockProduction; + return getStakeMinimumDelegation; }() /** - * Fetch a confirmed or finalized transaction from the cluster. + * Simulate a transaction * - * @deprecated Instead, call `getTransaction` using a - * `GetVersionedTransactionConfig` by setting the - * `maxSupportedTransactionVersion` property. + * @deprecated Instead, call {@link simulateTransaction} with {@link + * VersionedTransaction} and {@link SimulateTransactionConfig} parameters */ /** - * Fetch a confirmed or finalized transaction from the cluster. + * Simulate a transaction */ // eslint-disable-next-line no-dupe-class-members }, { - key: "getTransaction", + key: "simulateTransaction", value: function () { - var _getTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee69(signature, rawConfig) { - var _extractCommitmentFro19, commitment, config, args, unsafeRes, res, result; + var _simulateTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee90(transactionOrMessage, configOrSigners, includeAccounts) { + var versionedTx, _wireTransaction, _encodedTransaction, _config, _args91, _unsafeRes, _res5, transaction, originalTx, signers, _transaction3, disableCache, _transaction4, latestBlockhash, _signature3, message, signData, wireTransaction, encodedTransaction, config, addresses, args, unsafeRes, res, logs, traceIndent, logTrace; - return _regeneratorRuntime().wrap(function _callee69$(_context69) { - while (1) switch (_context69.prev = _context69.next) { + return _regeneratorRuntime().wrap(function _callee90$(_context90) { + while (1) switch (_context90.prev = _context90.next) { case 0: - _extractCommitmentFro19 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro19.commitment, config = _extractCommitmentFro19.config; - args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined - /* encoding */ - , config); - _context69.next = 4; - return this._rpcRequest('getTransaction', args); + if (!('message' in transactionOrMessage)) { + _context90.next = 17; + break; + } - case 4: - unsafeRes = _context69.sent; - res = _create(unsafeRes, GetTransactionRpcResult); + versionedTx = transactionOrMessage; + _wireTransaction = versionedTx.serialize(); + _encodedTransaction = Buffer$1.from(_wireTransaction).toString('base64'); - if (!('error' in res)) { - _context69.next = 8; + if (!(Array.isArray(configOrSigners) || includeAccounts !== undefined)) { + _context90.next = 6; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + throw new Error('Invalid arguments'); - case 8: - result = res.result; + case 6: + _config = configOrSigners || {}; + _config.encoding = 'base64'; - if (result) { - _context69.next = 11; - break; + if (!('commitment' in _config)) { + _config.commitment = this.commitment; } - return _context69.abrupt("return", result); - - case 11: - return _context69.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { - transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { - message: versionedMessageFromResponse(result.version, result.transaction.message) - }) - })); + _args91 = [_encodedTransaction, _config]; + _context90.next = 12; + return this._rpcRequest('simulateTransaction', _args91); case 12: - case "end": - return _context69.stop(); - } - }, _callee69, this); - })); + _unsafeRes = _context90.sent; + _res5 = _create(_unsafeRes, SimulatedTransactionResponseStruct); - function getTransaction(_x99, _x100) { - return _getTransaction.apply(this, arguments); - } + if (!('error' in _res5)) { + _context90.next = 16; + break; + } - return getTransaction; - }() - /** - * Fetch parsed transaction details for a confirmed or finalized transaction - */ + throw new Error('failed to simulate transaction: ' + _res5.error.message); - }, { - key: "getParsedTransaction", - value: function () { - var _getParsedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee70(signature, commitmentOrConfig) { - var _extractCommitmentFro20, commitment, config, args, unsafeRes, res; + case 16: + return _context90.abrupt("return", _res5.result); - return _regeneratorRuntime().wrap(function _callee70$(_context70) { - while (1) switch (_context70.prev = _context70.next) { - case 0: - _extractCommitmentFro20 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro20.commitment, config = _extractCommitmentFro20.config; - args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); - _context70.next = 4; - return this._rpcRequest('getTransaction', args); + case 17: + if (transactionOrMessage instanceof Transaction) { + originalTx = transactionOrMessage; + transaction = new Transaction(); + transaction.feePayer = originalTx.feePayer; + transaction.instructions = transactionOrMessage.instructions; + transaction.nonceInfo = originalTx.nonceInfo; + transaction.signatures = originalTx.signatures; + } else { + transaction = Transaction.populate(transactionOrMessage); // HACK: this function relies on mutating the populated transaction - case 4: - unsafeRes = _context70.sent; - res = _create(unsafeRes, GetParsedTransactionRpcResult); + transaction._message = transaction._json = undefined; + } - if (!('error' in res)) { - _context70.next = 8; + if (!(configOrSigners !== undefined && !Array.isArray(configOrSigners))) { + _context90.next = 20; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + throw new Error('Invalid arguments'); - case 8: - return _context70.abrupt("return", res.result); + case 20: + signers = configOrSigners; - case 9: - case "end": - return _context70.stop(); - } - }, _callee70, this); - })); + if (!(transaction.nonceInfo && signers)) { + _context90.next = 25; + break; + } - function getParsedTransaction(_x101, _x102) { - return _getParsedTransaction.apply(this, arguments); - } + (_transaction3 = transaction).sign.apply(_transaction3, _toConsumableArray(signers)); - return getParsedTransaction; - }() - /** - * Fetch parsed transaction details for a batch of confirmed transactions - */ + _context90.next = 45; + break; - }, { - key: "getParsedTransactions", - value: function () { - var _getParsedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee71(signatures, commitmentOrConfig) { - var _this20 = this; + case 25: + disableCache = this._disableBlockhashCaching; - var _extractCommitmentFro21, commitment, config, batch, unsafeRes, res; + case 26: + _context90.next = 28; + return this._blockhashWithExpiryBlockHeight(disableCache); - return _regeneratorRuntime().wrap(function _callee71$(_context71) { - while (1) switch (_context71.prev = _context71.next) { - case 0: - _extractCommitmentFro21 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro21.commitment, config = _extractCommitmentFro21.config; - batch = signatures.map(function (signature) { - var args = _this20._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); + case 28: + latestBlockhash = _context90.sent; + transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; + transaction.recentBlockhash = latestBlockhash.blockhash; - return { - methodName: 'getTransaction', - args: args - }; - }); - _context71.next = 4; - return this._rpcBatchRequest(batch); + if (signers) { + _context90.next = 33; + break; + } - case 4: - unsafeRes = _context71.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetParsedTransactionRpcResult); + return _context90.abrupt("break", 45); - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); - } + case 33: + (_transaction4 = transaction).sign.apply(_transaction4, _toConsumableArray(signers)); - return res.result; - }); - return _context71.abrupt("return", res); + if (transaction.signature) { + _context90.next = 36; + break; + } - case 7: - case "end": - return _context71.stop(); - } - }, _callee71, this); - })); + throw new Error('!signature'); - function getParsedTransactions(_x103, _x104) { - return _getParsedTransactions.apply(this, arguments); - } + case 36: + _signature3 = transaction.signature.toString('base64'); - return getParsedTransactions; - }() - /** - * Fetch transaction details for a batch of confirmed transactions. - * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}. - * - * @deprecated Instead, call `getTransactions` using a - * `GetVersionedTransactionConfig` by setting the - * `maxSupportedTransactionVersion` property. - */ + if (!(!this._blockhashInfo.simulatedSignatures.includes(_signature3) && !this._blockhashInfo.transactionSignatures.includes(_signature3))) { + _context90.next = 42; + break; + } - /** - * Fetch transaction details for a batch of confirmed transactions. - * Similar to {@link getParsedTransactions} but returns a {@link - * VersionedTransactionResponse}. - */ - // eslint-disable-next-line no-dupe-class-members + // The signature of this transaction has not been seen before with the + // current recentBlockhash, all done. Let's break + this._blockhashInfo.simulatedSignatures.push(_signature3); - }, { - key: "getTransactions", - value: function () { - var _getTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee72(signatures, commitmentOrConfig) { - var _this21 = this; + return _context90.abrupt("break", 45); - var _extractCommitmentFro22, commitment, config, batch, unsafeRes, res; + case 42: + // This transaction would be treated as duplicate (its derived signature + // matched to one of already recorded signatures). + // So, we must fetch a new blockhash for a different signature by disabling + // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). + disableCache = true; - return _regeneratorRuntime().wrap(function _callee72$(_context72) { - while (1) switch (_context72.prev = _context72.next) { - case 0: - _extractCommitmentFro22 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro22.commitment, config = _extractCommitmentFro22.config; - batch = signatures.map(function (signature) { - var args = _this21._buildArgsAtLeastConfirmed([signature], commitment, undefined - /* encoding */ - , config); + case 43: + _context90.next = 26; + break; - return { - methodName: 'getTransaction', - args: args + case 45: + message = transaction._compile(); + signData = message.serialize(); + wireTransaction = transaction._serialize(signData); + encodedTransaction = wireTransaction.toString('base64'); + config = { + encoding: 'base64', + commitment: this.commitment + }; + + if (includeAccounts) { + addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(function (key) { + return key.toBase58(); + }); + config['accounts'] = { + encoding: 'base64', + addresses: addresses }; - }); - _context72.next = 4; - return this._rpcBatchRequest(batch); + } - case 4: - unsafeRes = _context72.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetTransactionRpcResult); + if (signers) { + config.sigVerify = true; + } + + args = [encodedTransaction, config]; + _context90.next = 55; + return this._rpcRequest('simulateTransaction', args); + + case 55: + unsafeRes = _context90.sent; + res = _create(unsafeRes, SimulatedTransactionResponseStruct); + + if (!('error' in res)) { + _context90.next = 60; + break; + } - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + if ('data' in res.error) { + logs = res.error.data.logs; + + if (logs && Array.isArray(logs)) { + traceIndent = '\n '; + logTrace = traceIndent + logs.join(traceIndent); + console.error(res.error.message, logTrace); } + } - var result = res.result; - if (!result) return result; - return _objectSpread2(_objectSpread2({}, result), {}, { - transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { - message: versionedMessageFromResponse(result.version, result.transaction.message) - }) - }); - }); - return _context72.abrupt("return", res); + throw new SendTransactionError('failed to simulate transaction: ' + res.error.message, logs); - case 7: + case 60: + return _context90.abrupt("return", res.result); + + case 61: case "end": - return _context72.stop(); + return _context90.stop(); } - }, _callee72, this); + }, _callee90, this); })); - function getTransactions(_x105, _x106) { - return _getTransactions.apply(this, arguments); + function simulateTransaction(_x141, _x142, _x143) { + return _simulateTransaction.apply(this, arguments); } - return getTransactions; + return simulateTransaction; }() /** - * Fetch a list of Transactions and transaction statuses from the cluster - * for a confirmed block. + * Sign and send a transaction * - * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead. + * @deprecated Instead, call {@link sendTransaction} with a {@link + * VersionedTransaction} + */ + + /** + * Sign and send a transaction */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getConfirmedBlock", + key: "sendTransaction", value: function () { - var _getConfirmedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee73(slot, commitment) { - var args, unsafeRes, res, result, block; - return _regeneratorRuntime().wrap(function _callee73$(_context73) { - while (1) switch (_context73.prev = _context73.next) { + var _sendTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee91(transaction, signersOrOptions, options) { + var _wireTransaction2, signers, disableCache, latestBlockhash, _signature4, wireTransaction; + + return _regeneratorRuntime().wrap(function _callee91$(_context91) { + while (1) switch (_context91.prev = _context91.next) { case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment); - _context73.next = 3; - return this._rpcRequest('getConfirmedBlock', args); + if (!('version' in transaction)) { + _context91.next = 7; + break; + } + + if (!(signersOrOptions && Array.isArray(signersOrOptions))) { + _context91.next = 3; + break; + } + + throw new Error('Invalid arguments'); case 3: - unsafeRes = _context73.sent; - res = _create(unsafeRes, GetConfirmedBlockRpcResult); + _wireTransaction2 = transaction.serialize(); + _context91.next = 6; + return this.sendRawTransaction(_wireTransaction2, signersOrOptions); - if (!('error' in res)) { - _context73.next = 7; + case 6: + return _context91.abrupt("return", _context91.sent); + + case 7: + if (!(signersOrOptions === undefined || !Array.isArray(signersOrOptions))) { + _context91.next = 9; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); + throw new Error('Invalid arguments'); - case 7: - result = res.result; + case 9: + signers = signersOrOptions; - if (result) { - _context73.next = 10; + if (!transaction.nonceInfo) { + _context91.next = 14; break; } - throw new Error('Confirmed block ' + slot + ' not found'); + transaction.sign.apply(transaction, _toConsumableArray(signers)); + _context91.next = 32; + break; - case 10: - block = _objectSpread2(_objectSpread2({}, result), {}, { - transactions: result.transactions.map(function (_ref37) { - var transaction = _ref37.transaction, - meta = _ref37.meta; - var message = new Message(transaction.message); - return { - meta: meta, - transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { - message: message - }) - }; - }) - }); - return _context73.abrupt("return", _objectSpread2(_objectSpread2({}, block), {}, { - transactions: block.transactions.map(function (_ref38) { - var transaction = _ref38.transaction, - meta = _ref38.meta; - return { - meta: meta, - transaction: Transaction.populate(transaction.message, transaction.signatures) - }; - }) - })); + case 14: + disableCache = this._disableBlockhashCaching; - case 12: + case 15: + _context91.next = 17; + return this._blockhashWithExpiryBlockHeight(disableCache); + + case 17: + latestBlockhash = _context91.sent; + transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; + transaction.recentBlockhash = latestBlockhash.blockhash; + transaction.sign.apply(transaction, _toConsumableArray(signers)); + + if (transaction.signature) { + _context91.next = 23; + break; + } + + throw new Error('!signature'); + + case 23: + _signature4 = transaction.signature.toString('base64'); + + if (this._blockhashInfo.transactionSignatures.includes(_signature4)) { + _context91.next = 29; + break; + } + + // The signature of this transaction has not been seen before with the + // current recentBlockhash, all done. Let's break + this._blockhashInfo.transactionSignatures.push(_signature4); + + return _context91.abrupt("break", 32); + + case 29: + // This transaction would be treated as duplicate (its derived signature + // matched to one of already recorded signatures). + // So, we must fetch a new blockhash for a different signature by disabling + // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). + disableCache = true; + + case 30: + _context91.next = 15; + break; + + case 32: + wireTransaction = transaction.serialize(); + _context91.next = 35; + return this.sendRawTransaction(wireTransaction, options); + + case 35: + return _context91.abrupt("return", _context91.sent); + + case 36: case "end": - return _context73.stop(); + return _context91.stop(); } - }, _callee73, this); + }, _callee91, this); })); - function getConfirmedBlock(_x107, _x108) { - return _getConfirmedBlock.apply(this, arguments); + function sendTransaction(_x144, _x145, _x146) { + return _sendTransaction.apply(this, arguments); } - return getConfirmedBlock; + return sendTransaction; }() /** - * Fetch confirmed blocks between two slots + * Send a transaction that has already been signed and serialized into the + * wire format */ }, { - key: "getBlocks", + key: "sendRawTransaction", value: function () { - var _getBlocks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee74(startSlot, endSlot, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee74$(_context74) { - while (1) switch (_context74.prev = _context74.next) { + var _sendRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee92(rawTransaction, options) { + var encodedTransaction, result; + return _regeneratorRuntime().wrap(function _callee92$(_context92) { + while (1) switch (_context92.prev = _context92.next) { case 0: - args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment); - _context74.next = 3; - return this._rpcRequest('getBlocks', args); + encodedTransaction = toBuffer(rawTransaction).toString('base64'); + _context92.next = 3; + return this.sendEncodedTransaction(encodedTransaction, options); case 3: - unsafeRes = _context74.sent; - res = _create(unsafeRes, jsonRpcResult(array(number()))); - - if (!('error' in res)) { - _context74.next = 7; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get blocks'); - - case 7: - return _context74.abrupt("return", res.result); + result = _context92.sent; + return _context92.abrupt("return", result); - case 8: + case 5: case "end": - return _context74.stop(); + return _context92.stop(); } - }, _callee74, this); + }, _callee92, this); })); - function getBlocks(_x109, _x110, _x111) { - return _getBlocks.apply(this, arguments); + function sendRawTransaction(_x147, _x148) { + return _sendRawTransaction.apply(this, arguments); } - return getBlocks; + return sendRawTransaction; }() /** - * Fetch a list of Signatures from the cluster for a block, excluding rewards + * Send a transaction that has already been signed, serialized into the + * wire format, and encoded as a base64 string */ }, { - key: "getBlockSignatures", + key: "sendEncodedTransaction", value: function () { - var _getBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee75(slot, commitment) { - var args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee75$(_context75) { - while (1) switch (_context75.prev = _context75.next) { + var _sendEncodedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee93(encodedTransaction, options) { + var config, skipPreflight, preflightCommitment, args, unsafeRes, res, logs; + return _regeneratorRuntime().wrap(function _callee93$(_context93) { + while (1) switch (_context93.prev = _context93.next) { case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { - transactionDetails: 'signatures', - rewards: false - }); - _context75.next = 3; - return this._rpcRequest('getBlock', args); + config = { + encoding: 'base64' + }; + skipPreflight = options && options.skipPreflight; + preflightCommitment = options && options.preflightCommitment || this.commitment; - case 3: - unsafeRes = _context75.sent; - res = _create(unsafeRes, GetBlockSignaturesRpcResult); + if (options && options.maxRetries != null) { + config.maxRetries = options.maxRetries; + } - if (!('error' in res)) { - _context75.next = 7; - break; + if (options && options.minContextSlot != null) { + config.minContextSlot = options.minContextSlot; } - throw new SolanaJSONRPCError(res.error, 'failed to get block'); + if (skipPreflight) { + config.skipPreflight = skipPreflight; + } - case 7: - result = res.result; + if (preflightCommitment) { + config.preflightCommitment = preflightCommitment; + } - if (result) { - _context75.next = 10; + args = [encodedTransaction, config]; + _context93.next = 10; + return this._rpcRequest('sendTransaction', args); + + case 10: + unsafeRes = _context93.sent; + res = _create(unsafeRes, SendTransactionRpcResult); + + if (!('error' in res)) { + _context93.next = 15; break; } - throw new Error('Block ' + slot + ' not found'); + if ('data' in res.error) { + logs = res.error.data.logs; + } - case 10: - return _context75.abrupt("return", result); + throw new SendTransactionError('failed to send transaction: ' + res.error.message, logs); - case 11: + case 15: + return _context93.abrupt("return", res.result); + + case 16: case "end": - return _context75.stop(); + return _context93.stop(); } - }, _callee75, this); + }, _callee93, this); })); - function getBlockSignatures(_x112, _x113) { - return _getBlockSignatures.apply(this, arguments); + function sendEncodedTransaction(_x149, _x150) { + return _sendEncodedTransaction.apply(this, arguments); } - return getBlockSignatures; + return sendEncodedTransaction; }() /** - * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead. + * @internal */ }, { - key: "getConfirmedBlockSignatures", - value: function () { - var _getConfirmedBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee76(slot, commitment) { - var args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee76$(_context76) { - while (1) switch (_context76.prev = _context76.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { - transactionDetails: 'signatures', - rewards: false - }); - _context76.next = 3; - return this._rpcRequest('getConfirmedBlock', args); + key: "_wsOnOpen", + value: function _wsOnOpen() { + var _this23 = this; - case 3: - unsafeRes = _context76.sent; - res = _create(unsafeRes, GetBlockSignaturesRpcResult); + this._rpcWebSocketConnected = true; + this._rpcWebSocketHeartbeat = setInterval(function () { + // Ping server every 5s to prevent idle timeouts + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee94() { + return _regeneratorRuntime().wrap(function _callee94$(_context94) { + while (1) switch (_context94.prev = _context94.next) { + case 0: + _context94.prev = 0; + _context94.next = 3; + return _this23._rpcWebSocket.notify('ping'); - if (!('error' in res)) { - _context76.next = 7; + case 3: + _context94.next = 7; break; - } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); + case 5: + _context94.prev = 5; + _context94.t0 = _context94["catch"](0); - case 7: - result = res.result; + case 7: + case "end": + return _context94.stop(); + } + }, _callee94, null, [[0, 5]]); + }))(); + }, 5000); - if (result) { - _context76.next = 10; - break; - } + this._updateSubscriptions(); + } + /** + * @internal + */ - throw new Error('Confirmed block ' + slot + ' not found'); + }, { + key: "_wsOnError", + value: function _wsOnError(err) { + this._rpcWebSocketConnected = false; + console.error('ws error:', err.message); + } + /** + * @internal + */ - case 10: - return _context76.abrupt("return", result); + }, { + key: "_wsOnClose", + value: function _wsOnClose(code) { + var _this24 = this; - case 11: - case "end": - return _context76.stop(); - } - }, _callee76, this); - })); + this._rpcWebSocketConnected = false; + this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER; - function getConfirmedBlockSignatures(_x114, _x115) { - return _getConfirmedBlockSignatures.apply(this, arguments); + if (this._rpcWebSocketIdleTimeout) { + clearTimeout(this._rpcWebSocketIdleTimeout); + this._rpcWebSocketIdleTimeout = null; } - return getConfirmedBlockSignatures; - }() + if (this._rpcWebSocketHeartbeat) { + clearInterval(this._rpcWebSocketHeartbeat); + this._rpcWebSocketHeartbeat = null; + } + + if (code === 1000) { + // explicit close, check if any subscriptions have been made since close + this._updateSubscriptions(); + + return; + } // implicit close, prepare subscriptions for auto-reconnect + + + this._subscriptionCallbacksByServerSubscriptionId = {}; + Object.entries(this._subscriptionsByHash).forEach(function (_ref40) { + var _ref41 = _slicedToArray(_ref40, 2), + hash = _ref41[0], + subscription = _ref41[1]; + + _this24._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'pending' + })); + }); + } /** - * Fetch a transaction details for a confirmed transaction - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead. + * @internal */ }, { - key: "getConfirmedTransaction", - value: function () { - var _getConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee77(signature, commitment) { - var args, unsafeRes, res, result, message, signatures; - return _regeneratorRuntime().wrap(function _callee77$(_context77) { - while (1) switch (_context77.prev = _context77.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([signature], commitment); - _context77.next = 3; - return this._rpcRequest('getConfirmedTransaction', args); - - case 3: - unsafeRes = _context77.sent; - res = _create(unsafeRes, GetTransactionRpcResult); - - if (!('error' in res)) { - _context77.next = 7; - break; - } + key: "_setSubscription", + value: function _setSubscription(hash, nextSubscription) { + var _this$_subscriptionsB; - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + var prevState = (_this$_subscriptionsB = this._subscriptionsByHash[hash]) === null || _this$_subscriptionsB === void 0 ? void 0 : _this$_subscriptionsB.state; + this._subscriptionsByHash[hash] = nextSubscription; - case 7: - result = res.result; + if (prevState !== nextSubscription.state) { + var stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash]; - if (result) { - _context77.next = 10; - break; - } + if (stateChangeCallbacks) { + stateChangeCallbacks.forEach(function (cb) { + try { + cb(nextSubscription.state); // eslint-disable-next-line no-empty + } catch (_unused3) {} + }); + } + } + } + /** + * @internal + */ - return _context77.abrupt("return", result); + }, { + key: "_onSubscriptionStateChange", + value: function _onSubscriptionStateChange(clientSubscriptionId, callback) { + var _this25 = this; - case 10: - message = new Message(result.transaction.message); - signatures = result.transaction.signatures; - return _context77.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { - transaction: Transaction.populate(message, signatures) - })); + var _this$_subscriptionSt; - case 13: - case "end": - return _context77.stop(); - } - }, _callee77, this); - })); + var hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - function getConfirmedTransaction(_x116, _x117) { - return _getConfirmedTransaction.apply(this, arguments); + if (hash == null) { + return function () {}; } - return getConfirmedTransaction; - }() + var stateChangeCallbacks = (_this$_subscriptionSt = this._subscriptionStateChangeCallbacksByHash)[hash] || (_this$_subscriptionSt[hash] = new Set()); + stateChangeCallbacks.add(callback); + return function () { + stateChangeCallbacks["delete"](callback); + + if (stateChangeCallbacks.size === 0) { + delete _this25._subscriptionStateChangeCallbacksByHash[hash]; + } + }; + } /** - * Fetch parsed transaction details for a confirmed transaction - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead. + * @internal */ }, { - key: "getParsedConfirmedTransaction", + key: "_updateSubscriptions", value: function () { - var _getParsedConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee78(signature, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee78$(_context78) { - while (1) switch (_context78.prev = _context78.next) { + var _updateSubscriptions2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee98() { + var _this26 = this; + + var activeWebSocketGeneration, isCurrentConnectionStillActive; + return _regeneratorRuntime().wrap(function _callee98$(_context98) { + while (1) switch (_context98.prev = _context98.next) { case 0: - args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); - _context78.next = 3; - return this._rpcRequest('getConfirmedTransaction', args); + if (!(Object.keys(this._subscriptionsByHash).length === 0)) { + _context98.next = 3; + break; + } + + if (this._rpcWebSocketConnected) { + this._rpcWebSocketConnected = false; + this._rpcWebSocketIdleTimeout = setTimeout(function () { + _this26._rpcWebSocketIdleTimeout = null; + + try { + _this26._rpcWebSocket.close(); + } catch (err) { + // swallow error if socket has already been closed. + if (err instanceof Error) { + console.log("Error when closing socket connection: ".concat(err.message)); + } + } + }, 500); + } + + return _context98.abrupt("return"); case 3: - unsafeRes = _context78.sent; - res = _create(unsafeRes, GetParsedTransactionRpcResult); + if (this._rpcWebSocketIdleTimeout !== null) { + clearTimeout(this._rpcWebSocketIdleTimeout); + this._rpcWebSocketIdleTimeout = null; + this._rpcWebSocketConnected = true; + } - if (!('error' in res)) { - _context78.next = 7; + if (this._rpcWebSocketConnected) { + _context98.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction'); + this._rpcWebSocket.connect(); + + return _context98.abrupt("return"); case 7: - return _context78.abrupt("return", res.result); + activeWebSocketGeneration = this._rpcWebSocketGeneration; - case 8: - case "end": - return _context78.stop(); - } - }, _callee78, this); - })); + isCurrentConnectionStillActive = function isCurrentConnectionStillActive() { + return activeWebSocketGeneration === _this26._rpcWebSocketGeneration; + }; - function getParsedConfirmedTransaction(_x118, _x119) { - return _getParsedConfirmedTransaction.apply(this, arguments); - } + _context98.next = 11; + return Promise.all( // Don't be tempted to change this to `Object.entries`. We call + // `_updateSubscriptions` recursively when processing the state, + // so it's important that we look up the *current* version of + // each subscription, every time we process a hash. + Object.keys(this._subscriptionsByHash).map( /*#__PURE__*/function () { + var _ref42 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee97(hash) { + var subscription; + return _regeneratorRuntime().wrap(function _callee97$(_context97) { + while (1) switch (_context97.prev = _context97.next) { + case 0: + subscription = _this26._subscriptionsByHash[hash]; - return getParsedConfirmedTransaction; - }() - /** - * Fetch parsed transaction details for a batch of confirmed transactions - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead. - */ + if (!(subscription === undefined)) { + _context97.next = 3; + break; + } - }, { - key: "getParsedConfirmedTransactions", - value: function () { - var _getParsedConfirmedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee79(signatures, commitment) { - var _this22 = this; + return _context97.abrupt("return"); - var batch, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee79$(_context79) { - while (1) switch (_context79.prev = _context79.next) { - case 0: - batch = signatures.map(function (signature) { - var args = _this22._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); + case 3: + _context97.t0 = subscription.state; + _context97.next = _context97.t0 === 'pending' ? 6 : _context97.t0 === 'unsubscribed' ? 6 : _context97.t0 === 'subscribed' ? 15 : 19; + break; - return { - methodName: 'getConfirmedTransaction', - args: args - }; - }); - _context79.next = 3; - return this._rpcBatchRequest(batch); + case 6: + if (!(subscription.callbacks.size === 0)) { + _context97.next = 12; + break; + } - case 3: - unsafeRes = _context79.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetParsedTransactionRpcResult); + /** + * You can end up here when: + * + * - a subscription has recently unsubscribed + * without having new callbacks added to it + * while the unsubscribe was in flight, or + * - when a pending subscription has its + * listeners removed before a request was + * sent to the server. + * + * Being that nobody is interested in this + * subscription any longer, delete it. + */ + delete _this26._subscriptionsByHash[hash]; - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions'); - } + if (subscription.state === 'unsubscribed') { + delete _this26._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]; + } - return res.result; - }); - return _context79.abrupt("return", res); + _context97.next = 11; + return _this26._updateSubscriptions(); - case 6: - case "end": - return _context79.stop(); - } - }, _callee79, this); - })); + case 11: + return _context97.abrupt("return"); - function getParsedConfirmedTransactions(_x120, _x121) { - return _getParsedConfirmedTransactions.apply(this, arguments); - } + case 12: + _context97.next = 14; + return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee95() { + var args, method, serverSubscriptionId; + return _regeneratorRuntime().wrap(function _callee95$(_context95) { + while (1) switch (_context95.prev = _context95.next) { + case 0: + args = subscription.args, method = subscription.method; + _context95.prev = 1; - return getParsedConfirmedTransactions; - }() - /** - * Fetch a list of all the confirmed signatures for transactions involving an address - * within a specified slot range. Max range allowed is 10,000 slots. - * - * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead. - * - * @param address queried address - * @param startSlot start slot, inclusive - * @param endSlot end slot, inclusive - */ + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'subscribing' + })); - }, { - key: "getConfirmedSignaturesForAddress", - value: function () { - var _getConfirmedSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee80(address, startSlot, endSlot) { - var options, firstAvailableBlock, block, highestConfirmedRoot, _block, confirmedSignatureInfo; + _context95.next = 5; + return _this26._rpcWebSocket.call(method, args); - return _regeneratorRuntime().wrap(function _callee80$(_context80) { - while (1) switch (_context80.prev = _context80.next) { - case 0: - options = {}; - _context80.next = 3; - return this.getFirstAvailableBlock(); + case 5: + serverSubscriptionId = _context95.sent; - case 3: - firstAvailableBlock = _context80.sent; + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + serverSubscriptionId: serverSubscriptionId, + state: 'subscribed' + })); - case 4: - if ('until' in options) { - _context80.next = 24; - break; - } + _this26._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks; + _context95.next = 10; + return _this26._updateSubscriptions(); - startSlot--; + case 10: + _context95.next = 20; + break; - if (!(startSlot <= 0 || startSlot < firstAvailableBlock)) { - _context80.next = 8; - break; - } + case 12: + _context95.prev = 12; + _context95.t0 = _context95["catch"](1); - return _context80.abrupt("break", 24); + if (_context95.t0 instanceof Error) { + console.error("".concat(method, " error for argument"), args, _context95.t0.message); + } - case 8: - _context80.prev = 8; - _context80.next = 11; - return this.getConfirmedBlockSignatures(startSlot, 'finalized'); + if (isCurrentConnectionStillActive()) { + _context95.next = 17; + break; + } - case 11: - block = _context80.sent; + return _context95.abrupt("return"); - if (block.signatures.length > 0) { - options.until = block.signatures[block.signatures.length - 1].toString(); - } + case 17: + // TODO: Maybe add an 'errored' state or a retry limit? + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'pending' + })); - _context80.next = 22; - break; + _context95.next = 20; + return _this26._updateSubscriptions(); - case 15: - _context80.prev = 15; - _context80.t0 = _context80["catch"](8); + case 20: + case "end": + return _context95.stop(); + } + }, _callee95, null, [[1, 12]]); + }))(); - if (!(_context80.t0 instanceof Error && _context80.t0.message.includes('skipped'))) { - _context80.next = 21; - break; - } + case 14: + return _context97.abrupt("break", 19); - return _context80.abrupt("continue", 4); + case 15: + if (!(subscription.callbacks.size === 0)) { + _context97.next = 18; + break; + } - case 21: - throw _context80.t0; + _context97.next = 18; + return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee96() { + var serverSubscriptionId, unsubscribeMethod; + return _regeneratorRuntime().wrap(function _callee96$(_context96) { + while (1) switch (_context96.prev = _context96.next) { + case 0: + serverSubscriptionId = subscription.serverSubscriptionId, unsubscribeMethod = subscription.unsubscribeMethod; - case 22: - _context80.next = 4; - break; + if (!_this26._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) { + _context96.next = 5; + break; + } - case 24: - _context80.next = 26; - return this.getSlot('finalized'); + /** + * Special case. + * If we're dealing with a subscription that has been auto- + * disposed by the RPC, then we can skip the RPC call to + * tear down the subscription here. + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ + _this26._subscriptionsAutoDisposedByRpc["delete"](serverSubscriptionId); - case 26: - highestConfirmedRoot = _context80.sent; + _context96.next = 21; + break; - case 27: - if ('before' in options) { - _context80.next = 47; - break; - } + case 5: + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribing' + })); - endSlot++; + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribing' + })); - if (!(endSlot > highestConfirmedRoot)) { - _context80.next = 31; - break; - } + _context96.prev = 7; + _context96.next = 10; + return _this26._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]); - return _context80.abrupt("break", 47); + case 10: + _context96.next = 21; + break; - case 31: - _context80.prev = 31; - _context80.next = 34; - return this.getConfirmedBlockSignatures(endSlot); + case 12: + _context96.prev = 12; + _context96.t0 = _context96["catch"](7); - case 34: - _block = _context80.sent; + if (_context96.t0 instanceof Error) { + console.error("".concat(unsubscribeMethod, " error:"), _context96.t0.message); + } - if (_block.signatures.length > 0) { - options.before = _block.signatures[_block.signatures.length - 1].toString(); - } + if (isCurrentConnectionStillActive()) { + _context96.next = 17; + break; + } - _context80.next = 45; - break; + return _context96.abrupt("return"); - case 38: - _context80.prev = 38; - _context80.t1 = _context80["catch"](31); + case 17: + // TODO: Maybe add an 'errored' state or a retry limit? + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'subscribed' + })); - if (!(_context80.t1 instanceof Error && _context80.t1.message.includes('skipped'))) { - _context80.next = 44; - break; - } + _context96.next = 20; + return _this26._updateSubscriptions(); - return _context80.abrupt("continue", 27); + case 20: + return _context96.abrupt("return"); - case 44: - throw _context80.t1; + case 21: + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribed' + })); - case 45: - _context80.next = 27; - break; + _context96.next = 24; + return _this26._updateSubscriptions(); - case 47: - _context80.next = 49; - return this.getConfirmedSignaturesForAddress2(address, options); + case 24: + case "end": + return _context96.stop(); + } + }, _callee96, null, [[7, 12]]); + }))(); - case 49: - confirmedSignatureInfo = _context80.sent; - return _context80.abrupt("return", confirmedSignatureInfo.map(function (info) { - return info.signature; - })); + case 18: + return _context97.abrupt("break", 19); - case 51: + case 19: + case "end": + return _context97.stop(); + } + }, _callee97); + })); + + return function (_x151) { + return _ref42.apply(this, arguments); + }; + }())); + + case 11: case "end": - return _context80.stop(); + return _context98.stop(); } - }, _callee80, this, [[8, 15], [31, 38]]); + }, _callee98, this); })); - function getConfirmedSignaturesForAddress(_x122, _x123, _x124) { - return _getConfirmedSignaturesForAddress.apply(this, arguments); + function _updateSubscriptions() { + return _updateSubscriptions2.apply(this, arguments); } - return getConfirmedSignaturesForAddress; + return _updateSubscriptions; }() /** - * Returns confirmed signatures for transactions involving an - * address backwards in time from the provided signature or most recent confirmed block - * - * - * @param address queried address - * @param options + * @internal */ }, { - key: "getConfirmedSignaturesForAddress2", - value: function () { - var _getConfirmedSignaturesForAddress2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee81(address, options, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee81$(_context81) { - while (1) switch (_context81.prev = _context81.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); - _context81.next = 3; - return this._rpcRequest('getConfirmedSignaturesForAddress2', args); + key: "_handleServerNotification", + value: function _handleServerNotification(serverSubscriptionId, callbackArgs) { + var callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]; - case 3: - unsafeRes = _context81.sent; - res = _create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult); + if (callbacks === undefined) { + return; + } - if (!('error' in res)) { - _context81.next = 7; - break; - } + callbacks.forEach(function (cb) { + try { + cb.apply(void 0, _toConsumableArray(callbackArgs)); + } catch (e) { + console.error(e); + } + }); + } + /** + * @internal + */ + + }, { + key: "_wsOnAccountNotification", + value: function _wsOnAccountNotification(notification) { + var _create$1 = _create(notification, AccountNotificationResult), + result = _create$1.result, + subscription = _create$1.subscription; + + this._handleServerNotification(subscription, [result.value, result.context]); + } + /** + * @internal + */ + + }, { + key: "_makeSubscription", + value: function _makeSubscription(subscriptionConfig, + /** + * When preparing `args` for a call to `_makeSubscription`, be sure + * to carefully apply a default `commitment` property, if necessary. + * + * - If the user supplied a `commitment` use that. + * - Otherwise, if the `Connection::commitment` is set, use that. + * - Otherwise, set it to the RPC server default: `finalized`. + * + * This is extremely important to ensure that these two fundamentally + * identical subscriptions produce the same identifying hash: + * + * - A subscription made without specifying a commitment. + * - A subscription made where the commitment specified is the same + * as the default applied to the subscription above. + * + * Example; these two subscriptions must produce the same hash: + * + * - An `accountSubscribe` subscription for `'PUBKEY'` + * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment + * `'finalized'`. + * + * See the 'making a subscription with defaulted params omitted' test + * in `connection-subscriptions.ts` for more. + */ + args) { + var _this27 = this; + + var clientSubscriptionId = this._nextClientSubscriptionId++; + var hash = fastStableStringify$1([subscriptionConfig.method, args]); + var existingSubscription = this._subscriptionsByHash[hash]; + + if (existingSubscription === undefined) { + this._subscriptionsByHash[hash] = _objectSpread2(_objectSpread2({}, subscriptionConfig), {}, { + args: args, + callbacks: new Set([subscriptionConfig.callback]), + state: 'pending' + }); + } else { + existingSubscription.callbacks.add(subscriptionConfig.callback); + } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address'); + this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash; + this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee99() { + var subscription; + return _regeneratorRuntime().wrap(function _callee99$(_context99) { + while (1) switch (_context99.prev = _context99.next) { + case 0: + delete _this27._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; + delete _this27._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; + subscription = _this27._subscriptionsByHash[hash]; + assert(subscription !== undefined, "Could not find a `Subscription` when tearing down client subscription #".concat(clientSubscriptionId)); + subscription.callbacks["delete"](subscriptionConfig.callback); + _context99.next = 7; + return _this27._updateSubscriptions(); case 7: - return _context81.abrupt("return", res.result); - - case 8: case "end": - return _context81.stop(); + return _context99.stop(); } - }, _callee81, this); + }, _callee99); })); - function getConfirmedSignaturesForAddress2(_x125, _x126, _x127) { - return _getConfirmedSignaturesForAddress2.apply(this, arguments); - } + this._updateSubscriptions(); - return getConfirmedSignaturesForAddress2; - }() + return clientSubscriptionId; + } /** - * Returns confirmed signatures for transactions involving an - * address backwards in time from the provided signature or most recent confirmed block - * + * Register a callback to be invoked whenever the specified account changes * - * @param address queried address - * @param options + * @param publicKey Public key of the account to monitor + * @param callback Function to invoke whenever the account is changed + * @param commitment Specify the commitment level account changes must reach before notification + * @return subscription id */ }, { - key: "getSignaturesForAddress", - value: function () { - var _getSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee82(address, options, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee82$(_context82) { - while (1) switch (_context82.prev = _context82.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); - _context82.next = 3; - return this._rpcRequest('getSignaturesForAddress', args); - - case 3: - unsafeRes = _context82.sent; - res = _create(unsafeRes, GetSignaturesForAddressRpcResult); - - if (!('error' in res)) { - _context82.next = 7; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address'); - - case 7: - return _context82.abrupt("return", res.result); - - case 8: - case "end": - return _context82.stop(); - } - }, _callee82, this); - })); + key: "onAccountChange", + value: function onAccountChange(publicKey, callback, commitment) { + var args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. + 'base64'); - function getSignaturesForAddress(_x128, _x129, _x130) { - return _getSignaturesForAddress.apply(this, arguments); - } + return this._makeSubscription({ + callback: callback, + method: 'accountSubscribe', + unsubscribeMethod: 'accountUnsubscribe' + }, args); + } + /** + * Deregister an account notification callback + * + * @param id client subscription id to deregister + */ - return getSignaturesForAddress; - }() }, { - key: "getAddressLookupTable", + key: "removeAccountChangeListener", value: function () { - var _getAddressLookupTable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee83(accountKey, config) { - var _yield$this$getAccoun, context, accountInfo, value; - - return _regeneratorRuntime().wrap(function _callee83$(_context83) { - while (1) switch (_context83.prev = _context83.next) { + var _removeAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee100(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee100$(_context100) { + while (1) switch (_context100.prev = _context100.next) { case 0: - _context83.next = 2; - return this.getAccountInfoAndContext(accountKey, config); + _context100.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'account change'); case 2: - _yield$this$getAccoun = _context83.sent; - context = _yield$this$getAccoun.context; - accountInfo = _yield$this$getAccoun.value; - value = null; - - if (accountInfo !== null) { - value = new AddressLookupTableAccount({ - key: accountKey, - state: AddressLookupTableAccount.deserialize(accountInfo.data) - }); - } - - return _context83.abrupt("return", { - context: context, - value: value - }); - - case 8: case "end": - return _context83.stop(); + return _context100.stop(); } - }, _callee83, this); + }, _callee100, this); })); - function getAddressLookupTable(_x131, _x132) { - return _getAddressLookupTable.apply(this, arguments); + function removeAccountChangeListener(_x152) { + return _removeAccountChangeListener.apply(this, arguments); } - return getAddressLookupTable; + return removeAccountChangeListener; }() /** - * Fetch the contents of a Nonce account from the cluster, return with context + * @internal */ }, { - key: "getNonceAndContext", - value: function () { - var _getNonceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee84(nonceAccount, commitmentOrConfig) { - var _yield$this$getAccoun2, context, accountInfo, value; - - return _regeneratorRuntime().wrap(function _callee84$(_context84) { - while (1) switch (_context84.prev = _context84.next) { - case 0: - _context84.next = 2; - return this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig); - - case 2: - _yield$this$getAccoun2 = _context84.sent; - context = _yield$this$getAccoun2.context; - accountInfo = _yield$this$getAccoun2.value; - value = null; - - if (accountInfo !== null) { - value = NonceAccount.fromAccountData(accountInfo.data); - } - - return _context84.abrupt("return", { - context: context, - value: value - }); + key: "_wsOnProgramAccountNotification", + value: function _wsOnProgramAccountNotification(notification) { + var _create2 = _create(notification, ProgramAccountNotificationResult), + result = _create2.result, + subscription = _create2.subscription; - case 8: - case "end": - return _context84.stop(); - } - }, _callee84, this); - })); + this._handleServerNotification(subscription, [{ + accountId: result.value.pubkey, + accountInfo: result.value.account + }, result.context]); + } + /** + * Register a callback to be invoked whenever accounts owned by the + * specified program change + * + * @param programId Public key of the program to monitor + * @param callback Function to invoke whenever the account is changed + * @param commitment Specify the commitment level account changes must reach before notification + * @param filters The program account filters to pass into the RPC method + * @return subscription id + */ - function getNonceAndContext(_x133, _x134) { - return _getNonceAndContext.apply(this, arguments); - } + }, { + key: "onProgramAccountChange", + value: function onProgramAccountChange(programId, callback, commitment, filters) { + var args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. + 'base64' + /* encoding */ + , filters ? { + filters: filters + } : undefined + /* extra */ + ); - return getNonceAndContext; - }() + return this._makeSubscription({ + callback: callback, + method: 'programSubscribe', + unsubscribeMethod: 'programUnsubscribe' + }, args); + } /** - * Fetch the contents of a Nonce account from the cluster + * Deregister an account notification callback + * + * @param id client subscription id to deregister */ }, { - key: "getNonce", + key: "removeProgramAccountChangeListener", value: function () { - var _getNonce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee85(nonceAccount, commitmentOrConfig) { - return _regeneratorRuntime().wrap(function _callee85$(_context85) { - while (1) switch (_context85.prev = _context85.next) { + var _removeProgramAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee101(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee101$(_context101) { + while (1) switch (_context101.prev = _context101.next) { case 0: - _context85.next = 2; - return this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(function (x) { - return x.value; - })["catch"](function (e) { - throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e); - }); + _context101.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change'); case 2: - return _context85.abrupt("return", _context85.sent); - - case 3: case "end": - return _context85.stop(); + return _context101.stop(); } - }, _callee85, this); + }, _callee101, this); })); - function getNonce(_x135, _x136) { - return _getNonce.apply(this, arguments); + function removeProgramAccountChangeListener(_x153) { + return _removeProgramAccountChangeListener.apply(this, arguments); } - return getNonce; + return removeProgramAccountChangeListener; }() /** - * Request an allocation of lamports to the specified address - * - * ```typescript - * import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js"; + * Registers a callback to be invoked whenever logs are emitted. + */ + + }, { + key: "onLogs", + value: function onLogs(filter, callback, commitment) { + var args = this._buildArgs([_typeof$1(filter) === 'object' ? { + mentions: [filter.toString()] + } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default. + ); + + return this._makeSubscription({ + callback: callback, + method: 'logsSubscribe', + unsubscribeMethod: 'logsUnsubscribe' + }, args); + } + /** + * Deregister a logs callback. * - * (async () => { - * const connection = new Connection("https://api.testnet.solana.com", "confirmed"); - * const myAddress = new PublicKey("2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM"); - * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL); - * await connection.confirmTransaction(signature); - * })(); - * ``` + * @param id client subscription id to deregister. */ }, { - key: "requestAirdrop", + key: "removeOnLogsListener", value: function () { - var _requestAirdrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee86(to, lamports) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee86$(_context86) { - while (1) switch (_context86.prev = _context86.next) { + var _removeOnLogsListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee102(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee102$(_context102) { + while (1) switch (_context102.prev = _context102.next) { case 0: - _context86.next = 2; - return this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]); + _context102.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'logs'); case 2: - unsafeRes = _context86.sent; - res = _create(unsafeRes, RequestAirdropRpcResult); - - if (!('error' in res)) { - _context86.next = 6; - break; - } - - throw new SolanaJSONRPCError(res.error, "airdrop to ".concat(to.toBase58(), " failed")); - - case 6: - return _context86.abrupt("return", res.result); - - case 7: case "end": - return _context86.stop(); + return _context102.stop(); } - }, _callee86, this); + }, _callee102, this); })); - function requestAirdrop(_x137, _x138) { - return _requestAirdrop.apply(this, arguments); + function removeOnLogsListener(_x154) { + return _removeOnLogsListener.apply(this, arguments); } - return requestAirdrop; + return removeOnLogsListener; }() /** * @internal */ }, { - key: "_blockhashWithExpiryBlockHeight", - value: function () { - var _blockhashWithExpiryBlockHeight2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee87(disableCache) { - var timeSinceFetch, expired; - return _regeneratorRuntime().wrap(function _callee87$(_context87) { - while (1) switch (_context87.prev = _context87.next) { - case 0: - if (disableCache) { - _context87.next = 10; - break; - } - - case 1: - if (!this._pollingBlockhash) { - _context87.next = 6; - break; - } - - _context87.next = 4; - return sleep(100); - - case 4: - _context87.next = 1; - break; - - case 6: - timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch; - expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS; - - if (!(this._blockhashInfo.latestBlockhash !== null && !expired)) { - _context87.next = 10; - break; - } - - return _context87.abrupt("return", this._blockhashInfo.latestBlockhash); - - case 10: - _context87.next = 12; - return this._pollNewBlockhash(); + key: "_wsOnLogsNotification", + value: function _wsOnLogsNotification(notification) { + var _create3 = _create(notification, LogsNotificationResult), + result = _create3.result, + subscription = _create3.subscription; - case 12: - return _context87.abrupt("return", _context87.sent); + this._handleServerNotification(subscription, [result.value, result.context]); + } + /** + * @internal + */ - case 13: - case "end": - return _context87.stop(); - } - }, _callee87, this); - })); + }, { + key: "_wsOnSlotNotification", + value: function _wsOnSlotNotification(notification) { + var _create4 = _create(notification, SlotNotificationResult), + result = _create4.result, + subscription = _create4.subscription; - function _blockhashWithExpiryBlockHeight(_x139) { - return _blockhashWithExpiryBlockHeight2.apply(this, arguments); - } + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon slot changes + * + * @param callback Function to invoke whenever the slot changes + * @return subscription id + */ - return _blockhashWithExpiryBlockHeight; - }() + }, { + key: "onSlotChange", + value: function onSlotChange(callback) { + return this._makeSubscription({ + callback: callback, + method: 'slotSubscribe', + unsubscribeMethod: 'slotUnsubscribe' + }, [] + /* args */ + ); + } /** - * @internal + * Deregister a slot notification callback + * + * @param id client subscription id to deregister */ }, { - key: "_pollNewBlockhash", + key: "removeSlotChangeListener", value: function () { - var _pollNewBlockhash2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee88() { - var startTime, cachedLatestBlockhash, cachedBlockhash, i, latestBlockhash; - return _regeneratorRuntime().wrap(function _callee88$(_context88) { - while (1) switch (_context88.prev = _context88.next) { + var _removeSlotChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee103(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee103$(_context103) { + while (1) switch (_context103.prev = _context103.next) { case 0: - this._pollingBlockhash = true; - _context88.prev = 1; - startTime = Date.now(); - cachedLatestBlockhash = this._blockhashInfo.latestBlockhash; - cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null; - i = 0; - - case 6: - if (!(i < 50)) { - _context88.next = 18; - break; - } - - _context88.next = 9; - return this.getLatestBlockhash('finalized'); - - case 9: - latestBlockhash = _context88.sent; - - if (!(cachedBlockhash !== latestBlockhash.blockhash)) { - _context88.next = 13; - break; - } - - this._blockhashInfo = { - latestBlockhash: latestBlockhash, - lastFetch: Date.now(), - transactionSignatures: [], - simulatedSignatures: [] - }; - return _context88.abrupt("return", latestBlockhash); - - case 13: - _context88.next = 15; - return sleep(MS_PER_SLOT / 2); - - case 15: - i++; - _context88.next = 6; - break; - - case 18: - throw new Error("Unable to obtain a new blockhash after ".concat(Date.now() - startTime, "ms")); - - case 19: - _context88.prev = 19; - this._pollingBlockhash = false; - return _context88.finish(19); + _context103.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change'); - case 22: + case 2: case "end": - return _context88.stop(); + return _context103.stop(); } - }, _callee88, this, [[1,, 19, 22]]); + }, _callee103, this); })); - function _pollNewBlockhash() { - return _pollNewBlockhash2.apply(this, arguments); + function removeSlotChangeListener(_x155) { + return _removeSlotChangeListener.apply(this, arguments); } - return _pollNewBlockhash; + return removeSlotChangeListener; }() /** - * get the stake minimum delegation + * @internal */ }, { - key: "getStakeMinimumDelegation", - value: function () { - var _getStakeMinimumDelegation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee89(config) { - var _extractCommitmentFro23, commitment, configArg, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee89$(_context89) { - while (1) switch (_context89.prev = _context89.next) { - case 0: - _extractCommitmentFro23 = extractCommitmentFromConfig(config), commitment = _extractCommitmentFro23.commitment, configArg = _extractCommitmentFro23.config; - args = this._buildArgs([], commitment, 'base64', configArg); - _context89.next = 4; - return this._rpcRequest('getStakeMinimumDelegation', args); - - case 4: - unsafeRes = _context89.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(number())); + key: "_wsOnSlotUpdatesNotification", + value: function _wsOnSlotUpdatesNotification(notification) { + var _create5 = _create(notification, SlotUpdateNotificationResult), + result = _create5.result, + subscription = _create5.subscription; - if (!('error' in res)) { - _context89.next = 8; - break; - } + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s + * may be useful to track live progress of a cluster. + * + * @param callback Function to invoke whenever the slot updates + * @return subscription id + */ - throw new SolanaJSONRPCError(res.error, "failed to get stake minimum delegation"); + }, { + key: "onSlotUpdate", + value: function onSlotUpdate(callback) { + return this._makeSubscription({ + callback: callback, + method: 'slotsUpdatesSubscribe', + unsubscribeMethod: 'slotsUpdatesUnsubscribe' + }, [] + /* args */ + ); + } + /** + * Deregister a slot update notification callback + * + * @param id client subscription id to deregister + */ - case 8: - return _context89.abrupt("return", res.result); + }, { + key: "removeSlotUpdateListener", + value: function () { + var _removeSlotUpdateListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee104(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee104$(_context104) { + while (1) switch (_context104.prev = _context104.next) { + case 0: + _context104.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update'); - case 9: + case 2: case "end": - return _context89.stop(); + return _context104.stop(); } - }, _callee89, this); + }, _callee104, this); })); - function getStakeMinimumDelegation(_x140) { - return _getStakeMinimumDelegation.apply(this, arguments); + function removeSlotUpdateListener(_x156) { + return _removeSlotUpdateListener.apply(this, arguments); } - return getStakeMinimumDelegation; + return removeSlotUpdateListener; }() /** - * Simulate a transaction - * - * @deprecated Instead, call {@link simulateTransaction} with {@link - * VersionedTransaction} and {@link SimulateTransactionConfig} parameters - */ - - /** - * Simulate a transaction + * @internal */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "simulateTransaction", + key: "_unsubscribeClientSubscription", value: function () { - var _simulateTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee90(transactionOrMessage, configOrSigners, includeAccounts) { - var versionedTx, _wireTransaction, _encodedTransaction, _config, _args91, _unsafeRes, _res5, transaction, originalTx, signers, _transaction3, disableCache, _transaction4, latestBlockhash, _signature3, message, signData, wireTransaction, encodedTransaction, config, addresses, args, unsafeRes, res, logs, traceIndent, logTrace; - - return _regeneratorRuntime().wrap(function _callee90$(_context90) { - while (1) switch (_context90.prev = _context90.next) { + var _unsubscribeClientSubscription2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee105(clientSubscriptionId, subscriptionName) { + var dispose; + return _regeneratorRuntime().wrap(function _callee105$(_context105) { + while (1) switch (_context105.prev = _context105.next) { case 0: - if (!('message' in transactionOrMessage)) { - _context90.next = 17; - break; - } - - versionedTx = transactionOrMessage; - _wireTransaction = versionedTx.serialize(); - _encodedTransaction = Buffer$1.from(_wireTransaction).toString('base64'); + dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - if (!(Array.isArray(configOrSigners) || includeAccounts !== undefined)) { - _context90.next = 6; + if (!dispose) { + _context105.next = 6; break; } - throw new Error('Invalid arguments'); - - case 6: - _config = configOrSigners || {}; - _config.encoding = 'base64'; - - if (!('commitment' in _config)) { - _config.commitment = this.commitment; - } - - _args91 = [_encodedTransaction, _config]; - _context90.next = 12; - return this._rpcRequest('simulateTransaction', _args91); - - case 12: - _unsafeRes = _context90.sent; - _res5 = _create(_unsafeRes, SimulatedTransactionResponseStruct); - - if (!('error' in _res5)) { - _context90.next = 16; - break; - } + _context105.next = 4; + return dispose(); - throw new Error('failed to simulate transaction: ' + _res5.error.message); + case 4: + _context105.next = 7; + break; - case 16: - return _context90.abrupt("return", _res5.result); + case 6: + console.warn('Ignored unsubscribe request because an active subscription with id ' + "`".concat(clientSubscriptionId, "` for '").concat(subscriptionName, "' events ") + 'could not be found.'); - case 17: - if (transactionOrMessage instanceof Transaction) { - originalTx = transactionOrMessage; - transaction = new Transaction(); - transaction.feePayer = originalTx.feePayer; - transaction.instructions = transactionOrMessage.instructions; - transaction.nonceInfo = originalTx.nonceInfo; - transaction.signatures = originalTx.signatures; - } else { - transaction = Transaction.populate(transactionOrMessage); // HACK: this function relies on mutating the populated transaction + case 7: + case "end": + return _context105.stop(); + } + }, _callee105, this); + })); - transaction._message = transaction._json = undefined; - } + function _unsubscribeClientSubscription(_x157, _x158) { + return _unsubscribeClientSubscription2.apply(this, arguments); + } - if (!(configOrSigners !== undefined && !Array.isArray(configOrSigners))) { - _context90.next = 20; - break; - } + return _unsubscribeClientSubscription; + }() + }, { + key: "_buildArgs", + value: function _buildArgs(args, override, encoding, extra) { + var commitment = override || this._commitment; - throw new Error('Invalid arguments'); + if (commitment || encoding || extra) { + var options = {}; - case 20: - signers = configOrSigners; + if (encoding) { + options.encoding = encoding; + } - if (!(transaction.nonceInfo && signers)) { - _context90.next = 25; - break; - } + if (commitment) { + options.commitment = commitment; + } - (_transaction3 = transaction).sign.apply(_transaction3, _toConsumableArray(signers)); + if (extra) { + options = Object.assign(options, extra); + } - _context90.next = 45; - break; + args.push(options); + } - case 25: - disableCache = this._disableBlockhashCaching; + return args; + } + /** + * @internal + */ - case 26: - _context90.next = 28; - return this._blockhashWithExpiryBlockHeight(disableCache); + }, { + key: "_buildArgsAtLeastConfirmed", + value: function _buildArgsAtLeastConfirmed(args, override, encoding, extra) { + var commitment = override || this._commitment; - case 28: - latestBlockhash = _context90.sent; - transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; - transaction.recentBlockhash = latestBlockhash.blockhash; + if (commitment && !['confirmed', 'finalized'].includes(commitment)) { + throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`'); + } - if (signers) { - _context90.next = 33; - break; - } + return this._buildArgs(args, override, encoding, extra); + } + /** + * @internal + */ - return _context90.abrupt("break", 45); + }, { + key: "_wsOnSignatureNotification", + value: function _wsOnSignatureNotification(notification) { + var _create6 = _create(notification, SignatureNotificationResult), + result = _create6.result, + subscription = _create6.subscription; - case 33: - (_transaction4 = transaction).sign.apply(_transaction4, _toConsumableArray(signers)); + if (result.value !== 'receivedSignature') { + /** + * Special case. + * After a signature is processed, RPCs automatically dispose of the + * subscription on the server side. We need to track which of these + * subscriptions have been disposed in such a way, so that we know + * whether the client is dealing with a not-yet-processed signature + * (in which case we must tear down the server subscription) or an + * already-processed signature (in which case the client can simply + * clear out the subscription locally without telling the server). + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ + this._subscriptionsAutoDisposedByRpc.add(subscription); + } - if (transaction.signature) { - _context90.next = 36; - break; - } + this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{ + type: 'received' + }, result.context] : [{ + type: 'status', + result: result.value + }, result.context]); + } + /** + * Register a callback to be invoked upon signature updates + * + * @param signature Transaction signature string in base 58 + * @param callback Function to invoke on signature notifications + * @param commitment Specify the commitment level signature must reach before notification + * @return subscription id + */ - throw new Error('!signature'); + }, { + key: "onSignature", + value: function onSignature(signature, _callback, commitment) { + var _this28 = this; - case 36: - _signature3 = transaction.signature.toString('base64'); + var args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default. + ); - if (!(!this._blockhashInfo.simulatedSignatures.includes(_signature3) && !this._blockhashInfo.transactionSignatures.includes(_signature3))) { - _context90.next = 42; - break; - } + var clientSubscriptionId = this._makeSubscription({ + callback: function callback(notification, context) { + if (notification.type === 'status') { + _callback(notification.result, context); // Signatures subscriptions are auto-removed by the RPC service + // so no need to explicitly send an unsubscribe message. - // The signature of this transaction has not been seen before with the - // current recentBlockhash, all done. Let's break - this._blockhashInfo.simulatedSignatures.push(_signature3); - return _context90.abrupt("break", 45); + try { + _this28.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - case 42: - // This transaction would be treated as duplicate (its derived signature - // matched to one of already recorded signatures). - // So, we must fetch a new blockhash for a different signature by disabling - // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). - disableCache = true; + } catch (_err) {// Already removed. + } + } + }, + method: 'signatureSubscribe', + unsubscribeMethod: 'signatureUnsubscribe' + }, args); - case 43: - _context90.next = 26; - break; + return clientSubscriptionId; + } + /** + * Register a callback to be invoked when a transaction is + * received and/or processed. + * + * @param signature Transaction signature string in base 58 + * @param callback Function to invoke on signature notifications + * @param options Enable received notifications and set the commitment + * level that signature must reach before notification + * @return subscription id + */ - case 45: - message = transaction._compile(); - signData = message.serialize(); - wireTransaction = transaction._serialize(signData); - encodedTransaction = wireTransaction.toString('base64'); - config = { - encoding: 'base64', - commitment: this.commitment - }; + }, { + key: "onSignatureWithOptions", + value: function onSignatureWithOptions(signature, _callback2, options) { + var _this29 = this; - if (includeAccounts) { - addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(function (key) { - return key.toBase58(); - }); - config['accounts'] = { - encoding: 'base64', - addresses: addresses - }; - } + var _options$commitment = _objectSpread2(_objectSpread2({}, options), {}, { + commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default. - if (signers) { - config.sigVerify = true; - } + }), + commitment = _options$commitment.commitment, + extra = _objectWithoutProperties(_options$commitment, _excluded4); - args = [encodedTransaction, config]; - _context90.next = 55; - return this._rpcRequest('simulateTransaction', args); + var args = this._buildArgs([signature], commitment, undefined + /* encoding */ + , extra); - case 55: - unsafeRes = _context90.sent; - res = _create(unsafeRes, SimulatedTransactionResponseStruct); + var clientSubscriptionId = this._makeSubscription({ + callback: function callback(notification, context) { + _callback2(notification, context); // Signatures subscriptions are auto-removed by the RPC service + // so no need to explicitly send an unsubscribe message. - if (!('error' in res)) { - _context90.next = 60; - break; - } - if ('data' in res.error) { - logs = res.error.data.logs; + try { + _this29.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - if (logs && Array.isArray(logs)) { - traceIndent = '\n '; - logTrace = traceIndent + logs.join(traceIndent); - console.error(res.error.message, logTrace); - } - } + } catch (_err) {// Already removed. + } + }, + method: 'signatureSubscribe', + unsubscribeMethod: 'signatureUnsubscribe' + }, args); - throw new SendTransactionError('failed to simulate transaction: ' + res.error.message, logs); + return clientSubscriptionId; + } + /** + * Deregister a signature notification callback + * + * @param id client subscription id to deregister + */ - case 60: - return _context90.abrupt("return", res.result); + }, { + key: "removeSignatureListener", + value: function () { + var _removeSignatureListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee106(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee106$(_context106) { + while (1) switch (_context106.prev = _context106.next) { + case 0: + _context106.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result'); - case 61: + case 2: case "end": - return _context90.stop(); + return _context106.stop(); } - }, _callee90, this); + }, _callee106, this); })); - function simulateTransaction(_x141, _x142, _x143) { - return _simulateTransaction.apply(this, arguments); + function removeSignatureListener(_x159) { + return _removeSignatureListener.apply(this, arguments); } - return simulateTransaction; + return removeSignatureListener; }() /** - * Sign and send a transaction + * @internal + */ + + }, { + key: "_wsOnRootNotification", + value: function _wsOnRootNotification(notification) { + var _create7 = _create(notification, RootNotificationResult), + result = _create7.result, + subscription = _create7.subscription; + + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon root changes * - * @deprecated Instead, call {@link sendTransaction} with a {@link - * VersionedTransaction} + * @param callback Function to invoke whenever the root changes + * @return subscription id */ + }, { + key: "onRootChange", + value: function onRootChange(callback) { + return this._makeSubscription({ + callback: callback, + method: 'rootSubscribe', + unsubscribeMethod: 'rootUnsubscribe' + }, [] + /* args */ + ); + } /** - * Sign and send a transaction + * Deregister a root notification callback + * + * @param id client subscription id to deregister */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "sendTransaction", + key: "removeRootChangeListener", value: function () { - var _sendTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee91(transaction, signersOrOptions, options) { - var _wireTransaction2, signers, disableCache, latestBlockhash, _signature4, wireTransaction; - - return _regeneratorRuntime().wrap(function _callee91$(_context91) { - while (1) switch (_context91.prev = _context91.next) { + var _removeRootChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee107(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee107$(_context107) { + while (1) switch (_context107.prev = _context107.next) { case 0: - if (!('version' in transaction)) { - _context91.next = 7; - break; - } + _context107.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'root change'); - if (!(signersOrOptions && Array.isArray(signersOrOptions))) { - _context91.next = 3; - break; - } + case 2: + case "end": + return _context107.stop(); + } + }, _callee107, this); + })); - throw new Error('Invalid arguments'); + function removeRootChangeListener(_x160) { + return _removeRootChangeListener.apply(this, arguments); + } - case 3: - _wireTransaction2 = transaction.serialize(); - _context91.next = 6; - return this.sendRawTransaction(_wireTransaction2, signersOrOptions); + return removeRootChangeListener; + }() + }]); - case 6: - return _context91.abrupt("return", _context91.sent); + return Connection; +}(); +/** + * Keypair signer interface + */ - case 7: - if (!(signersOrOptions === undefined || !Array.isArray(signersOrOptions))) { - _context91.next = 9; - break; - } +/** + * An account keypair used for signing transactions. + */ - throw new Error('Invalid arguments'); - case 9: - signers = signersOrOptions; +var Keypair = /*#__PURE__*/function () { + /** + * Create a new keypair instance. + * Generate random keypair if no {@link Ed25519Keypair} is provided. + * + * @param keypair ed25519 keypair + */ + function Keypair(keypair) { + _classCallCheck(this, Keypair); + + this._keypair = void 0; + this._keypair = keypair !== null && keypair !== void 0 ? keypair : generateKeypair(); + } + /** + * Generate a new random keypair + */ + + + _createClass(Keypair, [{ + key: "publicKey", + get: + /** + * The public key for this keypair + */ + function get() { + return new PublicKey(this._keypair.publicKey); + } + /** + * The raw secret key for this keypair + */ + + }, { + key: "secretKey", + get: function get() { + return new Uint8Array(this._keypair.secretKey); + } + }], [{ + key: "generate", + value: function generate() { + return new Keypair(generateKeypair()); + } + /** + * Create a keypair from a raw secret key byte array. + * + * This method should only be used to recreate a keypair from a previously + * generated secret key. Generating keypairs from a random seed should be done + * with the {@link Keypair.fromSeed} method. + * + * @throws error if the provided secret key is invalid and validation is not skipped. + * + * @param secretKey secret key byte array + * @param options: skip secret key validation + */ + + }, { + key: "fromSecretKey", + value: function fromSecretKey(secretKey, options) { + if (secretKey.byteLength !== 64) { + throw new Error('bad secret key size'); + } - if (!transaction.nonceInfo) { - _context91.next = 14; - break; - } + var publicKey = secretKey.slice(32, 64); - transaction.sign.apply(transaction, _toConsumableArray(signers)); - _context91.next = 32; - break; + if (!options || !options.skipValidation) { + var privateScalar = secretKey.slice(0, 32); + var computedPublicKey = getPublicKey(privateScalar); - case 14: - disableCache = this._disableBlockhashCaching; + for (var ii = 0; ii < 32; ii++) { + if (publicKey[ii] !== computedPublicKey[ii]) { + throw new Error('provided secretKey is invalid'); + } + } + } - case 15: - _context91.next = 17; - return this._blockhashWithExpiryBlockHeight(disableCache); + return new Keypair({ + publicKey: publicKey, + secretKey: secretKey + }); + } + /** + * Generate a keypair from a 32 byte seed. + * + * @param seed seed byte array + */ - case 17: - latestBlockhash = _context91.sent; - transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; - transaction.recentBlockhash = latestBlockhash.blockhash; - transaction.sign.apply(transaction, _toConsumableArray(signers)); + }, { + key: "fromSeed", + value: function fromSeed(seed) { + var publicKey = getPublicKey(seed); + var secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, 32); + return new Keypair({ + publicKey: publicKey, + secretKey: secretKey + }); + } + }]); - if (transaction.signature) { - _context91.next = 23; - break; - } + return Keypair; +}(); +/** + * An enumeration of valid address lookup table InstructionType's + * @internal + */ - throw new Error('!signature'); - case 23: - _signature4 = transaction.signature.toString('base64'); +var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({ + CreateLookupTable: { + index: 0, + layout: struct([u32('instruction'), u64('recentSlot'), u8('bumpSeed')]) + }, + FreezeLookupTable: { + index: 1, + layout: struct([u32('instruction')]) + }, + ExtendLookupTable: { + index: 2, + layout: struct([u32('instruction'), u64(), seq$1(publicKey(), offset$1(u32(), -8), 'addresses')]) + }, + DeactivateLookupTable: { + index: 3, + layout: struct([u32('instruction')]) + }, + CloseLookupTable: { + index: 4, + layout: struct([u32('instruction')]) + } +}); - if (this._blockhashInfo.transactionSignatures.includes(_signature4)) { - _context91.next = 29; - break; - } +var AddressLookupTableInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function AddressLookupTableInstruction() { + _classCallCheck(this, AddressLookupTableInstruction); + } - // The signature of this transaction has not been seen before with the - // current recentBlockhash, all done. Let's break - this._blockhashInfo.transactionSignatures.push(_signature4); + _createClass(AddressLookupTableInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var index = instructionTypeLayout.decode(instruction.data); + var type; - return _context91.abrupt("break", 32); + for (var _i10 = 0, _Object$entries2 = Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS); _i10 < _Object$entries2.length; _i10++) { + var _Object$entries2$_i2 = _slicedToArray(_Object$entries2[_i10], 2), + layoutType = _Object$entries2$_i2[0], + layout = _Object$entries2$_i2[1]; - case 29: - // This transaction would be treated as duplicate (its derived signature - // matched to one of already recorded signatures). - // So, we must fetch a new blockhash for a different signature by disabling - // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). - disableCache = true; + if (layout.index == index) { + type = layoutType; + break; + } + } - case 30: - _context91.next = 15; - break; + if (!type) { + throw new Error('Invalid Instruction. Should be a LookupTable Instruction'); + } - case 32: - wireTransaction = transaction.serialize(); - _context91.next = 35; - return this.sendRawTransaction(wireTransaction, options); + return type; + } + }, { + key: "decodeCreateLookupTable", + value: function decodeCreateLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 4); - case 35: - return _context91.abrupt("return", _context91.sent); + var _decodeData$12 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data), + recentSlot = _decodeData$12.recentSlot; - case 36: - case "end": - return _context91.stop(); - } - }, _callee91, this); - })); + return { + authority: instruction.keys[1].pubkey, + payer: instruction.keys[2].pubkey, + recentSlot: Number(recentSlot) + }; + } + }, { + key: "decodeExtendLookupTable", + value: function decodeExtendLookupTable(instruction) { + this.checkProgramId(instruction.programId); - function sendTransaction(_x144, _x145, _x146) { - return _sendTransaction.apply(this, arguments); + if (instruction.keys.length < 2) { + throw new Error("invalid instruction; found ".concat(instruction.keys.length, " keys, expected at least 2")); } - return sendTransaction; - }() + var _decodeData$13 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data), + addresses = _decodeData$13.addresses; + + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey, + payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined, + addresses: addresses.map(function (buffer) { + return new PublicKey(buffer); + }) + }; + } + }, { + key: "decodeCloseLookupTable", + value: function decodeCloseLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 3); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey, + recipient: instruction.keys[2].pubkey + }; + } + }, { + key: "decodeFreezeLookupTable", + value: function decodeFreezeLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 2); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey + }; + } + }, { + key: "decodeDeactivateLookupTable", + value: function decodeDeactivateLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 2); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey + }; + } /** - * Send a transaction that has already been signed and serialized into the - * wire format + * @internal */ }, { - key: "sendRawTransaction", - value: function () { - var _sendRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee92(rawTransaction, options) { - var encodedTransaction, result; - return _regeneratorRuntime().wrap(function _callee92$(_context92) { - while (1) switch (_context92.prev = _context92.next) { - case 0: - encodedTransaction = toBuffer(rawTransaction).toString('base64'); - _context92.next = 3; - return this.sendEncodedTransaction(encodedTransaction, options); - - case 3: - result = _context92.sent; - return _context92.abrupt("return", result); - - case 5: - case "end": - return _context92.stop(); - } - }, _callee92, this); - })); - - function sendRawTransaction(_x147, _x148) { - return _sendRawTransaction.apply(this, arguments); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(AddressLookupTableProgram.programId)) { + throw new Error('invalid instruction; programId is not AddressLookupTable Program'); } - - return sendRawTransaction; - }() + } /** - * Send a transaction that has already been signed, serialized into the - * wire format, and encoded as a base64 string + * @internal */ }, { - key: "sendEncodedTransaction", - value: function () { - var _sendEncodedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee93(encodedTransaction, options) { - var config, skipPreflight, preflightCommitment, args, unsafeRes, res, logs; - return _regeneratorRuntime().wrap(function _callee93$(_context93) { - while (1) switch (_context93.prev = _context93.next) { - case 0: - config = { - encoding: 'base64' - }; - skipPreflight = options && options.skipPreflight; - preflightCommitment = options && options.preflightCommitment || this.commitment; - - if (options && options.maxRetries != null) { - config.maxRetries = options.maxRetries; - } - - if (options && options.minContextSlot != null) { - config.minContextSlot = options.minContextSlot; - } - - if (skipPreflight) { - config.skipPreflight = skipPreflight; - } - - if (preflightCommitment) { - config.preflightCommitment = preflightCommitment; - } + key: "checkKeysLength", + value: function checkKeysLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); + } + } + }]); - args = [encodedTransaction, config]; - _context93.next = 10; - return this._rpcRequest('sendTransaction', args); + return AddressLookupTableInstruction; +}(); - case 10: - unsafeRes = _context93.sent; - res = _create(unsafeRes, SendTransactionRpcResult); +var AddressLookupTableProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function AddressLookupTableProgram() { + _classCallCheck(this, AddressLookupTableProgram); + } - if (!('error' in res)) { - _context93.next = 15; - break; - } + _createClass(AddressLookupTableProgram, null, [{ + key: "createLookupTable", + value: function createLookupTable(params) { + var _PublicKey$findProgra = PublicKey.findProgramAddressSync([params.authority.toBuffer(), toBufferLE_1(BigInt(params.recentSlot), 8)], this.programId), + _PublicKey$findProgra2 = _slicedToArray(_PublicKey$findProgra, 2), + lookupTableAddress = _PublicKey$findProgra2[0], + bumpSeed = _PublicKey$findProgra2[1]; - if ('data' in res.error) { - logs = res.error.data.logs; - } + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable; + var data = encodeData(type, { + recentSlot: BigInt(params.recentSlot), + bumpSeed: bumpSeed + }); + var keys = [{ + pubkey: lookupTableAddress, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }, { + pubkey: params.payer, + isSigner: true, + isWritable: true + }, { + pubkey: SystemProgram.programId, + isSigner: false, + isWritable: false + }]; + return [new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }), lookupTableAddress]; + } + }, { + key: "freezeLookupTable", + value: function freezeLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "extendLookupTable", + value: function extendLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable; + var data = encodeData(type, { + addresses: params.addresses.map(function (addr) { + return addr.toBytes(); + }) + }); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; - throw new SendTransactionError('failed to send transaction: ' + res.error.message, logs); + if (params.payer) { + keys.push({ + pubkey: params.payer, + isSigner: true, + isWritable: true + }, { + pubkey: SystemProgram.programId, + isSigner: false, + isWritable: false + }); + } - case 15: - return _context93.abrupt("return", res.result); + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "deactivateLookupTable", + value: function deactivateLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "closeLookupTable", + value: function closeLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }, { + pubkey: params.recipient, + isSigner: false, + isWritable: true + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }]); - case 16: - case "end": - return _context93.stop(); - } - }, _callee93, this); - })); + return AddressLookupTableProgram; +}(); - function sendEncodedTransaction(_x149, _x150) { - return _sendEncodedTransaction.apply(this, arguments); - } +AddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111'); +/** + * Compute Budget Instruction class + */ - return sendEncodedTransaction; - }() - /** - * @internal - */ +var ComputeBudgetInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function ComputeBudgetInstruction() { + _classCallCheck(this, ComputeBudgetInstruction); + } + /** + * Decode a compute budget instruction and retrieve the instruction type. + */ - }, { - key: "_wsOnOpen", - value: function _wsOnOpen() { - var _this23 = this; - this._rpcWebSocketConnected = true; - this._rpcWebSocketHeartbeat = setInterval(function () { - // Ping server every 5s to prevent idle timeouts - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee94() { - return _regeneratorRuntime().wrap(function _callee94$(_context94) { - while (1) switch (_context94.prev = _context94.next) { - case 0: - _context94.prev = 0; - _context94.next = 3; - return _this23._rpcWebSocket.notify('ping'); + _createClass(ComputeBudgetInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u8('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; - case 3: - _context94.next = 7; - break; + for (var _i11 = 0, _Object$entries3 = Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS); _i11 < _Object$entries3.length; _i11++) { + var _Object$entries3$_i2 = _slicedToArray(_Object$entries3[_i11], 2), + ixType = _Object$entries3$_i2[0], + layout = _Object$entries3$_i2[1]; - case 5: - _context94.prev = 5; - _context94.t0 = _context94["catch"](0); + if (layout.index == typeIndex) { + type = ixType; + break; + } + } - case 7: - case "end": - return _context94.stop(); - } - }, _callee94, null, [[0, 5]]); - }))(); - }, 5000); + if (!type) { + throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction'); + } - this._updateSubscriptions(); + return type; } /** - * @internal + * Decode request units compute budget instruction and retrieve the instruction params. */ }, { - key: "_wsOnError", - value: function _wsOnError(err) { - this._rpcWebSocketConnected = false; - console.error('ws error:', err.message); + key: "decodeRequestUnits", + value: function decodeRequestUnits(instruction) { + this.checkProgramId(instruction.programId); + + var _decodeData$14 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data), + units = _decodeData$14.units, + additionalFee = _decodeData$14.additionalFee; + + return { + units: units, + additionalFee: additionalFee + }; } /** - * @internal + * Decode request heap frame compute budget instruction and retrieve the instruction params. */ }, { - key: "_wsOnClose", - value: function _wsOnClose(code) { - var _this24 = this; - - this._rpcWebSocketConnected = false; - this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER; - - if (this._rpcWebSocketIdleTimeout) { - clearTimeout(this._rpcWebSocketIdleTimeout); - this._rpcWebSocketIdleTimeout = null; - } - - if (this._rpcWebSocketHeartbeat) { - clearInterval(this._rpcWebSocketHeartbeat); - this._rpcWebSocketHeartbeat = null; - } - - if (code === 1000) { - // explicit close, check if any subscriptions have been made since close - this._updateSubscriptions(); - - return; - } // implicit close, prepare subscriptions for auto-reconnect - + key: "decodeRequestHeapFrame", + value: function decodeRequestHeapFrame(instruction) { + this.checkProgramId(instruction.programId); - this._subscriptionCallbacksByServerSubscriptionId = {}; - Object.entries(this._subscriptionsByHash).forEach(function (_ref40) { - var _ref41 = _slicedToArray(_ref40, 2), - hash = _ref41[0], - subscription = _ref41[1]; + var _decodeData$15 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data), + bytes = _decodeData$15.bytes; - _this24._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'pending' - })); - }); + return { + bytes: bytes + }; } /** - * @internal + * Decode set compute unit limit compute budget instruction and retrieve the instruction params. */ }, { - key: "_setSubscription", - value: function _setSubscription(hash, nextSubscription) { - var _this$_subscriptionsB; - - var prevState = (_this$_subscriptionsB = this._subscriptionsByHash[hash]) === null || _this$_subscriptionsB === void 0 ? void 0 : _this$_subscriptionsB.state; - this._subscriptionsByHash[hash] = nextSubscription; + key: "decodeSetComputeUnitLimit", + value: function decodeSetComputeUnitLimit(instruction) { + this.checkProgramId(instruction.programId); - if (prevState !== nextSubscription.state) { - var stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash]; + var _decodeData$16 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data), + units = _decodeData$16.units; - if (stateChangeCallbacks) { - stateChangeCallbacks.forEach(function (cb) { - try { - cb(nextSubscription.state); // eslint-disable-next-line no-empty - } catch (_unused3) {} - }); - } - } + return { + units: units + }; } /** - * @internal + * Decode set compute unit price compute budget instruction and retrieve the instruction params. */ }, { - key: "_onSubscriptionStateChange", - value: function _onSubscriptionStateChange(clientSubscriptionId, callback) { - var _this25 = this; - - var _this$_subscriptionSt; - - var hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - - if (hash == null) { - return function () {}; - } + key: "decodeSetComputeUnitPrice", + value: function decodeSetComputeUnitPrice(instruction) { + this.checkProgramId(instruction.programId); - var stateChangeCallbacks = (_this$_subscriptionSt = this._subscriptionStateChangeCallbacksByHash)[hash] || (_this$_subscriptionSt[hash] = new Set()); - stateChangeCallbacks.add(callback); - return function () { - stateChangeCallbacks["delete"](callback); + var _decodeData$17 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data), + microLamports = _decodeData$17.microLamports; - if (stateChangeCallbacks.size === 0) { - delete _this25._subscriptionStateChangeCallbacksByHash[hash]; - } + return { + microLamports: microLamports }; } /** @@ -29767,1245 +31300,1359 @@ var Connection = /*#__PURE__*/function () { */ }, { - key: "_updateSubscriptions", - value: function () { - var _updateSubscriptions2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee98() { - var _this26 = this; - - var activeWebSocketGeneration, isCurrentConnectionStillActive; - return _regeneratorRuntime().wrap(function _callee98$(_context98) { - while (1) switch (_context98.prev = _context98.next) { - case 0: - if (!(Object.keys(this._subscriptionsByHash).length === 0)) { - _context98.next = 3; - break; - } - - if (this._rpcWebSocketConnected) { - this._rpcWebSocketConnected = false; - this._rpcWebSocketIdleTimeout = setTimeout(function () { - _this26._rpcWebSocketIdleTimeout = null; - - try { - _this26._rpcWebSocket.close(); - } catch (err) { - // swallow error if socket has already been closed. - if (err instanceof Error) { - console.log("Error when closing socket connection: ".concat(err.message)); - } - } - }, 500); - } - - return _context98.abrupt("return"); - - case 3: - if (this._rpcWebSocketIdleTimeout !== null) { - clearTimeout(this._rpcWebSocketIdleTimeout); - this._rpcWebSocketIdleTimeout = null; - this._rpcWebSocketConnected = true; - } - - if (this._rpcWebSocketConnected) { - _context98.next = 7; - break; - } - - this._rpcWebSocket.connect(); - - return _context98.abrupt("return"); - - case 7: - activeWebSocketGeneration = this._rpcWebSocketGeneration; - - isCurrentConnectionStillActive = function isCurrentConnectionStillActive() { - return activeWebSocketGeneration === _this26._rpcWebSocketGeneration; - }; - - _context98.next = 11; - return Promise.all( // Don't be tempted to change this to `Object.entries`. We call - // `_updateSubscriptions` recursively when processing the state, - // so it's important that we look up the *current* version of - // each subscription, every time we process a hash. - Object.keys(this._subscriptionsByHash).map( /*#__PURE__*/function () { - var _ref42 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee97(hash) { - var subscription; - return _regeneratorRuntime().wrap(function _callee97$(_context97) { - while (1) switch (_context97.prev = _context97.next) { - case 0: - subscription = _this26._subscriptionsByHash[hash]; - - if (!(subscription === undefined)) { - _context97.next = 3; - break; - } - - return _context97.abrupt("return"); - - case 3: - _context97.t0 = subscription.state; - _context97.next = _context97.t0 === 'pending' ? 6 : _context97.t0 === 'unsubscribed' ? 6 : _context97.t0 === 'subscribed' ? 15 : 19; - break; - - case 6: - if (!(subscription.callbacks.size === 0)) { - _context97.next = 12; - break; - } - - /** - * You can end up here when: - * - * - a subscription has recently unsubscribed - * without having new callbacks added to it - * while the unsubscribe was in flight, or - * - when a pending subscription has its - * listeners removed before a request was - * sent to the server. - * - * Being that nobody is interested in this - * subscription any longer, delete it. - */ - delete _this26._subscriptionsByHash[hash]; - - if (subscription.state === 'unsubscribed') { - delete _this26._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]; - } - - _context97.next = 11; - return _this26._updateSubscriptions(); - - case 11: - return _context97.abrupt("return"); - - case 12: - _context97.next = 14; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee95() { - var args, method, serverSubscriptionId; - return _regeneratorRuntime().wrap(function _callee95$(_context95) { - while (1) switch (_context95.prev = _context95.next) { - case 0: - args = subscription.args, method = subscription.method; - _context95.prev = 1; - - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'subscribing' - })); - - _context95.next = 5; - return _this26._rpcWebSocket.call(method, args); - - case 5: - serverSubscriptionId = _context95.sent; - - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - serverSubscriptionId: serverSubscriptionId, - state: 'subscribed' - })); - - _this26._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks; - _context95.next = 10; - return _this26._updateSubscriptions(); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(ComputeBudgetProgram.programId)) { + throw new Error('invalid instruction; programId is not ComputeBudgetProgram'); + } + } + }]); - case 10: - _context95.next = 20; - break; + return ComputeBudgetInstruction; +}(); +/** + * An enumeration of valid ComputeBudgetInstructionType's + */ - case 12: - _context95.prev = 12; - _context95.t0 = _context95["catch"](1); +/** + * An enumeration of valid ComputeBudget InstructionType's + * @internal + */ - if (_context95.t0 instanceof Error) { - console.error("".concat(method, " error for argument"), args, _context95.t0.message); - } - if (isCurrentConnectionStillActive()) { - _context95.next = 17; - break; - } +var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({ + RequestUnits: { + index: 0, + layout: struct([u8('instruction'), u32('units'), u32('additionalFee')]) + }, + RequestHeapFrame: { + index: 1, + layout: struct([u8('instruction'), u32('bytes')]) + }, + SetComputeUnitLimit: { + index: 2, + layout: struct([u8('instruction'), u32('units')]) + }, + SetComputeUnitPrice: { + index: 3, + layout: struct([u8('instruction'), u64('microLamports')]) + } +}); +/** + * Factory class for transaction instructions to interact with the Compute Budget program + */ - return _context95.abrupt("return"); +var ComputeBudgetProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function ComputeBudgetProgram() { + _classCallCheck(this, ComputeBudgetProgram); + } + /** + * Public key that identifies the Compute Budget program + */ - case 17: - // TODO: Maybe add an 'errored' state or a retry limit? - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'pending' - })); + /** + * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice} + */ - _context95.next = 20; - return _this26._updateSubscriptions(); - case 20: - case "end": - return _context95.stop(); - } - }, _callee95, null, [[1, 12]]); - }))(); + _createClass(ComputeBudgetProgram, null, [{ + key: "requestUnits", + value: function requestUnits(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "requestHeapFrame", + value: function requestHeapFrame(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "setComputeUnitLimit", + value: function setComputeUnitLimit(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "setComputeUnitPrice", + value: function setComputeUnitPrice(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice; + var data = encodeData(type, { + microLamports: BigInt(params.microLamports) + }); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }]); - case 14: - return _context97.abrupt("break", 19); + return ComputeBudgetProgram; +}(); - case 15: - if (!(subscription.callbacks.size === 0)) { - _context97.next = 18; - break; - } +ComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111'); +var PRIVATE_KEY_BYTES$1 = 64; +var PUBLIC_KEY_BYTES$1 = 32; +var SIGNATURE_BYTES = 64; +/** + * Params for creating an ed25519 instruction using a public key + */ - _context97.next = 18; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee96() { - var serverSubscriptionId, unsubscribeMethod; - return _regeneratorRuntime().wrap(function _callee96$(_context96) { - while (1) switch (_context96.prev = _context96.next) { - case 0: - serverSubscriptionId = subscription.serverSubscriptionId, unsubscribeMethod = subscription.unsubscribeMethod; +var ED25519_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u8('padding'), u16('signatureOffset'), u16('signatureInstructionIndex'), u16('publicKeyOffset'), u16('publicKeyInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u16('messageInstructionIndex')]); - if (!_this26._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) { - _context96.next = 5; - break; - } +var Ed25519Program = /*#__PURE__*/function () { + /** + * @internal + */ + function Ed25519Program() { + _classCallCheck(this, Ed25519Program); + } + /** + * Public key that identifies the ed25519 program + */ - /** - * Special case. - * If we're dealing with a subscription that has been auto- - * disposed by the RPC, then we can skip the RPC call to - * tear down the subscription here. - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ - _this26._subscriptionsAutoDisposedByRpc["delete"](serverSubscriptionId); + /** + * Create an ed25519 instruction with a public key and signature. The + * public key must be a buffer that is 32 bytes long, and the signature + * must be a buffer of 64 bytes. + */ - _context96.next = 21; - break; - case 5: - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribing' - })); + _createClass(Ed25519Program, null, [{ + key: "createInstructionWithPublicKey", + value: function createInstructionWithPublicKey(params) { + var publicKey = params.publicKey, + message = params.message, + signature = params.signature, + instructionIndex = params.instructionIndex; + assert(publicKey.length === PUBLIC_KEY_BYTES$1, "Public Key must be ".concat(PUBLIC_KEY_BYTES$1, " bytes but received ").concat(publicKey.length, " bytes")); + assert(signature.length === SIGNATURE_BYTES, "Signature must be ".concat(SIGNATURE_BYTES, " bytes but received ").concat(signature.length, " bytes")); + var publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span; + var signatureOffset = publicKeyOffset + publicKey.length; + var messageDataOffset = signatureOffset + signature.length; + var numSignatures = 1; + var instructionData = Buffer$1.alloc(messageDataOffset + message.length); + var index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction. + : instructionIndex; + ED25519_INSTRUCTION_LAYOUT.encode({ + numSignatures: numSignatures, + padding: 0, + signatureOffset: signatureOffset, + signatureInstructionIndex: index, + publicKeyOffset: publicKeyOffset, + publicKeyInstructionIndex: index, + messageDataOffset: messageDataOffset, + messageDataSize: message.length, + messageInstructionIndex: index + }, instructionData); + instructionData.fill(publicKey, publicKeyOffset); + instructionData.fill(signature, signatureOffset); + instructionData.fill(message, messageDataOffset); + return new TransactionInstruction({ + keys: [], + programId: Ed25519Program.programId, + data: instructionData + }); + } + /** + * Create an ed25519 instruction with a private key. The private key + * must be a buffer that is 64 bytes long. + */ - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribing' - })); + }, { + key: "createInstructionWithPrivateKey", + value: function createInstructionWithPrivateKey(params) { + var privateKey = params.privateKey, + message = params.message, + instructionIndex = params.instructionIndex; + assert(privateKey.length === PRIVATE_KEY_BYTES$1, "Private key must be ".concat(PRIVATE_KEY_BYTES$1, " bytes but received ").concat(privateKey.length, " bytes")); - _context96.prev = 7; - _context96.next = 10; - return _this26._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]); + try { + var keypair = Keypair.fromSecretKey(privateKey); - case 10: - _context96.next = 21; - break; + var _publicKey2 = keypair.publicKey.toBytes(); - case 12: - _context96.prev = 12; - _context96.t0 = _context96["catch"](7); + var _signature5 = _sign(message, keypair.secretKey); - if (_context96.t0 instanceof Error) { - console.error("".concat(unsubscribeMethod, " error:"), _context96.t0.message); - } + return this.createInstructionWithPublicKey({ + publicKey: _publicKey2, + message: message, + signature: _signature5, + instructionIndex: instructionIndex + }); + } catch (error) { + throw new Error("Error creating instruction; ".concat(error)); + } + } + }]); - if (isCurrentConnectionStillActive()) { - _context96.next = 17; - break; - } + return Ed25519Program; +}(); - return _context96.abrupt("return"); +Ed25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111'); // Supply a synchronous hashing algorithm to make this +// library interoperable with the synchronous APIs in web3.js. - case 17: - // TODO: Maybe add an 'errored' state or a retry limit? - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'subscribed' - })); +utils.hmacSha256Sync = function (key) { + var h = hmac.create(sha256, key); - _context96.next = 20; - return _this26._updateSubscriptions(); + for (var _len8 = arguments.length, msgs = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) { + msgs[_key8 - 1] = arguments[_key8]; + } - case 20: - return _context96.abrupt("return"); + msgs.forEach(function (msg) { + return h.update(msg); + }); + return h.digest(); +}; - case 21: - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribed' - })); +var ecdsaSign = function ecdsaSign(msgHash, privKey) { + return signSync(msgHash, privKey, { + der: false, + recovered: true + }); +}; - _context96.next = 24; - return _this26._updateSubscriptions(); +utils.isValidPrivateKey; +var publicKeyCreate = getPublicKey$1; +var PRIVATE_KEY_BYTES = 32; +var ETHEREUM_ADDRESS_BYTES = 20; +var PUBLIC_KEY_BYTES = 64; +var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11; +/** + * Params for creating an secp256k1 instruction using a public key + */ - case 24: - case "end": - return _context96.stop(); - } - }, _callee96, null, [[7, 12]]); - }))(); +var SECP256K1_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u16('signatureOffset'), u8('signatureInstructionIndex'), u16('ethAddressOffset'), u8('ethAddressInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u8('messageInstructionIndex'), blob$1(20, 'ethAddress'), blob$1(64, 'signature'), u8('recoveryId')]); - case 18: - return _context97.abrupt("break", 19); +var Secp256k1Program = /*#__PURE__*/function () { + /** + * @internal + */ + function Secp256k1Program() { + _classCallCheck(this, Secp256k1Program); + } + /** + * Public key that identifies the secp256k1 program + */ - case 19: - case "end": - return _context97.stop(); - } - }, _callee97); - })); + /** + * Construct an Ethereum address from a secp256k1 public key buffer. + * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer + */ - return function (_x151) { - return _ref42.apply(this, arguments); - }; - }())); - case 11: - case "end": - return _context98.stop(); - } - }, _callee98, this); - })); + _createClass(Secp256k1Program, null, [{ + key: "publicKeyToEthAddress", + value: function publicKeyToEthAddress(publicKey) { + assert(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes")); - function _updateSubscriptions() { - return _updateSubscriptions2.apply(this, arguments); + try { + return Buffer$1.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES); + } catch (error) { + throw new Error("Error constructing Ethereum address: ".concat(error)); } - - return _updateSubscriptions; - }() + } /** - * @internal + * Create an secp256k1 instruction with a public key. The public key + * must be a buffer that is 64 bytes long. */ }, { - key: "_handleServerNotification", - value: function _handleServerNotification(serverSubscriptionId, callbackArgs) { - var callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]; - - if (callbacks === undefined) { - return; - } - - callbacks.forEach(function (cb) { - try { - cb.apply(void 0, _toConsumableArray(callbackArgs)); - } catch (e) { - console.error(e); - } + key: "createInstructionWithPublicKey", + value: function createInstructionWithPublicKey(params) { + var publicKey = params.publicKey, + message = params.message, + signature = params.signature, + recoveryId = params.recoveryId, + instructionIndex = params.instructionIndex; + return Secp256k1Program.createInstructionWithEthAddress({ + ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey), + message: message, + signature: signature, + recoveryId: recoveryId, + instructionIndex: instructionIndex }); } /** - * @internal + * Create an secp256k1 instruction with an Ethereum address. The address + * must be a hex string or a buffer that is 20 bytes long. */ }, { - key: "_wsOnAccountNotification", - value: function _wsOnAccountNotification(notification) { - var _create$1 = _create(notification, AccountNotificationResult), - result = _create$1.result, - subscription = _create$1.subscription; + key: "createInstructionWithEthAddress", + value: function createInstructionWithEthAddress(params) { + var rawAddress = params.ethAddress, + message = params.message, + signature = params.signature, + recoveryId = params.recoveryId, + _params$instructionIn = params.instructionIndex, + instructionIndex = _params$instructionIn === void 0 ? 0 : _params$instructionIn; + var ethAddress; - this._handleServerNotification(subscription, [result.value, result.context]); + if (typeof rawAddress === 'string') { + if (rawAddress.startsWith('0x')) { + ethAddress = Buffer$1.from(rawAddress.substr(2), 'hex'); + } else { + ethAddress = Buffer$1.from(rawAddress, 'hex'); + } + } else { + ethAddress = rawAddress; + } + + assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes")); + var dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE; + var ethAddressOffset = dataStart; + var signatureOffset = dataStart + ethAddress.length; + var messageDataOffset = signatureOffset + signature.length + 1; + var numSignatures = 1; + var instructionData = Buffer$1.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length); + SECP256K1_INSTRUCTION_LAYOUT.encode({ + numSignatures: numSignatures, + signatureOffset: signatureOffset, + signatureInstructionIndex: instructionIndex, + ethAddressOffset: ethAddressOffset, + ethAddressInstructionIndex: instructionIndex, + messageDataOffset: messageDataOffset, + messageDataSize: message.length, + messageInstructionIndex: instructionIndex, + signature: toBuffer(signature), + ethAddress: toBuffer(ethAddress), + recoveryId: recoveryId + }, instructionData); + instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span); + return new TransactionInstruction({ + keys: [], + programId: Secp256k1Program.programId, + data: instructionData + }); } /** - * @internal + * Create an secp256k1 instruction with a private key. The private key + * must be a buffer that is 32 bytes long. */ }, { - key: "_makeSubscription", - value: function _makeSubscription(subscriptionConfig, - /** - * When preparing `args` for a call to `_makeSubscription`, be sure - * to carefully apply a default `commitment` property, if necessary. - * - * - If the user supplied a `commitment` use that. - * - Otherwise, if the `Connection::commitment` is set, use that. - * - Otherwise, set it to the RPC server default: `finalized`. - * - * This is extremely important to ensure that these two fundamentally - * identical subscriptions produce the same identifying hash: - * - * - A subscription made without specifying a commitment. - * - A subscription made where the commitment specified is the same - * as the default applied to the subscription above. - * - * Example; these two subscriptions must produce the same hash: - * - * - An `accountSubscribe` subscription for `'PUBKEY'` - * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment - * `'finalized'`. - * - * See the 'making a subscription with defaulted params omitted' test - * in `connection-subscriptions.ts` for more. - */ - args) { - var _this27 = this; + key: "createInstructionWithPrivateKey", + value: function createInstructionWithPrivateKey(params) { + var pkey = params.privateKey, + message = params.message, + instructionIndex = params.instructionIndex; + assert(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes")); - var clientSubscriptionId = this._nextClientSubscriptionId++; - var hash = fastStableStringify$1([subscriptionConfig.method, args]); - var existingSubscription = this._subscriptionsByHash[hash]; + try { + var privateKey = toBuffer(pkey); - if (existingSubscription === undefined) { - this._subscriptionsByHash[hash] = _objectSpread2(_objectSpread2({}, subscriptionConfig), {}, { - args: args, - callbacks: new Set([subscriptionConfig.callback]), - state: 'pending' + var _publicKey3 = publicKeyCreate(privateKey, false + /* isCompressed */ + ).slice(1); // throw away leading byte + + + var messageHash = Buffer$1.from(keccak_256(toBuffer(message))); + + var _ecdsaSign3 = ecdsaSign(messageHash, privateKey), + _ecdsaSign4 = _slicedToArray(_ecdsaSign3, 2), + _signature6 = _ecdsaSign4[0], + recoveryId = _ecdsaSign4[1]; + + return this.createInstructionWithPublicKey({ + publicKey: _publicKey3, + message: message, + signature: _signature6, + recoveryId: recoveryId, + instructionIndex: instructionIndex }); - } else { - existingSubscription.callbacks.add(subscriptionConfig.callback); + } catch (error) { + throw new Error("Error creating instruction; ".concat(error)); } + } + }]); - this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash; - this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee99() { - var subscription; - return _regeneratorRuntime().wrap(function _callee99$(_context99) { - while (1) switch (_context99.prev = _context99.next) { - case 0: - delete _this27._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - delete _this27._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - subscription = _this27._subscriptionsByHash[hash]; - assert(subscription !== undefined, "Could not find a `Subscription` when tearing down client subscription #".concat(clientSubscriptionId)); - subscription.callbacks["delete"](subscriptionConfig.callback); - _context99.next = 7; - return _this27._updateSubscriptions(); + return Secp256k1Program; +}(); - case 7: - case "end": - return _context99.stop(); - } - }, _callee99); - })); +Secp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111'); +/** + * Address of the stake config account which configures the rate + * of stake warmup and cooldown as well as the slashing penalty. + */ - this._updateSubscriptions(); +var STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111'); +/** + * Stake account authority info + */ - return clientSubscriptionId; - } - /** - * Register a callback to be invoked whenever the specified account changes - * - * @param publicKey Public key of the account to monitor - * @param callback Function to invoke whenever the account is changed - * @param commitment Specify the commitment level account changes must reach before notification - * @return subscription id - */ +var Authorized = /*#__PURE__*/_createClass( +/** stake authority */ - }, { - key: "onAccountChange", - value: function onAccountChange(publicKey, callback, commitment) { - var args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. - 'base64'); +/** withdraw authority */ - return this._makeSubscription({ - callback: callback, - method: 'accountSubscribe', - unsubscribeMethod: 'accountUnsubscribe' - }, args); - } - /** - * Deregister an account notification callback - * - * @param id client subscription id to deregister - */ +/** + * Create a new Authorized object + * @param staker the stake authority + * @param withdrawer the withdraw authority + */ +function Authorized(staker, withdrawer) { + _classCallCheck(this, Authorized); - }, { - key: "removeAccountChangeListener", - value: function () { - var _removeAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee100(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee100$(_context100) { - while (1) switch (_context100.prev = _context100.next) { - case 0: - _context100.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'account change'); + this.staker = void 0; + this.withdrawer = void 0; + this.staker = staker; + this.withdrawer = withdrawer; +}); +/** + * Stake account lockup info + */ - case 2: - case "end": - return _context100.stop(); - } - }, _callee100, this); - })); - function removeAccountChangeListener(_x152) { - return _removeAccountChangeListener.apply(this, arguments); - } +var Lockup = /*#__PURE__*/_createClass( +/** Unix timestamp of lockup expiration */ - return removeAccountChangeListener; - }() - /** - * @internal - */ +/** Epoch of lockup expiration */ - }, { - key: "_wsOnProgramAccountNotification", - value: function _wsOnProgramAccountNotification(notification) { - var _create2 = _create(notification, ProgramAccountNotificationResult), - result = _create2.result, - subscription = _create2.subscription; +/** Lockup custodian authority */ - this._handleServerNotification(subscription, [{ - accountId: result.value.pubkey, - accountInfo: result.value.account - }, result.context]); - } - /** - * Register a callback to be invoked whenever accounts owned by the - * specified program change - * - * @param programId Public key of the program to monitor - * @param callback Function to invoke whenever the account is changed - * @param commitment Specify the commitment level account changes must reach before notification - * @param filters The program account filters to pass into the RPC method - * @return subscription id - */ +/** + * Create a new Lockup object + */ +function Lockup(unixTimestamp, epoch, custodian) { + _classCallCheck(this, Lockup); - }, { - key: "onProgramAccountChange", - value: function onProgramAccountChange(programId, callback, commitment, filters) { - var args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. - 'base64' - /* encoding */ - , filters ? { - filters: filters - } : undefined - /* extra */ - ); + this.unixTimestamp = void 0; + this.epoch = void 0; + this.custodian = void 0; + this.unixTimestamp = unixTimestamp; + this.epoch = epoch; + this.custodian = custodian; +} +/** + * Default, inactive Lockup value + */ +); - return this._makeSubscription({ - callback: callback, - method: 'programSubscribe', - unsubscribeMethod: 'programUnsubscribe' - }, args); +Lockup["default"] = new Lockup(0, 0, PublicKey["default"]); +/** + * Stake Instruction class + */ + +var StakeInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function StakeInstruction() { + _classCallCheck(this, StakeInstruction); + } + /** + * Decode a stake instruction and retrieve the instruction type. + */ + + + _createClass(StakeInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; + + for (var _i12 = 0, _Object$entries4 = Object.entries(STAKE_INSTRUCTION_LAYOUTS); _i12 < _Object$entries4.length; _i12++) { + var _Object$entries4$_i2 = _slicedToArray(_Object$entries4[_i12], 2), + ixType = _Object$entries4$_i2[0], + layout = _Object$entries4$_i2[1]; + + if (layout.index == typeIndex) { + type = ixType; + break; + } + } + + if (!type) { + throw new Error('Instruction type incorrect; not a StakeInstruction'); + } + + return type; } /** - * Deregister an account notification callback - * - * @param id client subscription id to deregister + * Decode a initialize stake instruction and retrieve the instruction params. */ }, { - key: "removeProgramAccountChangeListener", - value: function () { - var _removeProgramAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee101(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee101$(_context101) { - while (1) switch (_context101.prev = _context101.next) { - case 0: - _context101.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change'); - - case 2: - case "end": - return _context101.stop(); - } - }, _callee101, this); - })); + key: "decodeInitialize", + value: function decodeInitialize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - function removeProgramAccountChangeListener(_x153) { - return _removeProgramAccountChangeListener.apply(this, arguments); - } + var _decodeData$18 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data), + authorized = _decodeData$18.authorized, + lockup = _decodeData$18.lockup; - return removeProgramAccountChangeListener; - }() + return { + stakePubkey: instruction.keys[0].pubkey, + authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)), + lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian)) + }; + } /** - * Registers a callback to be invoked whenever logs are emitted. + * Decode a delegate stake instruction and retrieve the instruction params. */ }, { - key: "onLogs", - value: function onLogs(filter, callback, commitment) { - var args = this._buildArgs([_typeof$1(filter) === 'object' ? { - mentions: [filter.toString()] - } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default. - ); - - return this._makeSubscription({ - callback: callback, - method: 'logsSubscribe', - unsubscribeMethod: 'logsUnsubscribe' - }, args); + key: "decodeDelegate", + value: function decodeDelegate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 6); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + votePubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[5].pubkey + }; } /** - * Deregister a logs callback. - * - * @param id client subscription id to deregister. + * Decode an authorize stake instruction and retrieve the instruction params. */ }, { - key: "removeOnLogsListener", - value: function () { - var _removeOnLogsListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee102(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee102$(_context102) { - while (1) switch (_context102.prev = _context102.next) { - case 0: - _context102.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'logs'); + key: "decodeAuthorize", + value: function decodeAuthorize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - case 2: - case "end": - return _context102.stop(); - } - }, _callee102, this); - })); + var _decodeData$19 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), + newAuthorized = _decodeData$19.newAuthorized, + stakeAuthorizationType = _decodeData$19.stakeAuthorizationType; - function removeOnLogsListener(_x154) { - return _removeOnLogsListener.apply(this, arguments); + var o = { + stakePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + newAuthorizedPubkey: new PublicKey(newAuthorized), + stakeAuthorizationType: { + index: stakeAuthorizationType + } + }; + + if (instruction.keys.length > 3) { + o.custodianPubkey = instruction.keys[3].pubkey; } - return removeOnLogsListener; - }() + return o; + } /** - * @internal + * Decode an authorize-with-seed stake instruction and retrieve the instruction params. */ }, { - key: "_wsOnLogsNotification", - value: function _wsOnLogsNotification(notification) { - var _create3 = _create(notification, LogsNotificationResult), - result = _create3.result, - subscription = _create3.subscription; + key: "decodeAuthorizeWithSeed", + value: function decodeAuthorizeWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - this._handleServerNotification(subscription, [result.value, result.context]); + var _decodeData$20 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), + newAuthorized = _decodeData$20.newAuthorized, + stakeAuthorizationType = _decodeData$20.stakeAuthorizationType, + authoritySeed = _decodeData$20.authoritySeed, + authorityOwner = _decodeData$20.authorityOwner; + + var o = { + stakePubkey: instruction.keys[0].pubkey, + authorityBase: instruction.keys[1].pubkey, + authoritySeed: authoritySeed, + authorityOwner: new PublicKey(authorityOwner), + newAuthorizedPubkey: new PublicKey(newAuthorized), + stakeAuthorizationType: { + index: stakeAuthorizationType + } + }; + + if (instruction.keys.length > 3) { + o.custodianPubkey = instruction.keys[3].pubkey; + } + + return o; } /** - * @internal + * Decode a split stake instruction and retrieve the instruction params. */ }, { - key: "_wsOnSlotNotification", - value: function _wsOnSlotNotification(notification) { - var _create4 = _create(notification, SlotNotificationResult), - result = _create4.result, - subscription = _create4.subscription; + key: "decodeSplit", + value: function decodeSplit(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - this._handleServerNotification(subscription, [result]); + var _decodeData$21 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data), + lamports = _decodeData$21.lamports; + + return { + stakePubkey: instruction.keys[0].pubkey, + splitStakePubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + lamports: lamports + }; } /** - * Register a callback to be invoked upon slot changes - * - * @param callback Function to invoke whenever the slot changes - * @return subscription id + * Decode a merge stake instruction and retrieve the instruction params. */ }, { - key: "onSlotChange", - value: function onSlotChange(callback) { - return this._makeSubscription({ - callback: callback, - method: 'slotSubscribe', - unsubscribeMethod: 'slotUnsubscribe' - }, [] - /* args */ - ); + key: "decodeMerge", + value: function decodeMerge(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + sourceStakePubKey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey + }; } /** - * Deregister a slot notification callback - * - * @param id client subscription id to deregister + * Decode a withdraw stake instruction and retrieve the instruction params. */ }, { - key: "removeSlotChangeListener", - value: function () { - var _removeSlotChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee103(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee103$(_context103) { - while (1) switch (_context103.prev = _context103.next) { - case 0: - _context103.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change'); - - case 2: - case "end": - return _context103.stop(); - } - }, _callee103, this); - })); + key: "decodeWithdraw", + value: function decodeWithdraw(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 5); - function removeSlotChangeListener(_x155) { - return _removeSlotChangeListener.apply(this, arguments); - } + var _decodeData$22 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), + lamports = _decodeData$22.lamports; - return removeSlotChangeListener; - }() - /** - * @internal - */ + var o = { + stakePubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey, + lamports: lamports + }; - }, { - key: "_wsOnSlotUpdatesNotification", - value: function _wsOnSlotUpdatesNotification(notification) { - var _create5 = _create(notification, SlotUpdateNotificationResult), - result = _create5.result, - subscription = _create5.subscription; + if (instruction.keys.length > 5) { + o.custodianPubkey = instruction.keys[5].pubkey; + } - this._handleServerNotification(subscription, [result]); + return o; } /** - * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s - * may be useful to track live progress of a cluster. - * - * @param callback Function to invoke whenever the slot updates - * @return subscription id + * Decode a deactivate stake instruction and retrieve the instruction params. */ }, { - key: "onSlotUpdate", - value: function onSlotUpdate(callback) { - return this._makeSubscription({ - callback: callback, - method: 'slotsUpdatesSubscribe', - unsubscribeMethod: 'slotsUpdatesUnsubscribe' - }, [] - /* args */ - ); + key: "decodeDeactivate", + value: function decodeDeactivate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey + }; } /** - * Deregister a slot update notification callback - * - * @param id client subscription id to deregister + * @internal */ }, { - key: "removeSlotUpdateListener", - value: function () { - var _removeSlotUpdateListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee104(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee104$(_context104) { - while (1) switch (_context104.prev = _context104.next) { - case 0: - _context104.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update'); - - case 2: - case "end": - return _context104.stop(); - } - }, _callee104, this); - })); - - function removeSlotUpdateListener(_x156) { - return _removeSlotUpdateListener.apply(this, arguments); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(StakeProgram.programId)) { + throw new Error('invalid instruction; programId is not StakeProgram'); } - - return removeSlotUpdateListener; - }() + } /** * @internal */ }, { - key: "_unsubscribeClientSubscription", - value: function () { - var _unsubscribeClientSubscription2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee105(clientSubscriptionId, subscriptionName) { - var dispose; - return _regeneratorRuntime().wrap(function _callee105$(_context105) { - while (1) switch (_context105.prev = _context105.next) { - case 0: - dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - - if (!dispose) { - _context105.next = 6; - break; - } - - _context105.next = 4; - return dispose(); - - case 4: - _context105.next = 7; - break; - - case 6: - console.warn('Ignored unsubscribe request because an active subscription with id ' + "`".concat(clientSubscriptionId, "` for '").concat(subscriptionName, "' events ") + 'could not be found.'); - - case 7: - case "end": - return _context105.stop(); - } - }, _callee105, this); - })); - - function _unsubscribeClientSubscription(_x157, _x158) { - return _unsubscribeClientSubscription2.apply(this, arguments); + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); } + } + }]); - return _unsubscribeClientSubscription; - }() - }, { - key: "_buildArgs", - value: function _buildArgs(args, override, encoding, extra) { - var commitment = override || this._commitment; + return StakeInstruction; +}(); +/** + * An enumeration of valid StakeInstructionType's + */ - if (commitment || encoding || extra) { - var options = {}; +/** + * An enumeration of valid stake InstructionType's + * @internal + */ - if (encoding) { - options.encoding = encoding; - } - if (commitment) { - options.commitment = commitment; - } +var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({ + Initialize: { + index: 0, + layout: struct([u32('instruction'), authorized(), lockup()]) + }, + Authorize: { + index: 1, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType')]) + }, + Delegate: { + index: 2, + layout: struct([u32('instruction')]) + }, + Split: { + index: 3, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + Withdraw: { + index: 4, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + Deactivate: { + index: 5, + layout: struct([u32('instruction')]) + }, + Merge: { + index: 7, + layout: struct([u32('instruction')]) + }, + AuthorizeWithSeed: { + index: 8, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')]) + } +}); +/** + * Stake authorization type + */ - if (extra) { - options = Object.assign(options, extra); - } +/** + * An enumeration of valid StakeAuthorizationLayout's + */ - args.push(options); - } +var StakeAuthorizationLayout = Object.freeze({ + Staker: { + index: 0 + }, + Withdrawer: { + index: 1 + } +}); +/** + * Factory class for transactions to interact with the Stake program + */ - return args; - } - /** - * @internal - */ +var StakeProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function StakeProgram() { + _classCallCheck(this, StakeProgram); + } + /** + * Public key that identifies the Stake program + */ - }, { - key: "_buildArgsAtLeastConfirmed", - value: function _buildArgsAtLeastConfirmed(args, override, encoding, extra) { - var commitment = override || this._commitment; + /** + * Generate an Initialize instruction to add to a Stake Create transaction + */ - if (commitment && !['confirmed', 'finalized'].includes(commitment)) { - throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`'); - } - return this._buildArgs(args, override, encoding, extra); + _createClass(StakeProgram, null, [{ + key: "initialize", + value: function initialize(params) { + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + maybeLockup = params.lockup; + var lockup = maybeLockup || Lockup["default"]; + var type = STAKE_INSTRUCTION_LAYOUTS.Initialize; + var data = encodeData(type, { + authorized: { + staker: toBuffer(authorized.staker.toBuffer()), + withdrawer: toBuffer(authorized.withdrawer.toBuffer()) + }, + lockup: { + unixTimestamp: lockup.unixTimestamp, + epoch: lockup.epoch, + custodian: toBuffer(lockup.custodian.toBuffer()) + } + }); + var instructionData = { + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); } /** - * @internal + * Generate a Transaction that creates a new Stake account at + * an address generated with `from`, a seed, and the Stake programId */ }, { - key: "_wsOnSignatureNotification", - value: function _wsOnSignatureNotification(notification) { - var _create6 = _create(notification, SignatureNotificationResult), - result = _create6.result, - subscription = _create6.subscription; - - if (result.value !== 'receivedSignature') { - /** - * Special case. - * After a signature is processed, RPCs automatically dispose of the - * subscription on the server side. We need to track which of these - * subscriptions have been disposed in such a way, so that we know - * whether the client is dealing with a not-yet-processed signature - * (in which case we must tear down the server subscription) or an - * already-processed signature (in which case the client can simply - * clear out the subscription locally without telling the server). - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ - this._subscriptionsAutoDisposedByRpc.add(subscription); - } - - this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{ - type: 'received' - }, result.context] : [{ - type: 'status', - result: result.value - }, result.context]); + key: "createAccountWithSeed", + value: function createAccountWithSeed(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccountWithSeed({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.stakePubkey, + basePubkey: params.basePubkey, + seed: params.seed, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + lockup = params.lockup; + return transaction.add(this.initialize({ + stakePubkey: stakePubkey, + authorized: authorized, + lockup: lockup + })); } /** - * Register a callback to be invoked upon signature updates - * - * @param signature Transaction signature string in base 58 - * @param callback Function to invoke on signature notifications - * @param commitment Specify the commitment level signature must reach before notification - * @return subscription id + * Generate a Transaction that creates a new Stake account */ }, { - key: "onSignature", - value: function onSignature(signature, _callback, commitment) { - var _this28 = this; - - var args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default. - ); - - var clientSubscriptionId = this._makeSubscription({ - callback: function callback(notification, context) { - if (notification.type === 'status') { - _callback(notification.result, context); // Signatures subscriptions are auto-removed by the RPC service - // so no need to explicitly send an unsubscribe message. - - - try { - _this28.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - - } catch (_err) {// Already removed. - } - } - }, - method: 'signatureSubscribe', - unsubscribeMethod: 'signatureUnsubscribe' - }, args); - - return clientSubscriptionId; + key: "createAccount", + value: function createAccount(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.stakePubkey, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + lockup = params.lockup; + return transaction.add(this.initialize({ + stakePubkey: stakePubkey, + authorized: authorized, + lockup: lockup + })); } /** - * Register a callback to be invoked when a transaction is - * received and/or processed. - * - * @param signature Transaction signature string in base 58 - * @param callback Function to invoke on signature notifications - * @param options Enable received notifications and set the commitment - * level that signature must reach before notification - * @return subscription id + * Generate a Transaction that delegates Stake tokens to a validator + * Vote PublicKey. This transaction can also be used to redelegate Stake + * to a new validator Vote PublicKey. */ }, { - key: "onSignatureWithOptions", - value: function onSignatureWithOptions(signature, _callback2, options) { - var _this29 = this; - - var _options$commitment = _objectSpread2(_objectSpread2({}, options), {}, { - commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default. - - }), - commitment = _options$commitment.commitment, - extra = _objectWithoutProperties(_options$commitment, _excluded4); - - var args = this._buildArgs([signature], commitment, undefined - /* encoding */ - , extra); - - var clientSubscriptionId = this._makeSubscription({ - callback: function callback(notification, context) { - _callback2(notification, context); // Signatures subscriptions are auto-removed by the RPC service - // so no need to explicitly send an unsubscribe message. - + key: "delegate", + value: function delegate(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + votePubkey = params.votePubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Delegate; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: votePubkey, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: STAKE_CONFIG_ID, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a Transaction that authorizes a new PublicKey as Staker + * or Withdrawer on the Stake account. + */ - try { - _this29.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty + }, { + key: "authorize", + value: function authorize(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + newAuthorizedPubkey = params.newAuthorizedPubkey, + stakeAuthorizationType = params.stakeAuthorizationType, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Authorize; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + stakeAuthorizationType: stakeAuthorizationType.index + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }]; - } catch (_err) {// Already removed. - } - }, - method: 'signatureSubscribe', - unsubscribeMethod: 'signatureUnsubscribe' - }, args); + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); + } - return clientSubscriptionId; + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); } /** - * Deregister a signature notification callback - * - * @param id client subscription id to deregister + * Generate a Transaction that authorizes a new PublicKey as Staker + * or Withdrawer on the Stake account. */ }, { - key: "removeSignatureListener", - value: function () { - var _removeSignatureListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee106(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee106$(_context106) { - while (1) switch (_context106.prev = _context106.next) { - case 0: - _context106.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result'); - - case 2: - case "end": - return _context106.stop(); - } - }, _callee106, this); - })); + key: "authorizeWithSeed", + value: function authorizeWithSeed(params) { + var stakePubkey = params.stakePubkey, + authorityBase = params.authorityBase, + authoritySeed = params.authoritySeed, + authorityOwner = params.authorityOwner, + newAuthorizedPubkey = params.newAuthorizedPubkey, + stakeAuthorizationType = params.stakeAuthorizationType, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + stakeAuthorizationType: stakeAuthorizationType.index, + authoritySeed: authoritySeed, + authorityOwner: toBuffer(authorityOwner.toBuffer()) + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorityBase, + isSigner: true, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }]; - function removeSignatureListener(_x159) { - return _removeSignatureListener.apply(this, arguments); + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); } - return removeSignatureListener; - }() + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); + } /** * @internal */ }, { - key: "_wsOnRootNotification", - value: function _wsOnRootNotification(notification) { - var _create7 = _create(notification, RootNotificationResult), - result = _create7.result, - subscription = _create7.subscription; - - this._handleServerNotification(subscription, [result]); + key: "splitInstruction", + value: function splitInstruction(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + splitStakePubkey = params.splitStakePubkey, + lamports = params.lamports; + var type = STAKE_INSTRUCTION_LAYOUTS.Split; + var data = encodeData(type, { + lamports: lamports + }); + return new TransactionInstruction({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: splitStakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); } /** - * Register a callback to be invoked upon root changes - * - * @param callback Function to invoke whenever the root changes - * @return subscription id + * Generate a Transaction that splits Stake tokens into another stake account */ }, { - key: "onRootChange", - value: function onRootChange(callback) { - return this._makeSubscription({ - callback: callback, - method: 'rootSubscribe', - unsubscribeMethod: 'rootUnsubscribe' - }, [] - /* args */ - ); + key: "split", + value: function split(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.authorizedPubkey, + newAccountPubkey: params.splitStakePubkey, + lamports: 0, + space: this.space, + programId: this.programId + })); + return transaction.add(this.splitInstruction(params)); } /** - * Deregister a root notification callback - * - * @param id client subscription id to deregister + * Generate a Transaction that splits Stake tokens into another account + * derived from a base public key and seed */ }, { - key: "removeRootChangeListener", - value: function () { - var _removeRootChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee107(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee107$(_context107) { - while (1) switch (_context107.prev = _context107.next) { - case 0: - _context107.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'root change'); - - case 2: - case "end": - return _context107.stop(); - } - }, _callee107, this); + key: "splitWithSeed", + value: function splitWithSeed(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + splitStakePubkey = params.splitStakePubkey, + basePubkey = params.basePubkey, + seed = params.seed, + lamports = params.lamports; + var transaction = new Transaction(); + transaction.add(SystemProgram.allocate({ + accountPubkey: splitStakePubkey, + basePubkey: basePubkey, + seed: seed, + space: this.space, + programId: this.programId + })); + return transaction.add(this.splitInstruction({ + stakePubkey: stakePubkey, + authorizedPubkey: authorizedPubkey, + splitStakePubkey: splitStakePubkey, + lamports: lamports })); - - function removeRootChangeListener(_x160) { - return _removeRootChangeListener.apply(this, arguments); - } - - return removeRootChangeListener; - }() - }]); - - return Connection; -}(); -/** - * Keypair signer interface - */ - -/** - * An account keypair used for signing transactions. - */ - - -var Keypair = /*#__PURE__*/function () { - /** - * Create a new keypair instance. - * Generate random keypair if no {@link Ed25519Keypair} is provided. - * - * @param keypair ed25519 keypair - */ - function Keypair(keypair) { - _classCallCheck(this, Keypair); - - this._keypair = void 0; - this._keypair = keypair !== null && keypair !== void 0 ? keypair : generateKeypair(); - } - /** - * Generate a new random keypair - */ - - - _createClass(Keypair, [{ - key: "publicKey", - get: - /** - * The public key for this keypair - */ - function get() { - return new PublicKey(this._keypair.publicKey); } /** - * The raw secret key for this keypair + * Generate a Transaction that merges Stake accounts. */ }, { - key: "secretKey", - get: function get() { - return new Uint8Array(this._keypair.secretKey); - } - }], [{ - key: "generate", - value: function generate() { - return new Keypair(generateKeypair()); + key: "merge", + value: function merge(params) { + var stakePubkey = params.stakePubkey, + sourceStakePubKey = params.sourceStakePubKey, + authorizedPubkey = params.authorizedPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Merge; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: sourceStakePubKey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); } /** - * Create a keypair from a raw secret key byte array. - * - * This method should only be used to recreate a keypair from a previously - * generated secret key. Generating keypairs from a random seed should be done - * with the {@link Keypair.fromSeed} method. - * - * @throws error if the provided secret key is invalid and validation is not skipped. - * - * @param secretKey secret key byte array - * @param options: skip secret key validation + * Generate a Transaction that withdraws deactivated Stake tokens. */ }, { - key: "fromSecretKey", - value: function fromSecretKey(secretKey, options) { - if (secretKey.byteLength !== 64) { - throw new Error('bad secret key size'); - } - - var publicKey = secretKey.slice(32, 64); - - if (!options || !options.skipValidation) { - var privateScalar = secretKey.slice(0, 32); - var computedPublicKey = getPublicKey(privateScalar); + key: "withdraw", + value: function withdraw(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + toPubkey = params.toPubkey, + lamports = params.lamports, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Withdraw; + var data = encodeData(type, { + lamports: lamports + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }]; - for (var ii = 0; ii < 32; ii++) { - if (publicKey[ii] !== computedPublicKey[ii]) { - throw new Error('provided secretKey is invalid'); - } - } + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); } - return new Keypair({ - publicKey: publicKey, - secretKey: secretKey + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data }); } /** - * Generate a keypair from a 32 byte seed. - * - * @param seed seed byte array + * Generate a Transaction that deactivates Stake tokens. */ }, { - key: "fromSeed", - value: function fromSeed(seed) { - var publicKey = getPublicKey(seed); - var secretKey = new Uint8Array(64); - secretKey.set(seed); - secretKey.set(publicKey, 32); - return new Keypair({ - publicKey: publicKey, - secretKey: secretKey + key: "deactivate", + value: function deactivate(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Deactivate; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data }); } }]); - return Keypair; + return StakeProgram; }(); + +StakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111'); +StakeProgram.space = 200; +/** + * Vote account info + */ + +var VoteInit = /*#__PURE__*/_createClass( +/** [0, 100] */ +function VoteInit(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) { + _classCallCheck(this, VoteInit); + + this.nodePubkey = void 0; + this.authorizedVoter = void 0; + this.authorizedWithdrawer = void 0; + this.commission = void 0; + this.nodePubkey = nodePubkey; + this.authorizedVoter = authorizedVoter; + this.authorizedWithdrawer = authorizedWithdrawer; + this.commission = commission; +}); /** - * An enumeration of valid address lookup table InstructionType's - * @internal + * Create vote account transaction params */ +/** + * Vote Instruction class + */ -var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({ - CreateLookupTable: { - index: 0, - layout: struct([u32('instruction'), u64('recentSlot'), u8('bumpSeed')]) - }, - FreezeLookupTable: { - index: 1, - layout: struct([u32('instruction')]) - }, - ExtendLookupTable: { - index: 2, - layout: struct([u32('instruction'), u64(), seq$1(publicKey(), offset$1(u32(), -8), 'addresses')]) - }, - DeactivateLookupTable: { - index: 3, - layout: struct([u32('instruction')]) - }, - CloseLookupTable: { - index: 4, - layout: struct([u32('instruction')]) - } -}); -var AddressLookupTableInstruction = /*#__PURE__*/function () { +var VoteInstruction = /*#__PURE__*/function () { /** * @internal */ - function AddressLookupTableInstruction() { - _classCallCheck(this, AddressLookupTableInstruction); + function VoteInstruction() { + _classCallCheck(this, VoteInstruction); } + /** + * Decode a vote instruction and retrieve the instruction type. + */ - _createClass(AddressLookupTableInstruction, null, [{ + + _createClass(VoteInstruction, null, [{ key: "decodeInstructionType", value: function decodeInstructionType(instruction) { this.checkProgramId(instruction.programId); var instructionTypeLayout = u32('instruction'); - var index = instructionTypeLayout.decode(instruction.data); + var typeIndex = instructionTypeLayout.decode(instruction.data); var type; - for (var _i10 = 0, _Object$entries2 = Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS); _i10 < _Object$entries2.length; _i10++) { - var _Object$entries2$_i2 = _slicedToArray(_Object$entries2[_i10], 2), - layoutType = _Object$entries2$_i2[0], - layout = _Object$entries2$_i2[1]; + for (var _i13 = 0, _Object$entries5 = Object.entries(VOTE_INSTRUCTION_LAYOUTS); _i13 < _Object$entries5.length; _i13++) { + var _Object$entries5$_i2 = _slicedToArray(_Object$entries5[_i13], 2), + ixType = _Object$entries5$_i2[0], + layout = _Object$entries5$_i2[1]; - if (layout.index == index) { - type = layoutType; + if (layout.index == typeIndex) { + type = ixType; break; } } if (!type) { - throw new Error('Invalid Instruction. Should be a LookupTable Instruction'); + throw new Error('Instruction type incorrect; not a VoteInstruction'); } return type; } + /** + * Decode an initialize vote instruction and retrieve the instruction params. + */ + }, { - key: "decodeCreateLookupTable", - value: function decodeCreateLookupTable(instruction) { + key: "decodeInitializeAccount", + value: function decodeInitializeAccount(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 4); + this.checkKeyLength(instruction.keys, 4); - var _decodeData$12 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data), - recentSlot = _decodeData$12.recentSlot; + var _decodeData$23 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data), + voteInit = _decodeData$23.voteInit; return { - authority: instruction.keys[1].pubkey, - payer: instruction.keys[2].pubkey, - recentSlot: Number(recentSlot) + votePubkey: instruction.keys[0].pubkey, + nodePubkey: instruction.keys[3].pubkey, + voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission) }; } + /** + * Decode an authorize instruction and retrieve the instruction params. + */ + }, { - key: "decodeExtendLookupTable", - value: function decodeExtendLookupTable(instruction) { + key: "decodeAuthorize", + value: function decodeAuthorize(instruction) { this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - if (instruction.keys.length < 2) { - throw new Error("invalid instruction; found ".concat(instruction.keys.length, " keys, expected at least 2")); - } - - var _decodeData$13 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data), - addresses = _decodeData$13.addresses; + var _decodeData$24 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), + newAuthorized = _decodeData$24.newAuthorized, + voteAuthorizationType = _decodeData$24.voteAuthorizationType; return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey, - payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined, - addresses: addresses.map(function (buffer) { - return new PublicKey(buffer); - }) - }; - } - }, { - key: "decodeCloseLookupTable", - value: function decodeCloseLookupTable(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 3); - return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey, - recipient: instruction.keys[2].pubkey + votePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + newAuthorizedPubkey: new PublicKey(newAuthorized), + voteAuthorizationType: { + index: voteAuthorizationType + } }; } + /** + * Decode an authorize instruction and retrieve the instruction params. + */ + }, { - key: "decodeFreezeLookupTable", - value: function decodeFreezeLookupTable(instruction) { + key: "decodeAuthorizeWithSeed", + value: function decodeAuthorizeWithSeed(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 2); + this.checkKeyLength(instruction.keys, 3); + + var _decodeData$25 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), + _decodeData$25$voteAu = _decodeData$25.voteAuthorizeWithSeedArgs, + currentAuthorityDerivedKeyOwnerPubkey = _decodeData$25$voteAu.currentAuthorityDerivedKeyOwnerPubkey, + currentAuthorityDerivedKeySeed = _decodeData$25$voteAu.currentAuthorityDerivedKeySeed, + newAuthorized = _decodeData$25$voteAu.newAuthorized, + voteAuthorizationType = _decodeData$25$voteAu.voteAuthorizationType; + return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey + currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey, + currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey), + currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, + newAuthorizedPubkey: new PublicKey(newAuthorized), + voteAuthorizationType: { + index: voteAuthorizationType + }, + votePubkey: instruction.keys[0].pubkey }; } + /** + * Decode a withdraw instruction and retrieve the instruction params. + */ + }, { - key: "decodeDeactivateLookupTable", - value: function decodeDeactivateLookupTable(instruction) { + key: "decodeWithdraw", + value: function decodeWithdraw(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 2); + this.checkKeyLength(instruction.keys, 3); + + var _decodeData$26 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), + lamports = _decodeData$26.lamports; + return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey + votePubkey: instruction.keys[0].pubkey, + authorizedWithdrawerPubkey: instruction.keys[2].pubkey, + lamports: lamports, + toPubkey: instruction.keys[1].pubkey }; } /** @@ -31015,8 +32662,8 @@ var AddressLookupTableInstruction = /*#__PURE__*/function () { }, { key: "checkProgramId", value: function checkProgramId(programId) { - if (!programId.equals(AddressLookupTableProgram.programId)) { - throw new Error('invalid instruction; programId is not AddressLookupTable Program'); + if (!programId.equals(VoteProgram.programId)) { + throw new Error('invalid instruction; programId is not VoteProgram'); } } /** @@ -31024,2301 +32671,2096 @@ var AddressLookupTableInstruction = /*#__PURE__*/function () { */ }, { - key: "checkKeysLength", - value: function checkKeysLength(keys, expectedLength) { + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { if (keys.length < expectedLength) { throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); } } }]); - return AddressLookupTableInstruction; + return VoteInstruction; }(); +/** + * An enumeration of valid VoteInstructionType's + */ -var AddressLookupTableProgram = /*#__PURE__*/function () { + +var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({ + InitializeAccount: { + index: 0, + layout: struct([u32('instruction'), voteInit()]) + }, + Authorize: { + index: 1, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('voteAuthorizationType')]) + }, + Withdraw: { + index: 3, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + AuthorizeWithSeed: { + index: 10, + layout: struct([u32('instruction'), voteAuthorizeWithSeedArgs()]) + } +}); +/** + * VoteAuthorize type + */ + +/** + * An enumeration of valid VoteAuthorization layouts. + */ + +var VoteAuthorizationLayout = Object.freeze({ + Voter: { + index: 0 + }, + Withdrawer: { + index: 1 + } +}); +/** + * Factory class for transactions to interact with the Vote program + */ + +var VoteProgram = /*#__PURE__*/function () { /** * @internal */ - function AddressLookupTableProgram() { - _classCallCheck(this, AddressLookupTableProgram); + function VoteProgram() { + _classCallCheck(this, VoteProgram); } + /** + * Public key that identifies the Vote program + */ - _createClass(AddressLookupTableProgram, null, [{ - key: "createLookupTable", - value: function createLookupTable(params) { - var _PublicKey$findProgra = PublicKey.findProgramAddressSync([params.authority.toBuffer(), toBufferLE_1(BigInt(params.recentSlot), 8)], this.programId), - _PublicKey$findProgra2 = _slicedToArray(_PublicKey$findProgra, 2), - lookupTableAddress = _PublicKey$findProgra2[0], - bumpSeed = _PublicKey$findProgra2[1]; + /** + * Generate an Initialize instruction. + */ - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable; + + _createClass(VoteProgram, null, [{ + key: "initializeAccount", + value: function initializeAccount(params) { + var votePubkey = params.votePubkey, + nodePubkey = params.nodePubkey, + voteInit = params.voteInit; + var type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount; var data = encodeData(type, { - recentSlot: BigInt(params.recentSlot), - bumpSeed: bumpSeed + voteInit: { + nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()), + authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()), + authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()), + commission: voteInit.commission + } + }); + var instructionData = { + keys: [{ + pubkey: votePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: nodePubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); + } + /** + * Generate a transaction that creates a new Vote account. + */ + + }, { + key: "createAccount", + value: function createAccount(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.votePubkey, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + return transaction.add(this.initializeAccount({ + votePubkey: params.votePubkey, + nodePubkey: params.voteInit.nodePubkey, + voteInit: params.voteInit + })); + } + /** + * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account. + */ + + }, { + key: "authorize", + value: function authorize(params) { + var votePubkey = params.votePubkey, + authorizedPubkey = params.authorizedPubkey, + newAuthorizedPubkey = params.newAuthorizedPubkey, + voteAuthorizationType = params.voteAuthorizationType; + var type = VOTE_INSTRUCTION_LAYOUTS.Authorize; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + voteAuthorizationType: voteAuthorizationType.index }); var keys = [{ - pubkey: lookupTableAddress, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, - isSigner: true, + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, isWritable: false }, { - pubkey: params.payer, + pubkey: authorizedPubkey, isSigner: true, - isWritable: true - }, { - pubkey: SystemProgram.programId, - isSigner: false, isWritable: false }]; - return [new TransactionInstruction({ - programId: this.programId, + return new Transaction().add({ keys: keys, + programId: this.programId, data: data - }), lookupTableAddress]; + }); } + /** + * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account + * where the current Voter or Withdrawer authority is a derived key. + */ + }, { - key: "freezeLookupTable", - value: function freezeLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable; - var data = encodeData(type); + key: "authorizeWithSeed", + value: function authorizeWithSeed(params) { + var currentAuthorityDerivedKeyBasePubkey = params.currentAuthorityDerivedKeyBasePubkey, + currentAuthorityDerivedKeyOwnerPubkey = params.currentAuthorityDerivedKeyOwnerPubkey, + currentAuthorityDerivedKeySeed = params.currentAuthorityDerivedKeySeed, + newAuthorizedPubkey = params.newAuthorizedPubkey, + voteAuthorizationType = params.voteAuthorizationType, + votePubkey = params.votePubkey; + var type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; + var data = encodeData(type, { + voteAuthorizeWithSeedArgs: { + currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()), + currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + voteAuthorizationType: voteAuthorizationType.index + } + }); var keys = [{ - pubkey: params.lookupTable, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: currentAuthorityDerivedKeyBasePubkey, isSigner: true, isWritable: false }]; - return new TransactionInstruction({ - programId: this.programId, + return new Transaction().add({ keys: keys, + programId: this.programId, data: data }); } + /** + * Generate a transaction to withdraw from a Vote account. + */ + }, { - key: "extendLookupTable", - value: function extendLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable; + key: "withdraw", + value: function withdraw(params) { + var votePubkey = params.votePubkey, + authorizedWithdrawerPubkey = params.authorizedWithdrawerPubkey, + lamports = params.lamports, + toPubkey = params.toPubkey; + var type = VOTE_INSTRUCTION_LAYOUTS.Withdraw; var data = encodeData(type, { - addresses: params.addresses.map(function (addr) { - return addr.toBytes(); - }) + lamports: lamports }); var keys = [{ - pubkey: params.lookupTable, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, + pubkey: toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false }]; + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction to withdraw safely from a Vote account. + * + * This function was created as a safeguard for vote accounts running validators, `safeWithdraw` + * checks that the withdraw amount will not exceed the specified balance while leaving enough left + * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the + * `withdraw` method directly. + */ - if (params.payer) { - keys.push({ - pubkey: params.payer, - isSigner: true, - isWritable: true - }, { - pubkey: SystemProgram.programId, - isSigner: false, - isWritable: false + }, { + key: "safeWithdraw", + value: function safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) { + if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) { + throw new Error('Withdraw will leave vote account with insuffcient funds.'); + } + + return VoteProgram.withdraw(params); + } + }]); + + return VoteProgram; +}(); + +VoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111'); +VoteProgram.space = 3731; +var VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111'); +/** + * @internal + */ + +var InfoString = type({ + name: string(), + website: optional(string()), + details: optional(string()), + keybaseUsername: optional(string()) +}); +/** + * ValidatorInfo class + */ + +var ValidatorInfo = /*#__PURE__*/function () { + /** + * validator public key + */ + + /** + * validator information + */ + + /** + * Construct a valid ValidatorInfo + * + * @param key validator public key + * @param info validator information + */ + function ValidatorInfo(key, info) { + _classCallCheck(this, ValidatorInfo); + + this.key = void 0; + this.info = void 0; + this.key = key; + this.info = info; + } + /** + * Deserialize ValidatorInfo from the config account data. Exactly two config + * keys are required in the data. + * + * @param buffer config account data + * @return null if info was not found + */ + + + _createClass(ValidatorInfo, null, [{ + key: "fromConfigData", + value: function fromConfigData(buffer) { + var byteArray = _toConsumableArray(buffer); + + var configKeyCount = decodeLength(byteArray); + if (configKeyCount !== 2) return null; + var configKeys = []; + + for (var i = 0; i < 2; i++) { + var _publicKey4 = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH)); + + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + var isSigner = byteArray.slice(0, 1)[0] === 1; + byteArray = byteArray.slice(1); + configKeys.push({ + publicKey: _publicKey4, + isSigner: isSigner }); } - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); - } - }, { - key: "deactivateLookupTable", - value: function deactivateLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable; - var data = encodeData(type); - var keys = [{ - pubkey: params.lookupTable, - isSigner: false, - isWritable: true - }, { - pubkey: params.authority, - isSigner: true, - isWritable: false - }]; - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); - } - }, { - key: "closeLookupTable", - value: function closeLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable; - var data = encodeData(type); - var keys = [{ - pubkey: params.lookupTable, - isSigner: false, - isWritable: true - }, { - pubkey: params.authority, - isSigner: true, - isWritable: false - }, { - pubkey: params.recipient, - isSigner: false, - isWritable: true - }]; - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); + if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) { + if (configKeys[1].isSigner) { + var rawInfo = rustString().decode(Buffer$1.from(byteArray)); + var info = JSON.parse(rawInfo); + _assert(info, InfoString); + return new ValidatorInfo(configKeys[1].publicKey, info); + } + } + + return null; } }]); - return AddressLookupTableProgram; + return ValidatorInfo; }(); -AddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111'); +var VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111'); /** - * Compute Budget Instruction class + * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88 + * + * @internal */ -var ComputeBudgetInstruction = /*#__PURE__*/function () { +var VoteAccountLayout = struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), u8('commission'), nu64$1(), // votes.length +seq$1(struct([nu64$1('slot'), u32('confirmationCount')]), offset$1(u32(), -8), 'votes'), u8('rootSlotValid'), nu64$1('rootSlot'), nu64$1(), // authorizedVoters.length +seq$1(struct([nu64$1('epoch'), publicKey('authorizedVoter')]), offset$1(u32(), -8), 'authorizedVoters'), struct([seq$1(struct([publicKey('authorizedPubkey'), nu64$1('epochOfLastAuthorizedSwitch'), nu64$1('targetEpoch')]), 32, 'buf'), nu64$1('idx'), u8('isEmpty')], 'priorVoters'), nu64$1(), // epochCredits.length +seq$1(struct([nu64$1('epoch'), nu64$1('credits'), nu64$1('prevCredits')]), offset$1(u32(), -8), 'epochCredits'), struct([nu64$1('slot'), nu64$1('timestamp')], 'lastTimestamp')]); +/** + * VoteAccount class + */ + +var VoteAccount = /*#__PURE__*/function () { /** * @internal */ - function ComputeBudgetInstruction() { - _classCallCheck(this, ComputeBudgetInstruction); + function VoteAccount(args) { + _classCallCheck(this, VoteAccount); + + this.nodePubkey = void 0; + this.authorizedWithdrawer = void 0; + this.commission = void 0; + this.rootSlot = void 0; + this.votes = void 0; + this.authorizedVoters = void 0; + this.priorVoters = void 0; + this.epochCredits = void 0; + this.lastTimestamp = void 0; + this.nodePubkey = args.nodePubkey; + this.authorizedWithdrawer = args.authorizedWithdrawer; + this.commission = args.commission; + this.rootSlot = args.rootSlot; + this.votes = args.votes; + this.authorizedVoters = args.authorizedVoters; + this.priorVoters = args.priorVoters; + this.epochCredits = args.epochCredits; + this.lastTimestamp = args.lastTimestamp; } /** - * Decode a compute budget instruction and retrieve the instruction type. + * Deserialize VoteAccount from the account data. + * + * @param buffer account data + * @return VoteAccount */ - _createClass(ComputeBudgetInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u8('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; - - for (var _i11 = 0, _Object$entries3 = Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS); _i11 < _Object$entries3.length; _i11++) { - var _Object$entries3$_i2 = _slicedToArray(_Object$entries3[_i11], 2), - ixType = _Object$entries3$_i2[0], - layout = _Object$entries3$_i2[1]; - - if (layout.index == typeIndex) { - type = ixType; - break; - } - } + _createClass(VoteAccount, null, [{ + key: "fromAccountData", + value: function fromAccountData(buffer) { + var versionOffset = 4; + var va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset); + var rootSlot = va.rootSlot; - if (!type) { - throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction'); + if (!va.rootSlotValid) { + rootSlot = null; } - return type; + return new VoteAccount({ + nodePubkey: new PublicKey(va.nodePubkey), + authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer), + commission: va.commission, + votes: va.votes, + rootSlot: rootSlot, + authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter), + priorVoters: getPriorVoters(va.priorVoters), + epochCredits: va.epochCredits, + lastTimestamp: va.lastTimestamp + }); } - /** - * Decode request units compute budget instruction and retrieve the instruction params. - */ - - }, { - key: "decodeRequestUnits", - value: function decodeRequestUnits(instruction) { - this.checkProgramId(instruction.programId); - - var _decodeData$14 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data), - units = _decodeData$14.units, - additionalFee = _decodeData$14.additionalFee; + }]); - return { - units: units, - additionalFee: additionalFee - }; - } - /** - * Decode request heap frame compute budget instruction and retrieve the instruction params. - */ + return VoteAccount; +}(); - }, { - key: "decodeRequestHeapFrame", - value: function decodeRequestHeapFrame(instruction) { - this.checkProgramId(instruction.programId); +function parseAuthorizedVoter(_ref46) { + var authorizedVoter = _ref46.authorizedVoter, + epoch = _ref46.epoch; + return { + epoch: epoch, + authorizedVoter: new PublicKey(authorizedVoter) + }; +} - var _decodeData$15 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data), - bytes = _decodeData$15.bytes; +function parsePriorVoters(_ref47) { + var authorizedPubkey = _ref47.authorizedPubkey, + epochOfLastAuthorizedSwitch = _ref47.epochOfLastAuthorizedSwitch, + targetEpoch = _ref47.targetEpoch; + return { + authorizedPubkey: new PublicKey(authorizedPubkey), + epochOfLastAuthorizedSwitch: epochOfLastAuthorizedSwitch, + targetEpoch: targetEpoch + }; +} - return { - bytes: bytes - }; - } - /** - * Decode set compute unit limit compute budget instruction and retrieve the instruction params. - */ +function getPriorVoters(_ref48) { + var buf = _ref48.buf, + idx = _ref48.idx, + isEmpty = _ref48.isEmpty; - }, { - key: "decodeSetComputeUnitLimit", - value: function decodeSetComputeUnitLimit(instruction) { - this.checkProgramId(instruction.programId); + if (isEmpty) { + return []; + } - var _decodeData$16 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data), - units = _decodeData$16.units; + return [].concat(_toConsumableArray(buf.slice(idx + 1).map(parsePriorVoters)), _toConsumableArray(buf.slice(0, idx).map(parsePriorVoters))); +} - return { - units: units - }; - } - /** - * Decode set compute unit price compute budget instruction and retrieve the instruction params. - */ +var endpoint = { + http: { + devnet: 'http://api.devnet.solana.com', + testnet: 'http://api.testnet.solana.com', + 'mainnet-beta': 'http://api.mainnet-beta.solana.com/' + }, + https: { + devnet: 'https://api.devnet.solana.com', + testnet: 'https://api.testnet.solana.com', + 'mainnet-beta': 'https://api.mainnet-beta.solana.com/' + } +}; +/** + * Retrieves the RPC API URL for the specified cluster + */ - }, { - key: "decodeSetComputeUnitPrice", - value: function decodeSetComputeUnitPrice(instruction) { - this.checkProgramId(instruction.programId); +function clusterApiUrl(cluster, tls) { + var key = tls === false ? 'http' : 'https'; - var _decodeData$17 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data), - microLamports = _decodeData$17.microLamports; + if (!cluster) { + return endpoint[key]['devnet']; + } - return { - microLamports: microLamports - }; - } - /** - * @internal - */ + var url = endpoint[key][cluster]; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(ComputeBudgetProgram.programId)) { - throw new Error('invalid instruction; programId is not ComputeBudgetProgram'); - } - } - }]); + if (!url) { + throw new Error("Unknown ".concat(key, " cluster: ").concat(cluster)); + } - return ComputeBudgetInstruction; -}(); + return url; +} /** - * An enumeration of valid ComputeBudgetInstructionType's + * Send and confirm a raw transaction + * + * If `commitment` option is not specified, defaults to 'max' commitment. + * + * @param {Connection} connection + * @param {Buffer} rawTransaction + * @param {TransactionConfirmationStrategy} confirmationStrategy + * @param {ConfirmOptions} [options] + * @returns {Promise} */ /** - * An enumeration of valid ComputeBudget InstructionType's - * @internal + * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy` + * is no longer supported and will be removed in a future version. */ +// eslint-disable-next-line no-redeclare +// eslint-disable-next-line no-redeclare -var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({ - RequestUnits: { - index: 0, - layout: struct([u8('instruction'), u32('units'), u32('additionalFee')]) - }, - RequestHeapFrame: { - index: 1, - layout: struct([u8('instruction'), u32('bytes')]) - }, - SetComputeUnitLimit: { - index: 2, - layout: struct([u8('instruction'), u32('units')]) - }, - SetComputeUnitPrice: { - index: 3, - layout: struct([u8('instruction'), u64('microLamports')]) - } -}); +function sendAndConfirmRawTransaction(_x161, _x162, _x163, _x164) { + return _sendAndConfirmRawTransaction.apply(this, arguments); +} /** - * Factory class for transaction instructions to interact with the Compute Budget program + * There are 1-billion lamports in one SOL */ -var ComputeBudgetProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function ComputeBudgetProgram() { - _classCallCheck(this, ComputeBudgetProgram); - } - /** - * Public key that identifies the Compute Budget program - */ - /** - * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice} - */ +function _sendAndConfirmRawTransaction() { + _sendAndConfirmRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee109(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) { + var confirmationStrategy, options, sendOptions, signature, commitment, confirmationPromise, status; + return _regeneratorRuntime().wrap(function _callee109$(_context109) { + while (1) switch (_context109.prev = _context109.next) { + case 0: + if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) { + confirmationStrategy = confirmationStrategyOrConfirmOptions; + options = maybeConfirmOptions; + } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) { + confirmationStrategy = confirmationStrategyOrConfirmOptions; + options = maybeConfirmOptions; + } else { + options = confirmationStrategyOrConfirmOptions; + } + sendOptions = options && { + skipPreflight: options.skipPreflight, + preflightCommitment: options.preflightCommitment || options.commitment, + minContextSlot: options.minContextSlot + }; + _context109.next = 4; + return connection.sendRawTransaction(rawTransaction, sendOptions); - _createClass(ComputeBudgetProgram, null, [{ - key: "requestUnits", - value: function requestUnits(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "requestHeapFrame", - value: function requestHeapFrame(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "setComputeUnitLimit", - value: function setComputeUnitLimit(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "setComputeUnitPrice", - value: function setComputeUnitPrice(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice; - var data = encodeData(type, { - microLamports: BigInt(params.microLamports) - }); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }]); + case 4: + signature = _context109.sent; + commitment = options && options.commitment; + confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment); + _context109.next = 9; + return confirmationPromise; - return ComputeBudgetProgram; -}(); + case 9: + status = _context109.sent.value; -ComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111'); -var PRIVATE_KEY_BYTES$1 = 64; -var PUBLIC_KEY_BYTES$1 = 32; -var SIGNATURE_BYTES = 64; -/** - * Params for creating an ed25519 instruction using a public key - */ + if (!status.err) { + _context109.next = 12; + break; + } -var ED25519_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u8('padding'), u16('signatureOffset'), u16('signatureInstructionIndex'), u16('publicKeyOffset'), u16('publicKeyInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u16('messageInstructionIndex')]); + throw new Error("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); -var Ed25519Program = /*#__PURE__*/function () { - /** - * @internal - */ - function Ed25519Program() { - _classCallCheck(this, Ed25519Program); - } - /** - * Public key that identifies the ed25519 program - */ + case 12: + return _context109.abrupt("return", signature); - /** - * Create an ed25519 instruction with a public key and signature. The - * public key must be a buffer that is 32 bytes long, and the signature - * must be a buffer of 64 bytes. - */ + case 13: + case "end": + return _context109.stop(); + } + }, _callee109); + })); + return _sendAndConfirmRawTransaction.apply(this, arguments); +} + +var LAMPORTS_PER_SOL = 1000000000; + +var index_browser_esm = /*#__PURE__*/Object.freeze({ + __proto__: null, + Account: Account, + AddressLookupTableAccount: AddressLookupTableAccount, + AddressLookupTableInstruction: AddressLookupTableInstruction, + AddressLookupTableProgram: AddressLookupTableProgram, + Authorized: Authorized, + BLOCKHASH_CACHE_TIMEOUT_MS: BLOCKHASH_CACHE_TIMEOUT_MS, + BPF_LOADER_DEPRECATED_PROGRAM_ID: BPF_LOADER_DEPRECATED_PROGRAM_ID, + BPF_LOADER_PROGRAM_ID: BPF_LOADER_PROGRAM_ID, + BpfLoader: BpfLoader, + COMPUTE_BUDGET_INSTRUCTION_LAYOUTS: COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, + ComputeBudgetInstruction: ComputeBudgetInstruction, + ComputeBudgetProgram: ComputeBudgetProgram, + Connection: Connection, + Ed25519Program: Ed25519Program, + Enum: Enum, + EpochSchedule: EpochSchedule, + FeeCalculatorLayout: FeeCalculatorLayout, + Keypair: Keypair, + LAMPORTS_PER_SOL: LAMPORTS_PER_SOL, + LOOKUP_TABLE_INSTRUCTION_LAYOUTS: LOOKUP_TABLE_INSTRUCTION_LAYOUTS, + Loader: Loader, + Lockup: Lockup, + MAX_SEED_LENGTH: MAX_SEED_LENGTH, + Message: Message, + MessageAccountKeys: MessageAccountKeys, + MessageV0: MessageV0, + NONCE_ACCOUNT_LENGTH: NONCE_ACCOUNT_LENGTH, + NonceAccount: NonceAccount, + PACKET_DATA_SIZE: PACKET_DATA_SIZE, + PUBLIC_KEY_LENGTH: PUBLIC_KEY_LENGTH, + PublicKey: PublicKey, + SIGNATURE_LENGTH_IN_BYTES: SIGNATURE_LENGTH_IN_BYTES, + SOLANA_SCHEMA: SOLANA_SCHEMA, + STAKE_CONFIG_ID: STAKE_CONFIG_ID, + STAKE_INSTRUCTION_LAYOUTS: STAKE_INSTRUCTION_LAYOUTS, + SYSTEM_INSTRUCTION_LAYOUTS: SYSTEM_INSTRUCTION_LAYOUTS, + SYSVAR_CLOCK_PUBKEY: SYSVAR_CLOCK_PUBKEY, + SYSVAR_EPOCH_SCHEDULE_PUBKEY: SYSVAR_EPOCH_SCHEDULE_PUBKEY, + SYSVAR_INSTRUCTIONS_PUBKEY: SYSVAR_INSTRUCTIONS_PUBKEY, + SYSVAR_RECENT_BLOCKHASHES_PUBKEY: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + SYSVAR_RENT_PUBKEY: SYSVAR_RENT_PUBKEY, + SYSVAR_REWARDS_PUBKEY: SYSVAR_REWARDS_PUBKEY, + SYSVAR_SLOT_HASHES_PUBKEY: SYSVAR_SLOT_HASHES_PUBKEY, + SYSVAR_SLOT_HISTORY_PUBKEY: SYSVAR_SLOT_HISTORY_PUBKEY, + SYSVAR_STAKE_HISTORY_PUBKEY: SYSVAR_STAKE_HISTORY_PUBKEY, + Secp256k1Program: Secp256k1Program, + SendTransactionError: SendTransactionError, + SolanaJSONRPCError: SolanaJSONRPCError, + SolanaJSONRPCErrorCode: SolanaJSONRPCErrorCode, + StakeAuthorizationLayout: StakeAuthorizationLayout, + StakeInstruction: StakeInstruction, + StakeProgram: StakeProgram, + Struct: Struct, + SystemInstruction: SystemInstruction, + SystemProgram: SystemProgram, + Transaction: Transaction, + TransactionExpiredBlockheightExceededError: TransactionExpiredBlockheightExceededError, + TransactionExpiredNonceInvalidError: TransactionExpiredNonceInvalidError, + TransactionExpiredTimeoutError: TransactionExpiredTimeoutError, + TransactionInstruction: TransactionInstruction, + TransactionMessage: TransactionMessage, + get TransactionStatus () { return TransactionStatus; }, + VALIDATOR_INFO_KEY: VALIDATOR_INFO_KEY, + VERSION_PREFIX_MASK: VERSION_PREFIX_MASK, + VOTE_PROGRAM_ID: VOTE_PROGRAM_ID, + ValidatorInfo: ValidatorInfo, + VersionedMessage: VersionedMessage, + VersionedTransaction: VersionedTransaction, + VoteAccount: VoteAccount, + VoteAuthorizationLayout: VoteAuthorizationLayout, + VoteInit: VoteInit, + VoteInstruction: VoteInstruction, + VoteProgram: VoteProgram, + clusterApiUrl: clusterApiUrl, + sendAndConfirmRawTransaction: sendAndConfirmRawTransaction, + sendAndConfirmTransaction: sendAndConfirmTransaction +}); +var require$$1 = /*@__PURE__*/getAugmentedNamespace(index_browser_esm); - _createClass(Ed25519Program, null, [{ - key: "createInstructionWithPublicKey", - value: function createInstructionWithPublicKey(params) { - var publicKey = params.publicKey, - message = params.message, - signature = params.signature, - instructionIndex = params.instructionIndex; - assert(publicKey.length === PUBLIC_KEY_BYTES$1, "Public Key must be ".concat(PUBLIC_KEY_BYTES$1, " bytes but received ").concat(publicKey.length, " bytes")); - assert(signature.length === SIGNATURE_BYTES, "Signature must be ".concat(SIGNATURE_BYTES, " bytes but received ").concat(signature.length, " bytes")); - var publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span; - var signatureOffset = publicKeyOffset + publicKey.length; - var messageDataOffset = signatureOffset + signature.length; - var numSignatures = 1; - var instructionData = Buffer$1.alloc(messageDataOffset + message.length); - var index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction. - : instructionIndex; - ED25519_INSTRUCTION_LAYOUT.encode({ - numSignatures: numSignatures, - padding: 0, - signatureOffset: signatureOffset, - signatureInstructionIndex: index, - publicKeyOffset: publicKeyOffset, - publicKeyInstructionIndex: index, - messageDataOffset: messageDataOffset, - messageDataSize: message.length, - messageInstructionIndex: index - }, instructionData); - instructionData.fill(publicKey, publicKeyOffset); - instructionData.fill(signature, signatureOffset); - instructionData.fill(message, messageDataOffset); - return new TransactionInstruction({ - keys: [], - programId: Ed25519Program.programId, - data: instructionData - }); - } - /** - * Create an ed25519 instruction with a private key. The private key - * must be a buffer that is 64 bytes long. - */ +var cjs = {}; - }, { - key: "createInstructionWithPrivateKey", - value: function createInstructionWithPrivateKey(params) { - var privateKey = params.privateKey, - message = params.message, - instructionIndex = params.instructionIndex; - assert(privateKey.length === PRIVATE_KEY_BYTES$1, "Private key must be ".concat(PRIVATE_KEY_BYTES$1, " bytes but received ").concat(privateKey.length, " bytes")); +Object.defineProperty(cjs, '__esModule', { + value: true +}); // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ + +var SolanaMobileWalletAdapterErrorCode = { + ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE', + ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL', + ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED', + ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED', + ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT', + ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND' +}; - try { - var keypair = Keypair.fromSecretKey(privateKey); +var SolanaMobileWalletAdapterError = /*#__PURE__*/function (_Error) { + _inherits(SolanaMobileWalletAdapterError, _Error); - var _publicKey2 = keypair.publicKey.toBytes(); + var _super = _createSuper(SolanaMobileWalletAdapterError); - var _signature5 = _sign(message, keypair.secretKey); + function SolanaMobileWalletAdapterError() { + var _this; - return this.createInstructionWithPublicKey({ - publicKey: _publicKey2, - message: message, - signature: _signature5, - instructionIndex: instructionIndex - }); - } catch (error) { - throw new Error("Error creating instruction; ".concat(error)); - } - } - }]); + _classCallCheck(this, SolanaMobileWalletAdapterError); - return Ed25519Program; -}(); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -Ed25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111'); // Supply a synchronous hashing algorithm to make this -// library interoperable with the synchronous APIs in web3.js. + var code = args[0], + message = args[1], + data = args[2]; + _this = _super.call(this, message); + _this.code = code; + _this.data = data; + _this.name = 'SolanaMobileWalletAdapterError'; + return _this; + } -utils.hmacSha256Sync = function (key) { - var h = hmac.create(sha256, key); + return _createClass(SolanaMobileWalletAdapterError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - for (var _len8 = arguments.length, msgs = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) { - msgs[_key8 - 1] = arguments[_key8]; - } - msgs.forEach(function (msg) { - return h.update(msg); - }); - return h.digest(); +var SolanaMobileWalletAdapterProtocolErrorCode = { + // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`. + ERROR_AUTHORIZATION_FAILED: -1, + ERROR_INVALID_PAYLOADS: -2, + ERROR_NOT_SIGNED: -3, + ERROR_NOT_SUBMITTED: -4, + ERROR_TOO_MANY_PAYLOADS: -5, + ERROR_ATTEST_ORIGIN_ANDROID: -100 }; -var ecdsaSign = function ecdsaSign(msgHash, privKey) { - return signSync(msgHash, privKey, { - der: false, - recovered: true - }); -}; +var SolanaMobileWalletAdapterProtocolError = /*#__PURE__*/function (_Error2) { + _inherits(SolanaMobileWalletAdapterProtocolError, _Error2); -utils.isValidPrivateKey; -var publicKeyCreate = getPublicKey$1; -var PRIVATE_KEY_BYTES = 32; -var ETHEREUM_ADDRESS_BYTES = 20; -var PUBLIC_KEY_BYTES = 64; -var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11; -/** - * Params for creating an secp256k1 instruction using a public key - */ + var _super2 = _createSuper(SolanaMobileWalletAdapterProtocolError); -var SECP256K1_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u16('signatureOffset'), u8('signatureInstructionIndex'), u16('ethAddressOffset'), u8('ethAddressInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u8('messageInstructionIndex'), blob$1(20, 'ethAddress'), blob$1(64, 'signature'), u8('recoveryId')]); + function SolanaMobileWalletAdapterProtocolError() { + var _this2; -var Secp256k1Program = /*#__PURE__*/function () { - /** - * @internal - */ - function Secp256k1Program() { - _classCallCheck(this, Secp256k1Program); - } - /** - * Public key that identifies the secp256k1 program - */ + _classCallCheck(this, SolanaMobileWalletAdapterProtocolError); - /** - * Construct an Ethereum address from a secp256k1 public key buffer. - * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer - */ + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var jsonRpcMessageId = args[0], + code = args[1], + message = args[2], + data = args[3]; + _this2 = _super2.call(this, message); + _this2.code = code; + _this2.data = data; + _this2.jsonRpcMessageId = jsonRpcMessageId; + _this2.name = 'SolanaMobileWalletAdapterProtocolError'; + return _this2; + } - _createClass(Secp256k1Program, null, [{ - key: "publicKeyToEthAddress", - value: function publicKeyToEthAddress(publicKey) { - assert(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes")); + return _createClass(SolanaMobileWalletAdapterProtocolError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + + +function __awaiter$1(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { - return Buffer$1.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES); - } catch (error) { - throw new Error("Error constructing Ethereum address: ".concat(error)); + step(generator.next(value)); + } catch (e) { + reject(e); } } - /** - * Create an secp256k1 instruction with a public key. The public key - * must be a buffer that is 64 bytes long. - */ - - }, { - key: "createInstructionWithPublicKey", - value: function createInstructionWithPublicKey(params) { - var publicKey = params.publicKey, - message = params.message, - signature = params.signature, - recoveryId = params.recoveryId, - instructionIndex = params.instructionIndex; - return Secp256k1Program.createInstructionWithEthAddress({ - ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey), - message: message, - signature: signature, - recoveryId: recoveryId, - instructionIndex: instructionIndex - }); - } - /** - * Create an secp256k1 instruction with an Ethereum address. The address - * must be a hex string or a buffer that is 20 bytes long. - */ - - }, { - key: "createInstructionWithEthAddress", - value: function createInstructionWithEthAddress(params) { - var rawAddress = params.ethAddress, - message = params.message, - signature = params.signature, - recoveryId = params.recoveryId, - _params$instructionIn = params.instructionIndex, - instructionIndex = _params$instructionIn === void 0 ? 0 : _params$instructionIn; - var ethAddress; - if (typeof rawAddress === 'string') { - if (rawAddress.startsWith('0x')) { - ethAddress = Buffer$1.from(rawAddress.substr(2), 'hex'); - } else { - ethAddress = Buffer$1.from(rawAddress, 'hex'); - } - } else { - ethAddress = rawAddress; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - - assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes")); - var dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE; - var ethAddressOffset = dataStart; - var signatureOffset = dataStart + ethAddress.length; - var messageDataOffset = signatureOffset + signature.length + 1; - var numSignatures = 1; - var instructionData = Buffer$1.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length); - SECP256K1_INSTRUCTION_LAYOUT.encode({ - numSignatures: numSignatures, - signatureOffset: signatureOffset, - signatureInstructionIndex: instructionIndex, - ethAddressOffset: ethAddressOffset, - ethAddressInstructionIndex: instructionIndex, - messageDataOffset: messageDataOffset, - messageDataSize: message.length, - messageInstructionIndex: instructionIndex, - signature: toBuffer(signature), - ethAddress: toBuffer(ethAddress), - recoveryId: recoveryId - }, instructionData); - instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span); - return new TransactionInstruction({ - keys: [], - programId: Secp256k1Program.programId, - data: instructionData - }); } - /** - * Create an secp256k1 instruction with a private key. The private key - * must be a buffer that is 32 bytes long. - */ - - }, { - key: "createInstructionWithPrivateKey", - value: function createInstructionWithPrivateKey(params) { - var pkey = params.privateKey, - message = params.message, - instructionIndex = params.instructionIndex; - assert(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes")); - try { - var privateKey = toBuffer(pkey); + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } - var _publicKey3 = publicKeyCreate(privateKey, false - /* isCompressed */ - ).slice(1); // throw away leading byte + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function createHelloReq(ecdhPublicKey, associationKeypairPrivateKey) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var publicKeyBuffer, signatureBuffer, response; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return crypto.subtle.exportKey('raw', ecdhPublicKey); - var messageHash = Buffer$1.from(keccak_256(toBuffer(message))); + case 2: + publicKeyBuffer = _context.sent; + _context.next = 5; + return crypto.subtle.sign({ + hash: 'SHA-256', + name: 'ECDSA' + }, associationKeypairPrivateKey, publicKeyBuffer); - var _ecdsaSign3 = ecdsaSign(messageHash, privateKey), - _ecdsaSign4 = _slicedToArray(_ecdsaSign3, 2), - _signature6 = _ecdsaSign4[0], - recoveryId = _ecdsaSign4[1]; + case 5: + signatureBuffer = _context.sent; + response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength); + response.set(new Uint8Array(publicKeyBuffer), 0); + response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength); + return _context.abrupt("return", response); - return this.createInstructionWithPublicKey({ - publicKey: _publicKey3, - message: message, - signature: _signature6, - recoveryId: recoveryId, - instructionIndex: instructionIndex - }); - } catch (error) { - throw new Error("Error creating instruction; ".concat(error)); + case 10: + case "end": + return _context.stop(); } - } - }]); - - return Secp256k1Program; -}(); + }, _callee); + })); +} -Secp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111'); -/** - * Address of the stake config account which configures the rate - * of stake warmup and cooldown as well as the slashing penalty. - */ +var SEQUENCE_NUMBER_BYTES = 4; -var STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111'); -/** - * Stake account authority info - */ +function createSequenceNumberVector(sequenceNumber) { + if (sequenceNumber >= 4294967296) { + throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.'); + } -var Authorized = /*#__PURE__*/_createClass( -/** stake authority */ + var byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES); + var view = new DataView(byteArray); + view.setUint32(0, sequenceNumber, + /* littleEndian */ + false); + return new Uint8Array(byteArray); +} -/** withdraw authority */ +function generateAssociationKeypair() { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return crypto.subtle.generateKey({ + name: 'ECDSA', + namedCurve: 'P-256' + }, false + /* extractable */ + , ['sign'] + /* keyUsages */ + ); -/** - * Create a new Authorized object - * @param staker the stake authority - * @param withdrawer the withdraw authority - */ -function Authorized(staker, withdrawer) { - _classCallCheck(this, Authorized); + case 2: + return _context2.abrupt("return", _context2.sent); - this.staker = void 0; - this.withdrawer = void 0; - this.staker = staker; - this.withdrawer = withdrawer; -}); -/** - * Stake account lockup info - */ + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); +} +function generateECDHKeypair() { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return crypto.subtle.generateKey({ + name: 'ECDH', + namedCurve: 'P-256' + }, false + /* extractable */ + , ['deriveKey', 'deriveBits'] + /* keyUsages */ + ); -var Lockup = /*#__PURE__*/_createClass( -/** Unix timestamp of lockup expiration */ + case 2: + return _context3.abrupt("return", _context3.sent); -/** Epoch of lockup expiration */ + case 3: + case "end": + return _context3.stop(); + } + }, _callee3); + })); +} -/** Lockup custodian authority */ +var INITIALIZATION_VECTOR_BYTES = 12; -/** - * Create a new Lockup object - */ -function Lockup(unixTimestamp, epoch, custodian) { - _classCallCheck(this, Lockup); +function encryptJsonRpcMessage(jsonRpcMessage, sharedSecret) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var plaintext, sequenceNumberVector, initializationVector, ciphertext, response; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + plaintext = JSON.stringify(jsonRpcMessage); + sequenceNumberVector = createSequenceNumberVector(jsonRpcMessage.id); + initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES); + crypto.getRandomValues(initializationVector); + _context4.next = 6; + return crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, new TextEncoder().encode(plaintext)); + + case 6: + ciphertext = _context4.sent; + response = new Uint8Array(sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength); + response.set(new Uint8Array(sequenceNumberVector), 0); + response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength); + response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength); + return _context4.abrupt("return", response); - this.unixTimestamp = void 0; - this.epoch = void 0; - this.custodian = void 0; - this.unixTimestamp = unixTimestamp; - this.epoch = epoch; - this.custodian = custodian; + case 12: + case "end": + return _context4.stop(); + } + }, _callee4); + })); } -/** - * Default, inactive Lockup value - */ -); -Lockup["default"] = new Lockup(0, 0, PublicKey["default"]); -/** - * Stake Instruction class - */ +function decryptJsonRpcMessage(message, sharedSecret) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { + var sequenceNumberVector, initializationVector, ciphertext, plaintextBuffer, plaintext, jsonRpcMessage; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES); + initializationVector = message.slice(SEQUENCE_NUMBER_BYTES, SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES); + ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES); + _context5.next = 5; + return crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, ciphertext); -var StakeInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function StakeInstruction() { - _classCallCheck(this, StakeInstruction); - } - /** - * Decode a stake instruction and retrieve the instruction type. - */ + case 5: + plaintextBuffer = _context5.sent; + plaintext = getUtf8Decoder().decode(plaintextBuffer); + jsonRpcMessage = JSON.parse(plaintext); + if (!Object.hasOwnProperty.call(jsonRpcMessage, 'error')) { + _context5.next = 10; + break; + } - _createClass(StakeInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; + throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id, jsonRpcMessage.error.code, jsonRpcMessage.error.message); - for (var _i12 = 0, _Object$entries4 = Object.entries(STAKE_INSTRUCTION_LAYOUTS); _i12 < _Object$entries4.length; _i12++) { - var _Object$entries4$_i2 = _slicedToArray(_Object$entries4[_i12], 2), - ixType = _Object$entries4$_i2[0], - layout = _Object$entries4$_i2[1]; + case 10: + return _context5.abrupt("return", jsonRpcMessage); - if (layout.index == typeIndex) { - type = ixType; - break; - } + case 11: + case "end": + return _context5.stop(); } + }, _callee5); + })); +} - if (!type) { - throw new Error('Instruction type incorrect; not a StakeInstruction'); - } +function getAlgorithmParams(sequenceNumber, initializationVector) { + return { + additionalData: sequenceNumber, + iv: initializationVector, + name: 'AES-GCM', + tagLength: 128 // 16 byte tag => 128 bits - return type; - } - /** - * Decode a initialize stake instruction and retrieve the instruction params. - */ + }; +} - }, { - key: "decodeInitialize", - value: function decodeInitialize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); +var _utf8Decoder; - var _decodeData$18 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data), - authorized = _decodeData$18.authorized, - lockup = _decodeData$18.lockup; +function getUtf8Decoder() { + if (_utf8Decoder === undefined) { + _utf8Decoder = new TextDecoder('utf-8'); + } - return { - stakePubkey: instruction.keys[0].pubkey, - authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)), - lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian)) - }; - } - /** - * Decode a delegate stake instruction and retrieve the instruction params. - */ + return _utf8Decoder; +} - }, { - key: "decodeDelegate", - value: function decodeDelegate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 6); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - votePubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[5].pubkey - }; - } - /** - * Decode an authorize stake instruction and retrieve the instruction params. - */ +function parseHelloRsp(payloadBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint. +associationPublicKey, ecdhPrivateKey) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() { + var _yield$Promise$all, _yield$Promise$all2, associationPublicKeyBuffer, walletPublicKey, sharedSecret, ecdhSecretKey, aesKeyMaterialVal; - }, { - key: "decodeAuthorize", - value: function decodeAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return Promise.all([crypto.subtle.exportKey('raw', associationPublicKey), crypto.subtle.importKey('raw', payloadBuffer, { + name: 'ECDH', + namedCurve: 'P-256' + }, false + /* extractable */ + , [] + /* keyUsages */ + )]); - var _decodeData$19 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), - newAuthorized = _decodeData$19.newAuthorized, - stakeAuthorizationType = _decodeData$19.stakeAuthorizationType; + case 2: + _yield$Promise$all = _context6.sent; + _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2); + associationPublicKeyBuffer = _yield$Promise$all2[0]; + walletPublicKey = _yield$Promise$all2[1]; + _context6.next = 8; + return crypto.subtle.deriveBits({ + name: 'ECDH', + "public": walletPublicKey + }, ecdhPrivateKey, 256); + + case 8: + sharedSecret = _context6.sent; + _context6.next = 11; + return crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false + /* extractable */ + , ['deriveKey'] + /* keyUsages */ + ); + + case 11: + ecdhSecretKey = _context6.sent; + _context6.next = 14; + return crypto.subtle.deriveKey({ + name: 'HKDF', + hash: 'SHA-256', + salt: new Uint8Array(associationPublicKeyBuffer), + info: new Uint8Array() + }, ecdhSecretKey, { + name: 'AES-GCM', + length: 128 + }, false + /* extractable */ + , ['encrypt', 'decrypt']); - var o = { - stakePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - newAuthorizedPubkey: new PublicKey(newAuthorized), - stakeAuthorizationType: { - index: stakeAuthorizationType - } - }; + case 14: + aesKeyMaterialVal = _context6.sent; + return _context6.abrupt("return", aesKeyMaterialVal); - if (instruction.keys.length > 3) { - o.custodianPubkey = instruction.keys[3].pubkey; + case 16: + case "end": + return _context6.stop(); } + }, _callee6); + })); +} - return o; - } - /** - * Decode an authorize-with-seed stake instruction and retrieve the instruction params. - */ +function getRandomAssociationPort() { + return assertAssociationPort(49152 + Math.floor(Math.random() * (65535 - 49152 + 1))); +} - }, { - key: "decodeAuthorizeWithSeed", - value: function decodeAuthorizeWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); +function assertAssociationPort(port) { + if (port < 49152 || port > 65535) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE, "Association port number must be between 49152 and 65535. ".concat(port, " given."), { + port: port + }); + } - var _decodeData$20 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), - newAuthorized = _decodeData$20.newAuthorized, - stakeAuthorizationType = _decodeData$20.stakeAuthorizationType, - authoritySeed = _decodeData$20.authoritySeed, - authorityOwner = _decodeData$20.authorityOwner; + return port; +} // https://stackoverflow.com/a/9458996/802047 - var o = { - stakePubkey: instruction.keys[0].pubkey, - authorityBase: instruction.keys[1].pubkey, - authoritySeed: authoritySeed, - authorityOwner: new PublicKey(authorityOwner), - newAuthorizedPubkey: new PublicKey(newAuthorized), - stakeAuthorizationType: { - index: stakeAuthorizationType - } - }; - if (instruction.keys.length > 3) { - o.custodianPubkey = instruction.keys[3].pubkey; - } +function arrayBufferToBase64String(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var len = bytes.byteLength; - return o; - } - /** - * Decode a split stake instruction and retrieve the instruction params. - */ + for (var ii = 0; ii < len; ii++) { + binary += String.fromCharCode(bytes[ii]); + } - }, { - key: "decodeSplit", - value: function decodeSplit(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + return window.btoa(binary); +} - var _decodeData$21 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data), - lamports = _decodeData$21.lamports; +function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString) { + return unsafeBase64EncodedString.replace(/[/+=]/g, function (m) { + return { + '/': '_', + '+': '-', + '=': '.' + }[m]; + }); +} - return { - stakePubkey: instruction.keys[0].pubkey, - splitStakePubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - lamports: lamports - }; - } - /** - * Decode a merge stake instruction and retrieve the instruction params. - */ +var INTENT_NAME = 'solana-wallet'; - }, { - key: "decodeMerge", - value: function decodeMerge(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - sourceStakePubKey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey - }; - } - /** - * Decode a withdraw stake instruction and retrieve the instruction params. - */ +function getPathParts(pathString) { + return pathString // Strip leading and trailing slashes + .replace(/(^\/+|\/+$)/g, '') // Return an array of directories + .split('/'); +} - }, { - key: "decodeWithdraw", - value: function decodeWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 5); +function getIntentURL(methodPathname, intentUrlBase) { + var baseUrl = null; + + if (intentUrlBase) { + try { + baseUrl = new URL(intentUrlBase); + } catch (_a) {} // eslint-disable-line no-empty + + + if ((baseUrl === null || baseUrl === void 0 ? void 0 : baseUrl.protocol) !== 'https:') { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs'); + } + } - var _decodeData$22 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), - lamports = _decodeData$22.lamports; + baseUrl || (baseUrl = new URL("".concat(INTENT_NAME, ":/"))); + var pathname = methodPathname.startsWith('/') ? // Method is an absolute path. Replace it wholesale. + methodPathname : // Method is a relative path. Merge it with the existing one. + [].concat(_toConsumableArray(getPathParts(baseUrl.pathname)), _toConsumableArray(getPathParts(methodPathname))).join('/'); + return new URL(pathname, baseUrl); +} - var o = { - stakePubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey, - lamports: lamports - }; +function getAssociateAndroidIntentURL(associationPublicKey, putativePort, associationURLBase) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() { + var associationPort, exportedKey, encodedKey, url; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + associationPort = assertAssociationPort(putativePort); + _context7.next = 3; + return crypto.subtle.exportKey('raw', associationPublicKey); - if (instruction.keys.length > 5) { - o.custodianPubkey = instruction.keys[5].pubkey; + case 3: + exportedKey = _context7.sent; + encodedKey = arrayBufferToBase64String(exportedKey); + url = getIntentURL('v1/associate/local', associationURLBase); + url.searchParams.set('association', getStringWithURLUnsafeCharactersReplaced(encodedKey)); + url.searchParams.set('port', "".concat(associationPort)); + return _context7.abrupt("return", url); + + case 9: + case "end": + return _context7.stop(); } + }, _callee7); + })); +} // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - return o; - } - /** - * Decode a deactivate stake instruction and retrieve the instruction params. - */ - }, { - key: "decodeDeactivate", - value: function decodeDeactivate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey - }; - } - /** - * @internal - */ +var Browser = { + Firefox: 0, + Other: 1 +}; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(StakeProgram.programId)) { - throw new Error('invalid instruction; programId is not StakeProgram'); - } +function getBrowser() { + return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other; +} + +function getDetectionPromise() { + // Chrome and others silently fail if a custom protocol is not supported. + // For these, we wait to see if the browser is navigated away from in + // a reasonable amount of time (ie. the native wallet opened). + return new Promise(function (resolve, reject) { + function cleanup() { + clearTimeout(timeoutId); + window.removeEventListener('blur', handleBlur); } - /** - * @internal - */ - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } + function handleBlur() { + cleanup(); + resolve(); } - }]); - return StakeInstruction; -}(); -/** - * An enumeration of valid StakeInstructionType's - */ + window.addEventListener('blur', handleBlur); + var timeoutId = setTimeout(function () { + cleanup(); + reject(); + }, 2000); + }); +} -/** - * An enumeration of valid stake InstructionType's - * @internal - */ +var _frame = null; +function launchUrlThroughHiddenFrame(url) { + if (_frame == null) { + _frame = document.createElement('iframe'); + _frame.style.display = 'none'; + document.body.appendChild(_frame); + } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({ - Initialize: { - index: 0, - layout: struct([u32('instruction'), authorized(), lockup()]) - }, - Authorize: { - index: 1, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType')]) - }, - Delegate: { - index: 2, - layout: struct([u32('instruction')]) - }, - Split: { - index: 3, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - Withdraw: { - index: 4, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - Deactivate: { - index: 5, - layout: struct([u32('instruction')]) - }, - Merge: { - index: 7, - layout: struct([u32('instruction')]) - }, - AuthorizeWithSeed: { - index: 8, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')]) - } -}); -/** - * Stake authorization type - */ -/** - * An enumeration of valid StakeAuthorizationLayout's - */ + _frame.contentWindow.location.href = url.toString(); +} -var StakeAuthorizationLayout = Object.freeze({ - Staker: { - index: 0 - }, - Withdrawer: { - index: 1 - } -}); -/** - * Factory class for transactions to interact with the Stake program - */ +function startSession(associationPublicKey, associationURLBase) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { + var randomAssociationPort, associationUrl, browser, detectionPromise; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + randomAssociationPort = getRandomAssociationPort(); + _context8.next = 3; + return getAssociateAndroidIntentURL(associationPublicKey, randomAssociationPort, associationURLBase); -var StakeProgram = /*#__PURE__*/function () { + case 3: + associationUrl = _context8.sent; + + if (!(associationUrl.protocol === 'https:')) { + _context8.next = 8; + break; + } + + // The association URL is an Android 'App Link' or iOS 'Universal Link'. + // These are regular web URLs that are designed to launch an app if it + // is installed or load the actual target webpage if not. + window.location.assign(associationUrl); + _context8.next = 26; + break; + + case 8: + _context8.prev = 8; + browser = getBrowser(); + _context8.t0 = browser; + _context8.next = _context8.t0 === Browser.Firefox ? 13 : _context8.t0 === Browser.Other ? 15 : 20; + break; + + case 13: + // If a custom protocol is not supported in Firefox, it throws. + launchUrlThroughHiddenFrame(associationUrl); // If we reached this line, it's supported. + + return _context8.abrupt("break", 21); + + case 15: + detectionPromise = getDetectionPromise(); + window.location.assign(associationUrl); + _context8.next = 19; + return detectionPromise; + + case 19: + return _context8.abrupt("break", 21); + + case 20: + + case 21: + _context8.next = 26; + break; + + case 23: + _context8.prev = 23; + _context8.t1 = _context8["catch"](8); + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND, 'Found no installed wallet that supports the mobile wallet protocol.'); + + case 26: + return _context8.abrupt("return", randomAssociationPort); + + case 27: + case "end": + return _context8.stop(); + } + }, _callee8, null, [[8, 23]]); + })); +} + +var WEBSOCKET_CONNECTION_CONFIG = { /** - * @internal + * 300 milliseconds is a generally accepted threshold for what someone + * would consider an acceptable response time for a user interface + * after having performed a low-attention tapping task. We set the initial + * interval at which we wait for the wallet to set up the websocket at + * half this, as per the Nyquist frequency, with a progressive backoff + * sequence from there. The total wait time is 30s, which allows for the + * user to be presented with a disambiguation dialog, select a wallet, and + * for the wallet app to subsequently start. */ - function StakeProgram() { - _classCallCheck(this, StakeProgram); + retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000], + timeoutMs: 30000 +}; +var WEBSOCKET_PROTOCOL = 'com.solana.mobilewalletadapter.v1'; + +function assertSecureContext() { + if (typeof window === 'undefined' || window.isSecureContext !== true) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED, 'The mobile wallet adapter protocol must be used in a secure context (`https`).'); } - /** - * Public key that identifies the Stake program - */ +} - /** - * Generate an Initialize instruction to add to a Stake Create transaction - */ +function assertSecureEndpointSpecificURI(walletUriBase) { + var url; + try { + url = new URL(walletUriBase); + } catch (_a) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Invalid base URL supplied by wallet'); + } - _createClass(StakeProgram, null, [{ - key: "initialize", - value: function initialize(params) { - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - maybeLockup = params.lockup; - var lockup = maybeLockup || Lockup["default"]; - var type = STAKE_INSTRUCTION_LAYOUTS.Initialize; - var data = encodeData(type, { - authorized: { - staker: toBuffer(authorized.staker.toBuffer()), - withdrawer: toBuffer(authorized.withdrawer.toBuffer()) - }, - lockup: { - unixTimestamp: lockup.unixTimestamp, - epoch: lockup.epoch, - custodian: toBuffer(lockup.custodian.toBuffer()) - } - }); - var instructionData = { - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a Transaction that creates a new Stake account at - * an address generated with `from`, a seed, and the Stake programId - */ + if (url.protocol !== 'https:') { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs'); + } +} - }, { - key: "createAccountWithSeed", - value: function createAccountWithSeed(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccountWithSeed({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.stakePubkey, - basePubkey: params.basePubkey, - seed: params.seed, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - lockup = params.lockup; - return transaction.add(this.initialize({ - stakePubkey: stakePubkey, - authorized: authorized, - lockup: lockup - })); - } - /** - * Generate a Transaction that creates a new Stake account - */ +function getSequenceNumberFromByteArray(byteArray) { + var view = new DataView(byteArray); + return view.getUint32(0, + /* littleEndian */ + false); +} - }, { - key: "createAccount", - value: function createAccount(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.stakePubkey, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - lockup = params.lockup; - return transaction.add(this.initialize({ - stakePubkey: stakePubkey, - authorized: authorized, - lockup: lockup - })); - } - /** - * Generate a Transaction that delegates Stake tokens to a validator - * Vote PublicKey. This transaction can also be used to redelegate Stake - * to a new validator Vote PublicKey. - */ +function transact$2(callback, config) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { + var _this3 = this; - }, { - key: "delegate", - value: function delegate(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - votePubkey = params.votePubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Delegate; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: votePubkey, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: STAKE_CONFIG_ID, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that authorizes a new PublicKey as Staker - * or Withdrawer on the Stake account. - */ + var associationKeypair, sessionPort, websocketURL, connectionStartTime, getNextRetryDelayMs, nextJsonRpcMessageId, lastKnownInboundSequenceNumber, state; + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + assertSecureContext(); + _context13.next = 3; + return generateAssociationKeypair(); - }, { - key: "authorize", - value: function authorize(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - newAuthorizedPubkey = params.newAuthorizedPubkey, - stakeAuthorizationType = params.stakeAuthorizationType, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Authorize; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - stakeAuthorizationType: stakeAuthorizationType.index - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; + case 3: + associationKeypair = _context13.sent; + _context13.next = 6; + return startSession(associationKeypair.publicKey, config === null || config === void 0 ? void 0 : config.baseUri); - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + case 6: + sessionPort = _context13.sent; + websocketURL = "ws://localhost:".concat(sessionPort, "/solana-wallet"); - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that authorizes a new PublicKey as Staker - * or Withdrawer on the Stake account. - */ + getNextRetryDelayMs = function () { + var schedule = _toConsumableArray(WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs); - }, { - key: "authorizeWithSeed", - value: function authorizeWithSeed(params) { - var stakePubkey = params.stakePubkey, - authorityBase = params.authorityBase, - authoritySeed = params.authoritySeed, - authorityOwner = params.authorityOwner, - newAuthorizedPubkey = params.newAuthorizedPubkey, - stakeAuthorizationType = params.stakeAuthorizationType, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - stakeAuthorizationType: stakeAuthorizationType.index, - authoritySeed: authoritySeed, - authorityOwner: toBuffer(authorityOwner.toBuffer()) - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorityBase, - isSigner: true, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }]; + return function () { + return schedule.length > 1 ? schedule.shift() : schedule[0]; + }; + }(); - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + nextJsonRpcMessageId = 1; + lastKnownInboundSequenceNumber = 0; + state = { + __type: 'disconnected' + }; + return _context13.abrupt("return", new Promise(function (resolve, reject) { + var socket; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * @internal - */ + var jsonRpcResponsePromises = {}; - }, { - key: "splitInstruction", - value: function splitInstruction(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - splitStakePubkey = params.splitStakePubkey, - lamports = params.lamports; - var type = STAKE_INSTRUCTION_LAYOUTS.Split; - var data = encodeData(type, { - lamports: lamports - }); - return new TransactionInstruction({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: splitStakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that splits Stake tokens into another stake account - */ + var handleOpen = function handleOpen() { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() { + var _state, associationKeypair, ecdhKeypair; - }, { - key: "split", - value: function split(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.authorizedPubkey, - newAccountPubkey: params.splitStakePubkey, - lamports: 0, - space: this.space, - programId: this.programId - })); - return transaction.add(this.splitInstruction(params)); - } - /** - * Generate a Transaction that splits Stake tokens into another account - * derived from a base public key and seed - */ + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (!(state.__type !== 'connecting')) { + _context9.next = 3; + break; + } - }, { - key: "splitWithSeed", - value: function splitWithSeed(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - splitStakePubkey = params.splitStakePubkey, - basePubkey = params.basePubkey, - seed = params.seed, - lamports = params.lamports; - var transaction = new Transaction(); - transaction.add(SystemProgram.allocate({ - accountPubkey: splitStakePubkey, - basePubkey: basePubkey, - seed: seed, - space: this.space, - programId: this.programId - })); - return transaction.add(this.splitInstruction({ - stakePubkey: stakePubkey, - authorizedPubkey: authorizedPubkey, - splitStakePubkey: splitStakePubkey, - lamports: lamports - })); - } - /** - * Generate a Transaction that merges Stake accounts. - */ + console.warn('Expected adapter state to be `connecting` at the moment the websocket opens. ' + "Got `".concat(state.__type, "`.")); + return _context9.abrupt("return"); - }, { - key: "merge", - value: function merge(params) { - var stakePubkey = params.stakePubkey, - sourceStakePubKey = params.sourceStakePubKey, - authorizedPubkey = params.authorizedPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Merge; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: sourceStakePubKey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that withdraws deactivated Stake tokens. - */ + case 3: + _state = state, associationKeypair = _state.associationKeypair; + socket.removeEventListener('open', handleOpen); + _context9.next = 7; + return generateECDHKeypair(); + + case 7: + ecdhKeypair = _context9.sent; + _context9.t0 = socket; + _context9.next = 11; + return createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey); + + case 11: + _context9.t1 = _context9.sent; + + _context9.t0.send.call(_context9.t0, _context9.t1); + + state = { + __type: 'hello_req_sent', + associationPublicKey: associationKeypair.publicKey, + ecdhPrivateKey: ecdhKeypair.privateKey + }; + + case 14: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + }; - }, { - key: "withdraw", - value: function withdraw(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - toPubkey = params.toPubkey, - lamports = params.lamports, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Withdraw; - var data = encodeData(type, { - lamports: lamports - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; + var handleClose = function handleClose(evt) { + if (evt.wasClean) { + state = { + __type: 'disconnected' + }; + } else { + reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, "The wallet session dropped unexpectedly (".concat(evt.code, ": ").concat(evt.reason, ")."), { + closeEvent: evt + })); + } - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + disposeSocket(); + }; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that deactivates Stake tokens. - */ + var handleError = function handleError(_evt) { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + disposeSocket(); - }, { - key: "deactivate", - value: function deactivate(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Deactivate; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - }]); + if (!(Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs)) { + _context10.next = 5; + break; + } - return StakeProgram; -}(); + reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, "Failed to connect to the wallet websocket on port ".concat(sessionPort, "."))); + _context10.next = 8; + break; -StakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111'); -StakeProgram.space = 200; -/** - * Vote account info - */ + case 5: + _context10.next = 7; + return new Promise(function (resolve) { + var retryDelayMs = getNextRetryDelayMs(); + retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs); + }); -var VoteInit = /*#__PURE__*/_createClass( -/** [0, 100] */ -function VoteInit(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) { - _classCallCheck(this, VoteInit); + case 7: + attemptSocketConnection(); - this.nodePubkey = void 0; - this.authorizedVoter = void 0; - this.authorizedWithdrawer = void 0; - this.commission = void 0; - this.nodePubkey = nodePubkey; - this.authorizedVoter = authorizedVoter; - this.authorizedWithdrawer = authorizedWithdrawer; - this.commission = commission; -}); -/** - * Create vote account transaction params - */ + case 8: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + }; -/** - * Vote Instruction class - */ + var handleMessage = function handleMessage(evt) { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() { + var responseBuffer, sequenceNumberVector, sequenceNumber, jsonRpcMessage, responsePromise, _responsePromise, sharedSecret, wallet; + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return evt.data.arrayBuffer(); -var VoteInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteInstruction() { - _classCallCheck(this, VoteInstruction); - } - /** - * Decode a vote instruction and retrieve the instruction type. - */ + case 2: + responseBuffer = _context12.sent; + _context12.t0 = state.__type; + _context12.next = _context12.t0 === 'connected' ? 6 : _context12.t0 === 'hello_req_sent' ? 30 : 51; + break; + case 6: + _context12.prev = 6; + sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES); + sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector); - _createClass(VoteInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; + if (!(sequenceNumber !== lastKnownInboundSequenceNumber + 1)) { + _context12.next = 11; + break; + } - for (var _i13 = 0, _Object$entries5 = Object.entries(VOTE_INSTRUCTION_LAYOUTS); _i13 < _Object$entries5.length; _i13++) { - var _Object$entries5$_i2 = _slicedToArray(_Object$entries5[_i13], 2), - ixType = _Object$entries5$_i2[0], - layout = _Object$entries5$_i2[1]; + throw new Error('Encrypted message has invalid sequence number'); - if (layout.index == typeIndex) { - type = ixType; - break; - } - } + case 11: + lastKnownInboundSequenceNumber = sequenceNumber; + _context12.next = 14; + return decryptJsonRpcMessage(responseBuffer, state.sharedSecret); - if (!type) { - throw new Error('Instruction type incorrect; not a VoteInstruction'); - } + case 14: + jsonRpcMessage = _context12.sent; + responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id]; + delete jsonRpcResponsePromises[jsonRpcMessage.id]; + responsePromise.resolve(jsonRpcMessage.result); + _context12.next = 29; + break; - return type; - } - /** - * Decode an initialize vote instruction and retrieve the instruction params. - */ + case 20: + _context12.prev = 20; + _context12.t1 = _context12["catch"](6); - }, { - key: "decodeInitializeAccount", - value: function decodeInitializeAccount(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 4); + if (!(_context12.t1 instanceof SolanaMobileWalletAdapterProtocolError)) { + _context12.next = 28; + break; + } - var _decodeData$23 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data), - voteInit = _decodeData$23.voteInit; + _responsePromise = jsonRpcResponsePromises[_context12.t1.jsonRpcMessageId]; + delete jsonRpcResponsePromises[_context12.t1.jsonRpcMessageId]; - return { - votePubkey: instruction.keys[0].pubkey, - nodePubkey: instruction.keys[3].pubkey, - voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission) - }; - } - /** - * Decode an authorize instruction and retrieve the instruction params. - */ + _responsePromise.reject(_context12.t1); - }, { - key: "decodeAuthorize", - value: function decodeAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + _context12.next = 29; + break; - var _decodeData$24 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), - newAuthorized = _decodeData$24.newAuthorized, - voteAuthorizationType = _decodeData$24.voteAuthorizationType; + case 28: + throw _context12.t1; + + case 29: + return _context12.abrupt("break", 51); + + case 30: + _context12.next = 32; + return parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey); + + case 32: + sharedSecret = _context12.sent; + state = { + __type: 'connected', + sharedSecret: sharedSecret + }; + wallet = new Proxy({}, { + get: function get(target, p) { + if (target[p] == null) { + var method = p.toString().replace(/[A-Z]/g, function (letter) { + return "_".concat(letter.toLowerCase()); + }).toLowerCase(); + + target[p] = function (params) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() { + var id; + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + id = nextJsonRpcMessageId++; + _context11.t0 = socket; + _context11.next = 4; + return encryptJsonRpcMessage({ + id: id, + jsonrpc: '2.0', + method: method, + params: params !== null && params !== void 0 ? params : {} + }, sharedSecret); + + case 4: + _context11.t1 = _context11.sent; + + _context11.t0.send.call(_context11.t0, _context11.t1); + + return _context11.abrupt("return", new Promise(function (_resolve, reject) { + jsonRpcResponsePromises[id] = { + resolve: function resolve(result) { + switch (p) { + case 'authorize': + case 'reauthorize': + { + var wallet_uri_base = result.wallet_uri_base; + + if (wallet_uri_base != null) { + try { + assertSecureEndpointSpecificURI(wallet_uri_base); + } catch (e) { + reject(e); + return; + } + } + + break; + } + } + + _resolve(result); + }, + reject: reject + }; + })); + + case 7: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + }; + } + + return target[p]; + }, + defineProperty: function defineProperty() { + return false; + }, + deleteProperty: function deleteProperty() { + return false; + } + }); + _context12.prev = 35; + _context12.t2 = resolve; + _context12.next = 39; + return callback(wallet); + + case 39: + _context12.t3 = _context12.sent; + (0, _context12.t2)(_context12.t3); + _context12.next = 46; + break; - return { - votePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - newAuthorizedPubkey: new PublicKey(newAuthorized), - voteAuthorizationType: { - index: voteAuthorizationType - } - }; - } - /** - * Decode an authorize instruction and retrieve the instruction params. - */ + case 43: + _context12.prev = 43; + _context12.t4 = _context12["catch"](35); + reject(_context12.t4); - }, { - key: "decodeAuthorizeWithSeed", - value: function decodeAuthorizeWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 46: + _context12.prev = 46; + disposeSocket(); + socket.close(); + return _context12.finish(46); - var _decodeData$25 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), - _decodeData$25$voteAu = _decodeData$25.voteAuthorizeWithSeedArgs, - currentAuthorityDerivedKeyOwnerPubkey = _decodeData$25$voteAu.currentAuthorityDerivedKeyOwnerPubkey, - currentAuthorityDerivedKeySeed = _decodeData$25$voteAu.currentAuthorityDerivedKeySeed, - newAuthorized = _decodeData$25$voteAu.newAuthorized, - voteAuthorizationType = _decodeData$25$voteAu.voteAuthorizationType; + case 50: + return _context12.abrupt("break", 51); - return { - currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey, - currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey), - currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, - newAuthorizedPubkey: new PublicKey(newAuthorized), - voteAuthorizationType: { - index: voteAuthorizationType - }, - votePubkey: instruction.keys[0].pubkey - }; - } - /** - * Decode a withdraw instruction and retrieve the instruction params. - */ + case 51: + case "end": + return _context12.stop(); + } + }, _callee12, null, [[6, 20], [35, 43, 46, 50]]); + })); + }; - }, { - key: "decodeWithdraw", - value: function decodeWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + var disposeSocket; + var retryWaitTimeoutId; - var _decodeData$26 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), - lamports = _decodeData$26.lamports; + var attemptSocketConnection = function attemptSocketConnection() { + if (disposeSocket) { + disposeSocket(); + } - return { - votePubkey: instruction.keys[0].pubkey, - authorizedWithdrawerPubkey: instruction.keys[2].pubkey, - lamports: lamports, - toPubkey: instruction.keys[1].pubkey - }; - } - /** - * @internal - */ + state = { + __type: 'connecting', + associationKeypair: associationKeypair + }; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(VoteProgram.programId)) { - throw new Error('invalid instruction; programId is not VoteProgram'); - } - } - /** - * @internal - */ + if (connectionStartTime === undefined) { + connectionStartTime = Date.now(); + } - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } - } - }]); + socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]); + socket.addEventListener('open', handleOpen); + socket.addEventListener('close', handleClose); + socket.addEventListener('error', handleError); + socket.addEventListener('message', handleMessage); + + disposeSocket = function disposeSocket() { + window.clearTimeout(retryWaitTimeoutId); + socket.removeEventListener('open', handleOpen); + socket.removeEventListener('close', handleClose); + socket.removeEventListener('error', handleError); + socket.removeEventListener('message', handleMessage); + }; + }; - return VoteInstruction; -}(); -/** - * An enumeration of valid VoteInstructionType's - */ + attemptSocketConnection(); + })); + case 13: + case "end": + return _context13.stop(); + } + }, _callee13); + })); +} -var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({ - InitializeAccount: { - index: 0, - layout: struct([u32('instruction'), voteInit()]) - }, - Authorize: { - index: 1, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('voteAuthorizationType')]) - }, - Withdraw: { - index: 3, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - AuthorizeWithSeed: { - index: 10, - layout: struct([u32('instruction'), voteAuthorizeWithSeedArgs()]) - } -}); -/** - * VoteAuthorize type - */ +cjs.SolanaMobileWalletAdapterError = SolanaMobileWalletAdapterError; +cjs.SolanaMobileWalletAdapterErrorCode = SolanaMobileWalletAdapterErrorCode; +cjs.SolanaMobileWalletAdapterProtocolError = SolanaMobileWalletAdapterProtocolError; +cjs.SolanaMobileWalletAdapterProtocolErrorCode = SolanaMobileWalletAdapterProtocolErrorCode; +cjs.transact = transact$2; -/** - * An enumeration of valid VoteAuthorization layouts. - */ +// Copyright (c) 2018 base-x contributors +// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. -var VoteAuthorizationLayout = Object.freeze({ - Voter: { - index: 0 - }, - Withdrawer: { - index: 1 - } -}); -/** - * Factory class for transactions to interact with the Vote program - */ -var VoteProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteProgram() { - _classCallCheck(this, VoteProgram); +function base(ALPHABET) { + if (ALPHABET.length >= 255) { + throw new TypeError('Alphabet too long'); } - /** - * Public key that identifies the Vote program - */ - - /** - * Generate an Initialize instruction. - */ + var BASE_MAP = new Uint8Array(256); - _createClass(VoteProgram, null, [{ - key: "initializeAccount", - value: function initializeAccount(params) { - var votePubkey = params.votePubkey, - nodePubkey = params.nodePubkey, - voteInit = params.voteInit; - var type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount; - var data = encodeData(type, { - voteInit: { - nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()), - authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()), - authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()), - commission: voteInit.commission - } - }); - var instructionData = { - keys: [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: nodePubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a transaction that creates a new Vote account. - */ + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } - }, { - key: "createAccount", - value: function createAccount(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.votePubkey, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - return transaction.add(this.initializeAccount({ - votePubkey: params.votePubkey, - nodePubkey: params.voteInit.nodePubkey, - voteInit: params.voteInit - })); - } - /** - * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account. - */ + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); - }, { - key: "authorize", - value: function authorize(params) { - var votePubkey = params.votePubkey, - authorizedPubkey = params.authorizedPubkey, - newAuthorizedPubkey = params.newAuthorizedPubkey, - voteAuthorizationType = params.voteAuthorizationType; - var type = VOTE_INSTRUCTION_LAYOUTS.Authorize; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - voteAuthorizationType: voteAuthorizationType.index - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x + ' is ambiguous'); } - /** - * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account - * where the current Voter or Withdrawer authority is a derived key. - */ - }, { - key: "authorizeWithSeed", - value: function authorizeWithSeed(params) { - var currentAuthorityDerivedKeyBasePubkey = params.currentAuthorityDerivedKeyBasePubkey, - currentAuthorityDerivedKeyOwnerPubkey = params.currentAuthorityDerivedKeyOwnerPubkey, - currentAuthorityDerivedKeySeed = params.currentAuthorityDerivedKeySeed, - newAuthorizedPubkey = params.newAuthorizedPubkey, - voteAuthorizationType = params.voteAuthorizationType, - votePubkey = params.votePubkey; - var type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; - var data = encodeData(type, { - voteAuthorizeWithSeedArgs: { - currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()), - currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - voteAuthorizationType: voteAuthorizationType.index - } - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: currentAuthorityDerivedKeyBasePubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction to withdraw from a Vote account. - */ + BASE_MAP[xc] = i; + } - }, { - key: "withdraw", - value: function withdraw(params) { - var votePubkey = params.votePubkey, - authorizedWithdrawerPubkey = params.authorizedWithdrawerPubkey, - lamports = params.lamports, - toPubkey = params.toPubkey; - var type = VOTE_INSTRUCTION_LAYOUTS.Withdraw; - var data = encodeData(type, { - lamports: lamports - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedWithdrawerPubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction to withdraw safely from a Vote account. - * - * This function was created as a safeguard for vote accounts running validators, `safeWithdraw` - * checks that the withdraw amount will not exceed the specified balance while leaving enough left - * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the - * `withdraw` method directly. - */ + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - }, { - key: "safeWithdraw", - value: function safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) { - if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) { - throw new Error('Withdraw will leave vote account with insuffcient funds.'); - } + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - return VoteProgram.withdraw(params); + function encode(source) { + if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); } - }]); - return VoteProgram; -}(); + if (!(source instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array'); + } -VoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111'); -VoteProgram.space = 3731; -var VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111'); -/** - * @internal - */ + if (source.length === 0) { + return ''; + } // Skip & count leading zeroes. -var InfoString = type({ - name: string(), - website: optional(string()), - details: optional(string()), - keybaseUsername: optional(string()) -}); -/** - * ValidatorInfo class - */ -var ValidatorInfo = /*#__PURE__*/function () { - /** - * validator public key - */ + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; - /** - * validator information - */ + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } // Allocate enough space in big-endian base58 representation. - /** - * Construct a valid ValidatorInfo - * - * @param key validator public key - * @param info validator information - */ - function ValidatorInfo(key, info) { - _classCallCheck(this, ValidatorInfo); - this.key = void 0; - this.info = void 0; - this.key = key; - this.info = info; + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); // Process the bytes. + + while (pbegin !== pend) { + var carry = source[pbegin]; // Apply "b58 = b58 * 256 + ch". + + var i = 0; + + for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) { + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE >>> 0; + carry = carry / BASE >>> 0; + } + + if (carry !== 0) { + throw new Error('Non-zero carry'); + } + + length = i; + pbegin++; + } // Skip leading zeroes in base58 result. + + + var it2 = size - length; + + while (it2 !== size && b58[it2] === 0) { + it2++; + } // Translate the result into a string. + + + var str = LEADER.repeat(zeroes); + + for (; it2 < size; ++it2) { + str += ALPHABET.charAt(b58[it2]); + } + + return str; } - /** - * Deserialize ValidatorInfo from the config account data. Exactly two config - * keys are required in the data. - * - * @param buffer config account data - * @return null if info was not found - */ + function decodeUnsafe(source) { + if (typeof source !== 'string') { + throw new TypeError('Expected String'); + } - _createClass(ValidatorInfo, null, [{ - key: "fromConfigData", - value: function fromConfigData(buffer) { - var byteArray = _toConsumableArray(buffer); + if (source.length === 0) { + return new Uint8Array(); + } - var configKeyCount = decodeLength(byteArray); - if (configKeyCount !== 2) return null; - var configKeys = []; + var psz = 0; // Skip and count leading '1's. - for (var i = 0; i < 2; i++) { - var _publicKey4 = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH)); + var zeroes = 0; + var length = 0; - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - var isSigner = byteArray.slice(0, 1)[0] === 1; - byteArray = byteArray.slice(1); - configKeys.push({ - publicKey: _publicKey4, - isSigner: isSigner - }); + while (source[psz] === LEADER) { + zeroes++; + psz++; + } // Allocate enough space in big-endian base256 representation. + + + var size = (source.length - psz) * FACTOR + 1 >>> 0; // log(58) / log(256), rounded up. + + var b256 = new Uint8Array(size); // Process the characters. + + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; // Invalid character + + if (carry === 255) { + return; } - if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) { - if (configKeys[1].isSigner) { - var rawInfo = rustString().decode(Buffer$1.from(byteArray)); - var info = JSON.parse(rawInfo); - _assert(info, InfoString); - return new ValidatorInfo(configKeys[1].publicKey, info); - } + var i = 0; + + for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) { + carry += BASE * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; } - return null; - } - }]); + if (carry !== 0) { + throw new Error('Non-zero carry'); + } - return ValidatorInfo; -}(); + length = i; + psz++; + } // Skip leading zeroes in b256. -var VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111'); -/** - * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88 - * - * @internal - */ -var VoteAccountLayout = struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), u8('commission'), nu64$1(), // votes.length -seq$1(struct([nu64$1('slot'), u32('confirmationCount')]), offset$1(u32(), -8), 'votes'), u8('rootSlotValid'), nu64$1('rootSlot'), nu64$1(), // authorizedVoters.length -seq$1(struct([nu64$1('epoch'), publicKey('authorizedVoter')]), offset$1(u32(), -8), 'authorizedVoters'), struct([seq$1(struct([publicKey('authorizedPubkey'), nu64$1('epochOfLastAuthorizedSwitch'), nu64$1('targetEpoch')]), 32, 'buf'), nu64$1('idx'), u8('isEmpty')], 'priorVoters'), nu64$1(), // epochCredits.length -seq$1(struct([nu64$1('epoch'), nu64$1('credits'), nu64$1('prevCredits')]), offset$1(u32(), -8), 'epochCredits'), struct([nu64$1('slot'), nu64$1('timestamp')], 'lastTimestamp')]); -/** - * VoteAccount class - */ + var it4 = size - length; -var VoteAccount = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteAccount(args) { - _classCallCheck(this, VoteAccount); + while (it4 !== size && b256[it4] === 0) { + it4++; + } - this.nodePubkey = void 0; - this.authorizedWithdrawer = void 0; - this.commission = void 0; - this.rootSlot = void 0; - this.votes = void 0; - this.authorizedVoters = void 0; - this.priorVoters = void 0; - this.epochCredits = void 0; - this.lastTimestamp = void 0; - this.nodePubkey = args.nodePubkey; - this.authorizedWithdrawer = args.authorizedWithdrawer; - this.commission = args.commission; - this.rootSlot = args.rootSlot; - this.votes = args.votes; - this.authorizedVoters = args.authorizedVoters; - this.priorVoters = args.priorVoters; - this.epochCredits = args.epochCredits; - this.lastTimestamp = args.lastTimestamp; - } - /** - * Deserialize VoteAccount from the account data. - * - * @param buffer account data - * @return VoteAccount - */ + var vch = new Uint8Array(zeroes + (size - it4)); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } - _createClass(VoteAccount, null, [{ - key: "fromAccountData", - value: function fromAccountData(buffer) { - var versionOffset = 4; - var va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset); - var rootSlot = va.rootSlot; + return vch; + } - if (!va.rootSlotValid) { - rootSlot = null; - } + function decode(string) { + var buffer = decodeUnsafe(string); - return new VoteAccount({ - nodePubkey: new PublicKey(va.nodePubkey), - authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer), - commission: va.commission, - votes: va.votes, - rootSlot: rootSlot, - authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter), - priorVoters: getPriorVoters(va.priorVoters), - epochCredits: va.epochCredits, - lastTimestamp: va.lastTimestamp - }); + if (buffer) { + return buffer; } - }]); - return VoteAccount; -}(); + throw new Error('Non-base' + BASE + ' character'); + } -function parseAuthorizedVoter(_ref46) { - var authorizedVoter = _ref46.authorizedVoter, - epoch = _ref46.epoch; return { - epoch: epoch, - authorizedVoter: new PublicKey(authorizedVoter) + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode }; } -function parsePriorVoters(_ref47) { - var authorizedPubkey = _ref47.authorizedPubkey, - epochOfLastAuthorizedSwitch = _ref47.epochOfLastAuthorizedSwitch, - targetEpoch = _ref47.targetEpoch; - return { - authorizedPubkey: new PublicKey(authorizedPubkey), - epochOfLastAuthorizedSwitch: epochOfLastAuthorizedSwitch, - targetEpoch: targetEpoch +var src = base; + +var basex = src; +var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +var bs58$1 = basex(ALPHABET); + +Object.defineProperty(cjs$1, '__esModule', { + value: true +}); +var web3_js = require$$1; +var mobileWalletAdapterProtocol = cjs; +var bs58 = bs58$1; + +function _interopDefaultLegacy(e) { + return e && _typeof$1(e) === 'object' && 'default' in e ? e : { + 'default': e }; } -function getPriorVoters(_ref48) { - var buf = _ref48.buf, - idx = _ref48.idx, - isEmpty = _ref48.isEmpty; +var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58); +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ - if (isEmpty) { - return []; - } - return [].concat(_toConsumableArray(buf.slice(idx + 1).map(parsePriorVoters)), _toConsumableArray(buf.slice(0, idx).map(parsePriorVoters))); -} +function __rest(s, e) { + var t = {}; -var endpoint = { - http: { - devnet: 'http://api.devnet.solana.com', - testnet: 'http://api.testnet.solana.com', - 'mainnet-beta': 'http://api.mainnet-beta.solana.com/' - }, - https: { - devnet: 'https://api.devnet.solana.com', - testnet: 'https://api.testnet.solana.com', - 'mainnet-beta': 'https://api.mainnet-beta.solana.com/' - } -}; -/** - * Retrieves the RPC API URL for the specified cluster - */ + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; -function clusterApiUrl(cluster, tls) { - var key = tls === false ? 'http' : 'https'; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; +} - if (!cluster) { - return endpoint[key]['devnet']; +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); } - var url = endpoint[key][cluster]; + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } - if (!url) { - throw new Error("Unknown ".concat(key, " cluster: ").concat(cluster)); - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } - return url; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); } -/** - * Send and confirm a raw transaction - * - * If `commitment` option is not specified, defaults to 'max' commitment. - * - * @param {Connection} connection - * @param {Buffer} rawTransaction - * @param {TransactionConfirmationStrategy} confirmationStrategy - * @param {ConfirmOptions} [options] - * @returns {Promise} - */ -/** - * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy` - * is no longer supported and will be removed in a future version. - */ -// eslint-disable-next-line no-redeclare -// eslint-disable-next-line no-redeclare +function fromUint8Array(byteArray) { + var _String$fromCharCode; + return window.btoa((_String$fromCharCode = String.fromCharCode).call.apply(_String$fromCharCode, [null].concat(_toConsumableArray(byteArray)))); +} -function sendAndConfirmRawTransaction(_x161, _x162, _x163, _x164) { - return _sendAndConfirmRawTransaction.apply(this, arguments); +function toUint8Array(base64EncodedByteArray) { + return new Uint8Array(window.atob(base64EncodedByteArray).split('').map(function (c) { + return c.charCodeAt(0); + })); } -/** - * There are 1-billion lamports in one SOL - */ +function getPayloadFromTransaction(transaction) { + var serializedTransaction = 'version' in transaction ? transaction.serialize() : transaction.serialize({ + requireAllSignatures: false, + verifySignatures: false + }); + var payload = fromUint8Array(serializedTransaction); + return payload; +} -function _sendAndConfirmRawTransaction() { - _sendAndConfirmRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee109(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) { - var confirmationStrategy, options, sendOptions, signature, commitment, confirmationPromise, status; - return _regeneratorRuntime().wrap(function _callee109$(_context109) { - while (1) switch (_context109.prev = _context109.next) { +function getTransactionFromWireMessage(byteArray) { + var numSignatures = byteArray[0]; + var messageOffset = numSignatures * web3_js.SIGNATURE_LENGTH_IN_BYTES + 1; + var version = web3_js.VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset, byteArray.length)); + + if (version === 'legacy') { + return web3_js.Transaction.from(byteArray); + } else { + return web3_js.VersionedTransaction.deserialize(byteArray); + } +} + +function transact$1(callback, config) { + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var augmentedCallback; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { case 0: - if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) { - confirmationStrategy = confirmationStrategyOrConfirmOptions; - options = maybeConfirmOptions; - } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) { - confirmationStrategy = confirmationStrategyOrConfirmOptions; - options = maybeConfirmOptions; - } else { - options = confirmationStrategyOrConfirmOptions; - } + augmentedCallback = function augmentedCallback(wallet) { + var augmentedAPI = new Proxy({}, { + get: function get(target, p) { + if (target[p] == null) { + switch (p) { + case 'signAndSendTransactions': + target[p] = function (_a) { + var minContextSlot = _a.minContextSlot, + transactions = _a.transactions, + rest = __rest(_a, ["minContextSlot", "transactions"]); + + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var payloads, _yield$wallet$signAnd, base64EncodedSignatures, signatures; + + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + payloads = transactions.map(getPayloadFromTransaction); + _context.next = 3; + return wallet.signAndSendTransactions(Object.assign(Object.assign(Object.assign({}, rest), minContextSlot != null ? { + options: { + min_context_slot: minContextSlot + } + } : null), { + payloads: payloads + })); - sendOptions = options && { - skipPreflight: options.skipPreflight, - preflightCommitment: options.preflightCommitment || options.commitment, - minContextSlot: options.minContextSlot - }; - _context109.next = 4; - return connection.sendRawTransaction(rawTransaction, sendOptions); + case 3: + _yield$wallet$signAnd = _context.sent; + base64EncodedSignatures = _yield$wallet$signAnd.signatures; + signatures = base64EncodedSignatures.map(toUint8Array).map(bs58__default["default"].encode); + return _context.abrupt("return", signatures); - case 4: - signature = _context109.sent; - commitment = options && options.commitment; - confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment); - _context109.next = 9; - return confirmationPromise; + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + }; - case 9: - status = _context109.sent.value; + break; - if (!status.err) { - _context109.next = 12; - break; - } + case 'signMessages': + target[p] = function (_a) { + var payloads = _a.payloads, + rest = __rest(_a, ["payloads"]); - throw new Error("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var base64EncodedPayloads, _yield$wallet$signMes, base64EncodedSignedMessages, signedMessages; - case 12: - return _context109.abrupt("return", signature); + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + base64EncodedPayloads = payloads.map(fromUint8Array); + _context2.next = 3; + return wallet.signMessages(Object.assign(Object.assign({}, rest), { + payloads: base64EncodedPayloads + })); - case 13: + case 3: + _yield$wallet$signMes = _context2.sent; + base64EncodedSignedMessages = _yield$wallet$signMes.signed_payloads; + signedMessages = base64EncodedSignedMessages.map(toUint8Array); + return _context2.abrupt("return", signedMessages); + + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + }; + + break; + + case 'signTransactions': + target[p] = function (_a) { + var transactions = _a.transactions, + rest = __rest(_a, ["transactions"]); + + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var payloads, _yield$wallet$signTra, base64EncodedCompiledTransactions, compiledTransactions, signedTransactions; + + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + payloads = transactions.map(getPayloadFromTransaction); + _context3.next = 3; + return wallet.signTransactions(Object.assign(Object.assign({}, rest), { + payloads: payloads + })); + + case 3: + _yield$wallet$signTra = _context3.sent; + base64EncodedCompiledTransactions = _yield$wallet$signTra.signed_payloads; + compiledTransactions = base64EncodedCompiledTransactions.map(toUint8Array); + signedTransactions = compiledTransactions.map(getTransactionFromWireMessage); + return _context3.abrupt("return", signedTransactions); + + case 8: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + }; + + break; + + default: + { + target[p] = wallet[p]; + break; + } + } + } + + return target[p]; + }, + defineProperty: function defineProperty() { + return false; + }, + deleteProperty: function deleteProperty() { + return false; + } + }); + return callback(augmentedAPI); + }; + + _context4.next = 3; + return mobileWalletAdapterProtocol.transact(augmentedCallback, config); + + case 3: + return _context4.abrupt("return", _context4.sent); + + case 4: case "end": - return _context109.stop(); + return _context4.stop(); } - }, _callee109); + }, _callee4); })); - return _sendAndConfirmRawTransaction.apply(this, arguments); } -var LAMPORTS_PER_SOL = 1000000000; - -var index_browser_esm = /*#__PURE__*/Object.freeze({ - __proto__: null, - Account: Account, - AddressLookupTableAccount: AddressLookupTableAccount, - AddressLookupTableInstruction: AddressLookupTableInstruction, - AddressLookupTableProgram: AddressLookupTableProgram, - Authorized: Authorized, - BLOCKHASH_CACHE_TIMEOUT_MS: BLOCKHASH_CACHE_TIMEOUT_MS, - BPF_LOADER_DEPRECATED_PROGRAM_ID: BPF_LOADER_DEPRECATED_PROGRAM_ID, - BPF_LOADER_PROGRAM_ID: BPF_LOADER_PROGRAM_ID, - BpfLoader: BpfLoader, - COMPUTE_BUDGET_INSTRUCTION_LAYOUTS: COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, - ComputeBudgetInstruction: ComputeBudgetInstruction, - ComputeBudgetProgram: ComputeBudgetProgram, - Connection: Connection, - Ed25519Program: Ed25519Program, - Enum: Enum, - EpochSchedule: EpochSchedule, - FeeCalculatorLayout: FeeCalculatorLayout, - Keypair: Keypair, - LAMPORTS_PER_SOL: LAMPORTS_PER_SOL, - LOOKUP_TABLE_INSTRUCTION_LAYOUTS: LOOKUP_TABLE_INSTRUCTION_LAYOUTS, - Loader: Loader, - Lockup: Lockup, - MAX_SEED_LENGTH: MAX_SEED_LENGTH, - Message: Message, - MessageAccountKeys: MessageAccountKeys, - MessageV0: MessageV0, - NONCE_ACCOUNT_LENGTH: NONCE_ACCOUNT_LENGTH, - NonceAccount: NonceAccount, - PACKET_DATA_SIZE: PACKET_DATA_SIZE, - PUBLIC_KEY_LENGTH: PUBLIC_KEY_LENGTH, - PublicKey: PublicKey, - SIGNATURE_LENGTH_IN_BYTES: SIGNATURE_LENGTH_IN_BYTES, - SOLANA_SCHEMA: SOLANA_SCHEMA, - STAKE_CONFIG_ID: STAKE_CONFIG_ID, - STAKE_INSTRUCTION_LAYOUTS: STAKE_INSTRUCTION_LAYOUTS, - SYSTEM_INSTRUCTION_LAYOUTS: SYSTEM_INSTRUCTION_LAYOUTS, - SYSVAR_CLOCK_PUBKEY: SYSVAR_CLOCK_PUBKEY, - SYSVAR_EPOCH_SCHEDULE_PUBKEY: SYSVAR_EPOCH_SCHEDULE_PUBKEY, - SYSVAR_INSTRUCTIONS_PUBKEY: SYSVAR_INSTRUCTIONS_PUBKEY, - SYSVAR_RECENT_BLOCKHASHES_PUBKEY: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - SYSVAR_RENT_PUBKEY: SYSVAR_RENT_PUBKEY, - SYSVAR_REWARDS_PUBKEY: SYSVAR_REWARDS_PUBKEY, - SYSVAR_SLOT_HASHES_PUBKEY: SYSVAR_SLOT_HASHES_PUBKEY, - SYSVAR_SLOT_HISTORY_PUBKEY: SYSVAR_SLOT_HISTORY_PUBKEY, - SYSVAR_STAKE_HISTORY_PUBKEY: SYSVAR_STAKE_HISTORY_PUBKEY, - Secp256k1Program: Secp256k1Program, - SendTransactionError: SendTransactionError, - SolanaJSONRPCError: SolanaJSONRPCError, - SolanaJSONRPCErrorCode: SolanaJSONRPCErrorCode, - StakeAuthorizationLayout: StakeAuthorizationLayout, - StakeInstruction: StakeInstruction, - StakeProgram: StakeProgram, - Struct: Struct, - SystemInstruction: SystemInstruction, - SystemProgram: SystemProgram, - Transaction: Transaction, - TransactionExpiredBlockheightExceededError: TransactionExpiredBlockheightExceededError, - TransactionExpiredNonceInvalidError: TransactionExpiredNonceInvalidError, - TransactionExpiredTimeoutError: TransactionExpiredTimeoutError, - TransactionInstruction: TransactionInstruction, - TransactionMessage: TransactionMessage, - get TransactionStatus () { return TransactionStatus; }, - VALIDATOR_INFO_KEY: VALIDATOR_INFO_KEY, - VERSION_PREFIX_MASK: VERSION_PREFIX_MASK, - VOTE_PROGRAM_ID: VOTE_PROGRAM_ID, - ValidatorInfo: ValidatorInfo, - VersionedMessage: VersionedMessage, - VersionedTransaction: VersionedTransaction, - VoteAccount: VoteAccount, - VoteAuthorizationLayout: VoteAuthorizationLayout, - VoteInit: VoteInit, - VoteInstruction: VoteInstruction, - VoteProgram: VoteProgram, - clusterApiUrl: clusterApiUrl, - sendAndConfirmRawTransaction: sendAndConfirmRawTransaction, - sendAndConfirmTransaction: sendAndConfirmTransaction -}); +cjs$1.transact = transact$1; var Layout$1 = {}; @@ -36839,8 +38281,6 @@ Layout$1["const"] = function (value, property) { var lib = {}; -var require$$1 = /*@__PURE__*/getAugmentedNamespace(index_browser_esm); - var bn = {exports: {}}; (function (module) { @@ -36898,7 +38338,7 @@ var bn = {exports: {}}; if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { - Buffer = require$$0$1.Buffer; + Buffer = require$$1$1.Buffer; } } catch (e) {} @@ -40663,7 +42103,9 @@ var bn = {exports: {}}; exports.map = map; })(lib); -var Buffer = require$$0$1.Buffer; +var Web3MobileWallet = cjs$1.Web3MobileWallet; +var transact = cjs$1.transact; +var Buffer = require$$1$1.Buffer; var BN = bn$1.exports; var ACCOUNT_LAYOUT = lib.struct([lib.publicKey('mint'), lib.publicKey('owner'), lib.u64('amount'), lib.u32('delegateOption'), lib.publicKey('delegate'), lib.u8('state'), lib.u32('isNativeOption'), lib.u64('isNative'), lib.u64('delegatedAmount'), lib.u32('closeAuthorityOption'), lib.publicKey('closeAuthority')]); @@ -40688,4 +42130,4 @@ var u64$3 = lib.u64; var u8$1 = lib.u8; var vec = lib.vec; var vecU8 = lib.vecU8; -export { ACCOUNT_LAYOUT, AddressLookupTableProgram, BN, Buffer, Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction, array$1 as array, blob, bool$1 as bool, i128, i16, i32, i64, i8, map, nu64, offset, option, publicKey$1 as publicKey, rustEnum, seq, str, struct$1 as struct, tagged, u128, u16$1 as u16, u32$2 as u32, u64$3 as u64, u8$1 as u8, vec, vecU8 }; +export { ACCOUNT_LAYOUT, AddressLookupTableProgram, BN, Buffer, Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction, Web3MobileWallet, array$1 as array, blob, bool$1 as bool, i128, i16, i32, i64, i8, map, nu64, offset, option, publicKey$1 as publicKey, rustEnum, seq, str, struct$1 as struct, tagged, transact, u128, u16$1 as u16, u32$2 as u32, u64$3 as u64, u8$1 as u8, vec, vecU8 }; diff --git a/dist/umd/index.js b/dist/umd/index.js index dd7f506..abf3c6d 100644 --- a/dist/umd/index.js +++ b/dist/umd/index.js @@ -42,8086 +42,8088 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// return a; } - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + return keys; } - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - return arr + return target; } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] - } + function _regeneratorRuntime() { + /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ - function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } + _regeneratorRuntime = function () { + return exports; + }; - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 + var exports = {}, + Op = Object.prototype, + hasOwn = Op.hasOwnProperty, + $Symbol = "function" == typeof Symbol ? Symbol : {}, + iteratorSymbol = $Symbol.iterator || "@@iterator", + asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", + toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + function define(obj, key, value) { + return Object.defineProperty(obj, key, { + value: value, + enumerable: !0, + configurable: !0, + writable: !0 + }), obj[key]; } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; + try { + define({}, ""); + } catch (err) { + define = function (obj, key, value) { + return obj[key] = value; + }; } - parts.push(output); - - return parts.join('') - } - - function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, + generator = Object.create(protoGenerator.prototype), + context = new Context(tryLocsList || []); + return generator._invoke = function (innerFn, self, context) { + var state = "suspendedStart"; + return function (method, arg) { + if ("executing" === state) throw new Error("Generator is already running"); - i += d; + if ("completed" === state) { + if ("throw" === method) throw arg; + return doneResult(); + } - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + for (context.method = method, context.arg = arg;;) { + var delegate = context.delegate; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } - function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { + if ("suspendedStart" === state) throw state = "completed", context.arg; + context.dispatchException(context.arg); + } else "return" === context.method && context.abrupt("return", context.arg); + state = "executing"; + var record = tryCatch(innerFn, self, context); - value = Math.abs(value); + if ("normal" === record.type) { + if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; + return { + value: record.arg, + done: context.done + }; + } - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } + "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); + } + }; + }(innerFn, self, context), generator; + } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; } } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + exports.wrap = wrap; + var ContinueSentinel = {}; - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + function Generator() {} - buffer[offset + i - d] |= s * 128; - } + function GeneratorFunction() {} - var toString = {}.toString; + function GeneratorFunctionPrototype() {} - var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf, + NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); + } - var INSPECT_MAX_BYTES = 50; + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. + if ("throw" !== record.type) { + var result = record.arg, + value = result.value; + return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }) : PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped, resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); + } - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; + reject(record.arg); + } - /* - * Export kMaxLength after typed array support is determined. - */ - var _kMaxLength = kMaxLength(); + var previousPromise; - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } + this._invoke = function (method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + }; } - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; - function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } + if (undefined === method) { + if (context.delegate = null, "throw" === context.method) { + if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; + context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); + } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) + return ContinueSentinel; } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer$1.poolSize = 8192; // not used by this implementation - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr - }; + var record = tryCatch(method, delegate.iterator, context.arg); + if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; + var info = record.arg; + return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + } - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal", delete record.arg, entry.completion = record; } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } - return fromObject(that, value) - } + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) return iteratorMethod.call(iterable); + if ("function" == typeof iterable.next) return iterable; - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } + return next.value = undefined, next.done = !0, next; + }; - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } + return next.next = next; + } + } - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + return { + next: doneResult + }; } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } + function doneResult() { + return { + value: undefined, + done: !0 + }; } - return that - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; + return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { + var ctor = "function" == typeof genFun && genFun.constructor; + return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); + }, exports.mark = function (genFun) { + return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; + }, exports.awrap = function (arg) { + return { + __await: arg + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + void 0 === PromiseImpl && (PromiseImpl = Promise); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { + return this; + }), define(Gp, "toString", function () { + return "[object Generator]"; + }), exports.keys = function (object) { + var keys = []; - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } + for (var key in object) keys.push(key); - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } + return keys.reverse(), function next() { + for (; keys.length;) { + var key = keys.pop(); + if (key in object) return next.value = key, next.done = !1, next; + } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + return next.done = !0, next; + }; + }, exports.values = values, Context.prototype = { + constructor: Context, + reset: function (skipTempReset) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); + }, + stop: function () { + this.done = !0; + var rootRecord = this.tryEntries[0].completion; + if ("throw" === rootRecord.type) throw rootRecord.arg; + return this.rval; + }, + dispatchException: function (exception) { + if (this.done) throw exception; + var context = this; - var actual = that.write(string, encoding); + function handle(loc, caught) { + return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; + } - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i], + record = entry.completion; + if ("root" === entry.tryLoc) return handle("end"); - return that - } + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"), + hasFinally = hasOwn.call(entry, "finallyLoc"); - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } else if (hasCatch) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + } else { + if (!hasFinally) throw new Error("try statement without catch or finally"); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } + } + } + }, + abrupt: function (type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } + finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); + var record = finallyEntry ? finallyEntry.completion : {}; + return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); + }, + complete: function (record, afterLoc) { + if ("throw" === record.type) throw record.arg; + return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; + }, + finish: function (finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; + } + }, + catch: function (tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + if (entry.tryLoc === tryLoc) { + var record = entry.completion; - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } + if ("throw" === record.type) { + var thrown = record.arg; + resetTryEntry(entry); + } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that + return thrown; + } + } + + throw new Error("illegal catch attempt"); + }, + delegateYield: function (iterable, resultName, nextLoc) { + return this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }, "next" === this.method && (this.arg = undefined), ContinueSentinel; + } + }, exports; } - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + function _typeof$1(obj) { + "@babel/helpers - typeof"; - if (that.length === 0) { - return that - } + return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof$1(obj); + } - obj.copy(that, 0, 0, len); - return that + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } - return fromArrayLike(that, obj) - } - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + _next(undefined); + }); + }; } - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); } - return length | 0 } - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); } - return Buffer$1.alloc(+length) } - Buffer$1.isBuffer = isBuffer; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; } - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; } - if (a === b) return 0 + return obj; + } - var x = a.length; - var y = b.length; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true } - } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) _setPrototypeOf(subClass, superClass); + } - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } - Buffer$1.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - }; + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf(o, p); + } - Buffer$1.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; - if (list.length === 0) { - return Buffer$1.alloc(0) + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; } + } - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } + function _construct(Parent, args, Class) { + if (_isNativeReflectConstruct()) { + _construct = Reflect.construct.bind(); + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; } - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; + return _construct.apply(null, arguments); + } - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } - var len = string.length; - if (len === 0) return 0 + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes$1(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); } - } - } - Buffer$1.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + _cache.set(Class, Wrapper); + } - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } - if (end === undefined || end > this.length) { - end = this.length; - } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; - if (end <= 0) { - return '' - } + return _wrapNativeSuper(Class); + } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (end <= start) { - return '' + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - if (!encoding) encoding = 'utf8'; + return target; + } - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + var target = _objectWithoutPropertiesLoose(source, excluded); - case 'ascii': - return asciiSlice(this, start, end) + var key, i; - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; } } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$1.prototype._isBuffer = true; - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; + return target; } - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return this - }; - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this - }; + return self; + } - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); + function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); } - return this - }; - Buffer$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; + return _assertThisInitialized(self); + } - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 - }; + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' - }; + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), + result; - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + return _possibleConstructorReturn(this, result); + }; + } - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 + function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + return object; + } - if (this === target) return 0 + function _get() { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get.bind(); + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + if (desc.get) { + return desc.get.call(arguments.length < 3 ? target : receiver); + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } + return desc.value; + }; } - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; + return _get.apply(this, arguments); + } - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } + function _toArray(arr) { + return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); + } - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } - throw new TypeError('val must be string, number or Buffer') + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + var _s, _e; - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; } } - return -1 + return _arr; } - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i + return arr2; } - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } + function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } + if (!it) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } + var F = function () {}; - Buffer$1.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + var normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = it.call(o); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; + } - case 'ascii': - return asciiWrite(this, string, offset, length) + var cjs$1 = {}; - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } + function toByteArray (b64) { + if (!inited) { + init(); } - }; + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; - Buffer$1.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - }; - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } + var L = 0; - res.push(codePoint); - i += bytesPerSequence; + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; } - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res + return arr } - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); } - return ret + return output.join('') } - function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); } - return out - } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; } - return res + + parts.push(output); + + return parts.join('') } - Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } + i += d; - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - if (end < start) end = start; + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } + m = m + Math.pow(2, mLen); + e = e - eBias; } - - return newBuf - }; - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } - Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } + value = Math.abs(value); - return val - }; + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - return val - }; + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; + buffer[offset + i - d] |= s * 128; + } - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; + var toString = {}.toString; - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; + var INSPECT_MAX_BYTES = 50; - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + /* + * Export kMaxLength after typed array support is determined. + */ + var _kMaxLength = kMaxLength(); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + function kMaxLength () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return that + } - return val - }; + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ - Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) } - mul *= 0x80; + return from(this, arg, encodingOrOffset, length) + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + Buffer$1.poolSize = 8192; // not used by this implementation - return val + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr }; - Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + return fromObject(that, value) + } - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer$1.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) }; - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; + } - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer$1.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) }; - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$1.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) }; - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } - return offset + byteLength - }; + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + var actual = that.write(string, encoding); - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); } - return offset + byteLength - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; + return that + } - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; } + return that } - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } - return offset + 2 - }; - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } - } - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); } else { - objectWriteUInt32(this, value, offset, true); + array = new Uint8Array(array, byteOffset, length); } - return offset + 4 - }; - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; } else { - objectWriteUInt32(this, value, offset, false); + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); } - return offset + 4 - }; + return that + } - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - checkInt(this, value, offset, byteLength, limit - 1, -limit); + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } - return offset + byteLength - }; + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } - Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } - checkInt(this, value, offset, byteLength, limit - 1, -limit); + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; } + return Buffer$1.alloc(+length) + } + Buffer$1.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - return offset + byteLength - }; + if (a === b) return 0 - Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; + var x = a.length; + var y = b.length; - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } } - return offset + 2 - }; - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + if (x < y) return -1 + if (y < x) return 1 + return 0 }; - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); + Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } - return offset + 4 }; - Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); + Buffer$1.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - return offset + 4 - }; - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } + if (list.length === 0) { + return Buffer$1.alloc(0) + } - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer }; - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes$1(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 } + Buffer$1.byteLength = byteLength; - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; + function slowToString (encoding, start, end) { + var loweredCase = false; - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + if (end === undefined || end > this.length) { + end = this.length; + } - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') + if (end <= 0) { + return '' } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' } - var len = end - start; - var i; + if (!encoding) encoding = 'utf8'; - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); } + } - return len - }; + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$1.prototype._isBuffer = true; - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); } + return this + }; - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') + Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this + }; - if (end <= start) { - return this + Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); } + return this + }; - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; - if (!val) val = 0; + Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 + }; - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } + Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; } - - return this + return '' }; - // HELPER FUNCTIONS - // ================ + Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - return str - } - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - function utf8ToBytes$1 (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + if (this === target) return 0 - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - // valid lead - leadSurrogate = codePoint; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } - continue - } + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } - leadSurrogate = null; + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - return bytes + throw new TypeError('val must be string, number or Buffer') } - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } } - return byteArray - } - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } } - return byteArray + return -1 } + Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; - function base64ToBytes (str) { - return toByteArray(base64clean(str)) - } + Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; - function blitBuffer (src, dst, offset, length) { + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; } return i } - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) } + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ - __proto__: null, - Buffer: Buffer$1, - INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, - SlowBuffer: SlowBuffer, - isBuffer: isBuffer, - kMaxLength: _kMaxLength - }); + Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } - var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_buffer); + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } - return keys; - } + if (!encoding) encoding = 'utf8'; - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - return target; - } + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - function _regeneratorRuntime() { - /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + case 'ascii': + return asciiWrite(this, string, offset, length) - _regeneratorRuntime = function () { - return exports; - }; + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - var exports = {}, - Op = Object.prototype, - hasOwn = Op.hasOwnProperty, - $Symbol = "function" == typeof Symbol ? Symbol : {}, - iteratorSymbol = $Symbol.iterator || "@@iterator", - asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", - toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - function define(obj, key, value) { - return Object.defineProperty(obj, key, { - value: value, - enumerable: !0, - configurable: !0, - writable: !0 - }), obj[key]; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } } + }; - try { - define({}, ""); - } catch (err) { - define = function (obj, key, value) { - return obj[key] = value; - }; + Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } + }; - function wrap(innerFn, outerFn, self, tryLocsList) { - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, - generator = Object.create(protoGenerator.prototype), - context = new Context(tryLocsList || []); - return generator._invoke = function (innerFn, self, context) { - var state = "suspendedStart"; - return function (method, arg) { - if ("executing" === state) throw new Error("Generator is already running"); + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } - if ("completed" === state) { - if ("throw" === method) throw arg; - return doneResult(); - } + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - for (context.method = method, context.arg = arg;;) { - var delegate = context.delegate; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; } } - - if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { - if ("suspendedStart" === state) throw state = "completed", context.arg; - context.dispatchException(context.arg); - } else "return" === context.method && context.abrupt("return", context.arg); - state = "executing"; - var record = tryCatch(innerFn, self, context); - - if ("normal" === record.type) { - if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; - return { - value: record.arg, - done: context.done - }; + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } - "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); - } - }; - }(innerFn, self, context), generator; - } - - function tryCatch(fn, obj, arg) { - try { - return { - type: "normal", - arg: fn.call(obj, arg) - }; - } catch (err) { - return { - type: "throw", - arg: err - }; + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; } + + res.push(codePoint); + i += bytesPerSequence; } - exports.wrap = wrap; - var ContinueSentinel = {}; + return decodeCodePointsArray(res) + } - function Generator() {} + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; - function GeneratorFunction() {} + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - function GeneratorFunctionPrototype() {} + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } - var IteratorPrototype = {}; - define(IteratorPrototype, iteratorSymbol, function () { - return this; - }); - var getProto = Object.getPrototypeOf, - NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - define(prototype, method, function (arg) { - return this._invoke(method, arg); - }); - }); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); } + return ret + } - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - - if ("throw" !== record.type) { - var result = record.arg, - value = result.value; - return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }) : PromiseImpl.resolve(value).then(function (unwrapped) { - result.value = unwrapped, resolve(result); - }, function (error) { - return invoke("throw", error, resolve, reject); - }); - } + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - reject(record.arg); - } + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } - var previousPromise; + function hexSlice (buf, start, end) { + var len = buf.length; - this._invoke = function (method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - }; + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); } + return out + } - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - - if (undefined === method) { - if (context.delegate = null, "throw" === context.method) { - if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; - context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } - return ContinueSentinel; - } + Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - var record = tryCatch(method, delegate.iterator, context.arg); - if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; - var info = record.arg; - return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; } - function pushTryEntry(locs) { - var entry = { - tryLoc: locs[0] - }; - 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal", delete record.arg, entry.completion = record; - } + if (end < start) end = start; - function Context(tryLocsList) { - this.tryEntries = [{ - tryLoc: "root" - }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } } - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) return iteratorMethod.call(iterable); - if ("function" == typeof iterable.next) return iterable; + return newBuf + }; - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } - return next.value = undefined, next.done = !0, next; - }; + Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - return next.next = next; - } - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - return { - next: doneResult - }; + return val + }; + + Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - function doneResult() { - return { - value: undefined, - done: !0 - }; + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { - var ctor = "function" == typeof genFun && genFun.constructor; - return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); - }, exports.mark = function (genFun) { - return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; - }, exports.awrap = function (arg) { - return { - __await: arg - }; - }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { - return this; - }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { - void 0 === PromiseImpl && (PromiseImpl = Promise); - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); - return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { - return this; - }), define(Gp, "toString", function () { - return "[object Generator]"; - }), exports.keys = function (object) { - var keys = []; + return val + }; - for (var key in object) keys.push(key); + Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - return keys.reverse(), function next() { - for (; keys.length;) { - var key = keys.pop(); - if (key in object) return next.value = key, next.done = !1, next; - } + Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; - return next.done = !0, next; - }; - }, exports.values = values, Context.prototype = { - constructor: Context, - reset: function (skipTempReset) { - if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); - }, - stop: function () { - this.done = !0; - var rootRecord = this.tryEntries[0].completion; - if ("throw" === rootRecord.type) throw rootRecord.arg; - return this.rval; - }, - dispatchException: function (exception) { - if (this.done) throw exception; - var context = this; + Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; - function handle(loc, caught) { - return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; - } + Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i], - record = entry.completion; - if ("root" === entry.tryLoc) return handle("end"); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"), - hasFinally = hasOwn.call(entry, "finallyLoc"); + Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); - if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); - } else if (hasCatch) { - if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); - } else { - if (!hasFinally) throw new Error("try statement without catch or finally"); - if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); - } - } - } - }, - abrupt: function (type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } + Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); - var record = finallyEntry ? finallyEntry.completion : {}; - return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); - }, - complete: function (record, afterLoc) { - if ("throw" === record.type) throw record.arg; - return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; - }, - finish: function (finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; - } - }, - catch: function (tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if ("throw" === record.type) { - var thrown = record.arg; - resetTryEntry(entry); - } + return val + }; - return thrown; - } - } + Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - throw new Error("illegal catch attempt"); - }, - delegateYield: function (iterable, resultName, nextLoc) { - return this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }, "next" === this.method && (this.arg = undefined), ContinueSentinel; - } - }, exports; - } + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - function _typeof$1(obj) { - "@babel/helpers - typeof"; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }, _typeof$1(obj); - } + return val + }; - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } + Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } + Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); + Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } + Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; - _next(undefined); - }); - }; - } + Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } + Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; - } + Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } + Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; - return obj; + Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); + Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - Object.defineProperty(subClass, "prototype", { - writable: false - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } + return offset + byteLength + }; - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } + Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; + return offset + byteLength + }; + + Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; } } - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct.bind(); + Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; + objectWriteUInt16(this, value, offset, true); } + return offset + 2 + }; - return _construct.apply(null, arguments); - } + Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } } - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; + Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } + Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); + Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - _cache.set(Class, Wrapper); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } + return offset + byteLength + }; - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; + Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - return target; - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } - var target = _objectWithoutPropertiesLoose(source, excluded); + return offset + byteLength + }; - var key, i; + Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } + Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); } + return offset + 2 + }; - return target; - } + Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); } + return offset + 4 + }; - return self; + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') } - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); } - - return _assertThisInitialized(self); + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 } - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); + Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; + Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } + Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - return _possibleConstructorReturn(this, result); - }; - } + Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - return object; - } + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - function _get() { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get.bind(); + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); + return len + }; - if (desc.get) { - return desc.get.call(arguments.length < 3 ? target : receiver); + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } - return desc.value; - }; + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') } - return _get.apply(this, arguments); - } + if (end <= start) { + return this + } - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); - } + if (!val) val = 0; - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str } - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') } - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) } - function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + function utf8ToBytes$1 (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - var _s, _e; + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); + // valid lead + leadSurrogate = codePoint; - if (i && _arr.length === i) break; + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') } } - return _arr; + return bytes } - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray } - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - return arr2; + return byteArray } - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + function base64ToBytes (str) { + return toByteArray(base64clean(str)) } - function _createForOfIteratorHelper(o, allowArrayLike) { - var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } - if (!it) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } - var F = function () {}; - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = it.call(o); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } - var bn$1 = {exports: {}}; + var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + Buffer: Buffer$1, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + SlowBuffer: SlowBuffer, + isBuffer: isBuffer, + kMaxLength: _kMaxLength + }); - (function (module) { - (function (module, exports) { + function number$1(n) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error("Wrong positive integer: ".concat(n)); + } + function bool(b) { + if (typeof b !== 'boolean') throw new Error("Expected boolean, not ".concat(b)); + } + function bytes(b) { + if (!(b instanceof Uint8Array)) throw new TypeError('Expected Uint8Array'); - function assert(val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } // Could use `inherits` module, but don't want to move from single file - // architecture yet. + for (var _len = arguments.length, lengths = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + lengths[_key - 1] = arguments[_key]; + } + if (lengths.length > 0 && !lengths.includes(b.length)) throw new TypeError("Expected Uint8Array of length ".concat(lengths, ", not of length=").concat(b.length)); + } + function hash(hash) { + if (typeof hash !== 'function' || typeof hash.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); + number$1(hash.outputLen); + number$1(hash.blockLen); + } + function exists(instance) { + var checkFinished = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); + } + function output(out, instance) { + bytes(out); + var min = instance.outputLen; - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least ".concat(min)); + } + } + var assert$1 = { + number: number$1, + bool: bool, + bytes: bytes, + hash: hash, + exists: exists, + output: output + }; + var assert$2 = assert$1; - var TempCtor = function TempCtor() {}; + var u32$1 = function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + }; // Cast array to view - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } // BN + var createView = function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + }; // The rotate right (circular right shift) operation for uint32 + var rotr = function rotr(word, shift) { + return word << 32 - shift | word >>> shift; + }; // big-endian hardware is rare. Just in case someone still decides to run hashes: + // early-throw an error because we don't support BE yet. - function BN(number, base, endian) { - if (BN.isBN(number)) { - return number; - } + var isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; + if (!isLE) throw new Error('Non little-endian hardware is not supported'); + Array.from({ + length: 256 + }, function (v, i) { + return i.toString(16).padStart(2, '0'); + }); - this.negative = 0; - this.words = null; - this.length = 0; // Reduction context + function utf8ToBytes(str) { + if (typeof str !== 'string') { + throw new TypeError("utf8ToBytes expected string, got ".concat(_typeof$1(str))); + } - this.red = null; + return new TextEncoder().encode(str); + } + function toBytes(data) { + if (typeof data === 'string') data = utf8ToBytes(data); + if (!(data instanceof Uint8Array)) throw new TypeError("Expected input type is Uint8Array (got ".concat(_typeof$1(data), ")")); + return data; + } - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + var Hash = /*#__PURE__*/function () { + function Hash() { + _classCallCheck(this, Hash); + } - this._init(number || 0, base || 10, endian || 'be'); - } + _createClass(Hash, [{ + key: "clone", + value: // Safe version that clones internal state + function clone() { + return this._cloneInto(); } + }]); - if (_typeof$1(module) === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } + return Hash; + }(); // Check if object doens't have custom constructor (like Uint8Array/Array) + function wrapConstructor(hashConstructor) { + var hashC = function hashC(message) { + return hashConstructor().update(toBytes(message)).digest(); + }; - BN.BN = BN; - BN.wordSize = 26; - var Buffer; + var tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require$$0$1.Buffer; - } - } catch (e) {} + hashC.create = function () { + return hashConstructor(); + }; - BN.isBN = function isBN(num) { - if (num instanceof BN) { - return true; - } + return hashC; + } + function wrapConstructorWithOpts(hashCons) { + var hashC = function hashC(msg, opts) { + return hashCons(opts).update(toBytes(msg)).digest(); + }; - return num !== null && _typeof$1(num) === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; + var tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; - BN.max = function max(left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + hashC.create = function (opts) { + return hashCons(opts); + }; - BN.min = function min(left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + return hashC; + } - BN.prototype._init = function init(number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); - if (_typeof$1(number) === 'object') { - return this._initArray(number, base, endian); - } + var _32n = BigInt(32); - if (base === 'hex') { - base = 16; - } + var _u32_max = BigInt(0xffffffff); - assert(base === (base | 0) && base >= 2 && base <= 36); - number = number.toString().replace(/\s+/g, ''); - var start = 0; + var wh = Number(value >> _32n & _u32_max); + var wl = Number(value & _u32_max); + var h = isLE ? 4 : 0; + var l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); + } // Base SHA2 class (RFC 6234) - if (number[0] === '-') { - start++; - this.negative = 1; - } - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); + var SHA2 = /*#__PURE__*/function (_Hash) { + _inherits(SHA2, _Hash); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; + var _super = _createSuper(SHA2); - BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } + function SHA2(blockLen, outputLen, padOffset, isLE) { + var _this; - if (number < 0x4000000) { - this.words = [number & 0x3ffffff]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + _classCallCheck(this, SHA2); - this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1]; - this.length = 3; - } + _this = _super.call(this); + _this.blockLen = blockLen; + _this.outputLen = outputLen; + _this.padOffset = padOffset; + _this.isLE = isLE; + _this.finished = false; + _this.length = 0; + _this.pos = 0; + _this.destroyed = false; + _this.buffer = new Uint8Array(blockLen); + _this.view = createView(_this.buffer); + return _this; + } - if (endian !== 'le') return; // Reverse the bytes + _createClass(SHA2, [{ + key: "update", + value: function update(data) { + assert$2.exists(this); + var view = this.view, + buffer = this.buffer, + blockLen = this.blockLen; + data = toBytes(data); + var len = data.length; - this._initArray(this.toArray(), base, endian); - }; + for (var pos = 0; pos < len;) { + var take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process - BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); + if (take === blockLen) { + var dataView = createView(data); - if (number.length <= 0) { - this.words = [0]; - this.length = 1; - return this; - } + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); + continue; + } - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } } - var j, w; - var off = 0; + this.length += data.length; + this.roundClean(); + return this; + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.exists(this); + assert$2.output(out, this); + this.finished = true; // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; - this.words[j] |= w << off & 0x3ffffff; - this.words[j + 1] = w >>> 26 - off & 0x3ffffff; - off += 24; + var buffer = this.buffer, + view = this.view, + blockLen = this.blockLen, + isLE = this.isLE; + var pos = this.pos; // append the bit '1' to the message - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; - this.words[j] |= w << off & 0x3ffffff; - this.words[j + 1] = w >>> 26 - off & 0x3ffffff; - off += 24; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (off >= 26) { - off -= 26; - j++; - } - } - } + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } // Pad until full block byte with zeros - return this._strip(); - }; - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); // '0' - '9' + for (var i = pos; i < blockLen; i++) buffer[i] = 0; // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. - if (c >= 48 && c <= 57) { - return c - 48; // 'A' - 'F' - } else if (c >= 65 && c <= 70) { - return c - 55; // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, 'Invalid character in ' + string); - } - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + var oview = createView(out); + var len = this.outputLen; // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } + if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); + var outLen = len / 4; + var state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); - return r; + for (var _i2 = 0; _i2 < outLen; _i2++) oview.setUint32(4 * _i2, state[_i2], isLE); } + }, { + key: "digest", + value: function digest() { + var buffer = this.buffer, + outputLen = this.outputLen; + this.digestInto(buffer); + var res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + var _to; - BN.prototype._parseHex = function _parseHex(number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } // 24-bits chunks - + to || (to = new this.constructor()); - var off = 0; - var j = 0; - var w; + (_to = to).set.apply(_to, _toConsumableArray(this.get())); - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; + var blockLen = this.blockLen, + buffer = this.buffer, + length = this.length, + finished = this.finished, + destroyed = this.destroyed, + pos = this.pos; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } + }]); - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; + return SHA2; + }(Hash); - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; + var U32_MASK64 = BigInt(Math.pow(2, 32) - 1); - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } + var _32n = BigInt(32); // We are not using BigUint64Array, because they are extremely slow as per 2022 - this._strip(); - }; - function parseBase(str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); + function fromBig(n) { + var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (le) return { + h: Number(n & U32_MASK64), + l: Number(n >> _32n & U32_MASK64) + }; + return { + h: Number(n >> _32n & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0 + }; + } + function split(lst) { + var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var Ah = new Uint32Array(lst.length); + var Al = new Uint32Array(lst.length); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - r *= mul; // 'a' + for (var i = 0; i < lst.length; i++) { + var _fromBig2 = fromBig(lst[i], le), + h = _fromBig2.h, + l = _fromBig2.l; - if (c >= 49) { - b = c - 49 + 0xa; // 'A' - } else if (c >= 17) { - b = c - 17 + 0xa; // '0' - '9' - } else { - b = c; - } + var _ref = [h, l]; + Ah[i] = _ref[0]; + Al[i] = _ref[1]; + } - assert(c >= 0 && b < mul, 'Invalid character'); - r += b; - } + return [Ah, Al]; + } + var toBig = function toBig(h, l) { + return BigInt(h >>> 0) << _32n | BigInt(l >>> 0); + }; // for Shift in [0, 32) - return r; - } + var shrSH = function shrSH(h, l, s) { + return h >>> s; + }; - BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [0]; - this.length = 1; // Find length of limb in base + var shrSL = function shrSL(h, l, s) { + return h << 32 - s | l >>> s; + }; // Right rotate for Shift in [1, 32) - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = limbPow / base | 0; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - var word = 0; + var rotrSH = function rotrSH(h, l, s) { + return h >>> s | l << 32 - s; + }; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); + var rotrSL = function rotrSL(h, l, s) { + return h << 32 - s | l >>> s; + }; // Right rotate for Shift in (32, 64), NOTE: 32 is special case. - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + var rotrBH = function rotrBH(h, l, s) { + return h << 64 - s | l >>> s - 32; + }; - for (i = 0; i < mod; i++) { - pow *= base; - } + var rotrBL = function rotrBL(h, l, s) { + return h >>> s - 32 | l << 64 - s; + }; // Right rotate for shift===32 (just swaps l&h) - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + var rotr32H = function rotr32H(h, l) { + return l; + }; - this._strip(); - }; + var rotr32L = function rotr32L(h, l) { + return h; + }; // Left rotate for Shift in [1, 32) - BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } + var rotlSH = function rotlSH(h, l, s) { + return h << s | l >>> 32 - s; + }; - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; + var rotlSL = function rotlSL(h, l, s) { + return l << s | h >>> 32 - s; + }; // Left rotate for Shift in (32, 64), NOTE: 32 is special case. - function move(dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; - } - BN.prototype._move = function _move(dest) { - move(dest, this); - }; + var rotlBH = function rotlBH(h, l, s) { + return l << s - 32 | h >>> 64 - s; + }; - BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; - }; + var rotlBL = function rotlBL(h, l, s) { + return h << s - 32 | l >>> 64 - s; + }; // JS uses 32-bit signed integers for bitwise operations which means we cannot + // simple take carry out of low bit sum by shift, we need to use division. + // Removing "export" has 5% perf penalty -_- - BN.prototype._expand = function _expand(size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; // Remove leading `0` from `this` + function add(Ah, Al, Bh, Bl) { + var l = (Al >>> 0) + (Bl >>> 0); + return { + h: Ah + Bh + (l / Math.pow(2, 32) | 0) | 0, + l: l | 0 + }; + } // Addition with more than 2 elements + var add3L = function add3L(Al, Bl, Cl) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); + }; - BN.prototype._strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } + var add3H = function add3H(low, Ah, Bh, Ch) { + return Ah + Bh + Ch + (low / Math.pow(2, 32) | 0) | 0; + }; - return this._normSign(); - }; + var add4L = function add4L(Al, Bl, Cl, Dl) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); + }; - BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } + var add4H = function add4H(low, Ah, Bh, Ch, Dh) { + return Ah + Bh + Ch + Dh + (low / Math.pow(2, 32) | 0) | 0; + }; - return this; - }; // Check Symbol.for because not everywhere where Symbol defined - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility + var add5L = function add5L(Al, Bl, Cl, Dl, El) { + return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); + }; + var add5H = function add5H(low, Ah, Bh, Ch, Dh, Eh) { + return Ah + Bh + Ch + Dh + Eh + (low / Math.pow(2, 32) | 0) | 0; + }; // prettier-ignore - if (typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function') { - try { - BN.prototype[Symbol["for"]('nodejs.util.inspect.custom')] = inspect; - } catch (e) { - BN.prototype.inspect = inspect; - } - } else { - BN.prototype.inspect = inspect; - } - function inspect() { - return (this.red ? ''; - } - /* - var zeros = []; - var groupSizes = []; - var groupBases = []; - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - */ + var u64$1 = { + fromBig: fromBig, + split: split, + toBig: toBig, + shrSH: shrSH, + shrSL: shrSL, + rotrSH: rotrSH, + rotrSL: rotrSL, + rotrBH: rotrBH, + rotrBL: rotrBL, + rotr32H: rotr32H, + rotr32L: rotr32L, + rotlSH: rotlSH, + rotlSL: rotlSL, + rotlBH: rotlBH, + rotlBL: rotlBL, + add: add, + add3L: add3L, + add3H: add3H, + add4L: add4L, + add4H: add4H, + add5H: add5H, + add5L: add5L + }; + var u64$2 = u64$1; + // prettier-ignore - var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000']; - var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; - var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + var _u64$split$1 = u64$2.split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(function (n) { + return BigInt(n); + })), + _u64$split2$1 = _slicedToArray(_u64$split$1, 2), + SHA512_Kh = _u64$split2$1[0], + SHA512_Kl = _u64$split2$1[1]; // Temporary buffer, not used to store anything between runs - BN.prototype.toString = function toString(base, padding) { - base = base || 10; - padding = padding | 0 || 1; - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; + var SHA512_W_H = new Uint32Array(80); + var SHA512_W_L = new Uint32Array(80); + var SHA512 = /*#__PURE__*/function (_SHA) { + _inherits(SHA512, _SHA); - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = ((w << off | carry) & 0xffffff).toString(16); - carry = w >>> 24 - off & 0xffffff; + var _super = _createSuper(SHA512); - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } + function SHA512() { + var _this; - off += 2; + _classCallCheck(this, SHA512); - if (off >= 26) { - off -= 26; - i--; - } - } + _this = _super.call(this, 128, 64, 16, false); // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits - if (carry !== 0) { - out = carry.toString(16) + out; - } + _this.Ah = 0x6a09e667 | 0; + _this.Al = 0xf3bcc908 | 0; + _this.Bh = 0xbb67ae85 | 0; + _this.Bl = 0x84caa73b | 0; + _this.Ch = 0x3c6ef372 | 0; + _this.Cl = 0xfe94f82b | 0; + _this.Dh = 0xa54ff53a | 0; + _this.Dl = 0x5f1d36f1 | 0; + _this.Eh = 0x510e527f | 0; + _this.El = 0xade682d1 | 0; + _this.Fh = 0x9b05688c | 0; + _this.Fl = 0x2b3e6c1f | 0; + _this.Gh = 0x1f83d9ab | 0; + _this.Gl = 0xfb41bd6b | 0; + _this.Hh = 0x5be0cd19 | 0; + _this.Hl = 0x137e2179 | 0; + return _this; + } // prettier-ignore - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } + _createClass(SHA512, [{ + key: "get", + value: function get() { + var Ah = this.Ah, + Al = this.Al, + Bh = this.Bh, + Bl = this.Bl, + Ch = this.Ch, + Cl = this.Cl, + Dh = this.Dh, + Dl = this.Dl, + Eh = this.Eh, + El = this.El, + Fh = this.Fh, + Fl = this.Fl, + Gh = this.Gh, + Gl = this.Gl, + Hh = this.Hh, + Hl = this.Hl; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } // prettier-ignore - return out; + }, { + key: "set", + value: function set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + }, { + key: "process", + value: function process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (var i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); } - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); + for (var _i2 = 16; _i2 < 80; _i2++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + var W15h = SHA512_W_H[_i2 - 15] | 0; + var W15l = SHA512_W_L[_i2 - 15] | 0; + var s0h = u64$2.rotrSH(W15h, W15l, 1) ^ u64$2.rotrSH(W15h, W15l, 8) ^ u64$2.shrSH(W15h, W15l, 7); + var s0l = u64$2.rotrSL(W15h, W15l, 1) ^ u64$2.rotrSL(W15h, W15l, 8) ^ u64$2.shrSL(W15h, W15l, 7); // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; + var W2h = SHA512_W_H[_i2 - 2] | 0; + var W2l = SHA512_W_L[_i2 - 2] | 0; + var s1h = u64$2.rotrSH(W2h, W2l, 19) ^ u64$2.rotrBH(W2h, W2l, 61) ^ u64$2.shrSH(W2h, W2l, 6); + var s1l = u64$2.rotrSL(W2h, W2l, 19) ^ u64$2.rotrBL(W2h, W2l, 61) ^ u64$2.shrSL(W2h, W2l, 6); // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - while (!c.isZero()) { - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); + var SUMl = u64$2.add4L(s0l, s1l, SHA512_W_L[_i2 - 7], SHA512_W_L[_i2 - 16]); + var SUMh = u64$2.add4H(SUMl, s0h, s1h, SHA512_W_H[_i2 - 7], SHA512_W_H[_i2 - 16]); + SHA512_W_H[_i2] = SUMh | 0; + SHA512_W_L[_i2] = SUMl | 0; + } - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } + var Ah = this.Ah, + Al = this.Al, + Bh = this.Bh, + Bl = this.Bl, + Ch = this.Ch, + Cl = this.Cl, + Dh = this.Dh, + Dl = this.Dl, + Eh = this.Eh, + El = this.El, + Fh = this.Fh, + Fl = this.Fl, + Gh = this.Gh, + Gl = this.Gl, + Hh = this.Hh, + Hl = this.Hl; // Compression function main loop, 80 rounds - if (this.isZero()) { - out = '0' + out; - } + for (var _i4 = 0; _i4 < 80; _i4++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + var sigma1h = u64$2.rotrSH(Eh, El, 14) ^ u64$2.rotrSH(Eh, El, 18) ^ u64$2.rotrBH(Eh, El, 41); + var sigma1l = u64$2.rotrSL(Eh, El, 14) ^ u64$2.rotrSL(Eh, El, 18) ^ u64$2.rotrBL(Eh, El, 41); //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - while (out.length % padding !== 0) { - out = '0' + out; - } + var CHIh = Eh & Fh ^ ~Eh & Gh; + var CHIl = El & Fl ^ ~El & Gl; // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore - if (this.negative !== 0) { - out = '-' + out; - } + var T1ll = u64$2.add5L(Hl, sigma1l, CHIl, SHA512_Kl[_i4], SHA512_W_L[_i4]); + var T1h = u64$2.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[_i4], SHA512_W_H[_i4]); + var T1l = T1ll | 0; // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) - return out; - } + var sigma0h = u64$2.rotrSH(Ah, Al, 28) ^ u64$2.rotrBH(Ah, Al, 34) ^ u64$2.rotrBH(Ah, Al, 39); + var sigma0l = u64$2.rotrSL(Ah, Al, 28) ^ u64$2.rotrBL(Ah, Al, 34) ^ u64$2.rotrBL(Ah, Al, 39); + var MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + var MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; - assert(false, 'Base should be between 2 and 36'); - }; + var _u64$add = u64$2.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0); - BN.prototype.toNumber = function toNumber() { - var ret = this.words[0]; + Eh = _u64$add.h; + El = _u64$add.l; + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + var All = u64$2.add3L(T1l, sigma0l, MAJl); + Ah = u64$2.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } // Add the compressed chunk to the current hash value - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + this.words[1] * 0x4000000; - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return this.negative !== 0 ? -ret : ret; - }; + var _u64$add2 = u64$2.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0); - BN.prototype.toJSON = function toJSON() { - return this.toString(16, 2); - }; + Ah = _u64$add2.h; + Al = _u64$add2.l; - if (Buffer) { - BN.prototype.toBuffer = function toBuffer(endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; - } + var _u64$add3 = u64$2.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0); - BN.prototype.toArray = function toArray(endian, length) { - return this.toArrayLike(Array, endian, length); - }; + Bh = _u64$add3.h; + Bl = _u64$add3.l; - var allocate = function allocate(ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); - } + var _u64$add4 = u64$2.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0); - return new ArrayType(size); - }; + Ch = _u64$add4.h; + Cl = _u64$add4.l; - BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { - this._strip(); + var _u64$add5 = u64$2.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0); - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - var res = allocate(ArrayType, reqLength); - var postfix = endian === 'le' ? 'LE' : 'BE'; - this['_toArrayLike' + postfix](res, byteLength); - return res; - }; + Dh = _u64$add5.h; + Dl = _u64$add5.l; - BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { - var position = 0; - var carry = 0; + var _u64$add6 = u64$2.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0); - for (var i = 0, shift = 0; i < this.length; i++) { - var word = this.words[i] << shift | carry; - res[position++] = word & 0xff; + Eh = _u64$add6.h; + El = _u64$add6.l; - if (position < res.length) { - res[position++] = word >> 8 & 0xff; - } + var _u64$add7 = u64$2.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0); - if (position < res.length) { - res[position++] = word >> 16 & 0xff; - } + Fh = _u64$add7.h; + Fl = _u64$add7.l; - if (shift === 6) { - if (position < res.length) { - res[position++] = word >> 24 & 0xff; - } + var _u64$add8 = u64$2.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0); - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } + Gh = _u64$add8.h; + Gl = _u64$add8.l; - if (position < res.length) { - res[position++] = carry; + var _u64$add9 = u64$2.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0); - while (position < res.length) { - res[position++] = 0; - } - } - }; + Hh = _u64$add9.h; + Hl = _u64$add9.l; + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + }, { + key: "roundClean", + value: function roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + }, { + key: "destroy", + value: function destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + }]); - BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { - var position = res.length - 1; - var carry = 0; + return SHA512; + }(SHA2); - for (var i = 0, shift = 0; i < this.length; i++) { - var word = this.words[i] << shift | carry; - res[position--] = word & 0xff; + var SHA512_224 = /*#__PURE__*/function (_SHA2) { + _inherits(SHA512_224, _SHA2); - if (position >= 0) { - res[position--] = word >> 8 & 0xff; - } + var _super2 = _createSuper(SHA512_224); - if (position >= 0) { - res[position--] = word >> 16 & 0xff; - } + function SHA512_224() { + var _this2; - if (shift === 6) { - if (position >= 0) { - res[position--] = word >> 24 & 0xff; - } + _classCallCheck(this, SHA512_224); - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } + _this2 = _super2.call(this); // h -- high 32 bits, l -- low 32 bits - if (position >= 0) { - res[position--] = carry; + _this2.Ah = 0x8c3d37c8 | 0; + _this2.Al = 0x19544da2 | 0; + _this2.Bh = 0x73e19966 | 0; + _this2.Bl = 0x89dcd4d6 | 0; + _this2.Ch = 0x1dfab7ae | 0; + _this2.Cl = 0x32ff9c82 | 0; + _this2.Dh = 0x679dd514 | 0; + _this2.Dl = 0x582f9fcf | 0; + _this2.Eh = 0x0f6d2b69 | 0; + _this2.El = 0x7bd44da8 | 0; + _this2.Fh = 0x77e36f73 | 0; + _this2.Fl = 0x04c48942 | 0; + _this2.Gh = 0x3f9d85a8 | 0; + _this2.Gl = 0x6a1d36c8 | 0; + _this2.Hh = 0x1112e6ad | 0; + _this2.Hl = 0x91d692a1 | 0; + _this2.outputLen = 28; + return _this2; + } - while (position >= 0) { - res[position--] = 0; - } - } - }; + return _createClass(SHA512_224); + }(SHA512); - if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; + var SHA512_256 = /*#__PURE__*/function (_SHA3) { + _inherits(SHA512_256, _SHA3); - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } + var _super3 = _createSuper(SHA512_256); - if (t >= 0x40) { - r += 7; - t >>>= 7; - } + function SHA512_256() { + var _this3; - if (t >= 0x8) { - r += 4; - t >>>= 4; - } + _classCallCheck(this, SHA512_256); - if (t >= 0x02) { - r += 2; - t >>>= 2; - } + _this3 = _super3.call(this); // h -- high 32 bits, l -- low 32 bits - return r + t; - }; - } + _this3.Ah = 0x22312194 | 0; + _this3.Al = 0xfc2bf72c | 0; + _this3.Bh = 0x9f555fa3 | 0; + _this3.Bl = 0xc84c64c2 | 0; + _this3.Ch = 0x2393b86b | 0; + _this3.Cl = 0x6f53b151 | 0; + _this3.Dh = 0x96387719 | 0; + _this3.Dl = 0x5940eabd | 0; + _this3.Eh = 0x96283ee2 | 0; + _this3.El = 0xa88effe3 | 0; + _this3.Fh = 0xbe5e1e25 | 0; + _this3.Fl = 0x53863992 | 0; + _this3.Gh = 0x2b0199fc | 0; + _this3.Gl = 0x2c85b8aa | 0; + _this3.Hh = 0x0eb72ddc | 0; + _this3.Hl = 0x81c52ca2 | 0; + _this3.outputLen = 32; + return _this3; + } - BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) return 26; - var t = w; - var r = 0; + return _createClass(SHA512_256); + }(SHA512); - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } + var SHA384 = /*#__PURE__*/function (_SHA4) { + _inherits(SHA384, _SHA4); - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } + var _super4 = _createSuper(SHA384); - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } + function SHA384() { + var _this4; - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } + _classCallCheck(this, SHA384); - if ((t & 0x1) === 0) { - r++; - } - - return r; - }; // Return number of used bits in a BN + _this4 = _super4.call(this); // h -- high 32 bits, l -- low 32 bits + _this4.Ah = 0xcbbb9d5d | 0; + _this4.Al = 0xc1059ed8 | 0; + _this4.Bh = 0x629a292a | 0; + _this4.Bl = 0x367cd507 | 0; + _this4.Ch = 0x9159015a | 0; + _this4.Cl = 0x3070dd17 | 0; + _this4.Dh = 0x152fecd8 | 0; + _this4.Dl = 0xf70e5939 | 0; + _this4.Eh = 0x67332667 | 0; + _this4.El = 0xffc00b31 | 0; + _this4.Fh = 0x8eb44a87 | 0; + _this4.Fl = 0x68581511 | 0; + _this4.Gh = 0xdb0c2e0d | 0; + _this4.Gl = 0x64f98fa7 | 0; + _this4.Hh = 0x47b5481d | 0; + _this4.Hl = 0xbefa4fa4 | 0; + _this4.outputLen = 48; + return _this4; + } - BN.prototype.bitLength = function bitLength() { - var w = this.words[this.length - 1]; + return _createClass(SHA384); + }(SHA512); - var hi = this._countBits(w); + var sha512 = wrapConstructor(function () { + return new SHA512(); + }); + wrapConstructor(function () { + return new SHA512_224(); + }); + wrapConstructor(function () { + return new SHA512_256(); + }); + wrapConstructor(function () { + return new SHA384(); + }); - return (this.length - 1) * 26 + hi; - }; + var _polyfillNode_crypto = {}; - function toBitArray(num) { - var w = new Array(num.bitLength()); + var nodeCrypto = _global$1.crypto; - for (var bit = 0; bit < w.length; bit++) { - var off = bit / 26 | 0; - var wbit = bit % 26; - w[bit] = num.words[off] >>> wbit & 0x01; - } + var _0n$2 = BigInt(0); - return w; - } // Number of trailing zero bits + var _1n$2 = BigInt(1); + var _2n$2 = BigInt(2); - BN.prototype.zeroBits = function zeroBits() { - if (this.isZero()) return 0; - var r = 0; + var _8n$1 = BigInt(8); - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); + var CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'); + var CURVE$1 = Object.freeze({ + a: BigInt(-1), + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'), + l: CU_O, + n: CU_O, + h: BigInt(8), + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960') + }); + var POW_2_256$1 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); + var SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); + BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742'); + var SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); + var INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); + var ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); + var D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); - r += b; - if (b !== 26) break; - } + var ExtendedPoint = /*#__PURE__*/function () { + function ExtendedPoint(x, y, z, t) { + _classCallCheck(this, ExtendedPoint); - return r; - }; + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } - BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); - }; + _createClass(ExtendedPoint, [{ + key: "equals", + value: function equals(other) { + assertExtPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + var X1Z2 = mod$1(X1 * Z2); + var X2Z1 = mod$1(X2 * Z1); + var Y1Z2 = mod$1(Y1 * Z2); + var Y2Z1 = mod$1(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + }, { + key: "negate", + value: function negate() { + return new ExtendedPoint(mod$1(-this.x), this.y, this.z, mod$1(-this.t)); + } + }, { + key: "double", + value: function double() { + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var a = CURVE$1.a; + var A = mod$1(X1 * X1); + var B = mod$1(Y1 * Y1); + var C = mod$1(_2n$2 * mod$1(Z1 * Z1)); + var D = mod$1(a * A); + var x1y1 = X1 + Y1; + var E = mod$1(mod$1(x1y1 * x1y1) - A - B); + var G = D + B; + var F = G - C; + var H = D - B; + var X3 = mod$1(E * F); + var Y3 = mod$1(G * H); + var T3 = mod$1(E * H); + var Z3 = mod$1(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + }, { + key: "add", + value: function add(other) { + assertExtPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z, + T1 = this.t; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z, + T2 = other.t; + var A = mod$1((Y1 - X1) * (Y2 + X2)); + var B = mod$1((Y1 + X1) * (Y2 - X2)); + var F = mod$1(B - A); + if (F === _0n$2) return this["double"](); + var C = mod$1(Z1 * _2n$2 * T2); + var D = mod$1(T1 * _2n$2 * Z2); + var E = D + C; + var G = B + A; + var H = D - C; + var X3 = mod$1(E * F); + var Y3 = mod$1(G * H); + var T3 = mod$1(E * H); + var Z3 = mod$1(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "precomputeWindow", + value: function precomputeWindow(W) { + var windows = 1 + 256 / W; + var points = []; + var p = this; + var base = p; - BN.prototype.toTwos = function toTwos(width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } + for (var window = 0; window < windows; window++) { + base = p; + points.push(base); - return this.clone(); - }; + for (var i = 1; i < Math.pow(2, W - 1); i++) { + base = base.add(p); + points.push(base); + } - BN.prototype.fromTwos = function fromTwos(width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + p = base["double"](); } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg() { - return this.negative !== 0; - }; // Return negative clone of `this` - - - BN.prototype.neg = function neg() { - return this.clone().ineg(); - }; + return points; + } + }, { + key: "wNAF", + value: function wNAF(n, affinePoint) { + if (!affinePoint && this.equals(ExtendedPoint.BASE)) affinePoint = Point$1.BASE; + var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - BN.prototype.ineg = function ineg() { - if (!this.isZero()) { - this.negative ^= 1; + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); } - return this; - }; // Or `num` with `this` in-place - + var precomputes = affinePoint && pointPrecomputes$1.get(affinePoint); - BN.prototype.iuor = function iuor(num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + if (!precomputes) { + precomputes = this.precomputeWindow(W); - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + if (affinePoint && W !== 1) { + precomputes = ExtendedPoint.normalizeZ(precomputes); + pointPrecomputes$1.set(affinePoint, precomputes); + } } - return this._strip(); - }; - - BN.prototype.ior = function ior(num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; // Or `num` with `this` - - - BN.prototype.or = function or(num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor(num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; // And `num` with `this` in-place + var p = ExtendedPoint.ZERO; + var f = ExtendedPoint.BASE; + var windows = 1 + 256 / W; + var windowSize = Math.pow(2, W - 1); + var mask = BigInt(Math.pow(2, W) - 1); + var maxNumber = Math.pow(2, W); + var shiftBy = BigInt(W); + for (var window = 0; window < windows; window++) { + var offset = window * windowSize; + var wbits = Number(n & mask); + n >>= shiftBy; - BN.prototype.iuand = function iuand(num) { - // b = min-length(num, this) - var b; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$2; + } - if (this.length > num.length) { - b = num; - } else { - b = this; - } + var offset1 = offset; + var offset2 = offset + Math.abs(wbits) - 1; + var cond1 = window % 2 !== 0; + var cond2 = wbits < 0; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + if (wbits === 0) { + f = f.add(constTimeNegate$1(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate$1(cond2, precomputes[offset2])); + } } - this.length = b.length; - return this._strip(); - }; - - BN.prototype.iand = function iand(num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; // And `num` with `this` - - - BN.prototype.and = function and(num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand(num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; // Xor `num` with `this` in-place - - - BN.prototype.iuxor = function iuxor(num) { - // a.length > b.length - var a; - var b; - - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return ExtendedPoint.normalizeZ([p, f])[0]; + } + }, { + key: "multiply", + value: function multiply(scalar, affinePoint) { + return this.wNAF(normalizeScalar$1(scalar, CURVE$1.l), affinePoint); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + var n = normalizeScalar$1(scalar, CURVE$1.l, false); + var G = ExtendedPoint.BASE; + var P0 = ExtendedPoint.ZERO; + if (n === _0n$2) return P0; + if (this.equals(P0) || n === _1n$2) return this; + if (this.equals(G)) return this.wNAF(n); + var p = P0; + var d = this; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + while (n > _0n$2) { + if (n & _1n$2) p = p.add(d); + d = d["double"](); + n >>= _1n$2; } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + return p; + } + }, { + key: "isSmallOrder", + value: function isSmallOrder() { + return this.multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); + } + }, { + key: "isTorsionFree", + value: function isTorsionFree() { + var p = this.multiplyUnsafe(CURVE$1.l / _2n$2)["double"](); + if (CURVE$1.l % _2n$2) p = p.add(this); + return p.equals(ExtendedPoint.ZERO); + } + }, { + key: "toAffine", + value: function toAffine(invZ) { + var x = this.x, + y = this.y, + z = this.z; + var is0 = this.equals(ExtendedPoint.ZERO); + if (invZ == null) invZ = is0 ? _8n$1 : invert$1(z); + var ax = mod$1(x * invZ); + var ay = mod$1(y * invZ); + var zz = mod$1(z * invZ); + if (is0) return Point$1.ZERO; + if (zz !== _1n$2) throw new Error('invZ was invalid'); + return new Point$1(ax, ay); + } + }, { + key: "fromRistrettoBytes", + value: function fromRistrettoBytes() { + legacyRist(); + } + }, { + key: "toRistrettoBytes", + value: function toRistrettoBytes() { + legacyRist(); + } + }, { + key: "fromRistrettoHash", + value: function fromRistrettoHash() { + legacyRist(); + } + }], [{ + key: "fromAffine", + value: function fromAffine(p) { + if (!(p instanceof Point$1)) { + throw new TypeError('ExtendedPoint#fromAffine: expected Point'); } - this.length = a.length; - return this._strip(); - }; - - BN.prototype.ixor = function ixor(num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; // Xor `num` with `this` - - - BN.prototype.xor = function xor(num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor(num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; // Not ``this`` with ``width`` bitwidth - + if (p.equals(Point$1.ZERO)) return ExtendedPoint.ZERO; + return new ExtendedPoint(p.x, p.y, _1n$2, mod$1(p.x * p.y)); + } + }, { + key: "toAffineBatch", + value: function toAffineBatch(points) { + var toInv = invertBatch$1(points.map(function (p) { + return p.z; + })); + return points.map(function (p, i) { + return p.toAffine(toInv[i]); + }); + } + }, { + key: "normalizeZ", + value: function normalizeZ(points) { + return this.toAffineBatch(points).map(this.fromAffine); + } + }]); - BN.prototype.inotn = function inotn(width) { - assert(typeof width === 'number' && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; // Extend the buffer with leading zeroes + return ExtendedPoint; + }(); - this._expand(bytesNeeded); + ExtendedPoint.BASE = new ExtendedPoint(CURVE$1.Gx, CURVE$1.Gy, _1n$2, mod$1(CURVE$1.Gx * CURVE$1.Gy)); + ExtendedPoint.ZERO = new ExtendedPoint(_0n$2, _1n$2, _1n$2, _0n$2); - if (bitsLeft > 0) { - bytesNeeded--; - } // Handle complete words + function constTimeNegate$1(condition, item) { + var neg = item.negate(); + return condition ? neg : item; + } + function assertExtPoint(other) { + if (!(other instanceof ExtendedPoint)) throw new TypeError('ExtendedPoint expected'); + } - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } // Handle the residue + function assertRstPoint(other) { + if (!(other instanceof RistrettoPoint)) throw new TypeError('RistrettoPoint expected'); + } + function legacyRist() { + throw new Error('Legacy method: switch to RistrettoPoint'); + } - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft; - } // And remove leading zeroes + var RistrettoPoint = /*#__PURE__*/function () { + function RistrettoPoint(ep) { + _classCallCheck(this, RistrettoPoint); + this.ep = ep; + } - return this._strip(); - }; + _createClass(RistrettoPoint, [{ + key: "toRawBytes", + value: function toRawBytes() { + var _this$ep = this.ep, + x = _this$ep.x, + y = _this$ep.y, + z = _this$ep.z, + t = _this$ep.t; + var u1 = mod$1(mod$1(z + y) * mod$1(z - y)); + var u2 = mod$1(x * y); + var u2sq = mod$1(u2 * u2); - BN.prototype.notn = function notn(width) { - return this.clone().inotn(width); - }; // Set `bit` of `this` + var _invertSqrt = invertSqrt(mod$1(u1 * u2sq)), + invsqrt = _invertSqrt.value; + var D1 = mod$1(invsqrt * u1); + var D2 = mod$1(invsqrt * u2); + var zInv = mod$1(D1 * D2 * t); + var D; - BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === 'number' && bit >= 0); - var off = bit / 26 | 0; - var wbit = bit % 26; + if (edIsNegative(t * zInv)) { + var _x = mod$1(y * SQRT_M1); - this._expand(off + 1); + var _y = mod$1(x * SQRT_M1); - if (val) { - this.words[off] = this.words[off] | 1 << wbit; + x = _x; + y = _y; + D = mod$1(D1 * INVSQRT_A_MINUS_D); } else { - this.words[off] = this.words[off] & ~(1 << wbit); + D = D2; } - return this._strip(); - }; // Add `num` to `this` in-place - - - BN.prototype.iadd = function iadd(num) { - var r; // negative + positive - - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } // a.length > b.length + if (edIsNegative(x * zInv)) y = mod$1(-y); + var s = mod$1((z - y) * D); + if (edIsNegative(s)) s = mod$1(-s); + return numberTo32BytesLE(s); + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }, { + key: "toString", + value: function toString() { + return this.toHex(); + } + }, { + key: "equals", + value: function equals(other) { + assertRstPoint(other); + var a = this.ep; + var b = other.ep; + var one = mod$1(a.x * b.y) === mod$1(a.y * b.x); + var two = mod$1(a.y * b.y) === mod$1(a.x * b.x); + return one || two; + } + }, { + key: "add", + value: function add(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.add(other.ep)); + } + }, { + key: "subtract", + value: function subtract(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.subtract(other.ep)); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return new RistrettoPoint(this.ep.multiply(scalar)); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + return new RistrettoPoint(this.ep.multiplyUnsafe(scalar)); + } + }], [{ + key: "calcElligatorRistrettoMap", + value: function calcElligatorRistrettoMap(r0) { + var d = CURVE$1.d; + var r = mod$1(SQRT_M1 * r0 * r0); + var Ns = mod$1((r + _1n$2) * ONE_MINUS_D_SQ); + var c = BigInt(-1); + var D = mod$1((c - d * r) * mod$1(r + d)); + var _uvRatio = uvRatio(Ns, D), + Ns_D_is_sq = _uvRatio.isValid, + s = _uvRatio.value; - var a, b; + var s_ = mod$1(s * r0); + if (!edIsNegative(s_)) s_ = mod$1(-s_); + if (!Ns_D_is_sq) s = s_; + if (!Ns_D_is_sq) c = r; + var Nt = mod$1(c * (r - _1n$2) * D_MINUS_ONE_SQ - D); + var s2 = s * s; + var W0 = mod$1((s + s) * D); + var W1 = mod$1(Nt * SQRT_AD_MINUS_ONE); + var W2 = mod$1(_1n$2 - s2); + var W3 = mod$1(_1n$2 + s2); + return new ExtendedPoint(mod$1(W0 * W3), mod$1(W2 * W1), mod$1(W1 * W3), mod$1(W0 * W2)); + } + }, { + key: "hashToCurve", + value: function hashToCurve(hex) { + hex = ensureBytes$1(hex, 64); + var r1 = bytes255ToNumberLE(hex.slice(0, 32)); + var R1 = this.calcElligatorRistrettoMap(r1); + var r2 = bytes255ToNumberLE(hex.slice(32, 64)); + var R2 = this.calcElligatorRistrettoMap(r2); + return new RistrettoPoint(R1.add(R2)); + } + }, { + key: "fromHex", + value: function fromHex(hex) { + hex = ensureBytes$1(hex, 32); + var a = CURVE$1.a, + d = CURVE$1.d; + var emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + var s = bytes255ToNumberLE(hex); + if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s)) throw new Error(emsg); + var s2 = mod$1(s * s); + var u1 = mod$1(_1n$2 + a * s2); + var u2 = mod$1(_1n$2 - a * s2); + var u1_2 = mod$1(u1 * u1); + var u2_2 = mod$1(u2 * u2); + var v = mod$1(a * d * u1_2 - u2_2); - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + var _invertSqrt2 = invertSqrt(mod$1(v * u2_2)), + isValid = _invertSqrt2.isValid, + I = _invertSqrt2.value; - var carry = 0; + var Dx = mod$1(I * u2); + var Dy = mod$1(I * Dx * v); + var x = mod$1((s + s) * Dx); + if (edIsNegative(x)) x = mod$1(-x); + var y = mod$1(u1 * Dy); + var t = mod$1(x * y); + if (!isValid || edIsNegative(t) || y === _0n$2) throw new Error(emsg); + return new RistrettoPoint(new ExtendedPoint(x, y, _1n$2, t)); + } + }]); - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } + return RistrettoPoint; + }(); - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } + RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE); + RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO); + var pointPrecomputes$1 = new WeakMap(); - this.length = a.length; + var Point$1 = /*#__PURE__*/function () { + function Point(x, y) { + _classCallCheck(this, Point); - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + this.x = x; + this.y = y; + } + + _createClass(Point, [{ + key: "_setWindowSize", + value: function _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes$1["delete"](this); + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var bytes = numberTo32BytesLE(this.y); + bytes[31] |= this.x & _1n$2 ? 0x80 : 0; + return bytes; + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }, { + key: "toX25519", + value: function toX25519() { + var y = this.y; + var u = mod$1((_1n$2 + y) * invert$1(_1n$2 - y)); + return numberTo32BytesLE(u); + } + }, { + key: "isTorsionFree", + value: function isTorsionFree() { + return ExtendedPoint.fromAffine(this).isTorsionFree(); + } + }, { + key: "equals", + value: function equals(other) { + return this.x === other.x && this.y === other.y; + } + }, { + key: "negate", + value: function negate() { + return new Point(mod$1(-this.x), this.y); + } + }, { + key: "add", + value: function add(other) { + return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine(); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + }], [{ + key: "fromHex", + value: function fromHex(hex) { + var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var d = CURVE$1.d, + P = CURVE$1.P; + hex = ensureBytes$1(hex, 32); + var normed = hex.slice(); + normed[31] = hex[31] & ~0x80; + var y = bytesToNumberLE(normed); + if (strict && y >= P) throw new Error('Expected 0 < hex < P'); + if (!strict && y >= POW_2_256$1) throw new Error('Expected 0 < hex < 2**256'); + var y2 = mod$1(y * y); + var u = mod$1(y2 - _1n$2); + var v = mod$1(d * y2 + _1n$2); + + var _uvRatio2 = uvRatio(u, v), + isValid = _uvRatio2.isValid, + x = _uvRatio2.value; + + if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); + var isXOdd = (x & _1n$2) === _1n$2; + var isLastByteOdd = (hex[31] & 0x80) !== 0; + + if (isLastByteOdd !== isXOdd) { + x = mod$1(-x); } - return this; - }; // Add `num` to `this` + return new Point(x, y); + } + }, { + key: "fromPrivateKey", + value: function () { + var _fromPrivateKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(privateKey) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return getExtendedPublicKey(privateKey); + case 2: + return _context.abrupt("return", _context.sent.point); - BN.prototype.add = function add(num) { - var res; + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; + function fromPrivateKey(_x2) { + return _fromPrivateKey.apply(this, arguments); } - if (this.length > num.length) return this.clone().iadd(num); - return num.clone().iadd(this); - }; // Subtract `num` from `this` in-place + return fromPrivateKey; + }() + }]); + return Point; + }(); - BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } // At this point both numbers are positive + Point$1.BASE = new Point$1(CURVE$1.Gx, CURVE$1.Gy); + Point$1.ZERO = new Point$1(_0n$2, _1n$2); + var Signature$1 = /*#__PURE__*/function () { + function Signature(r, s) { + _classCallCheck(this, Signature); - var cmp = this.cmp(num); // Optimization - zeroify + this.r = r; + this.s = s; + this.assertValidity(); + } - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } // a > b + _createClass(Signature, [{ + key: "assertValidity", + value: function assertValidity() { + var r = this.r, + s = this.s; + if (!(r instanceof Point$1)) throw new Error('Expected Point instance'); + normalizeScalar$1(s, CURVE$1.l, false); + return this; + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var u8 = new Uint8Array(64); + u8.set(this.r.toRawBytes()); + u8.set(numberTo32BytesLE(this.s), 32); + return u8; + } + }, { + key: "toHex", + value: function toHex() { + return bytesToHex$1(this.toRawBytes()); + } + }], [{ + key: "fromHex", + value: function fromHex(hex) { + var bytes = ensureBytes$1(hex, 64); + var r = Point$1.fromHex(bytes.slice(0, 32), false); + var s = bytesToNumberLE(bytes.slice(32, 64)); + return new Signature(r, s); + } + }]); + return Signature; + }(); - var a, b; + function concatBytes$1() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; + } - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + if (!arrays.every(function (a) { + return a instanceof Uint8Array; + })) throw new Error('Expected Uint8Array list'); + if (arrays.length === 1) return arrays[0]; + var length = arrays.reduce(function (a, arr) { + return a + arr.length; + }, 0); + var result = new Uint8Array(length); - var carry = 0; + for (var i = 0, pad = 0; i < arrays.length; i++) { + var arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } + return result; + } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } // Copy rest of the words + var hexes$1 = Array.from({ + length: 256 + }, function (v, i) { + return i.toString(16).padStart(2, '0'); + }); + function bytesToHex$1(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); + var hex = ''; - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + for (var i = 0; i < uint8a.length; i++) { + hex += hexes$1[uint8a[i]]; + } - this.length = Math.max(this.length, i); + return hex; + } - if (a !== this) { - this.negative = 1; - } + function hexToBytes$1(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); + } - return this._strip(); - }; // Subtract `num` from `this` + if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); + var array = new Uint8Array(hex.length / 2); + for (var i = 0; i < array.length; i++) { + var j = i * 2; + var hexByte = hex.slice(j, j + 2); - BN.prototype.sub = function sub(num) { - return this.clone().isub(num); - }; + var _byte = Number.parseInt(hexByte, 16); - function smallMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - var len = self.length + num.length | 0; - out.length = len; - len = len - 1 | 0; // Peel one iteration (compiler can't do it, because of code complexity) + if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); + array[i] = _byte; + } - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - var lo = r & 0x3ffffff; - var carry = r / 0x4000000 | 0; - out.words[0] = lo; + return array; + } - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); + function numberTo32BytesBE(num) { + var length = 32; + var hex = num.toString(16).padStart(length * 2, '0'); + return hexToBytes$1(hex); + } - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += r / 0x4000000 | 0; - rword = r & 0x3ffffff; - } + function numberTo32BytesLE(num) { + return numberTo32BytesBE(num).reverse(); + } - out.words[k] = rword | 0; - carry = ncarry | 0; - } + function edIsNegative(num) { + return (mod$1(num) & _1n$2) === _1n$2; + } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } + function bytesToNumberLE(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + return BigInt('0x' + bytesToHex$1(Uint8Array.from(uint8a).reverse())); + } - return out._strip(); - } // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). + var MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + function bytes255ToNumberLE(bytes) { + return mod$1(bytesToNumberLE(bytes) & MAX_255B); + } - var comb10MulTo = function comb10MulTo(self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = mid + Math.imul(ah0, bl0) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = mid + Math.imul(ah1, bl0) | 0; - hi = Math.imul(ah1, bh0); - lo = lo + Math.imul(al0, bl1) | 0; - mid = mid + Math.imul(al0, bh1) | 0; - mid = mid + Math.imul(ah0, bl1) | 0; - hi = hi + Math.imul(ah0, bh1) | 0; - var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = mid + Math.imul(ah2, bl0) | 0; - hi = Math.imul(ah2, bh0); - lo = lo + Math.imul(al1, bl1) | 0; - mid = mid + Math.imul(al1, bh1) | 0; - mid = mid + Math.imul(ah1, bl1) | 0; - hi = hi + Math.imul(ah1, bh1) | 0; - lo = lo + Math.imul(al0, bl2) | 0; - mid = mid + Math.imul(al0, bh2) | 0; - mid = mid + Math.imul(ah0, bl2) | 0; - hi = hi + Math.imul(ah0, bh2) | 0; - var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = mid + Math.imul(ah3, bl0) | 0; - hi = Math.imul(ah3, bh0); - lo = lo + Math.imul(al2, bl1) | 0; - mid = mid + Math.imul(al2, bh1) | 0; - mid = mid + Math.imul(ah2, bl1) | 0; - hi = hi + Math.imul(ah2, bh1) | 0; - lo = lo + Math.imul(al1, bl2) | 0; - mid = mid + Math.imul(al1, bh2) | 0; - mid = mid + Math.imul(ah1, bl2) | 0; - hi = hi + Math.imul(ah1, bh2) | 0; - lo = lo + Math.imul(al0, bl3) | 0; - mid = mid + Math.imul(al0, bh3) | 0; - mid = mid + Math.imul(ah0, bl3) | 0; - hi = hi + Math.imul(ah0, bh3) | 0; - var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = mid + Math.imul(ah4, bl0) | 0; - hi = Math.imul(ah4, bh0); - lo = lo + Math.imul(al3, bl1) | 0; - mid = mid + Math.imul(al3, bh1) | 0; - mid = mid + Math.imul(ah3, bl1) | 0; - hi = hi + Math.imul(ah3, bh1) | 0; - lo = lo + Math.imul(al2, bl2) | 0; - mid = mid + Math.imul(al2, bh2) | 0; - mid = mid + Math.imul(ah2, bl2) | 0; - hi = hi + Math.imul(ah2, bh2) | 0; - lo = lo + Math.imul(al1, bl3) | 0; - mid = mid + Math.imul(al1, bh3) | 0; - mid = mid + Math.imul(ah1, bl3) | 0; - hi = hi + Math.imul(ah1, bh3) | 0; - lo = lo + Math.imul(al0, bl4) | 0; - mid = mid + Math.imul(al0, bh4) | 0; - mid = mid + Math.imul(ah0, bl4) | 0; - hi = hi + Math.imul(ah0, bh4) | 0; - var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = mid + Math.imul(ah5, bl0) | 0; - hi = Math.imul(ah5, bh0); - lo = lo + Math.imul(al4, bl1) | 0; - mid = mid + Math.imul(al4, bh1) | 0; - mid = mid + Math.imul(ah4, bl1) | 0; - hi = hi + Math.imul(ah4, bh1) | 0; - lo = lo + Math.imul(al3, bl2) | 0; - mid = mid + Math.imul(al3, bh2) | 0; - mid = mid + Math.imul(ah3, bl2) | 0; - hi = hi + Math.imul(ah3, bh2) | 0; - lo = lo + Math.imul(al2, bl3) | 0; - mid = mid + Math.imul(al2, bh3) | 0; - mid = mid + Math.imul(ah2, bl3) | 0; - hi = hi + Math.imul(ah2, bh3) | 0; - lo = lo + Math.imul(al1, bl4) | 0; - mid = mid + Math.imul(al1, bh4) | 0; - mid = mid + Math.imul(ah1, bl4) | 0; - hi = hi + Math.imul(ah1, bh4) | 0; - lo = lo + Math.imul(al0, bl5) | 0; - mid = mid + Math.imul(al0, bh5) | 0; - mid = mid + Math.imul(ah0, bl5) | 0; - hi = hi + Math.imul(ah0, bh5) | 0; - var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = mid + Math.imul(ah6, bl0) | 0; - hi = Math.imul(ah6, bh0); - lo = lo + Math.imul(al5, bl1) | 0; - mid = mid + Math.imul(al5, bh1) | 0; - mid = mid + Math.imul(ah5, bl1) | 0; - hi = hi + Math.imul(ah5, bh1) | 0; - lo = lo + Math.imul(al4, bl2) | 0; - mid = mid + Math.imul(al4, bh2) | 0; - mid = mid + Math.imul(ah4, bl2) | 0; - hi = hi + Math.imul(ah4, bh2) | 0; - lo = lo + Math.imul(al3, bl3) | 0; - mid = mid + Math.imul(al3, bh3) | 0; - mid = mid + Math.imul(ah3, bl3) | 0; - hi = hi + Math.imul(ah3, bh3) | 0; - lo = lo + Math.imul(al2, bl4) | 0; - mid = mid + Math.imul(al2, bh4) | 0; - mid = mid + Math.imul(ah2, bl4) | 0; - hi = hi + Math.imul(ah2, bh4) | 0; - lo = lo + Math.imul(al1, bl5) | 0; - mid = mid + Math.imul(al1, bh5) | 0; - mid = mid + Math.imul(ah1, bl5) | 0; - hi = hi + Math.imul(ah1, bh5) | 0; - lo = lo + Math.imul(al0, bl6) | 0; - mid = mid + Math.imul(al0, bh6) | 0; - mid = mid + Math.imul(ah0, bl6) | 0; - hi = hi + Math.imul(ah0, bh6) | 0; - var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = mid + Math.imul(ah7, bl0) | 0; - hi = Math.imul(ah7, bh0); - lo = lo + Math.imul(al6, bl1) | 0; - mid = mid + Math.imul(al6, bh1) | 0; - mid = mid + Math.imul(ah6, bl1) | 0; - hi = hi + Math.imul(ah6, bh1) | 0; - lo = lo + Math.imul(al5, bl2) | 0; - mid = mid + Math.imul(al5, bh2) | 0; - mid = mid + Math.imul(ah5, bl2) | 0; - hi = hi + Math.imul(ah5, bh2) | 0; - lo = lo + Math.imul(al4, bl3) | 0; - mid = mid + Math.imul(al4, bh3) | 0; - mid = mid + Math.imul(ah4, bl3) | 0; - hi = hi + Math.imul(ah4, bh3) | 0; - lo = lo + Math.imul(al3, bl4) | 0; - mid = mid + Math.imul(al3, bh4) | 0; - mid = mid + Math.imul(ah3, bl4) | 0; - hi = hi + Math.imul(ah3, bh4) | 0; - lo = lo + Math.imul(al2, bl5) | 0; - mid = mid + Math.imul(al2, bh5) | 0; - mid = mid + Math.imul(ah2, bl5) | 0; - hi = hi + Math.imul(ah2, bh5) | 0; - lo = lo + Math.imul(al1, bl6) | 0; - mid = mid + Math.imul(al1, bh6) | 0; - mid = mid + Math.imul(ah1, bl6) | 0; - hi = hi + Math.imul(ah1, bh6) | 0; - lo = lo + Math.imul(al0, bl7) | 0; - mid = mid + Math.imul(al0, bh7) | 0; - mid = mid + Math.imul(ah0, bl7) | 0; - hi = hi + Math.imul(ah0, bh7) | 0; - var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = mid + Math.imul(ah8, bl0) | 0; - hi = Math.imul(ah8, bh0); - lo = lo + Math.imul(al7, bl1) | 0; - mid = mid + Math.imul(al7, bh1) | 0; - mid = mid + Math.imul(ah7, bl1) | 0; - hi = hi + Math.imul(ah7, bh1) | 0; - lo = lo + Math.imul(al6, bl2) | 0; - mid = mid + Math.imul(al6, bh2) | 0; - mid = mid + Math.imul(ah6, bl2) | 0; - hi = hi + Math.imul(ah6, bh2) | 0; - lo = lo + Math.imul(al5, bl3) | 0; - mid = mid + Math.imul(al5, bh3) | 0; - mid = mid + Math.imul(ah5, bl3) | 0; - hi = hi + Math.imul(ah5, bh3) | 0; - lo = lo + Math.imul(al4, bl4) | 0; - mid = mid + Math.imul(al4, bh4) | 0; - mid = mid + Math.imul(ah4, bl4) | 0; - hi = hi + Math.imul(ah4, bh4) | 0; - lo = lo + Math.imul(al3, bl5) | 0; - mid = mid + Math.imul(al3, bh5) | 0; - mid = mid + Math.imul(ah3, bl5) | 0; - hi = hi + Math.imul(ah3, bh5) | 0; - lo = lo + Math.imul(al2, bl6) | 0; - mid = mid + Math.imul(al2, bh6) | 0; - mid = mid + Math.imul(ah2, bl6) | 0; - hi = hi + Math.imul(ah2, bh6) | 0; - lo = lo + Math.imul(al1, bl7) | 0; - mid = mid + Math.imul(al1, bh7) | 0; - mid = mid + Math.imul(ah1, bl7) | 0; - hi = hi + Math.imul(ah1, bh7) | 0; - lo = lo + Math.imul(al0, bl8) | 0; - mid = mid + Math.imul(al0, bh8) | 0; - mid = mid + Math.imul(ah0, bl8) | 0; - hi = hi + Math.imul(ah0, bh8) | 0; - var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = mid + Math.imul(ah9, bl0) | 0; - hi = Math.imul(ah9, bh0); - lo = lo + Math.imul(al8, bl1) | 0; - mid = mid + Math.imul(al8, bh1) | 0; - mid = mid + Math.imul(ah8, bl1) | 0; - hi = hi + Math.imul(ah8, bh1) | 0; - lo = lo + Math.imul(al7, bl2) | 0; - mid = mid + Math.imul(al7, bh2) | 0; - mid = mid + Math.imul(ah7, bl2) | 0; - hi = hi + Math.imul(ah7, bh2) | 0; - lo = lo + Math.imul(al6, bl3) | 0; - mid = mid + Math.imul(al6, bh3) | 0; - mid = mid + Math.imul(ah6, bl3) | 0; - hi = hi + Math.imul(ah6, bh3) | 0; - lo = lo + Math.imul(al5, bl4) | 0; - mid = mid + Math.imul(al5, bh4) | 0; - mid = mid + Math.imul(ah5, bl4) | 0; - hi = hi + Math.imul(ah5, bh4) | 0; - lo = lo + Math.imul(al4, bl5) | 0; - mid = mid + Math.imul(al4, bh5) | 0; - mid = mid + Math.imul(ah4, bl5) | 0; - hi = hi + Math.imul(ah4, bh5) | 0; - lo = lo + Math.imul(al3, bl6) | 0; - mid = mid + Math.imul(al3, bh6) | 0; - mid = mid + Math.imul(ah3, bl6) | 0; - hi = hi + Math.imul(ah3, bh6) | 0; - lo = lo + Math.imul(al2, bl7) | 0; - mid = mid + Math.imul(al2, bh7) | 0; - mid = mid + Math.imul(ah2, bl7) | 0; - hi = hi + Math.imul(ah2, bh7) | 0; - lo = lo + Math.imul(al1, bl8) | 0; - mid = mid + Math.imul(al1, bh8) | 0; - mid = mid + Math.imul(ah1, bl8) | 0; - hi = hi + Math.imul(ah1, bh8) | 0; - lo = lo + Math.imul(al0, bl9) | 0; - mid = mid + Math.imul(al0, bh9) | 0; - mid = mid + Math.imul(ah0, bl9) | 0; - hi = hi + Math.imul(ah0, bh9) | 0; - var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = mid + Math.imul(ah9, bl1) | 0; - hi = Math.imul(ah9, bh1); - lo = lo + Math.imul(al8, bl2) | 0; - mid = mid + Math.imul(al8, bh2) | 0; - mid = mid + Math.imul(ah8, bl2) | 0; - hi = hi + Math.imul(ah8, bh2) | 0; - lo = lo + Math.imul(al7, bl3) | 0; - mid = mid + Math.imul(al7, bh3) | 0; - mid = mid + Math.imul(ah7, bl3) | 0; - hi = hi + Math.imul(ah7, bh3) | 0; - lo = lo + Math.imul(al6, bl4) | 0; - mid = mid + Math.imul(al6, bh4) | 0; - mid = mid + Math.imul(ah6, bl4) | 0; - hi = hi + Math.imul(ah6, bh4) | 0; - lo = lo + Math.imul(al5, bl5) | 0; - mid = mid + Math.imul(al5, bh5) | 0; - mid = mid + Math.imul(ah5, bl5) | 0; - hi = hi + Math.imul(ah5, bh5) | 0; - lo = lo + Math.imul(al4, bl6) | 0; - mid = mid + Math.imul(al4, bh6) | 0; - mid = mid + Math.imul(ah4, bl6) | 0; - hi = hi + Math.imul(ah4, bh6) | 0; - lo = lo + Math.imul(al3, bl7) | 0; - mid = mid + Math.imul(al3, bh7) | 0; - mid = mid + Math.imul(ah3, bl7) | 0; - hi = hi + Math.imul(ah3, bh7) | 0; - lo = lo + Math.imul(al2, bl8) | 0; - mid = mid + Math.imul(al2, bh8) | 0; - mid = mid + Math.imul(ah2, bl8) | 0; - hi = hi + Math.imul(ah2, bh8) | 0; - lo = lo + Math.imul(al1, bl9) | 0; - mid = mid + Math.imul(al1, bh9) | 0; - mid = mid + Math.imul(ah1, bl9) | 0; - hi = hi + Math.imul(ah1, bh9) | 0; - var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = mid + Math.imul(ah9, bl2) | 0; - hi = Math.imul(ah9, bh2); - lo = lo + Math.imul(al8, bl3) | 0; - mid = mid + Math.imul(al8, bh3) | 0; - mid = mid + Math.imul(ah8, bl3) | 0; - hi = hi + Math.imul(ah8, bh3) | 0; - lo = lo + Math.imul(al7, bl4) | 0; - mid = mid + Math.imul(al7, bh4) | 0; - mid = mid + Math.imul(ah7, bl4) | 0; - hi = hi + Math.imul(ah7, bh4) | 0; - lo = lo + Math.imul(al6, bl5) | 0; - mid = mid + Math.imul(al6, bh5) | 0; - mid = mid + Math.imul(ah6, bl5) | 0; - hi = hi + Math.imul(ah6, bh5) | 0; - lo = lo + Math.imul(al5, bl6) | 0; - mid = mid + Math.imul(al5, bh6) | 0; - mid = mid + Math.imul(ah5, bl6) | 0; - hi = hi + Math.imul(ah5, bh6) | 0; - lo = lo + Math.imul(al4, bl7) | 0; - mid = mid + Math.imul(al4, bh7) | 0; - mid = mid + Math.imul(ah4, bl7) | 0; - hi = hi + Math.imul(ah4, bh7) | 0; - lo = lo + Math.imul(al3, bl8) | 0; - mid = mid + Math.imul(al3, bh8) | 0; - mid = mid + Math.imul(ah3, bl8) | 0; - hi = hi + Math.imul(ah3, bh8) | 0; - lo = lo + Math.imul(al2, bl9) | 0; - mid = mid + Math.imul(al2, bh9) | 0; - mid = mid + Math.imul(ah2, bl9) | 0; - hi = hi + Math.imul(ah2, bh9) | 0; - var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = mid + Math.imul(ah9, bl3) | 0; - hi = Math.imul(ah9, bh3); - lo = lo + Math.imul(al8, bl4) | 0; - mid = mid + Math.imul(al8, bh4) | 0; - mid = mid + Math.imul(ah8, bl4) | 0; - hi = hi + Math.imul(ah8, bh4) | 0; - lo = lo + Math.imul(al7, bl5) | 0; - mid = mid + Math.imul(al7, bh5) | 0; - mid = mid + Math.imul(ah7, bl5) | 0; - hi = hi + Math.imul(ah7, bh5) | 0; - lo = lo + Math.imul(al6, bl6) | 0; - mid = mid + Math.imul(al6, bh6) | 0; - mid = mid + Math.imul(ah6, bl6) | 0; - hi = hi + Math.imul(ah6, bh6) | 0; - lo = lo + Math.imul(al5, bl7) | 0; - mid = mid + Math.imul(al5, bh7) | 0; - mid = mid + Math.imul(ah5, bl7) | 0; - hi = hi + Math.imul(ah5, bh7) | 0; - lo = lo + Math.imul(al4, bl8) | 0; - mid = mid + Math.imul(al4, bh8) | 0; - mid = mid + Math.imul(ah4, bl8) | 0; - hi = hi + Math.imul(ah4, bh8) | 0; - lo = lo + Math.imul(al3, bl9) | 0; - mid = mid + Math.imul(al3, bh9) | 0; - mid = mid + Math.imul(ah3, bl9) | 0; - hi = hi + Math.imul(ah3, bh9) | 0; - var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = mid + Math.imul(ah9, bl4) | 0; - hi = Math.imul(ah9, bh4); - lo = lo + Math.imul(al8, bl5) | 0; - mid = mid + Math.imul(al8, bh5) | 0; - mid = mid + Math.imul(ah8, bl5) | 0; - hi = hi + Math.imul(ah8, bh5) | 0; - lo = lo + Math.imul(al7, bl6) | 0; - mid = mid + Math.imul(al7, bh6) | 0; - mid = mid + Math.imul(ah7, bl6) | 0; - hi = hi + Math.imul(ah7, bh6) | 0; - lo = lo + Math.imul(al6, bl7) | 0; - mid = mid + Math.imul(al6, bh7) | 0; - mid = mid + Math.imul(ah6, bl7) | 0; - hi = hi + Math.imul(ah6, bh7) | 0; - lo = lo + Math.imul(al5, bl8) | 0; - mid = mid + Math.imul(al5, bh8) | 0; - mid = mid + Math.imul(ah5, bl8) | 0; - hi = hi + Math.imul(ah5, bh8) | 0; - lo = lo + Math.imul(al4, bl9) | 0; - mid = mid + Math.imul(al4, bh9) | 0; - mid = mid + Math.imul(ah4, bl9) | 0; - hi = hi + Math.imul(ah4, bh9) | 0; - var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = mid + Math.imul(ah9, bl5) | 0; - hi = Math.imul(ah9, bh5); - lo = lo + Math.imul(al8, bl6) | 0; - mid = mid + Math.imul(al8, bh6) | 0; - mid = mid + Math.imul(ah8, bl6) | 0; - hi = hi + Math.imul(ah8, bh6) | 0; - lo = lo + Math.imul(al7, bl7) | 0; - mid = mid + Math.imul(al7, bh7) | 0; - mid = mid + Math.imul(ah7, bl7) | 0; - hi = hi + Math.imul(ah7, bh7) | 0; - lo = lo + Math.imul(al6, bl8) | 0; - mid = mid + Math.imul(al6, bh8) | 0; - mid = mid + Math.imul(ah6, bl8) | 0; - hi = hi + Math.imul(ah6, bh8) | 0; - lo = lo + Math.imul(al5, bl9) | 0; - mid = mid + Math.imul(al5, bh9) | 0; - mid = mid + Math.imul(ah5, bl9) | 0; - hi = hi + Math.imul(ah5, bh9) | 0; - var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = mid + Math.imul(ah9, bl6) | 0; - hi = Math.imul(ah9, bh6); - lo = lo + Math.imul(al8, bl7) | 0; - mid = mid + Math.imul(al8, bh7) | 0; - mid = mid + Math.imul(ah8, bl7) | 0; - hi = hi + Math.imul(ah8, bh7) | 0; - lo = lo + Math.imul(al7, bl8) | 0; - mid = mid + Math.imul(al7, bh8) | 0; - mid = mid + Math.imul(ah7, bl8) | 0; - hi = hi + Math.imul(ah7, bh8) | 0; - lo = lo + Math.imul(al6, bl9) | 0; - mid = mid + Math.imul(al6, bh9) | 0; - mid = mid + Math.imul(ah6, bl9) | 0; - hi = hi + Math.imul(ah6, bh9) | 0; - var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = mid + Math.imul(ah9, bl7) | 0; - hi = Math.imul(ah9, bh7); - lo = lo + Math.imul(al8, bl8) | 0; - mid = mid + Math.imul(al8, bh8) | 0; - mid = mid + Math.imul(ah8, bl8) | 0; - hi = hi + Math.imul(ah8, bh8) | 0; - lo = lo + Math.imul(al7, bl9) | 0; - mid = mid + Math.imul(al7, bh9) | 0; - mid = mid + Math.imul(ah7, bl9) | 0; - hi = hi + Math.imul(ah7, bh9) | 0; - var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = mid + Math.imul(ah9, bl8) | 0; - hi = Math.imul(ah9, bh8); - lo = lo + Math.imul(al8, bl9) | 0; - mid = mid + Math.imul(al8, bh9) | 0; - mid = mid + Math.imul(ah8, bl9) | 0; - hi = hi + Math.imul(ah8, bh9) | 0; - var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = mid + Math.imul(ah9, bl9) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - - if (c !== 0) { - o[19] = c; - out.length++; - } - - return out; - }; // Polyfill comb - - - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - var carry = 0; - var hncarry = 0; - - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - var lo = r & 0x3ffffff; - ncarry = ncarry + (r / 0x4000000 | 0) | 0; - lo = lo + rword | 0; - rword = lo & 0x3ffffff; - ncarry = ncarry + (lo >>> 26) | 0; - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } + function mod$1(a) { + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var res = a % b; + return res >= _0n$2 ? res : b + res; + } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } + function invert$1(number) { + var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } + if (number === _0n$2 || modulo <= _0n$2) { + throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); + } - return out._strip(); - } + var a = mod$1(number, modulo); + var b = modulo; + var x = _0n$2, + u = _1n$2; - function jumboMulTo(self, num, out) { - // Temporary disable, see https://github.com/indutny/bn.js/issues/211 - // var fftm = new FFTM(); - // return fftm.mulp(self, num, out); - return bigMulTo(self, num, out); - } + while (a !== _0n$2) { + var q = b / a; + var r = b % a; + var m = x - u * q; + b = a, a = r, x = u, u = m; + } - BN.prototype.mulTo = function mulTo(num, out) { - var res; - var len = this.length + num.length; + var gcd = b; + if (gcd !== _1n$2) throw new Error('invert: does not exist'); + return mod$1(x, modulo); + } - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } + function invertBatch$1(nums) { + var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var tmp = new Array(nums.length); + var lastMultiplied = nums.reduce(function (acc, num, i) { + if (num === _0n$2) return acc; + tmp[i] = acc; + return mod$1(acc * num, p); + }, _1n$2); + var inverted = invert$1(lastMultiplied, p); + nums.reduceRight(function (acc, num, i) { + if (num === _0n$2) return acc; + tmp[i] = mod$1(acc * tmp[i], p); + return mod$1(acc * num, p); + }, inverted); + return tmp; + } - return res; - }; // Cooley-Tukey algorithm for FFT + function pow2$1(x, power) { + var P = CURVE$1.P; + var res = x; + while (power-- > _0n$2) { + res *= res; + res %= P; + } - BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; // Multiply employing FFT + return res; + } + function pow_2_252_3(x) { + var P = CURVE$1.P; - BN.prototype.mulf = function mulf(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; // In-place Multiplication + var _5n = BigInt(5); + var _10n = BigInt(10); - BN.prototype.imul = function imul(num) { - return this.clone().mulTo(num, this); - }; + var _20n = BigInt(20); - BN.prototype.imuln = function imuln(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(typeof num === 'number'); - assert(num < 0x4000000); // Carry + var _40n = BigInt(40); - var carry = 0; + var _80n = BigInt(80); - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += w / 0x4000000 | 0; // NOTE: lo is 27bit maximum + var x2 = x * x % P; + var b2 = x2 * x % P; + var b4 = pow2$1(b2, _2n$2) * b2 % P; + var b5 = pow2$1(b4, _1n$2) * x % P; + var b10 = pow2$1(b5, _5n) * b5 % P; + var b20 = pow2$1(b10, _10n) * b10 % P; + var b40 = pow2$1(b20, _20n) * b20 % P; + var b80 = pow2$1(b40, _40n) * b40 % P; + var b160 = pow2$1(b80, _80n) * b80 % P; + var b240 = pow2$1(b160, _80n) * b80 % P; + var b250 = pow2$1(b240, _10n) * b10 % P; + var pow_p_5_8 = pow2$1(b250, _2n$2) * x % P; + return { + pow_p_5_8: pow_p_5_8, + b2: b2 + }; + } - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } + function uvRatio(u, v) { + var v3 = mod$1(v * v * v); + var v7 = mod$1(v3 * v3 * v); + var pow = pow_2_252_3(u * v7).pow_p_5_8; + var x = mod$1(u * v3 * pow); + var vx2 = mod$1(v * x * x); + var root1 = x; + var root2 = mod$1(x * SQRT_M1); + var useRoot1 = vx2 === u; + var useRoot2 = vx2 === mod$1(-u); + var noRoot = vx2 === mod$1(-u * SQRT_M1); + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; + if (edIsNegative(x)) x = mod$1(-x); + return { + isValid: useRoot1 || useRoot2, + value: x + }; + } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } + function invertSqrt(number) { + return uvRatio(_1n$2, number); + } - return isNegNum ? this.ineg() : this; - }; + function modlLE(hash) { + return mod$1(bytesToNumberLE(hash), CURVE$1.l); + } - BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); - }; // `this` * `this` + function equalBytes(b1, b2) { + if (b1.length !== b2.length) { + return false; + } + for (var i = 0; i < b1.length; i++) { + if (b1[i] !== b2[i]) { + return false; + } + } - BN.prototype.sqr = function sqr() { - return this.mul(this); - }; // `this` * `this` in-place + return true; + } + function ensureBytes$1(hex, expectedLength) { + var bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex); + if (typeof expectedLength === 'number' && bytes.length !== expectedLength) throw new Error("Expected ".concat(expectedLength, " bytes")); + return bytes; + } - BN.prototype.isqr = function isqr() { - return this.imul(this.clone()); - }; // Math.pow(`this`, `num`) + function normalizeScalar$1(num, max) { + var strict = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + if (!max) throw new TypeError('Specify max value'); + if (typeof num === 'number' && Number.isSafeInteger(num)) num = BigInt(num); + if (typeof num === 'bigint' && num < max) { + if (strict) { + if (_0n$2 < num) return num; + } else { + if (_0n$2 <= num) return num; + } + } - BN.prototype.pow = function pow(num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); // Skip leading zeroes + throw new TypeError('Expected valid scalar: 0 < scalar < max'); + } - var res = this; + function adjustBytes25519(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; + } - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } + function checkPrivateKey(key) { + key = typeof key === 'bigint' || typeof key === 'number' ? numberTo32BytesBE(normalizeScalar$1(key, POW_2_256$1)) : ensureBytes$1(key); + if (key.length !== 32) throw new Error("Expected 32 bytes"); + return key; + } - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - res = res.mul(q); - } - } + function getKeyFromHash(hashed) { + var head = adjustBytes25519(hashed.slice(0, 32)); + var prefix = hashed.slice(32, 64); + var scalar = modlLE(head); + var point = Point$1.BASE.multiply(scalar); + var pointBytes = point.toRawBytes(); + return { + head: head, + prefix: prefix, + scalar: scalar, + point: point, + pointBytes: pointBytes + }; + } - return res; - }; // Shift-left in-place + var _sha512Sync; + function sha512s() { + if (typeof _sha512Sync !== 'function') throw new Error('utils.sha512Sync must be set to use sync methods'); + return _sha512Sync.apply(void 0, arguments); + } - BN.prototype.iushln = function iushln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = 0x3ffffff >>> 26 - r << 26 - r; - var i; + function getExtendedPublicKey(_x3) { + return _getExtendedPublicKey.apply(this, arguments); + } - if (r !== 0) { - var carry = 0; + function _getExtendedPublicKey() { + _getExtendedPublicKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.t0 = getKeyFromHash; + _context3.next = 3; + return utils$1.sha512(checkPrivateKey(key)); - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] | 0) - newCarry << r; - this.words[i] = c | carry; - carry = newCarry >>> 26 - r; - } + case 3: + _context3.t1 = _context3.sent; + return _context3.abrupt("return", (0, _context3.t0)(_context3.t1)); - if (carry) { - this.words[i] = carry; - this.length++; - } + case 5: + case "end": + return _context3.stop(); } + }, _callee3); + })); + return _getExtendedPublicKey.apply(this, arguments); + } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } + function getExtendedPublicKeySync(key) { + return getKeyFromHash(sha512s(checkPrivateKey(key))); + } - this.length += s; - } + function getPublicKeySync(privateKey) { + return getExtendedPublicKeySync(privateKey).pointBytes; + } - return this._strip(); - }; + function signSync$1(message, privateKey) { + message = ensureBytes$1(message); - BN.prototype.ishln = function ishln(bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits + var _getExtendedPublicKey2 = getExtendedPublicKeySync(privateKey), + prefix = _getExtendedPublicKey2.prefix, + scalar = _getExtendedPublicKey2.scalar, + pointBytes = _getExtendedPublicKey2.pointBytes; + var r = modlLE(sha512s(prefix, message)); + var R = Point$1.BASE.multiply(r); + var k = modlLE(sha512s(R.toRawBytes(), pointBytes, message)); + var s = mod$1(r + k * scalar, CURVE$1.l); + return new Signature$1(R, s).toRawBytes(); + } - BN.prototype.iushrn = function iushrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; + function prepareVerification(sig, message, publicKey) { + message = ensureBytes$1(message); + if (!(publicKey instanceof Point$1)) publicKey = Point$1.fromHex(publicKey, false); - if (hint) { - h = (hint - hint % 26) / 26; - } else { - h = 0; - } + var _ref = sig instanceof Signature$1 ? sig.assertValidity() : Signature$1.fromHex(sig), + r = _ref.r, + s = _ref.s; - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; - var maskedWords = extended; - h -= s; - h = Math.max(0, h); // Extended mode, copy masked part + var SB = ExtendedPoint.BASE.multiplyUnsafe(s); + return { + r: r, + s: s, + SB: SB, + pub: publicKey, + msg: message + }; + } - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } + function finishVerification(publicKey, r, SB, hashed) { + var k = modlLE(hashed); + var kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k); + var RkA = ExtendedPoint.fromAffine(r).add(kA); + return RkA.subtract(SB).multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); + } - maskedWords.length = s; - } + function verifySync(sig, message, publicKey) { + var _prepareVerification = prepareVerification(sig, message, publicKey), + r = _prepareVerification.r, + SB = _prepareVerification.SB, + msg = _prepareVerification.msg, + pub = _prepareVerification.pub; - if (s === 0) ; else if (this.length > s) { - this.length -= s; + var hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg); + return finishVerification(pub, r, SB, hashed); + } - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } + var sync = { + getExtendedPublicKey: getExtendedPublicKeySync, + getPublicKey: getPublicKeySync, + sign: signSync$1, + verify: verifySync + }; - var carry = 0; + Point$1.BASE._setWindowSize(8); + var crypto$2 = { + node: nodeCrypto, + web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined + }; + var utils$1 = { + bytesToHex: bytesToHex$1, + hexToBytes: hexToBytes$1, + concatBytes: concatBytes$1, + getExtendedPublicKey: getExtendedPublicKey, + mod: mod$1, + invert: invert$1, + TORSION_SUBGROUP: ['0100000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', '0000000000000000000000000000000000000000000000000000000000000080', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', '0000000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa'], + hashToPrivateScalar: function hashToPrivateScalar(hash) { + hash = ensureBytes$1(hash); + if (hash.length < 40 || hash.length > 1024) throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); + return mod$1(bytesToNumberLE(hash), CURVE$1.l - _1n$2) + _1n$2; + }, + randomBytes: function randomBytes() { + var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = carry << 26 - r | word >>> r; - carry = word & mask; - } // Push carried bits as a mask + if (crypto$2.web) { + return crypto$2.web.getRandomValues(new Uint8Array(bytesLength)); + } else if (crypto$2.node) { + var randomBytes = crypto$2.node.randomBytes; + return new Uint8Array(randomBytes(bytesLength).buffer); + } else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: function randomPrivateKey() { + return utils$1.randomBytes(32); + }, + sha512: function () { + var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var message, + buffer, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + message = concatBytes$1.apply(void 0, _args2); + if (!crypto$2.web) { + _context2.next = 8; + break; + } - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } + _context2.next = 4; + return crypto$2.web.subtle.digest('SHA-512', message.buffer); - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } + case 4: + buffer = _context2.sent; + return _context2.abrupt("return", new Uint8Array(buffer)); - return this._strip(); - }; + case 8: + if (!crypto$2.node) { + _context2.next = 12; + break; + } - BN.prototype.ishrn = function ishrn(bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; // Shift-left + return _context2.abrupt("return", Uint8Array.from(crypto$2.node.createHash('sha512').update(message).digest())); + case 12: + throw new Error("The environment doesn't have sha512 function"); - BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); - }; + case 13: + case "end": + return _context2.stop(); + } + }, _callee2); + })); - BN.prototype.ushln = function ushln(bits) { - return this.clone().iushln(bits); - }; // Shift-right + function sha512() { + return _sha.apply(this, arguments); + } + return sha512; + }(), + precompute: function precompute() { + var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; + var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point$1.BASE; + var cached = point.equals(Point$1.BASE) ? point : new Point$1(point.x, point.y); - BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); - }; + cached._setWindowSize(windowSize); - BN.prototype.ushrn = function ushrn(bits) { - return this.clone().iushrn(bits); - }; // Test if n bit is set + cached.multiply(_2n$2); + return cached; + }, + sha512Sync: undefined + }; + Object.defineProperties(utils$1, { + sha512Sync: { + configurable: false, + get: function get() { + return _sha512Sync; + }, + set: function set(val) { + if (!_sha512Sync) _sha512Sync = val; + } + } + }); + var bn$1 = {exports: {}}; - BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; // Fast case: bit is much higher than all existing words + var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_buffer); - if (this.length <= s) return false; // Check bit and return + (function (module) { + (function (module, exports) { - var w = this.words[s]; - return !!(w & q); - }; // Return only lowers bits of number (in-place) + function assert(val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } // Could use `inherits` module, but don't want to move from single file + // architecture yet. - BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; - if (this.length <= s) { - return this; - } + var TempCtor = function TempCtor() {}; - if (r !== 0) { - s++; - } + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } // BN - this.length = Math.min(s, this.length); - if (r !== 0) { - var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; - this.words[this.length - 1] &= mask; + function BN(number, base, endian) { + if (BN.isBN(number)) { + return number; } - return this._strip(); - }; // Return only lowers bits of number + this.negative = 0; + this.words = null; + this.length = 0; // Reduction context + this.red = null; - BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); - }; // Add plain number `num` to `this` + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + this._init(number || 0, base || 10, endian || 'be'); + } + } - BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); // Possible sign change + if (_typeof$1(module) === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } + BN.BN = BN; + BN.wordSize = 26; + var Buffer; - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } // Add without checks + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require$$1$1.Buffer; + } + } catch (e) {} + BN.isBN = function isBN(num) { + if (num instanceof BN) { + return true; + } - return this._iaddn(num); + return num !== null && _typeof$1(num) === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; - BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; // Carry + BN.max = function max(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; + BN.min = function min(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } + BN.prototype._init = function init(number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); } - this.length = Math.max(this.length, i + 1); - return this; - }; // Subtract plain number `num` from `this` + if (_typeof$1(number) === 'object') { + return this._initArray(number, base, endian); + } + if (base === 'hex') { + base = 16; + } - BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); + assert(base === (base | 0) && base >= 2 && base <= 36); + number = number.toString().replace(/\s+/g, ''); + var start = 0; - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); + if (number[0] === '-') { + start++; this.negative = 1; - return this; } - this.words[0] -= num; + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; + if (endian === 'le') { + this._initArray(this.toArray(), base, endian); + } } } - - return this._strip(); }; - BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); - }; + BN.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } - BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); - }; + if (number < 0x4000000) { + this.words = [number & 0x3ffffff]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - BN.prototype.iabs = function iabs() { - this.negative = 0; - return this; - }; + this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1]; + this.length = 3; + } - BN.prototype.abs = function abs() { - return this.clone().iabs(); + if (endian !== 'le') return; // Reverse the bytes + + this._initArray(this.toArray(), base, endian); }; - BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - var len = num.length + shift; - var i; + BN.prototype._initArray = function _initArray(number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); - this._expand(len); + if (number.length <= 0) { + this.words = [0]; + this.length = 1; + return this; + } - var w; - var carry = 0; + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - (right / 0x4000000 | 0); - this.words[i + shift] = w & 0x3ffffff; + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } + var j, w; + var off = 0; - if (carry === 0) return this._strip(); // Subtraction overflow + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 0x3ffffff; + this.words[j + 1] = w >>> 26 - off & 0x3ffffff; + off += 24; - assert(carry === -1); - carry = 0; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 0x3ffffff; + this.words[j + 1] = w >>> 26 - off & 0x3ffffff; + off += 24; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; + if (off >= 26) { + off -= 26; + j++; + } + } } - this.negative = 1; return this._strip(); }; - BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - var a = this.clone(); - var b = num; // Normalize + function parseHex4Bits(string, index) { + var c = string.charCodeAt(index); // '0' - '9' - var bhi = b.words[b.length - 1] | 0; + if (c >= 48 && c <= 57) { + return c - 48; // 'A' - 'F' + } else if (c >= 65 && c <= 70) { + return c - 55; // 'a' - 'f' + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, 'Invalid character in ' + string); + } + } - var bhiBits = this._countBits(bhi); + function parseHexByte(string, lowerBound, index) { + var r = parseHex4Bits(string, index); - shift = 26 - bhiBits; + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } // Initialize quotient + return r; + } + + BN.prototype._parseHex = function _parseHex(number, start, endian) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } // 24-bits chunks - var m = a.length - b.length; - var q; - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); + var off = 0; + var j = 0; + var w; - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; + if (endian === 'be') { + for (i = number.length - 1; i >= start; i -= 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + + for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 0x3ffffff; + + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } } } - var diff = a.clone()._ishlnsubmul(b, 1, m); + this._strip(); + }; - if (diff.negative === 0) { - a = diff; + function parseBase(str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); - if (q) { - q.words[m] = 1; + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + r *= mul; // 'a' + + if (c >= 49) { + b = c - 49 + 0xa; // 'A' + } else if (c >= 17) { + b = c - 17 + 0xa; // '0' - '9' + } else { + b = c; } + + assert(c >= 0 && b < mul, 'Invalid character'); + r += b; } - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) + return r; + } - qj = Math.min(qj / bhi | 0, 0x3ffffff); + BN.prototype._parseBase = function _parseBase(number, base, start) { + // Initialize as zero + this.words = [0]; + this.length = 1; // Find length of limb in base - a._ishlnsubmul(b, qj, j); + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } - while (a.negative !== 0) { - qj--; - a.negative = 0; + limbLen--; + limbPow = limbPow / base | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; - a._ishlnsubmul(b, 1, j); + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + this.imuln(limbPow); - if (!a.isZero()) { - a.negative ^= 1; - } + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); } + } - if (q) { - q.words[j] = qj; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; } - } - if (q) { - q._strip(); + this.imuln(pow); + + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - a._strip(); // Denormalize + this._strip(); + }; + BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; } - return { - div: q || null, - mod: a - }; - }; // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + function move(dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } - BN.prototype.divmod = function divmod(num, mode, positive) { - assert(!num.isZero()); + BN.prototype._move = function _move(dest) { + move(dest, this); + }; - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } + BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; + }; - var div, mod, res; + BN.prototype._expand = function _expand(size) { + while (this.length < size) { + this.words[this.length++] = 0; + } - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); + return this; + }; // Remove leading `0` from `this` - if (mode !== 'mod') { - div = res.div.neg(); - } - if (mode !== 'div') { - mod = res.mod.neg(); + BN.prototype._strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + return this._normSign(); + }; - return { - div: div, - mod: mod - }; + BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + return this; + }; // Check Symbol.for because not everywhere where Symbol defined + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility - if (mode !== 'mod') { - div = res.div.neg(); - } - return { - div: div, - mod: res.mod - }; + if (typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function') { + try { + BN.prototype[Symbol["for"]('nodejs.util.inspect.custom')] = inspect; + } catch (e) { + BN.prototype.inspect = inspect; } + } else { + BN.prototype.inspect = inspect; + } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + function inspect() { + return (this.red ? ''; + } + /* + var zeros = []; + var groupSizes = []; + var groupBases = []; + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + */ - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000']; + var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; + var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; - return { - div: res.div, - mod: mod - }; - } // Both numbers are positive at this point - // Strip both numbers to approximate shift value + BN.prototype.toString = function toString(base, padding) { + base = base || 10; + padding = padding | 0 || 1; + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } // Very short reduction + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = ((w << off | carry) & 0xffffff).toString(16); + carry = w >>> 24 - off & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; + off += 2; + + if (off >= 26) { + off -= 26; + i--; + } } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modrn(num.words[0])) - }; + if (carry !== 0) { + out = carry.toString(16) + out; } - return { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])) - }; - } + while (out.length % padding !== 0) { + out = '0' + out; + } - return this._wordDiv(num, mode); - }; // Find `this` / `num` + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } - BN.prototype.div = function div(num) { - return this.divmod(num, 'div', false).div; - }; // Find `this` % `num` + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; - BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod', false).mod; - }; + while (!c.isZero()) { + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); - BN.prototype.umod = function umod(num) { - return this.divmod(num, 'mod', true).mod; - }; // Find Round(`this` / `num`) + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } - BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); // Fast case - exact division + while (out.length % padding !== 0) { + out = '0' + out; + } - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); // Round down + if (this.negative !== 0) { + out = '-' + out; + } - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up + return out; + } - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + assert(false, 'Base should be between 2 and 36'); }; - BN.prototype.modrn = function modrn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - var acc = 0; - - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } + BN.prototype.toNumber = function toNumber() { + var ret = this.words[0]; - return isNegNum ? -acc : acc; - }; // WARNING: DEPRECATED + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + this.words[1] * 0x4000000; + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return this.negative !== 0 ? -ret : ret; + }; - BN.prototype.modn = function modn(num) { - return this.modrn(num); - }; // In-place division by number + BN.prototype.toJSON = function toJSON() { + return this.toString(16, 2); + }; + if (Buffer) { + BN.prototype.toBuffer = function toBuffer(endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; + } - BN.prototype.idivn = function idivn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 0x3ffffff); - var carry = 0; + BN.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = w / num | 0; - carry = w % num; + var allocate = function allocate(ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); } - this._strip(); - - return isNegNum ? this.ineg() : this; + return new ArrayType(size); }; - BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); + BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + this._strip(); + + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + var res = allocate(ArrayType, reqLength); + var postfix = endian === 'le' ? 'LE' : 'BE'; + this['_toArrayLike' + postfix](res, byteLength); + return res; }; - BN.prototype.egcd = function egcd(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var x = this; - var y = p.clone(); + BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { + var position = 0; + var carry = 0; - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } // A * x + B * y = x + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position++] = word & 0xff; + if (position < res.length) { + res[position++] = word >> 8 & 0xff; + } - var A = new BN(1); - var B = new BN(0); // C * x + D * y = y + if (position < res.length) { + res[position++] = word >> 16 & 0xff; + } - var C = new BN(0); - var D = new BN(1); - var g = 0; + if (shift === 6) { + if (position < res.length) { + res[position++] = word >> 24 & 0xff; + } - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } } - var yp = y.clone(); - var xp = x.clone(); + if (position < res.length) { + res[position++] = carry; - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + while (position < res.length) { + res[position++] = 0; + } + } + }; - if (i > 0) { - x.iushrn(i); + BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { + var position = res.length - 1; + var carry = 0; - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } + for (var i = 0, shift = 0; i < this.length; i++) { + var word = this.words[i] << shift | carry; + res[position--] = word & 0xff; - A.iushrn(1); - B.iushrn(1); - } + if (position >= 0) { + res[position--] = word >> 8 & 0xff; } - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - - if (j > 0) { - y.iushrn(j); - - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } + if (position >= 0) { + res[position--] = word >> 16 & 0xff; + } - C.iushrn(1); - D.iushrn(1); + if (shift === 6) { + if (position >= 0) { + res[position--] = word >> 24 & 0xff; } - } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + carry = 0; + shift = 0; } else { - y.isub(x); - C.isub(A); - D.isub(B); + carry = word >>> 24; + shift += 2; } } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - - - BN.prototype._invmp = function _invmp(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var a = this; - var b = p.clone(); + if (position >= 0) { + res[position--] = carry; - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + while (position >= 0) { + res[position--] = 0; + } } + }; - var x1 = new BN(1); - var x2 = new BN(0); - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; - if (i > 0) { - a.iushrn(i); + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } - x1.iushrn(1); - } + if (t >= 0x8) { + r += 4; + t >>>= 4; } - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (t >= 0x02) { + r += 2; + t >>>= 2; + } - if (j > 0) { - b.iushrn(j); + return r + t; + }; + } - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } + BN.prototype._zeroBits = function _zeroBits(w) { + // Short-cut + if (w === 0) return 26; + var t = w; + var r = 0; - x2.iushrn(1); - } - } + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; } - var res; + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; } - if (res.cmpn(0) < 0) { - res.iadd(p); + if ((t & 0x1) === 0) { + r++; } - return res; - }; + return r; + }; // Return number of used bits in a BN - BN.prototype.gcd = function gcd(num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } + BN.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; - do { - while (a.isEven()) { - a.iushrn(1); - } + var hi = this._countBits(w); - while (b.isEven()) { - b.iushrn(1); - } + return (this.length - 1) * 26 + hi; + }; - var r = a.cmp(b); + function toBitArray(num) { + var w = new Array(num.bitLength()); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + for (var bit = 0; bit < w.length; bit++) { + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = num.words[off] >>> wbit & 0x01; + } - a.isub(b); - } while (true); + return w; + } // Number of trailing zero bits - return b.iushln(shift); - }; // Invert number in the field F(num) + BN.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; - BN.prototype.invm = function invm(num) { - return this.egcd(num).a.umod(num); + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + + r += b; + if (b !== 26) break; + } + + return r; }; - BN.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; + BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); }; - BN.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; - }; // And first word and num + BN.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - BN.prototype.andln = function andln(num) { - return this.words[0] & num; - }; // Increment at the bit position in-line + BN.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; // Fast case: bit is much higher than all existing words + BN.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; // Return negative clone of `this` - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } // Add bit and propagate, if needed + BN.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } - var carry = q; + return this; + }; // Or `num` with `this` in-place - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; + + BN.prototype.iuor = function iuor(num) { + while (this.length < num.length) { + this.words[this.length++] = 0; } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; } - return this; + return this._strip(); }; - BN.prototype.isZero = function isZero() { - return this.length === 1 && this.words[0] === 0; + BN.prototype.ior = function ior(num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; // Or `num` with `this` + + + BN.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); }; - BN.prototype.cmpn = function cmpn(num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + BN.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; // And `num` with `this` in-place - this._strip(); - var res; + BN.prototype.iuand = function iuand(num) { + // b = min-length(num, this) + var b; - if (this.length > 1) { - res = 1; + if (this.length > num.length) { + b = num; } else { - if (negative) { - num = -num; - } + b = this; + } - assert(num <= 0x3ffffff, 'Number is too big'); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; } - if (this.negative !== 0) return -res | 0; - return res; - }; // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` + this.length = b.length; + return this._strip(); + }; + BN.prototype.iand = function iand(num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; // And `num` with `this` - BN.prototype.cmp = function cmp(num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; // Unsigned comparison + BN.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; - BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - var res = 0; + BN.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; // Xor `num` with `this` in-place - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } + BN.prototype.iuxor = function iuxor(num) { + // a.length > b.length + var a; + var b; - break; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - return res; - }; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - BN.prototype.gtn = function gtn(num) { - return this.cmpn(num) === 1; - }; + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - BN.prototype.gt = function gt(num) { - return this.cmp(num) === 1; + this.length = a.length; + return this._strip(); }; - BN.prototype.gten = function gten(num) { - return this.cmpn(num) >= 0; - }; + BN.prototype.ixor = function ixor(num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; // Xor `num` with `this` - BN.prototype.gte = function gte(num) { - return this.cmp(num) >= 0; + + BN.prototype.xor = function xor(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); }; - BN.prototype.ltn = function ltn(num) { - return this.cmpn(num) === -1; - }; + BN.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; // Not ``this`` with ``width`` bitwidth + + + BN.prototype.inotn = function inotn(width) { + assert(typeof width === 'number' && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; // Extend the buffer with leading zeroes + + this._expand(bytesNeeded); - BN.prototype.lt = function lt(num) { - return this.cmp(num) === -1; - }; + if (bitsLeft > 0) { + bytesNeeded--; + } // Handle complete words - BN.prototype.lten = function lten(num) { - return this.cmpn(num) <= 0; - }; - BN.prototype.lte = function lte(num) { - return this.cmp(num) <= 0; - }; + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } // Handle the residue - BN.prototype.eqn = function eqn(num) { - return this.cmpn(num) === 0; - }; - BN.prototype.eq = function eq(num) { - return this.cmp(num) === 0; - }; // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft; + } // And remove leading zeroes - BN.red = function red(num) { - return new Red(num); + return this._strip(); }; - BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; + BN.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; // Set `bit` of `this` - BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; - }; + BN.prototype.setn = function setn(bit, val) { + assert(typeof bit === 'number' && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; - BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + this._expand(off + 1); - BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + return this._strip(); + }; // Add `num` to `this` in-place - BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + BN.prototype.iadd = function iadd(num) { + var r; // negative + positive - BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } // a.length > b.length - BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); + var a, b; - return this.red.mul(this, num); - }; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } - BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); + var carry = 0; - this.red._verify2(this, num); + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - return this.red.imul(this, num); - }; + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); + this.length = a.length; - this.red._verify1(this); + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - return this.red.sqr(this); - }; + return this; + }; // Add `num` to `this` - BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); + BN.prototype.add = function add(num) { + var res; - return this.red.isqr(this); - }; // Square root over p + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; // Subtract `num` from `this` in-place - BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); + BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } // At this point both numbers are positive - return this.red.sqrt(this); - }; - BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); + var cmp = this.cmp(num); // Optimization - zeroify - this.red._verify1(this); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } // a > b - return this.red.invm(this); - }; // Return negative clone of `this` % `red modulo` + var a, b; - BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - this.red._verify1(this); + var carry = 0; - return this.red.neg(this); - }; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } - BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } // Copy rest of the words - this.red._verify1(this); - return this.red.pow(this, num); - }; // Prime numbers with efficient reduction + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; // Pseudo-Mersenne prime + if (a !== this) { + this.negative = 1; + } - function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - this.tmp = this._tmp(); - } + return this._strip(); + }; // Subtract `num` from `this` - MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; + + BN.prototype.sub = function sub(num) { + return this.clone().isub(num); }; - MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; + function smallMulTo(self, num, out) { + out.negative = num.negative ^ self.negative; + var len = self.length + num.length | 0; + out.length = len; + len = len - 1 | 0; // Peel one iteration (compiler can't do it, because of code complexity) - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 0x3ffffff; + var carry = r / 0x4000000 | 0; + out.words[0] = lo; - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is a BN v4 instance - r.strip(); - } else { - // r is a BN v5 instance - r._strip(); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 0x4000000 | 0; + rword = r & 0x3ffffff; } + + out.words[k] = rword | 0; + carry = ncarry | 0; } - return r; - }; + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } - MPrime.prototype.split = function split(input, out) { - input.iushrn(this.n, 0, out); - }; + return out._strip(); + } // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). - MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); - }; - function K256() { - MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } + var comb10MulTo = function comb10MulTo(self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ - inherits(K256, MPrime); + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ - K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - var outLen = Math.min(input.length, 9); + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ - output.length = outLen; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } // Shift by 9 limbs + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = (next & mask) << 4 | prev >>> 22; - prev = next; - } + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ - prev >>>= 22; - input.words[i - 10] = prev; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ - K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ - var lo = 0; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + (lo / 0x4000000 | 0); - } // Fast length reduction + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ - if (num.words[num.length - 1] === 0) { - num.length--; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; - if (num.words[num.length - 1] === 0) { - num.length--; - } + if (c !== 0) { + o[19] = c; + out.length++; } - return num; - }; - - function P224() { - MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } + return out; + }; // Polyfill comb - inherits(P224, MPrime); - function P192() { - MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + if (!Math.imul) { + comb10MulTo = smallMulTo; } - inherits(P192, MPrime); - - function P25519() { - // 2 ^ 255 - 19 - MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } + function bigMulTo(self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + var carry = 0; + var hncarry = 0; - inherits(P25519, MPrime); + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); - P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 0x3ffffff; + ncarry = ncarry + (r / 0x4000000 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 0x3ffffff; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - num.words[i] = lo; - carry = hi; + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; } if (carry !== 0) { - num.words[num.length++] = carry; - } - - return num; - }; // Exported mostly for testing purposes, use plain name instead - - - BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) return primes[name]; - var prime; - - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); + out.words[k] = carry; } else { - throw new Error('Unknown prime ' + name); + out.length--; } - primes[name] = prime; - return prime; - }; // - // Base reduction engine - // + return out._strip(); + } + function jumboMulTo(self, num, out) { + // Temporary disable, see https://github.com/indutny/bn.js/issues/211 + // var fftm = new FFTM(); + // return fftm.mulp(self, num, out); + return bigMulTo(self, num, out); + } - function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); + BN.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; - this.m = prime.p; - this.prime = prime; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; + res = jumboMulTo(this, num, out); } - } - Red.prototype._verify1 = function _verify1(a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + return res; + }; // Cooley-Tukey algorithm for FFT - Red.prototype._verify2 = function _verify2(a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, 'red works only with red numbers'); - }; - Red.prototype.imod = function imod(a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - move(a, a.umod(this.m)._forceRed(this)); - return a; - }; + BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; // Multiply employing FFT - Red.prototype.neg = function neg(a) { - if (a.isZero()) { - return a.clone(); - } - return this.m.sub(a)._forceRed(this); - }; + BN.prototype.mulf = function mulf(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; // In-place Multiplication - Red.prototype.add = function add(a, b) { - this._verify2(a, b); - var res = a.add(b); + BN.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } + BN.prototype.imuln = function imuln(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(typeof num === 'number'); + assert(num < 0x4000000); // Carry - return res._forceRed(this); - }; + var carry = 0; - Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += w / 0x4000000 | 0; // NOTE: lo is 27bit maximum - var res = a.iadd(b); + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - return res; + return isNegNum ? this.ineg() : this; }; - Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); + BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; // `this` * `this` - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } + BN.prototype.sqr = function sqr() { + return this.mul(this); + }; // `this` * `this` in-place - return res._forceRed(this); - }; - Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); + BN.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; // Math.pow(`this`, `num`) - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + BN.prototype.pow = function pow(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); // Skip leading zeroes + + var res = this; + + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + res = res.mul(q); + } } return res; - }; + }; // Shift-left in-place - Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; + BN.prototype.iushln = function iushln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 0x3ffffff >>> 26 - r << 26 - r; + var i; - Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); + if (r !== 0) { + var carry = 0; - return this.imod(a.imul(b)); - }; + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } - Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); + if (carry) { + this.words[i] = carry; + this.length++; + } + } - return this.imod(a.mul(b)); - }; + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } - Red.prototype.isqr = function isqr(a) { - return this.imul(a, a.clone()); - }; + for (i = 0; i < s; i++) { + this.words[i] = 0; + } - Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); - }; + this.length += s; + } - Red.prototype.sqrt = function sqrt(a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); // Fast case + return this._strip(); + }; - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) + BN.prototype.ishln = function ishln(bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits - var q = this.m.subn(1); - var s = 0; + BN.prototype.iushrn = function iushrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; } - assert(!q.isZero()); - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); // Extended mode, copy masked part - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); + maskedWords.length = s; } - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - - while (t.cmp(one) !== 0) { - var tmp = t; + if (s === 0) ; else if (this.length > s) { + this.length -= s; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; } - - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + } else { + this.words[0] = 0; + this.length = 1; } - return r; - }; + var carry = 0; - Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } // Push carried bits as a mask - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); + + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; } + + return this._strip(); }; - Red.prototype.pow = function pow(a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; + BN.prototype.ishrn = function ishrn(bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; // Shift-left - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; + BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; - if (start === 0) { - start = 26; - } + BN.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; // Shift-right - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = word >> j & 1; + BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; - if (res !== wnd[0]) { - res = this.sqr(res); - } + BN.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; // Test if n bit is set - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } + BN.prototype.testn = function testn(bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; // Fast case: bit is much higher than all existing words - start = 26; - } + if (this.length <= s) return false; // Check bit and return - return res; - }; + var w = this.words[s]; + return !!(w & q); + }; // Return only lowers bits of number (in-place) - Red.prototype.convertTo = function convertTo(num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }; - Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; - }; // - // Montgomery method engine - // + BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert(this.negative === 0, 'imaskn works only with positive numbers'); + if (this.length <= s) { + return this; + } - BN.mont = function mont(num) { - return new Mont(num); - }; + if (r !== 0) { + s++; + } - function Mont(m) { - Red.call(this, m); - this.shift = this.m.bitLength(); + this.length = Math.min(s, this.length); - if (this.shift % 26 !== 0) { - this.shift += 26 - this.shift % 26; + if (r !== 0) { + var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; + this.words[this.length - 1] &= mask; } - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } + return this._strip(); + }; // Return only lowers bits of number - inherits(Mont, Red); - Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.ushln(this.shift)); - }; + BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; // Add plain number `num` to `this` - Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - Mont.prototype.imul = function imul(a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } + BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); // Possible sign change - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } // Add without checks - return res._forceRed(this); + + return this._iaddn(num); }; - Mont.prototype.mul = function mul(a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; + BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; // Carry - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } } - return res._forceRed(this); - }; + this.length = Math.max(this.length, i + 1); + return this; + }; // Subtract plain number `num` from `this` - Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; - })(module, commonjsGlobal); - })(bn$1); - var BN$1 = bn$1.exports; + BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); - function number$1(n) { - if (!Number.isSafeInteger(n) || n < 0) throw new Error("Wrong positive integer: ".concat(n)); - } - function bool(b) { - if (typeof b !== 'boolean') throw new Error("Expected boolean, not ".concat(b)); - } - function bytes(b) { - if (!(b instanceof Uint8Array)) throw new TypeError('Expected Uint8Array'); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } - for (var _len = arguments.length, lengths = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - lengths[_key - 1] = arguments[_key]; - } + this.words[0] -= num; - if (lengths.length > 0 && !lengths.includes(b.length)) throw new TypeError("Expected Uint8Array of length ".concat(lengths, ", not of length=").concat(b.length)); - } - function hash(hash) { - if (typeof hash !== 'function' || typeof hash.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); - number$1(hash.outputLen); - number$1(hash.blockLen); - } - function exists(instance) { - var checkFinished = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - if (instance.destroyed) throw new Error('Hash instance has been destroyed'); - if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); - } - function output(out, instance) { - bytes(out); - var min = instance.outputLen; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least ".concat(min)); - } - } - var assert$1 = { - number: number$1, - bool: bool, - bytes: bytes, - hash: hash, - exists: exists, - output: output - }; - var assert$2 = assert$1; + return this._strip(); + }; - var u32$1 = function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - }; // Cast array to view + BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; - var createView = function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - }; // The rotate right (circular right shift) operation for uint32 + BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; - var rotr = function rotr(word, shift) { - return word << 32 - shift | word >>> shift; - }; // big-endian hardware is rare. Just in case someone still decides to run hashes: - // early-throw an error because we don't support BE yet. + BN.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; - var isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; - if (!isLE) throw new Error('Non little-endian hardware is not supported'); - Array.from({ - length: 256 - }, function (v, i) { - return i.toString(16).padStart(2, '0'); - }); + BN.prototype.abs = function abs() { + return this.clone().iabs(); + }; - function utf8ToBytes(str) { - if (typeof str !== 'string') { - throw new TypeError("utf8ToBytes expected string, got ".concat(_typeof$1(str))); - } + BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; - return new TextEncoder().encode(str); - } - function toBytes(data) { - if (typeof data === 'string') data = utf8ToBytes(data); - if (!(data instanceof Uint8Array)) throw new TypeError("Expected input type is Uint8Array (got ".concat(_typeof$1(data), ")")); - return data; - } + this._expand(len); - var Hash = /*#__PURE__*/function () { - function Hash() { - _classCallCheck(this, Hash); - } + var w; + var carry = 0; - _createClass(Hash, [{ - key: "clone", - value: // Safe version that clones internal state - function clone() { - return this._cloneInto(); - } - }]); + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - (right / 0x4000000 | 0); + this.words[i + shift] = w & 0x3ffffff; + } - return Hash; - }(); // Check if object doens't have custom constructor (like Uint8Array/Array) - function wrapConstructor(hashConstructor) { - var hashC = function hashC(message) { - return hashConstructor().update(toBytes(message)).digest(); - }; + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } - var tmp = hashConstructor(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; + if (carry === 0) return this._strip(); // Subtraction overflow - hashC.create = function () { - return hashConstructor(); - }; + assert(carry === -1); + carry = 0; - return hashC; - } - function wrapConstructorWithOpts(hashCons) { - var hashC = function hashC(msg, opts) { - return hashCons(opts).update(toBytes(msg)).digest(); - }; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } - var tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; + this.negative = 1; + return this._strip(); + }; - hashC.create = function (opts) { - return hashCons(opts); - }; + BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; // Normalize - return hashC; - } + var bhi = b.words[b.length - 1] | 0; - function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE); + var bhiBits = this._countBits(bhi); - var _32n = BigInt(32); + shift = 26 - bhiBits; - var _u32_max = BigInt(0xffffffff); + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } // Initialize quotient - var wh = Number(value >> _32n & _u32_max); - var wl = Number(value & _u32_max); - var h = isLE ? 4 : 0; - var l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); - } // Base SHA2 class (RFC 6234) + var m = a.length - b.length; + var q; - var SHA2 = /*#__PURE__*/function (_Hash) { - _inherits(SHA2, _Hash); + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); - var _super = _createSuper(SHA2); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } - function SHA2(blockLen, outputLen, padOffset, isLE) { - var _this; + var diff = a.clone()._ishlnsubmul(b, 1, m); - _classCallCheck(this, SHA2); + if (diff.negative === 0) { + a = diff; - _this = _super.call(this); - _this.blockLen = blockLen; - _this.outputLen = outputLen; - _this.padOffset = padOffset; - _this.isLE = isLE; - _this.finished = false; - _this.length = 0; - _this.pos = 0; - _this.destroyed = false; - _this.buffer = new Uint8Array(blockLen); - _this.view = createView(_this.buffer); - return _this; - } + if (q) { + q.words[m] = 1; + } + } - _createClass(SHA2, [{ - key: "update", - value: function update(data) { - assert$2.exists(this); - var view = this.view, - buffer = this.buffer, - blockLen = this.blockLen; - data = toBytes(data); - var len = data.length; + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) - for (var pos = 0; pos < len;) { - var take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process + qj = Math.min(qj / bhi | 0, 0x3ffffff); - if (take === blockLen) { - var dataView = createView(data); + a._ishlnsubmul(b, qj, j); - for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + while (a.negative !== 0) { + qj--; + a.negative = 0; - continue; - } + a._ishlnsubmul(b, 1, j); - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; + if (!a.isZero()) { + a.negative ^= 1; + } + } - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; + if (q) { + q.words[j] = qj; } } - this.length += data.length; - this.roundClean(); - return this; - } - }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.exists(this); - assert$2.output(out, this); - this.finished = true; // Padding - // We can avoid allocation of buffer for padding completely if it - // was previously not allocated here. But it won't change performance. + if (q) { + q._strip(); + } - var buffer = this.buffer, - view = this.view, - blockLen = this.blockLen, - isLE = this.isLE; - var pos = this.pos; // append the bit '1' to the message + a._strip(); // Denormalize - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } // Pad until full block byte with zeros + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested - for (var i = pos; i < blockLen; i++) buffer[i] = 0; // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that - // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. - // So we just write lowest 64 bits of that value. + BN.prototype.divmod = function divmod(num, mode, positive) { + assert(!num.isZero()); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - var oview = createView(out); - var len = this.outputLen; // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + var div, mod, res; - if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit'); - var outLen = len / 4; - var state = this.get(); - if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - for (var _i2 = 0; _i2 < outLen; _i2++) oview.setUint32(4 * _i2, state[_i2], isLE); - } - }, { - key: "digest", - value: function digest() { - var buffer = this.buffer, - outputLen = this.outputLen; - this.digestInto(buffer); - var res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - }, { - key: "_cloneInto", - value: function _cloneInto(to) { - var _to; + if (mode !== 'mod') { + div = res.div.neg(); + } - to || (to = new this.constructor()); + if (mode !== 'div') { + mod = res.mod.neg(); - (_to = to).set.apply(_to, _toConsumableArray(this.get())); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } - var blockLen = this.blockLen, - buffer = this.buffer, - length = this.length, - finished = this.finished, - destroyed = this.destroyed, - pos = this.pos; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) to.buffer.set(buffer); - return to; - } - }]); + return { + div: div, + mod: mod + }; + } - return SHA2; - }(Hash); + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); - var U32_MASK64 = BigInt(Math.pow(2, 32) - 1); + if (mode !== 'mod') { + div = res.div.neg(); + } - var _32n = BigInt(32); // We are not using BigUint64Array, because they are extremely slow as per 2022 + return { + div: div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); - function fromBig(n) { - var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (le) return { - h: Number(n & U32_MASK64), - l: Number(n >> _32n & U32_MASK64) - }; - return { - h: Number(n >> _32n & U32_MASK64) | 0, - l: Number(n & U32_MASK64) | 0 - }; - } - function split(lst) { - var le = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var Ah = new Uint32Array(lst.length); - var Al = new Uint32Array(lst.length); + if (mode !== 'div') { + mod = res.mod.neg(); - for (var i = 0; i < lst.length; i++) { - var _fromBig2 = fromBig(lst[i], le), - h = _fromBig2.h, - l = _fromBig2.l; + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } - var _ref = [h, l]; - Ah[i] = _ref[0]; - Al[i] = _ref[1]; - } + return { + div: res.div, + mod: mod + }; + } // Both numbers are positive at this point + // Strip both numbers to approximate shift value - return [Ah, Al]; - } - var toBig = function toBig(h, l) { - return BigInt(h >>> 0) << _32n | BigInt(l >>> 0); - }; // for Shift in [0, 32) - var shrSH = function shrSH(h, l, s) { - return h >>> s; - }; + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } // Very short reduction - var shrSL = function shrSL(h, l, s) { - return h << 32 - s | l >>> s; - }; // Right rotate for Shift in [1, 32) + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } - var rotrSH = function rotrSH(h, l, s) { - return h >>> s | l << 32 - s; - }; + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modrn(num.words[0])) + }; + } - var rotrSL = function rotrSL(h, l, s) { - return h << 32 - s | l >>> s; - }; // Right rotate for Shift in (32, 64), NOTE: 32 is special case. + return { + div: this.divn(num.words[0]), + mod: new BN(this.modrn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; // Find `this` / `num` - var rotrBH = function rotrBH(h, l, s) { - return h << 64 - s | l >>> s - 32; - }; - var rotrBL = function rotrBL(h, l, s) { - return h >>> s - 32 | l << 64 - s; - }; // Right rotate for shift===32 (just swaps l&h) + BN.prototype.div = function div(num) { + return this.divmod(num, 'div', false).div; + }; // Find `this` % `num` - var rotr32H = function rotr32H(h, l) { - return l; - }; + BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod', false).mod; + }; - var rotr32L = function rotr32L(h, l) { - return h; - }; // Left rotate for Shift in [1, 32) + BN.prototype.umod = function umod(num) { + return this.divmod(num, 'mod', true).mod; + }; // Find Round(`this` / `num`) - var rotlSH = function rotlSH(h, l, s) { - return h << s | l >>> 32 - s; - }; + BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); // Fast case - exact division - var rotlSL = function rotlSL(h, l, s) { - return l << s | h >>> 32 - s; - }; // Left rotate for Shift in (32, 64), NOTE: 32 is special case. + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up - var rotlBH = function rotlBH(h, l, s) { - return l << s - 32 | h >>> 64 - s; - }; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; - var rotlBL = function rotlBL(h, l, s) { - return h << s - 32 | l >>> 64 - s; - }; // JS uses 32-bit signed integers for bitwise operations which means we cannot - // simple take carry out of low bit sum by shift, we need to use division. - // Removing "export" has 5% perf penalty -_- + BN.prototype.modrn = function modrn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } - function add(Ah, Al, Bh, Bl) { - var l = (Al >>> 0) + (Bl >>> 0); - return { - h: Ah + Bh + (l / Math.pow(2, 32) | 0) | 0, - l: l | 0 - }; - } // Addition with more than 2 elements + return isNegNum ? -acc : acc; + }; // WARNING: DEPRECATED - var add3L = function add3L(Al, Bl, Cl) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); - }; - var add3H = function add3H(low, Ah, Bh, Ch) { - return Ah + Bh + Ch + (low / Math.pow(2, 32) | 0) | 0; - }; + BN.prototype.modn = function modn(num) { + return this.modrn(num); + }; // In-place division by number + + + BN.prototype.idivn = function idivn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 0x3ffffff); + var carry = 0; + + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = w / num | 0; + carry = w % num; + } + + this._strip(); - var add4L = function add4L(Al, Bl, Cl, Dl) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); - }; + return isNegNum ? this.ineg() : this; + }; - var add4H = function add4H(low, Ah, Bh, Ch, Dh) { - return Ah + Bh + Ch + Dh + (low / Math.pow(2, 32) | 0) | 0; - }; + BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; - var add5L = function add5L(Al, Bl, Cl, Dl, El) { - return (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); - }; + BN.prototype.egcd = function egcd(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var x = this; + var y = p.clone(); - var add5H = function add5H(low, Ah, Bh, Ch, Dh, Eh) { - return Ah + Bh + Ch + Dh + Eh + (low / Math.pow(2, 32) | 0) | 0; - }; // prettier-ignore + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } // A * x + B * y = x - var u64$1 = { - fromBig: fromBig, - split: split, - toBig: toBig, - shrSH: shrSH, - shrSL: shrSL, - rotrSH: rotrSH, - rotrSL: rotrSL, - rotrBH: rotrBH, - rotrBL: rotrBL, - rotr32H: rotr32H, - rotr32L: rotr32L, - rotlSH: rotlSH, - rotlSL: rotlSL, - rotlBH: rotlBH, - rotlBL: rotlBL, - add: add, - add3L: add3L, - add3H: add3H, - add4L: add4L, - add4H: add4H, - add5H: add5H, - add5L: add5L - }; - var u64$2 = u64$1; + var A = new BN(1); + var B = new BN(0); // C * x + D * y = y - // prettier-ignore + var C = new BN(0); + var D = new BN(1); + var g = 0; - var _u64$split$1 = u64$2.split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(function (n) { - return BigInt(n); - })), - _u64$split2$1 = _slicedToArray(_u64$split$1, 2), - SHA512_Kh = _u64$split2$1[0], - SHA512_Kl = _u64$split2$1[1]; // Temporary buffer, not used to store anything between runs + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); - var SHA512_W_H = new Uint32Array(80); - var SHA512_W_L = new Uint32Array(80); - var SHA512 = /*#__PURE__*/function (_SHA) { - _inherits(SHA512, _SHA); + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - var _super = _createSuper(SHA512); + if (i > 0) { + x.iushrn(i); - function SHA512() { - var _this; + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } - _classCallCheck(this, SHA512); + A.iushrn(1); + B.iushrn(1); + } + } - _this = _super.call(this, 128, 64, 16, false); // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. - // Also looks cleaner and easier to verify with spec. - // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - // h -- high 32 bits, l -- low 32 bits + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - _this.Ah = 0x6a09e667 | 0; - _this.Al = 0xf3bcc908 | 0; - _this.Bh = 0xbb67ae85 | 0; - _this.Bl = 0x84caa73b | 0; - _this.Ch = 0x3c6ef372 | 0; - _this.Cl = 0xfe94f82b | 0; - _this.Dh = 0xa54ff53a | 0; - _this.Dl = 0x5f1d36f1 | 0; - _this.Eh = 0x510e527f | 0; - _this.El = 0xade682d1 | 0; - _this.Fh = 0x9b05688c | 0; - _this.Fl = 0x2b3e6c1f | 0; - _this.Gh = 0x1f83d9ab | 0; - _this.Gl = 0xfb41bd6b | 0; - _this.Hh = 0x5be0cd19 | 0; - _this.Hl = 0x137e2179 | 0; - return _this; - } // prettier-ignore + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } - _createClass(SHA512, [{ - key: "get", - value: function get() { - var Ah = this.Ah, - Al = this.Al, - Bh = this.Bh, - Bl = this.Bl, - Ch = this.Ch, - Cl = this.Cl, - Dh = this.Dh, - Dl = this.Dl, - Eh = this.Eh, - El = this.El, - Fh = this.Fh, - Fl = this.Fl, - Gh = this.Gh, - Gl = this.Gl, - Hh = this.Hh, - Hl = this.Hl; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } // prettier-ignore + C.iushrn(1); + D.iushrn(1); + } + } - }, { - key: "set", - value: function set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - }, { - key: "process", - value: function process(view, offset) { - // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array - for (var i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } } - for (var _i2 = 16; _i2 < 80; _i2++) { - // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) - var W15h = SHA512_W_H[_i2 - 15] | 0; - var W15l = SHA512_W_L[_i2 - 15] | 0; - var s0h = u64$2.rotrSH(W15h, W15l, 1) ^ u64$2.rotrSH(W15h, W15l, 8) ^ u64$2.shrSH(W15h, W15l, 7); - var s0l = u64$2.rotrSL(W15h, W15l, 1) ^ u64$2.rotrSL(W15h, W15l, 8) ^ u64$2.shrSL(W15h, W15l, 7); // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed - var W2h = SHA512_W_H[_i2 - 2] | 0; - var W2l = SHA512_W_L[_i2 - 2] | 0; - var s1h = u64$2.rotrSH(W2h, W2l, 19) ^ u64$2.rotrBH(W2h, W2l, 61) ^ u64$2.shrSH(W2h, W2l, 6); - var s1l = u64$2.rotrSL(W2h, W2l, 19) ^ u64$2.rotrBL(W2h, W2l, 61) ^ u64$2.shrSL(W2h, W2l, 6); // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - var SUMl = u64$2.add4L(s0l, s1l, SHA512_W_L[_i2 - 7], SHA512_W_L[_i2 - 16]); - var SUMh = u64$2.add4H(SUMl, s0h, s1h, SHA512_W_H[_i2 - 7], SHA512_W_H[_i2 - 16]); - SHA512_W_H[_i2] = SUMh | 0; - SHA512_W_L[_i2] = SUMl | 0; + BN.prototype._invmp = function _invmp(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); } - var Ah = this.Ah, - Al = this.Al, - Bh = this.Bh, - Bl = this.Bl, - Ch = this.Ch, - Cl = this.Cl, - Dh = this.Dh, - Dl = this.Dl, - Eh = this.Eh, - El = this.El, - Fh = this.Fh, - Fl = this.Fl, - Gh = this.Gh, - Gl = this.Gl, - Hh = this.Hh, - Hl = this.Hl; // Compression function main loop, 80 rounds + var x1 = new BN(1); + var x2 = new BN(0); + var delta = b.clone(); - for (var _i4 = 0; _i4 < 80; _i4++) { - // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) - var sigma1h = u64$2.rotrSH(Eh, El, 14) ^ u64$2.rotrSH(Eh, El, 18) ^ u64$2.rotrBH(Eh, El, 41); - var sigma1l = u64$2.rotrSL(Eh, El, 14) ^ u64$2.rotrSL(Eh, El, 18) ^ u64$2.rotrBL(Eh, El, 41); //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - var CHIh = Eh & Fh ^ ~Eh & Gh; - var CHIl = El & Fl ^ ~El & Gl; // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] - // prettier-ignore + if (i > 0) { + a.iushrn(i); - var T1ll = u64$2.add5L(Hl, sigma1l, CHIl, SHA512_Kl[_i4], SHA512_W_L[_i4]); - var T1h = u64$2.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[_i4], SHA512_W_H[_i4]); - var T1l = T1ll | 0; // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } - var sigma0h = u64$2.rotrSH(Ah, Al, 28) ^ u64$2.rotrBH(Ah, Al, 34) ^ u64$2.rotrBH(Ah, Al, 39); - var sigma0l = u64$2.rotrSL(Ah, Al, 28) ^ u64$2.rotrBL(Ah, Al, 34) ^ u64$2.rotrBL(Ah, Al, 39); - var MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - var MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; + x1.iushrn(1); + } + } - var _u64$add = u64$2.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0); + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - Eh = _u64$add.h; - El = _u64$add.l; - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - var All = u64$2.add3L(T1l, sigma0l, MAJl); - Ah = u64$2.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } // Add the compressed chunk to the current hash value + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } - var _u64$add2 = u64$2.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0); + x2.iushrn(1); + } + } - Ah = _u64$add2.h; - Al = _u64$add2.l; + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } - var _u64$add3 = u64$2.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0); + var res; - Bh = _u64$add3.h; - Bl = _u64$add3.l; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - var _u64$add4 = u64$2.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0); + if (res.cmpn(0) < 0) { + res.iadd(p); + } - Ch = _u64$add4.h; - Cl = _u64$add4.l; + return res; + }; - var _u64$add5 = u64$2.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0); + BN.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; // Remove common factor of two - Dh = _u64$add5.h; - Dl = _u64$add5.l; + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } - var _u64$add6 = u64$2.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0); + do { + while (a.isEven()) { + a.iushrn(1); + } - Eh = _u64$add6.h; - El = _u64$add6.l; + while (b.isEven()) { + b.iushrn(1); + } - var _u64$add7 = u64$2.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0); + var r = a.cmp(b); - Fh = _u64$add7.h; - Fl = _u64$add7.l; + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } - var _u64$add8 = u64$2.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0); + a.isub(b); + } while (true); - Gh = _u64$add8.h; - Gl = _u64$add8.l; + return b.iushln(shift); + }; // Invert number in the field F(num) - var _u64$add9 = u64$2.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0); - Hh = _u64$add9.h; - Hl = _u64$add9.l; - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - }, { - key: "roundClean", - value: function roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); - } - }, { - key: "destroy", - value: function destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - }]); + BN.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; - return SHA512; - }(SHA2); + BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; - var SHA512_224 = /*#__PURE__*/function (_SHA2) { - _inherits(SHA512_224, _SHA2); + BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; // And first word and num - var _super2 = _createSuper(SHA512_224); - function SHA512_224() { - var _this2; + BN.prototype.andln = function andln(num) { + return this.words[0] & num; + }; // Increment at the bit position in-line - _classCallCheck(this, SHA512_224); - _this2 = _super2.call(this); // h -- high 32 bits, l -- low 32 bits + BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; // Fast case: bit is much higher than all existing words - _this2.Ah = 0x8c3d37c8 | 0; - _this2.Al = 0x19544da2 | 0; - _this2.Bh = 0x73e19966 | 0; - _this2.Bl = 0x89dcd4d6 | 0; - _this2.Ch = 0x1dfab7ae | 0; - _this2.Cl = 0x32ff9c82 | 0; - _this2.Dh = 0x679dd514 | 0; - _this2.Dl = 0x582f9fcf | 0; - _this2.Eh = 0x0f6d2b69 | 0; - _this2.El = 0x7bd44da8 | 0; - _this2.Fh = 0x77e36f73 | 0; - _this2.Fl = 0x04c48942 | 0; - _this2.Gh = 0x3f9d85a8 | 0; - _this2.Gl = 0x6a1d36c8 | 0; - _this2.Hh = 0x1112e6ad | 0; - _this2.Hl = 0x91d692a1 | 0; - _this2.outputLen = 28; - return _this2; - } + if (this.length <= s) { + this._expand(s + 1); - return _createClass(SHA512_224); - }(SHA512); + this.words[s] |= q; + return this; + } // Add bit and propagate, if needed - var SHA512_256 = /*#__PURE__*/function (_SHA3) { - _inherits(SHA512_256, _SHA3); - var _super3 = _createSuper(SHA512_256); + var carry = q; - function SHA512_256() { - var _this3; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } - _classCallCheck(this, SHA512_256); + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } - _this3 = _super3.call(this); // h -- high 32 bits, l -- low 32 bits + return this; + }; - _this3.Ah = 0x22312194 | 0; - _this3.Al = 0xfc2bf72c | 0; - _this3.Bh = 0x9f555fa3 | 0; - _this3.Bl = 0xc84c64c2 | 0; - _this3.Ch = 0x2393b86b | 0; - _this3.Cl = 0x6f53b151 | 0; - _this3.Dh = 0x96387719 | 0; - _this3.Dl = 0x5940eabd | 0; - _this3.Eh = 0x96283ee2 | 0; - _this3.El = 0xa88effe3 | 0; - _this3.Fh = 0xbe5e1e25 | 0; - _this3.Fl = 0x53863992 | 0; - _this3.Gh = 0x2b0199fc | 0; - _this3.Gl = 0x2c85b8aa | 0; - _this3.Hh = 0x0eb72ddc | 0; - _this3.Hl = 0x81c52ca2 | 0; - _this3.outputLen = 32; - return _this3; - } + BN.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; - return _createClass(SHA512_256); - }(SHA512); + BN.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; - var SHA384 = /*#__PURE__*/function (_SHA4) { - _inherits(SHA384, _SHA4); + this._strip(); - var _super4 = _createSuper(SHA384); + var res; - function SHA384() { - var _this4; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - _classCallCheck(this, SHA384); + assert(num <= 0x3ffffff, 'Number is too big'); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } - _this4 = _super4.call(this); // h -- high 32 bits, l -- low 32 bits + if (this.negative !== 0) return -res | 0; + return res; + }; // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + + + BN.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; // Unsigned comparison - _this4.Ah = 0xcbbb9d5d | 0; - _this4.Al = 0xc1059ed8 | 0; - _this4.Bh = 0x629a292a | 0; - _this4.Bl = 0x367cd507 | 0; - _this4.Ch = 0x9159015a | 0; - _this4.Cl = 0x3070dd17 | 0; - _this4.Dh = 0x152fecd8 | 0; - _this4.Dl = 0xf70e5939 | 0; - _this4.Eh = 0x67332667 | 0; - _this4.El = 0xffc00b31 | 0; - _this4.Fh = 0x8eb44a87 | 0; - _this4.Fl = 0x68581511 | 0; - _this4.Gh = 0xdb0c2e0d | 0; - _this4.Gl = 0x64f98fa7 | 0; - _this4.Hh = 0x47b5481d | 0; - _this4.Hl = 0xbefa4fa4 | 0; - _this4.outputLen = 48; - return _this4; - } - return _createClass(SHA384); - }(SHA512); + BN.prototype.ucmp = function ucmp(num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; - var sha512 = wrapConstructor(function () { - return new SHA512(); - }); - wrapConstructor(function () { - return new SHA512_224(); - }); - wrapConstructor(function () { - return new SHA512_256(); - }); - wrapConstructor(function () { - return new SHA384(); - }); + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; - var _polyfillNode_crypto = {}; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } - var nodeCrypto = _global$1.crypto; + break; + } - var _0n$2 = BigInt(0); + return res; + }; - var _1n$2 = BigInt(1); + BN.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; - var _2n$2 = BigInt(2); + BN.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; - var _8n$1 = BigInt(8); + BN.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; - var CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'); - var CURVE$1 = Object.freeze({ - a: BigInt(-1), - d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), - P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'), - l: CU_O, - n: CU_O, - h: BigInt(8), - Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), - Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960') - }); - var POW_2_256$1 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); - var SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); - BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742'); - var SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); - var INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); - var ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); - var D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); + BN.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; - var ExtendedPoint = /*#__PURE__*/function () { - function ExtendedPoint(x, y, z, t) { - _classCallCheck(this, ExtendedPoint); + BN.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; - this.x = x; - this.y = y; - this.z = z; - this.t = t; - } + BN.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; - _createClass(ExtendedPoint, [{ - key: "equals", - value: function equals(other) { - assertExtPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - var X1Z2 = mod$1(X1 * Z2); - var X2Z1 = mod$1(X2 * Z1); - var Y1Z2 = mod$1(Y1 * Z2); - var Y2Z1 = mod$1(Y2 * Z1); - return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; - } - }, { - key: "negate", - value: function negate() { - return new ExtendedPoint(mod$1(-this.x), this.y, this.z, mod$1(-this.t)); - } - }, { - key: "double", - value: function double() { - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var a = CURVE$1.a; - var A = mod$1(X1 * X1); - var B = mod$1(Y1 * Y1); - var C = mod$1(_2n$2 * mod$1(Z1 * Z1)); - var D = mod$1(a * A); - var x1y1 = X1 + Y1; - var E = mod$1(mod$1(x1y1 * x1y1) - A - B); - var G = D + B; - var F = G - C; - var H = D - B; - var X3 = mod$1(E * F); - var Y3 = mod$1(G * H); - var T3 = mod$1(E * H); - var Z3 = mod$1(F * G); - return new ExtendedPoint(X3, Y3, Z3, T3); - } - }, { - key: "add", - value: function add(other) { - assertExtPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z, - T1 = this.t; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z, - T2 = other.t; - var A = mod$1((Y1 - X1) * (Y2 + X2)); - var B = mod$1((Y1 + X1) * (Y2 - X2)); - var F = mod$1(B - A); - if (F === _0n$2) return this["double"](); - var C = mod$1(Z1 * _2n$2 * T2); - var D = mod$1(T1 * _2n$2 * Z2); - var E = D + C; - var G = B + A; - var H = D - C; - var X3 = mod$1(E * F); - var Y3 = mod$1(G * H); - var T3 = mod$1(E * H); - var Z3 = mod$1(F * G); - return new ExtendedPoint(X3, Y3, Z3, T3); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "precomputeWindow", - value: function precomputeWindow(W) { - var windows = 1 + 256 / W; - var points = []; - var p = this; - var base = p; + BN.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; - for (var window = 0; window < windows; window++) { - base = p; - points.push(base); + BN.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; - for (var i = 1; i < Math.pow(2, W - 1); i++) { - base = base.add(p); - points.push(base); - } + BN.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; - p = base["double"](); - } + BN.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // - return points; - } - }, { - key: "wNAF", - value: function wNAF(n, affinePoint) { - if (!affinePoint && this.equals(ExtendedPoint.BASE)) affinePoint = Point$1.BASE; - var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - if (256 % W) { - throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); - } + BN.red = function red(num) { + return new Red(num); + }; - var precomputes = affinePoint && pointPrecomputes$1.get(affinePoint); + BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; - if (!precomputes) { - precomputes = this.precomputeWindow(W); + BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; - if (affinePoint && W !== 1) { - precomputes = ExtendedPoint.normalizeZ(precomputes); - pointPrecomputes$1.set(affinePoint, precomputes); - } - } + BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; - var p = ExtendedPoint.ZERO; - var f = ExtendedPoint.BASE; - var windows = 1 + 256 / W; - var windowSize = Math.pow(2, W - 1); - var mask = BigInt(Math.pow(2, W) - 1); - var maxNumber = Math.pow(2, W); - var shiftBy = BigInt(W); + BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - for (var window = 0; window < windows; window++) { - var offset = window * windowSize; - var wbits = Number(n & mask); - n >>= shiftBy; + BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n$2; - } + BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - var offset1 = offset; - var offset2 = offset + Math.abs(wbits) - 1; - var cond1 = window % 2 !== 0; - var cond2 = wbits < 0; + BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - if (wbits === 0) { - f = f.add(constTimeNegate$1(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate$1(cond2, precomputes[offset2])); - } - } + BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - return ExtendedPoint.normalizeZ([p, f])[0]; - } - }, { - key: "multiply", - value: function multiply(scalar, affinePoint) { - return this.wNAF(normalizeScalar$1(scalar, CURVE$1.l), affinePoint); - } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - var n = normalizeScalar$1(scalar, CURVE$1.l, false); - var G = ExtendedPoint.BASE; - var P0 = ExtendedPoint.ZERO; - if (n === _0n$2) return P0; - if (this.equals(P0) || n === _1n$2) return this; - if (this.equals(G)) return this.wNAF(n); - var p = P0; - var d = this; + BN.prototype.redShl = function redShl(num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; - while (n > _0n$2) { - if (n & _1n$2) p = p.add(d); - d = d["double"](); - n >>= _1n$2; - } + BN.prototype.redMul = function redMul(num) { + assert(this.red, 'redMul works only with red numbers'); - return p; - } - }, { - key: "isSmallOrder", - value: function isSmallOrder() { - return this.multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); - } - }, { - key: "isTorsionFree", - value: function isTorsionFree() { - var p = this.multiplyUnsafe(CURVE$1.l / _2n$2)["double"](); - if (CURVE$1.l % _2n$2) p = p.add(this); - return p.equals(ExtendedPoint.ZERO); - } - }, { - key: "toAffine", - value: function toAffine(invZ) { - var x = this.x, - y = this.y, - z = this.z; - var is0 = this.equals(ExtendedPoint.ZERO); - if (invZ == null) invZ = is0 ? _8n$1 : invert$1(z); - var ax = mod$1(x * invZ); - var ay = mod$1(y * invZ); - var zz = mod$1(z * invZ); - if (is0) return Point$1.ZERO; - if (zz !== _1n$2) throw new Error('invZ was invalid'); - return new Point$1(ax, ay); - } - }, { - key: "fromRistrettoBytes", - value: function fromRistrettoBytes() { - legacyRist(); - } - }, { - key: "toRistrettoBytes", - value: function toRistrettoBytes() { - legacyRist(); - } - }, { - key: "fromRistrettoHash", - value: function fromRistrettoHash() { - legacyRist(); - } - }], [{ - key: "fromAffine", - value: function fromAffine(p) { - if (!(p instanceof Point$1)) { - throw new TypeError('ExtendedPoint#fromAffine: expected Point'); - } + this.red._verify2(this, num); - if (p.equals(Point$1.ZERO)) return ExtendedPoint.ZERO; - return new ExtendedPoint(p.x, p.y, _1n$2, mod$1(p.x * p.y)); - } - }, { - key: "toAffineBatch", - value: function toAffineBatch(points) { - var toInv = invertBatch$1(points.map(function (p) { - return p.z; - })); - return points.map(function (p, i) { - return p.toAffine(toInv[i]); - }); - } - }, { - key: "normalizeZ", - value: function normalizeZ(points) { - return this.toAffineBatch(points).map(this.fromAffine); - } - }]); + return this.red.mul(this, num); + }; - return ExtendedPoint; - }(); + BN.prototype.redIMul = function redIMul(num) { + assert(this.red, 'redMul works only with red numbers'); - ExtendedPoint.BASE = new ExtendedPoint(CURVE$1.Gx, CURVE$1.Gy, _1n$2, mod$1(CURVE$1.Gx * CURVE$1.Gy)); - ExtendedPoint.ZERO = new ExtendedPoint(_0n$2, _1n$2, _1n$2, _0n$2); + this.red._verify2(this, num); - function constTimeNegate$1(condition, item) { - var neg = item.negate(); - return condition ? neg : item; - } + return this.red.imul(this, num); + }; - function assertExtPoint(other) { - if (!(other instanceof ExtendedPoint)) throw new TypeError('ExtendedPoint expected'); - } + BN.prototype.redSqr = function redSqr() { + assert(this.red, 'redSqr works only with red numbers'); - function assertRstPoint(other) { - if (!(other instanceof RistrettoPoint)) throw new TypeError('RistrettoPoint expected'); - } + this.red._verify1(this); - function legacyRist() { - throw new Error('Legacy method: switch to RistrettoPoint'); - } + return this.red.sqr(this); + }; - var RistrettoPoint = /*#__PURE__*/function () { - function RistrettoPoint(ep) { - _classCallCheck(this, RistrettoPoint); + BN.prototype.redISqr = function redISqr() { + assert(this.red, 'redISqr works only with red numbers'); - this.ep = ep; - } + this.red._verify1(this); - _createClass(RistrettoPoint, [{ - key: "toRawBytes", - value: function toRawBytes() { - var _this$ep = this.ep, - x = _this$ep.x, - y = _this$ep.y, - z = _this$ep.z, - t = _this$ep.t; - var u1 = mod$1(mod$1(z + y) * mod$1(z - y)); - var u2 = mod$1(x * y); - var u2sq = mod$1(u2 * u2); + return this.red.isqr(this); + }; // Square root over p - var _invertSqrt = invertSqrt(mod$1(u1 * u2sq)), - invsqrt = _invertSqrt.value; - var D1 = mod$1(invsqrt * u1); - var D2 = mod$1(invsqrt * u2); - var zInv = mod$1(D1 * D2 * t); - var D; + BN.prototype.redSqrt = function redSqrt() { + assert(this.red, 'redSqrt works only with red numbers'); - if (edIsNegative(t * zInv)) { - var _x = mod$1(y * SQRT_M1); + this.red._verify1(this); - var _y = mod$1(x * SQRT_M1); + return this.red.sqrt(this); + }; - x = _x; - y = _y; - D = mod$1(D1 * INVSQRT_A_MINUS_D); - } else { - D = D2; - } + BN.prototype.redInvm = function redInvm() { + assert(this.red, 'redInvm works only with red numbers'); - if (edIsNegative(x * zInv)) y = mod$1(-y); - var s = mod$1((z - y) * D); - if (edIsNegative(s)) s = mod$1(-s); - return numberTo32BytesLE(s); - } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); - } - }, { - key: "toString", - value: function toString() { - return this.toHex(); - } - }, { - key: "equals", - value: function equals(other) { - assertRstPoint(other); - var a = this.ep; - var b = other.ep; - var one = mod$1(a.x * b.y) === mod$1(a.y * b.x); - var two = mod$1(a.y * b.y) === mod$1(a.x * b.x); - return one || two; - } - }, { - key: "add", - value: function add(other) { - assertRstPoint(other); - return new RistrettoPoint(this.ep.add(other.ep)); - } - }, { - key: "subtract", - value: function subtract(other) { - assertRstPoint(other); - return new RistrettoPoint(this.ep.subtract(other.ep)); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return new RistrettoPoint(this.ep.multiply(scalar)); - } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - return new RistrettoPoint(this.ep.multiplyUnsafe(scalar)); - } - }], [{ - key: "calcElligatorRistrettoMap", - value: function calcElligatorRistrettoMap(r0) { - var d = CURVE$1.d; - var r = mod$1(SQRT_M1 * r0 * r0); - var Ns = mod$1((r + _1n$2) * ONE_MINUS_D_SQ); - var c = BigInt(-1); - var D = mod$1((c - d * r) * mod$1(r + d)); + this.red._verify1(this); - var _uvRatio = uvRatio(Ns, D), - Ns_D_is_sq = _uvRatio.isValid, - s = _uvRatio.value; + return this.red.invm(this); + }; // Return negative clone of `this` % `red modulo` - var s_ = mod$1(s * r0); - if (!edIsNegative(s_)) s_ = mod$1(-s_); - if (!Ns_D_is_sq) s = s_; - if (!Ns_D_is_sq) c = r; - var Nt = mod$1(c * (r - _1n$2) * D_MINUS_ONE_SQ - D); - var s2 = s * s; - var W0 = mod$1((s + s) * D); - var W1 = mod$1(Nt * SQRT_AD_MINUS_ONE); - var W2 = mod$1(_1n$2 - s2); - var W3 = mod$1(_1n$2 + s2); - return new ExtendedPoint(mod$1(W0 * W3), mod$1(W2 * W1), mod$1(W1 * W3), mod$1(W0 * W2)); - } - }, { - key: "hashToCurve", - value: function hashToCurve(hex) { - hex = ensureBytes$1(hex, 64); - var r1 = bytes255ToNumberLE(hex.slice(0, 32)); - var R1 = this.calcElligatorRistrettoMap(r1); - var r2 = bytes255ToNumberLE(hex.slice(32, 64)); - var R2 = this.calcElligatorRistrettoMap(r2); - return new RistrettoPoint(R1.add(R2)); - } - }, { - key: "fromHex", - value: function fromHex(hex) { - hex = ensureBytes$1(hex, 32); - var a = CURVE$1.a, - d = CURVE$1.d; - var emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; - var s = bytes255ToNumberLE(hex); - if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s)) throw new Error(emsg); - var s2 = mod$1(s * s); - var u1 = mod$1(_1n$2 + a * s2); - var u2 = mod$1(_1n$2 - a * s2); - var u1_2 = mod$1(u1 * u1); - var u2_2 = mod$1(u2 * u2); - var v = mod$1(a * d * u1_2 - u2_2); - var _invertSqrt2 = invertSqrt(mod$1(v * u2_2)), - isValid = _invertSqrt2.isValid, - I = _invertSqrt2.value; + BN.prototype.redNeg = function redNeg() { + assert(this.red, 'redNeg works only with red numbers'); - var Dx = mod$1(I * u2); - var Dy = mod$1(I * Dx * v); - var x = mod$1((s + s) * Dx); - if (edIsNegative(x)) x = mod$1(-x); - var y = mod$1(u1 * Dy); - var t = mod$1(x * y); - if (!isValid || edIsNegative(t) || y === _0n$2) throw new Error(emsg); - return new RistrettoPoint(new ExtendedPoint(x, y, _1n$2, t)); - } - }]); + this.red._verify1(this); - return RistrettoPoint; - }(); + return this.red.neg(this); + }; - RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE); - RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO); - var pointPrecomputes$1 = new WeakMap(); + BN.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, 'redPow(normalNum)'); - var Point$1 = /*#__PURE__*/function () { - function Point(x, y) { - _classCallCheck(this, Point); + this.red._verify1(this); - this.x = x; - this.y = y; - } + return this.red.pow(this, num); + }; // Prime numbers with efficient reduction - _createClass(Point, [{ - key: "_setWindowSize", - value: function _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes$1["delete"](this); - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var bytes = numberTo32BytesLE(this.y); - bytes[31] |= this.x & _1n$2 ? 0x80 : 0; - return bytes; - } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); - } - }, { - key: "toX25519", - value: function toX25519() { - var y = this.y; - var u = mod$1((_1n$2 + y) * invert$1(_1n$2 - y)); - return numberTo32BytesLE(u); - } - }, { - key: "isTorsionFree", - value: function isTorsionFree() { - return ExtendedPoint.fromAffine(this).isTorsionFree(); - } - }, { - key: "equals", - value: function equals(other) { - return this.x === other.x && this.y === other.y; - } - }, { - key: "negate", - value: function negate() { - return new Point(mod$1(-this.x), this.y); - } - }, { - key: "add", - value: function add(other) { - return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine(); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine(); + + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; // Pseudo-Mersenne prime + + function MPrime(name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); } - }], [{ - key: "fromHex", - value: function fromHex(hex) { - var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var d = CURVE$1.d, - P = CURVE$1.P; - hex = ensureBytes$1(hex, 32); - var normed = hex.slice(); - normed[31] = hex[31] & ~0x80; - var y = bytesToNumberLE(normed); - if (strict && y >= P) throw new Error('Expected 0 < hex < P'); - if (!strict && y >= POW_2_256$1) throw new Error('Expected 0 < hex < 2**256'); - var y2 = mod$1(y * y); - var u = mod$1(y2 - _1n$2); - var v = mod$1(d * y2 + _1n$2); - var _uvRatio2 = uvRatio(u, v), - isValid = _uvRatio2.isValid, - x = _uvRatio2.value; + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - if (!isValid) throw new Error('Point.fromHex: invalid y coordinate'); - var isXOdd = (x & _1n$2) === _1n$2; - var isLastByteOdd = (hex[31] & 0x80) !== 0; + MPrime.prototype.ireduce = function ireduce(num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; - if (isLastByteOdd !== isXOdd) { - x = mod$1(-x); + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== undefined) { + // r is a BN v4 instance + r.strip(); + } else { + // r is a BN v5 instance + r._strip(); + } } - return new Point(x, y); + return r; + }; + + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + + function K256() { + MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } - }, { - key: "fromPrivateKey", - value: function () { - var _fromPrivateKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(privateKey) { - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return getExtendedPublicKey(privateKey); - case 2: - return _context.abrupt("return", _context.sent.point); + inherits(K256, MPrime); - case 3: - case "end": - return _context.stop(); - } - }, _callee); - })); + K256.prototype.split = function split(input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + var outLen = Math.min(input.length, 9); - function fromPrivateKey(_x2) { - return _fromPrivateKey.apply(this, arguments); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; } - return fromPrivateKey; - }() - }]); + output.length = outLen; - return Point; - }(); + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } // Shift by 9 limbs - Point$1.BASE = new Point$1(CURVE$1.Gx, CURVE$1.Gy); - Point$1.ZERO = new Point$1(_0n$2, _1n$2); - var Signature$1 = /*#__PURE__*/function () { - function Signature(r, s) { - _classCallCheck(this, Signature); + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - this.r = r; - this.s = s; - this.assertValidity(); - } + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } - _createClass(Signature, [{ - key: "assertValidity", - value: function assertValidity() { - var r = this.r, - s = this.s; - if (!(r instanceof Point$1)) throw new Error('Expected Point instance'); - normalizeScalar$1(s, CURVE$1.l, false); - return this; - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var u8 = new Uint8Array(64); - u8.set(this.r.toRawBytes()); - u8.set(numberTo32BytesLE(this.s), 32); - return u8; + prev >>>= 22; + input.words[i - 10] = prev; + + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + + var lo = 0; + + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + (lo / 0x4000000 | 0); + } // Fast length reduction + + + if (num.words[num.length - 1] === 0) { + num.length--; + + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + + return num; + }; + + function P224() { + MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } - }, { - key: "toHex", - value: function toHex() { - return bytesToHex$1(this.toRawBytes()); + + inherits(P224, MPrime); + + function P192() { + MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } - }], [{ - key: "fromHex", - value: function fromHex(hex) { - var bytes = ensureBytes$1(hex, 64); - var r = Point$1.fromHex(bytes.slice(0, 32), false); - var s = bytesToNumberLE(bytes.slice(32, 64)); - return new Signature(r, s); + + inherits(P192, MPrime); + + function P25519() { + // 2 ^ 255 - 19 + MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } - }]); - return Signature; - }(); + inherits(P25519, MPrime); - function concatBytes$1() { - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } + P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; - if (!arrays.every(function (a) { - return a instanceof Uint8Array; - })) throw new Error('Expected Uint8Array list'); - if (arrays.length === 1) return arrays[0]; - var length = arrays.reduce(function (a, arr) { - return a + arr.length; - }, 0); - var result = new Uint8Array(length); + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } - for (var i = 0, pad = 0; i < arrays.length; i++) { - var arr = arrays[i]; - result.set(arr, pad); - pad += arr.length; - } + if (carry !== 0) { + num.words[num.length++] = carry; + } - return result; - } + return num; + }; // Exported mostly for testing purposes, use plain name instead - var hexes$1 = Array.from({ - length: 256 - }, function (v, i) { - return i.toString(16).padStart(2, '0'); - }); - function bytesToHex$1(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); - var hex = ''; + BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) return primes[name]; + var prime; - for (var i = 0; i < uint8a.length; i++) { - hex += hexes$1[uint8a[i]]; - } + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } - return hex; - } + primes[name] = prime; + return prime; + }; // + // Base reduction engine + // - function hexToBytes$1(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); - } - if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); - var array = new Uint8Array(hex.length / 2); + function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); - for (var i = 0; i < array.length; i++) { - var j = i * 2; - var hexByte = hex.slice(j, j + 2); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } - var _byte = Number.parseInt(hexByte, 16); + Red.prototype._verify1 = function _verify1(a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); - array[i] = _byte; - } + Red.prototype._verify2 = function _verify2(a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, 'red works only with red numbers'); + }; - return array; - } + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; - function numberTo32BytesBE(num) { - var length = 32; - var hex = num.toString(16).padStart(length * 2, '0'); - return hexToBytes$1(hex); - } + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } - function numberTo32BytesLE(num) { - return numberTo32BytesBE(num).reverse(); - } + return this.m.sub(a)._forceRed(this); + }; - function edIsNegative(num) { - return (mod$1(num) & _1n$2) === _1n$2; - } + Red.prototype.add = function add(a, b) { + this._verify2(a, b); - function bytesToNumberLE(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); - return BigInt('0x' + bytesToHex$1(Uint8Array.from(uint8a).reverse())); - } + var res = a.add(b); - var MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } - function bytes255ToNumberLE(bytes) { - return mod$1(bytesToNumberLE(bytes) & MAX_255B); - } + return res._forceRed(this); + }; - function mod$1(a) { - var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - var res = a % b; - return res >= _0n$2 ? res : b + res; - } + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); - function invert$1(number) { - var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; + var res = a.iadd(b); - if (number === _0n$2 || modulo <= _0n$2) { - throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); - } + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + + return res; + }; + + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + + var res = a.sub(b); - var a = mod$1(number, modulo); - var b = modulo; - var x = _0n$2, - u = _1n$2; + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } - while (a !== _0n$2) { - var q = b / a; - var r = b % a; - var m = x - u * q; - b = a, a = r, x = u, u = m; - } + return res._forceRed(this); + }; - var gcd = b; - if (gcd !== _1n$2) throw new Error('invert: does not exist'); - return mod$1(x, modulo); - } + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); - function invertBatch$1(nums) { - var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE$1.P; - var tmp = new Array(nums.length); - var lastMultiplied = nums.reduce(function (acc, num, i) { - if (num === _0n$2) return acc; - tmp[i] = acc; - return mod$1(acc * num, p); - }, _1n$2); - var inverted = invert$1(lastMultiplied, p); - nums.reduceRight(function (acc, num, i) { - if (num === _0n$2) return acc; - tmp[i] = mod$1(acc * tmp[i], p); - return mod$1(acc * num, p); - }, inverted); - return tmp; - } + var res = a.isub(b); - function pow2$1(x, power) { - var P = CURVE$1.P; - var res = x; + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } - while (power-- > _0n$2) { - res *= res; - res %= P; - } + return res; + }; - return res; - } + Red.prototype.shl = function shl(a, num) { + this._verify1(a); - function pow_2_252_3(x) { - var P = CURVE$1.P; + return this.imod(a.ushln(num)); + }; - var _5n = BigInt(5); + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); - var _10n = BigInt(10); + return this.imod(a.imul(b)); + }; - var _20n = BigInt(20); + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); - var _40n = BigInt(40); + return this.imod(a.mul(b)); + }; - var _80n = BigInt(80); + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; - var x2 = x * x % P; - var b2 = x2 * x % P; - var b4 = pow2$1(b2, _2n$2) * b2 % P; - var b5 = pow2$1(b4, _1n$2) * x % P; - var b10 = pow2$1(b5, _5n) * b5 % P; - var b20 = pow2$1(b10, _10n) * b10 % P; - var b40 = pow2$1(b20, _20n) * b20 % P; - var b80 = pow2$1(b40, _40n) * b40 % P; - var b160 = pow2$1(b80, _80n) * b80 % P; - var b240 = pow2$1(b160, _80n) * b80 % P; - var b250 = pow2$1(b240, _10n) * b10 % P; - var pow_p_5_8 = pow2$1(b250, _2n$2) * x % P; - return { - pow_p_5_8: pow_p_5_8, - b2: b2 - }; - } + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; - function uvRatio(u, v) { - var v3 = mod$1(v * v * v); - var v7 = mod$1(v3 * v3 * v); - var pow = pow_2_252_3(u * v7).pow_p_5_8; - var x = mod$1(u * v3 * pow); - var vx2 = mod$1(v * x * x); - var root1 = x; - var root2 = mod$1(x * SQRT_M1); - var useRoot1 = vx2 === u; - var useRoot2 = vx2 === mod$1(-u); - var noRoot = vx2 === mod$1(-u * SQRT_M1); - if (useRoot1) x = root1; - if (useRoot2 || noRoot) x = root2; - if (edIsNegative(x)) x = mod$1(-x); - return { - isValid: useRoot1 || useRoot2, - value: x - }; - } + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); // Fast case - function invertSqrt(number) { - return uvRatio(_1n$2, number); - } + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) - function modlLE(hash) { - return mod$1(bytesToNumberLE(hash), CURVE$1.l); - } - function equalBytes(b1, b2) { - if (b1.length !== b2.length) { - return false; - } + var q = this.m.subn(1); + var s = 0; - for (var i = 0; i < b1.length; i++) { - if (b1[i] !== b2[i]) { - return false; - } - } + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } - return true; - } + assert(!q.isZero()); + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. - function ensureBytes$1(hex, expectedLength) { - var bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes$1(hex); - if (typeof expectedLength === 'number' && bytes.length !== expectedLength) throw new Error("Expected ".concat(expectedLength, " bytes")); - return bytes; - } + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); - function normalizeScalar$1(num, max) { - var strict = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; - if (!max) throw new TypeError('Specify max value'); - if (typeof num === 'number' && Number.isSafeInteger(num)) num = BigInt(num); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - if (typeof num === 'bigint' && num < max) { - if (strict) { - if (_0n$2 < num) return num; - } else { - if (_0n$2 <= num) return num; - } - } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; - throw new TypeError('Expected valid scalar: 0 < scalar < max'); - } + while (t.cmp(one) !== 0) { + var tmp = t; - function adjustBytes25519(bytes) { - bytes[0] &= 248; - bytes[31] &= 127; - bytes[31] |= 64; - return bytes; - } + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } - function checkPrivateKey(key) { - key = typeof key === 'bigint' || typeof key === 'number' ? numberTo32BytesBE(normalizeScalar$1(key, POW_2_256$1)) : ensureBytes$1(key); - if (key.length !== 32) throw new Error("Expected 32 bytes"); - return key; - } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } - function getKeyFromHash(hashed) { - var head = adjustBytes25519(hashed.slice(0, 32)); - var prefix = hashed.slice(32, 64); - var scalar = modlLE(head); - var point = Point$1.BASE.multiply(scalar); - var pointBytes = point.toRawBytes(); - return { - head: head, - prefix: prefix, - scalar: scalar, - point: point, - pointBytes: pointBytes - }; - } + return r; + }; - var _sha512Sync; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); - function sha512s() { - if (typeof _sha512Sync !== 'function') throw new Error('utils.sha512Sync must be set to use sync methods'); - return _sha512Sync.apply(void 0, arguments); - } + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; - function getExtendedPublicKey(_x3) { - return _getExtendedPublicKey.apply(this, arguments); - } + Red.prototype.pow = function pow(a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; - function _getExtendedPublicKey() { - _getExtendedPublicKey = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) { - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - _context3.t0 = getKeyFromHash; - _context3.next = 3; - return utils$1.sha512(checkPrivateKey(key)); + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } - case 3: - _context3.t1 = _context3.sent; - return _context3.abrupt("return", (0, _context3.t0)(_context3.t1)); + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; - case 5: - case "end": - return _context3.stop(); + if (start === 0) { + start = 26; } - }, _callee3); - })); - return _getExtendedPublicKey.apply(this, arguments); - } - function getExtendedPublicKeySync(key) { - return getKeyFromHash(sha512s(checkPrivateKey(key))); - } + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; - function getPublicKeySync(privateKey) { - return getExtendedPublicKeySync(privateKey).pointBytes; - } + for (var j = start - 1; j >= 0; j--) { + var bit = word >> j & 1; - function signSync$1(message, privateKey) { - message = ensureBytes$1(message); + if (res !== wnd[0]) { + res = this.sqr(res); + } - var _getExtendedPublicKey2 = getExtendedPublicKeySync(privateKey), - prefix = _getExtendedPublicKey2.prefix, - scalar = _getExtendedPublicKey2.scalar, - pointBytes = _getExtendedPublicKey2.pointBytes; + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - var r = modlLE(sha512s(prefix, message)); - var R = Point$1.BASE.multiply(r); - var k = modlLE(sha512s(R.toRawBytes(), pointBytes, message)); - var s = mod$1(r + k * scalar, CURVE$1.l); - return new Signature$1(R, s).toRawBytes(); - } + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } - function prepareVerification(sig, message, publicKey) { - message = ensureBytes$1(message); - if (!(publicKey instanceof Point$1)) publicKey = Point$1.fromHex(publicKey, false); + start = 26; + } - var _ref = sig instanceof Signature$1 ? sig.assertValidity() : Signature$1.fromHex(sig), - r = _ref.r, - s = _ref.s; + return res; + }; - var SB = ExtendedPoint.BASE.multiplyUnsafe(s); - return { - r: r, - s: s, - SB: SB, - pub: publicKey, - msg: message - }; - } + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; - function finishVerification(publicKey, r, SB, hashed) { - var k = modlLE(hashed); - var kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k); - var RkA = ExtendedPoint.fromAffine(r).add(kA); - return RkA.subtract(SB).multiplyUnsafe(CURVE$1.h).equals(ExtendedPoint.ZERO); - } + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; // + // Montgomery method engine + // - function verifySync(sig, message, publicKey) { - var _prepareVerification = prepareVerification(sig, message, publicKey), - r = _prepareVerification.r, - SB = _prepareVerification.SB, - msg = _prepareVerification.msg, - pub = _prepareVerification.pub; - var hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg); - return finishVerification(pub, r, SB, hashed); - } + BN.mont = function mont(num) { + return new Mont(num); + }; - var sync = { - getExtendedPublicKey: getExtendedPublicKeySync, - getPublicKey: getPublicKeySync, - sign: signSync$1, - verify: verifySync - }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); - Point$1.BASE._setWindowSize(8); - var crypto$2 = { - node: nodeCrypto, - web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined - }; - var utils$1 = { - bytesToHex: bytesToHex$1, - hexToBytes: hexToBytes$1, - concatBytes: concatBytes$1, - getExtendedPublicKey: getExtendedPublicKey, - mod: mod$1, - invert: invert$1, - TORSION_SUBGROUP: ['0100000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', '0000000000000000000000000000000000000000000000000000000000000080', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', '0000000000000000000000000000000000000000000000000000000000000000', 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa'], - hashToPrivateScalar: function hashToPrivateScalar(hash) { - hash = ensureBytes$1(hash); - if (hash.length < 40 || hash.length > 1024) throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); - return mod$1(bytesToNumberLE(hash), CURVE$1.l - _1n$2) + _1n$2; - }, - randomBytes: function randomBytes() { - var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } - if (crypto$2.web) { - return crypto$2.web.getRandomValues(new Uint8Array(bytesLength)); - } else if (crypto$2.node) { - var randomBytes = crypto$2.node.randomBytes; - return new Uint8Array(randomBytes(bytesLength).buffer); - } else { - throw new Error("The environment doesn't have randomBytes function"); + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); } - }, - randomPrivateKey: function randomPrivateKey() { - return utils$1.randomBytes(32); - }, - sha512: function () { - var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var message, - buffer, - _args2 = arguments; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - message = concatBytes$1.apply(void 0, _args2); - if (!crypto$2.web) { - _context2.next = 8; - break; - } + inherits(Mont, Red); - _context2.next = 4; - return crypto$2.web.subtle.digest('SHA-512', message.buffer); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; - case 4: - buffer = _context2.sent; - return _context2.abrupt("return", new Uint8Array(buffer)); + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - case 8: - if (!crypto$2.node) { - _context2.next = 12; - break; - } + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - return _context2.abrupt("return", Uint8Array.from(crypto$2.node.createHash('sha512').update(message).digest())); + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; - case 12: - throw new Error("The environment doesn't have sha512 function"); + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - case 13: - case "end": - return _context2.stop(); - } - }, _callee2); - })); + return res._forceRed(this); + }; - function sha512() { - return _sha.apply(this, arguments); - } + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; - return sha512; - }(), - precompute: function precompute() { - var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; - var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point$1.BASE; - var cached = point.equals(Point$1.BASE) ? point : new Point$1(point.x, point.y); + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - cached._setWindowSize(windowSize); + return res._forceRed(this); + }; - cached.multiply(_2n$2); - return cached; - }, - sha512Sync: undefined - }; - Object.defineProperties(utils$1, { - sha512Sync: { - configurable: false, - get: function get() { - return _sha512Sync; - }, - set: function set(val) { - if (!_sha512Sync) _sha512Sync = val; - } - } - }); + Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, commonjsGlobal); + })(bn$1); + + var BN$1 = bn$1.exports; var safeBuffer = {exports: {}}; @@ -8129,7 +8131,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// (function (module, exports) { /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0$1; + var buffer = require$$1$1; var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { @@ -8208,7 +8210,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// var _Buffer = safeBuffer.exports.Buffer; - function base(ALPHABET) { + function base$1(ALPHABET) { if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long'); } @@ -8384,12 +8386,12 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// }; } - var src = base; + var src$1 = base$1; - var basex = src; - var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - var bs58 = basex(ALPHABET); - var bs58$1 = bs58; + var basex$1 = src$1; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + var bs58$2 = basex$1(ALPHABET$1); + var bs58$3 = bs58$2; var Chi = function Chi(a, b, c) { return a & b ^ ~a & c; @@ -9224,7 +9226,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// var bn_js_1 = __importDefault(bn$1.exports); - var bs58_1 = __importDefault(bs58); // TODO: Make sure this polyfill not included when not required + var bs58_1 = __importDefault(bs58$2); // TODO: Make sure this polyfill not included when not required var encoding = __importStar(require$$2); @@ -9796,7 +9798,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// }); Layout$3.s16 = Layout$3.s8 = Layout$3.nu64be = Layout$3.u48be = Layout$3.u40be = Layout$3.u32be = Layout$3.u24be = Layout$3.u16be = nu64$1 = Layout$3.nu64 = Layout$3.u48 = Layout$3.u40 = u32 = Layout$3.u32 = Layout$3.u24 = u16 = Layout$3.u16 = u8 = Layout$3.u8 = offset$1 = Layout$3.offset = Layout$3.greedy = Layout$3.Constant = Layout$3.UTF8 = Layout$3.CString = Layout$3.Blob = Layout$3.Boolean = Layout$3.BitField = Layout$3.BitStructure = Layout$3.VariantLayout = Layout$3.Union = Layout$3.UnionLayoutDiscriminator = Layout$3.UnionDiscriminator = Layout$3.Structure = Layout$3.Sequence = Layout$3.DoubleBE = Layout$3.Double = Layout$3.FloatBE = Layout$3.Float = Layout$3.NearInt64BE = Layout$3.NearInt64 = Layout$3.NearUInt64BE = Layout$3.NearUInt64 = Layout$3.IntBE = Layout$3.Int = Layout$3.UIntBE = Layout$3.UInt = Layout$3.OffsetLayout = Layout$3.GreedyCount = Layout$3.ExternalLayout = Layout$3.bindConstructorLayout = Layout$3.nameWithProperty = Layout$3.Layout = Layout$3.uint8ArrayToBuffer = Layout$3.checkUint8Array = void 0; Layout$3.constant = Layout$3.utf8 = Layout$3.cstr = blob$1 = Layout$3.blob = Layout$3.unionLayoutDiscriminator = Layout$3.union = seq$1 = Layout$3.seq = Layout$3.bits = struct = Layout$3.struct = Layout$3.f64be = Layout$3.f64 = Layout$3.f32be = Layout$3.f32 = Layout$3.ns64be = Layout$3.s48be = Layout$3.s40be = Layout$3.s32be = Layout$3.s24be = Layout$3.s16be = ns64 = Layout$3.ns64 = Layout$3.s48 = Layout$3.s40 = Layout$3.s32 = Layout$3.s24 = void 0; - var buffer_1 = require$$0$1; + var buffer_1 = require$$1$1; /* Check if a value is a Uint8Array. * * @ignore */ @@ -14542,7 +14544,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// } var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; - var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; + var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; function v35 (name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { if (typeof value === 'string') { @@ -14587,7 +14589,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// generateUUID.DNS = DNS; - generateUUID.URL = URL; + generateUUID.URL = URL$1; return generateUUID; } @@ -16150,57 +16152,572 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt); - } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;else clearEvent(this, evt); + } + + return this; + }; + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + + + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; // + // Alias methods names because people roll like that. + // + + + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; // + // Expose the prefix. + // + + EventEmitter.prefixed = prefix; // + // Allow `EventEmitter` to be imported as module namespace. + // + + EventEmitter.EventEmitter = EventEmitter; // + // Expose the module. + // + + { + module.exports = EventEmitter; + } + })(eventemitter3); + + return eventemitter3.exports; + } + + (function (exports) { + + var _interopRequireDefault = interopRequireDefault.exports; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = void 0; + + var _regenerator = _interopRequireDefault(requireRegenerator()); + + var _asyncToGenerator2 = _interopRequireDefault(requireAsyncToGenerator()); + + var _typeof2 = _interopRequireDefault(require_typeof()); + + var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + + var _createClass2 = _interopRequireDefault(requireCreateClass()); + + var _inherits2 = _interopRequireDefault(requireInherits()); + + var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + + var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + + var _eventemitter = requireEventemitter3(); + + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = (0, _getPrototypeOf2["default"])(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return (0, _possibleConstructorReturn2["default"])(this, result); + }; + } + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + var __rest = function (s, e) { + var t = {}; + + for (var p in s) { + if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + } + + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + }; // @ts-ignore + + + var CommonClient = /*#__PURE__*/function (_EventEmitter) { + (0, _inherits2["default"])(CommonClient, _EventEmitter); + + var _super = _createSuper(CommonClient); + /** + * Instantiate a Client class. + * @constructor + * @param {webSocketFactory} webSocketFactory - factory method for WebSocket + * @param {String} address - url to a websocket server + * @param {Object} options - ws options object with reconnect parameters + * @param {Function} generate_request_id - custom generation request Id + * @return {CommonClient} + */ + + + function CommonClient(webSocketFactory) { + var _this; + + var address = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "ws://localhost:8080"; + + var _a = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var generate_request_id = arguments.length > 3 ? arguments[3] : undefined; + (0, _classCallCheck2["default"])(this, CommonClient); + + var _a$autoconnect = _a.autoconnect, + autoconnect = _a$autoconnect === void 0 ? true : _a$autoconnect, + _a$reconnect = _a.reconnect, + reconnect = _a$reconnect === void 0 ? true : _a$reconnect, + _a$reconnect_interval = _a.reconnect_interval, + reconnect_interval = _a$reconnect_interval === void 0 ? 1000 : _a$reconnect_interval, + _a$max_reconnects = _a.max_reconnects, + max_reconnects = _a$max_reconnects === void 0 ? 5 : _a$max_reconnects, + rest_options = __rest(_a, ["autoconnect", "reconnect", "reconnect_interval", "max_reconnects"]); + + _this = _super.call(this); + _this.webSocketFactory = webSocketFactory; + _this.queue = {}; + _this.rpc_id = 0; + _this.address = address; + _this.autoconnect = autoconnect; + _this.ready = false; + _this.reconnect = reconnect; + _this.reconnect_timer_id = undefined; + _this.reconnect_interval = reconnect_interval; + _this.max_reconnects = max_reconnects; + _this.rest_options = rest_options; + _this.current_reconnects = 0; + + _this.generate_request_id = generate_request_id || function () { + return ++_this.rpc_id; + }; + + if (_this.autoconnect) _this._connect(_this.address, Object.assign({ + autoconnect: _this.autoconnect, + reconnect: _this.reconnect, + reconnect_interval: _this.reconnect_interval, + max_reconnects: _this.max_reconnects + }, _this.rest_options)); + return _this; + } + /** + * Connects to a defined server if not connected already. + * @method + * @return {Undefined} + */ + + + (0, _createClass2["default"])(CommonClient, [{ + key: "connect", + value: function connect() { + if (this.socket) return; + + this._connect(this.address, Object.assign({ + autoconnect: this.autoconnect, + reconnect: this.reconnect, + reconnect_interval: this.reconnect_interval, + max_reconnects: this.max_reconnects + }, this.rest_options)); + } + /** + * Calls a registered RPC method on server. + * @method + * @param {String} method - RPC method name + * @param {Object|Array} params - optional method parameters + * @param {Number} timeout - RPC reply timeout value + * @param {Object} ws_opts - options passed to ws + * @return {Promise} + */ + + }, { + key: "call", + value: function call(method, params, timeout, ws_opts) { + var _this2 = this; + + if (!ws_opts && "object" === (0, _typeof2["default"])(timeout)) { + ws_opts = timeout; + timeout = null; + } + + return new Promise(function (resolve, reject) { + if (!_this2.ready) return reject(new Error("socket not ready")); + + var rpc_id = _this2.generate_request_id(method, params); + + var message = { + jsonrpc: "2.0", + method: method, + params: params || null, + id: rpc_id + }; + + _this2.socket.send(JSON.stringify(message), ws_opts, function (error) { + if (error) return reject(error); + _this2.queue[rpc_id] = { + promise: [resolve, reject] + }; + + if (timeout) { + _this2.queue[rpc_id].timeout = setTimeout(function () { + delete _this2.queue[rpc_id]; + reject(new Error("reply timeout")); + }, timeout); + } + }); + }); + } + /** + * Logins with the other side of the connection. + * @method + * @param {Object} params - Login credentials object + * @return {Promise} + */ + + }, { + key: "login", + value: function () { + var _login = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var resp; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.call("rpc.login", params); + + case 2: + resp = _context.sent; + + if (resp) { + _context.next = 5; + break; + } + + throw new Error("authentication failed"); + + case 5: + return _context.abrupt("return", resp); + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function login(_x) { + return _login.apply(this, arguments); + } + + return login; + }() + /** + * Fetches a list of client's methods registered on server. + * @method + * @return {Array} + */ + + }, { + key: "listMethods", + value: function () { + var _listMethods = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.call("__listMethods"); + + case 2: + return _context2.abrupt("return", _context2.sent); + + case 3: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function listMethods() { + return _listMethods.apply(this, arguments); + } + + return listMethods; + }() + /** + * Sends a JSON-RPC 2.0 notification to server. + * @method + * @param {String} method - RPC method name + * @param {Object} params - optional method parameters + * @return {Promise} + */ + + }, { + key: "notify", + value: function notify(method, params) { + var _this3 = this; + + return new Promise(function (resolve, reject) { + if (!_this3.ready) return reject(new Error("socket not ready")); + var message = { + jsonrpc: "2.0", + method: method, + params: params || null + }; + + _this3.socket.send(JSON.stringify(message), function (error) { + if (error) return reject(error); + resolve(); + }); + }); + } + /** + * Subscribes for a defined event. + * @method + * @param {String|Array} event - event name + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "subscribe", + value: function () { + var _subscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(event) { + var result; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + if (typeof event === "string") event = [event]; + _context3.next = 3; + return this.call("rpc.on", event); + + case 3: + result = _context3.sent; + + if (!(typeof event === "string" && result[event] !== "ok")) { + _context3.next = 6; + break; + } + + throw new Error("Failed subscribing to an event '" + event + "' with: " + result[event]); + + case 6: + return _context3.abrupt("return", result); + + case 7: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function subscribe(_x2) { + return _subscribe.apply(this, arguments); + } + + return subscribe; + }() + /** + * Unsubscribes from a defined event. + * @method + * @param {String|Array} event - event name + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "unsubscribe", + value: function () { + var _unsubscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(event) { + var result; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + if (typeof event === "string") event = [event]; + _context4.next = 3; + return this.call("rpc.off", event); + + case 3: + result = _context4.sent; + + if (!(typeof event === "string" && result[event] !== "ok")) { + _context4.next = 6; + break; + } + + throw new Error("Failed unsubscribing from an event with: " + result); + + case 6: + return _context4.abrupt("return", result); + + case 7: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + function unsubscribe(_x3) { + return _unsubscribe.apply(this, arguments); + } + + return unsubscribe; + }() + /** + * Closes a WebSocket connection gracefully. + * @method + * @param {Number} code - socket close code + * @param {String} data - optional data to be sent before closing + * @return {Undefined} + */ + + }, { + key: "close", + value: function close(code, data) { + this.socket.close(code || 1000, data); + } + /** + * Connection/Message handler. + * @method + * @private + * @param {String} address - WebSocket API address + * @param {Object} options - ws options object + * @return {Undefined} + */ + + }, { + key: "_connect", + value: function _connect(address, options) { + var _this4 = this; + + clearTimeout(this.reconnect_timer_id); + this.socket = this.webSocketFactory(address, options); + this.socket.addEventListener("open", function () { + _this4.ready = true; + + _this4.emit("open"); - return this; - }; - /** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ + _this4.current_reconnects = 0; + }); + this.socket.addEventListener("message", function (_ref) { + var message = _ref.data; + if (message instanceof ArrayBuffer) message = Buffer$1.from(message).toString(); + try { + message = JSON.parse(message); + } catch (error) { + return; + } // check if any listeners are attached and forward event - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } + if (message.notification && _this4.listeners(message.notification).length) { + if (!Object.keys(message.params).length) return _this4.emit(message.notification); + var args = [message.notification]; + if (message.params.constructor === Object) args.push(message.params);else // using for-loop instead of unshift/spread because performance is better + for (var i = 0; i < message.params.length; i++) { + args.push(message.params[i]); + } // run as microtask so that pending queue messages are resolved first + // eslint-disable-next-line prefer-spread - return this; - }; // - // Alias methods names because people roll like that. - // + return Promise.resolve().then(function () { + _this4.emit.apply(_this4, args); + }); + } + if (!_this4.queue[message.id]) { + // general JSON RPC 2.0 events + if (message.method && message.params) { + // run as microtask so that pending queue messages are resolved first + return Promise.resolve().then(function () { + _this4.emit(message.method, message.params); + }); + } - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; // - // Expose the prefix. - // + return; + } // reject early since server's response is invalid - EventEmitter.prefixed = prefix; // - // Allow `EventEmitter` to be imported as module namespace. - // - EventEmitter.EventEmitter = EventEmitter; // - // Expose the module. - // + if ("error" in message === "result" in message) _this4.queue[message.id].promise[1](new Error("Server response malformed. Response must include either \"result\"" + " or \"error\", but not both.")); + if (_this4.queue[message.id].timeout) clearTimeout(_this4.queue[message.id].timeout); + if (message.error) _this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result); + delete _this4.queue[message.id]; + }); + this.socket.addEventListener("error", function (error) { + return _this4.emit("error", error); + }); + this.socket.addEventListener("close", function (_ref2) { + var code = _ref2.code, + reason = _ref2.reason; + if (_this4.ready) // Delay close event until internal state is updated + setTimeout(function () { + return _this4.emit("close", code, reason); + }, 0); + _this4.ready = false; + _this4.socket = undefined; + if (code === 1000) return; + _this4.current_reconnects++; + if (_this4.reconnect && (_this4.max_reconnects > _this4.current_reconnects || _this4.max_reconnects === 0)) _this4.reconnect_timer_id = setTimeout(function () { + return _this4._connect(address, options); + }, _this4.reconnect_interval); + }); + } + }]); + return CommonClient; + }(_eventemitter.EventEmitter); - { - module.exports = EventEmitter; - } - })(eventemitter3); + exports["default"] = CommonClient; + })(client); - return eventemitter3.exports; - } + var RpcWebSocketCommonClient = /*@__PURE__*/getDefaultExportFromCjs(client); + + var websocket_browser = {}; + + /** + * WebSocket implements a browser-side WebSocket specification. + * @module Client + */ (function (exports) { @@ -16208,13 +16725,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// Object.defineProperty(exports, "__esModule", { value: true }); - exports["default"] = void 0; - - var _regenerator = _interopRequireDefault(requireRegenerator()); - - var _asyncToGenerator2 = _interopRequireDefault(requireAsyncToGenerator()); - - var _typeof2 = _interopRequireDefault(require_typeof()); + exports["default"] = _default; var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); @@ -16259,13513 +16770,14535 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// } } - var __rest = function (s, e) { - var t = {}; + var WebSocketBrowserImpl = /*#__PURE__*/function (_EventEmitter) { + (0, _inherits2["default"])(WebSocketBrowserImpl, _EventEmitter); - for (var p in s) { - if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - } + var _super = _createSuper(WebSocketBrowserImpl); + /** Instantiate a WebSocket class + * @constructor + * @param {String} address - url to a websocket server + * @param {(Object)} options - websocket options + * @param {(String|Array)} protocols - a list of protocols + * @return {WebSocketBrowserImpl} - returns a WebSocket instance + */ - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; - }; // @ts-ignore + function WebSocketBrowserImpl(address, options, protocols) { + var _this; - var CommonClient = /*#__PURE__*/function (_EventEmitter) { - (0, _inherits2["default"])(CommonClient, _EventEmitter); + (0, _classCallCheck2["default"])(this, WebSocketBrowserImpl); + _this = _super.call(this); + _this.socket = new window.WebSocket(address, protocols); - var _super = _createSuper(CommonClient); + _this.socket.onopen = function () { + return _this.emit("open"); + }; + + _this.socket.onmessage = function (event) { + return _this.emit("message", event.data); + }; + + _this.socket.onerror = function (error) { + return _this.emit("error", error); + }; + + _this.socket.onclose = function (event) { + _this.emit("close", event.code, event.reason); + }; + + return _this; + } /** - * Instantiate a Client class. - * @constructor - * @param {webSocketFactory} webSocketFactory - factory method for WebSocket - * @param {String} address - url to a websocket server - * @param {Object} options - ws options object with reconnect parameters - * @param {Function} generate_request_id - custom generation request Id - * @return {CommonClient} + * Sends data through a websocket connection + * @method + * @param {(String|Object)} data - data to be sent via websocket + * @param {Object} optionsOrCallback - ws options + * @param {Function} callback - a callback called once the data is sent + * @return {Undefined} */ - function CommonClient(webSocketFactory) { - var _this; + (0, _createClass2["default"])(WebSocketBrowserImpl, [{ + key: "send", + value: function send(data, optionsOrCallback, callback) { + var cb = callback || optionsOrCallback; + + try { + this.socket.send(data); + cb(); + } catch (error) { + cb(error); + } + } + /** + * Closes an underlying socket + * @method + * @param {Number} code - status code explaining why the connection is being closed + * @param {String} reason - a description why the connection is closing + * @return {Undefined} + * @throws {Error} + */ + + }, { + key: "close", + value: function close(code, reason) { + this.socket.close(code, reason); + } + }, { + key: "addEventListener", + value: function addEventListener(type, listener, options) { + this.socket.addEventListener(type, listener, options); + } + }]); + return WebSocketBrowserImpl; + }(_eventemitter.EventEmitter); + /** + * factory method for common WebSocket instance + * @method + * @param {String} address - url to a websocket server + * @param {(Object)} options - websocket options + * @return {Undefined} + */ + + + function _default(address, options) { + return new WebSocketBrowserImpl(address, options); + } + })(websocket_browser); + + var createRpc = /*@__PURE__*/getDefaultExportFromCjs(websocket_browser); + + var SHA3_PI = [], + SHA3_ROTL = [], + _SHA3_IOTA = []; + + var _0n$1 = BigInt(0); + + var _1n$1 = BigInt(1); + + var _2n$1 = BigInt(2); + + var _7n = BigInt(7); + + var _256n = BigInt(256); + + var _0x71n = BigInt(0x71); + + for (var round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) { + // Pi + var _ref = [y, (2 * x + 3 * y) % 5]; + x = _ref[0]; + y = _ref[1]; + SHA3_PI.push(2 * (5 * y + x)); // Rotational + + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); // Iota + + var t = _0n$1; + + for (var j = 0; j < 7; j++) { + R = (R << _1n$1 ^ (R >> _7n) * _0x71n) % _256n; + if (R & _2n$1) t ^= _1n$1 << (_1n$1 << BigInt(j)) - _1n$1; + } + + _SHA3_IOTA.push(t); + } + + var _u64$split = u64$2.split(_SHA3_IOTA, true), + _u64$split2 = _slicedToArray(_u64$split, 2), + SHA3_IOTA_H = _u64$split2[0], + SHA3_IOTA_L = _u64$split2[1]; // Left rotation (without 0, 32, 64) + + + var rotlH = function rotlH(h, l, s) { + return s > 32 ? u64$2.rotlBH(h, l, s) : u64$2.rotlSH(h, l, s); + }; + + var rotlL = function rotlL(h, l, s) { + return s > 32 ? u64$2.rotlBL(h, l, s) : u64$2.rotlSL(h, l, s); + }; // Same as keccakf1600, but allows to skip some rounds + + + function keccakP(s) { + var rounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 24; + var B = new Uint32Array(5 * 2); // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + + for (var _round2 = 24 - rounds; _round2 < 24; _round2++) { + // Theta θ + for (var _x2 = 0; _x2 < 10; _x2++) B[_x2] = s[_x2] ^ s[_x2 + 10] ^ s[_x2 + 20] ^ s[_x2 + 30] ^ s[_x2 + 40]; + + for (var _x4 = 0; _x4 < 10; _x4 += 2) { + var idx1 = (_x4 + 8) % 10; + var idx0 = (_x4 + 2) % 10; + var B0 = B[idx0]; + var B1 = B[idx0 + 1]; + var Th = rotlH(B0, B1, 1) ^ B[idx1]; + var Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + + for (var _y2 = 0; _y2 < 50; _y2 += 10) { + s[_x4 + _y2] ^= Th; + s[_x4 + _y2 + 1] ^= Tl; + } + } // Rho (ρ) and Pi (π) + + + var curH = s[2]; + var curL = s[3]; + + for (var _t2 = 0; _t2 < 24; _t2++) { + var shift = SHA3_ROTL[_t2]; + + var _Th = rotlH(curH, curL, shift); + + var _Tl = rotlL(curH, curL, shift); + + var PI = SHA3_PI[_t2]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = _Th; + s[PI + 1] = _Tl; + } // Chi (χ) + + + for (var _y4 = 0; _y4 < 50; _y4 += 10) { + for (var _x6 = 0; _x6 < 10; _x6++) B[_x6] = s[_y4 + _x6]; + + for (var _x8 = 0; _x8 < 10; _x8++) s[_y4 + _x8] ^= ~B[(_x8 + 2) % 10] & B[(_x8 + 4) % 10]; + } // Iota (ι) + + + s[0] ^= SHA3_IOTA_H[_round2]; + s[1] ^= SHA3_IOTA_L[_round2]; + } + + B.fill(0); + } + var Keccak = /*#__PURE__*/function (_Hash) { + _inherits(Keccak, _Hash); + + var _super = _createSuper(Keccak); + + // NOTE: we accept arguments in bytes instead of bits here. + function Keccak(blockLen, suffix, outputLen) { + var _this; + + var enableXOF = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var rounds = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 24; + + _classCallCheck(this, Keccak); + + _this = _super.call(this); + _this.blockLen = blockLen; + _this.suffix = suffix; + _this.outputLen = outputLen; + _this.enableXOF = enableXOF; + _this.rounds = rounds; + _this.pos = 0; + _this.posOut = 0; + _this.finished = false; + _this.destroyed = false; // Can be passed from user as dkLen + + assert$2.number(outputLen); // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + + if (0 >= _this.blockLen || _this.blockLen >= 200) throw new Error('Sha3 supports only keccak-f1600 function'); + _this.state = new Uint8Array(200); + _this.state32 = u32$1(_this.state); + return _this; + } + + _createClass(Keccak, [{ + key: "keccak", + value: function keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + }, { + key: "update", + value: function update(data) { + assert$2.exists(this); + var blockLen = this.blockLen, + state = this.state; + data = toBytes(data); + var len = data.length; + + for (var pos = 0; pos < len;) { + var take = Math.min(blockLen - this.pos, len - pos); + + for (var i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + + if (this.pos === blockLen) this.keccak(); + } + + return this; + } + }, { + key: "finish", + value: function finish() { + if (this.finished) return; + this.finished = true; + var state = this.state, + suffix = this.suffix, + pos = this.pos, + blockLen = this.blockLen; // Do the padding + + state[pos] ^= suffix; + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + }, { + key: "writeInto", + value: function writeInto(out) { + assert$2.exists(this, false); + assert$2.bytes(out); + this.finish(); + var bufferOut = this.state; + var blockLen = this.blockLen; + + for (var pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) this.keccak(); + var take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + + return out; + } + }, { + key: "xofInto", + value: function xofInto(out) { + // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + }, { + key: "xof", + value: function xof(bytes) { + assert$2.number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.output(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.writeInto(out); + this.destroy(); + return out; + } + }, { + key: "digest", + value: function digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + }, { + key: "destroy", + value: function destroy() { + this.destroyed = true; + this.state.fill(0); + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + var blockLen = this.blockLen, + suffix = this.suffix, + outputLen = this.outputLen, + rounds = this.rounds, + enableXOF = this.enableXOF; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; // Suffix can change in cSHAKE + + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } + }]); + + return Keccak; + }(Hash); + + var gen = function gen(suffix, blockLen, outputLen) { + return wrapConstructor(function () { + return new Keccak(blockLen, suffix, outputLen); + }); + }; + + gen(0x06, 144, 224 / 8); + /** + * SHA3-256 hash function + * @param message - that would be hashed + */ + + gen(0x06, 136, 256 / 8); + gen(0x06, 104, 384 / 8); + gen(0x06, 72, 512 / 8); + gen(0x01, 144, 224 / 8); + /** + * keccak-256 hash function. Different from SHA3-256. + * @param message - that would be hashed + */ + + var keccak_256 = gen(0x01, 136, 256 / 8); + gen(0x01, 104, 384 / 8); + gen(0x01, 72, 512 / 8); + + var genShake = function genShake(suffix, blockLen, outputLen) { + return wrapConstructorWithOpts(function () { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true); + }); + }; - var address = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "ws://localhost:8080"; + genShake(0x1f, 168, 128 / 8); + genShake(0x1f, 136, 256 / 8); - var _a = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var HMAC = /*#__PURE__*/function (_Hash) { + _inherits(HMAC, _Hash); - var generate_request_id = arguments.length > 3 ? arguments[3] : undefined; - (0, _classCallCheck2["default"])(this, CommonClient); + var _super = _createSuper(HMAC); - var _a$autoconnect = _a.autoconnect, - autoconnect = _a$autoconnect === void 0 ? true : _a$autoconnect, - _a$reconnect = _a.reconnect, - reconnect = _a$reconnect === void 0 ? true : _a$reconnect, - _a$reconnect_interval = _a.reconnect_interval, - reconnect_interval = _a$reconnect_interval === void 0 ? 1000 : _a$reconnect_interval, - _a$max_reconnects = _a.max_reconnects, - max_reconnects = _a$max_reconnects === void 0 ? 5 : _a$max_reconnects, - rest_options = __rest(_a, ["autoconnect", "reconnect", "reconnect_interval", "max_reconnects"]); + function HMAC(hash, _key) { + var _this; - _this = _super.call(this); - _this.webSocketFactory = webSocketFactory; - _this.queue = {}; - _this.rpc_id = 0; - _this.address = address; - _this.autoconnect = autoconnect; - _this.ready = false; - _this.reconnect = reconnect; - _this.reconnect_timer_id = undefined; - _this.reconnect_interval = reconnect_interval; - _this.max_reconnects = max_reconnects; - _this.rest_options = rest_options; - _this.current_reconnects = 0; + _classCallCheck(this, HMAC); - _this.generate_request_id = generate_request_id || function () { - return ++_this.rpc_id; - }; + _this = _super.call(this); + _this.finished = false; + _this.destroyed = false; + assert$2.hash(hash); + var key = toBytes(_key); + _this.iHash = hash.create(); + if (typeof _this.iHash.update !== 'function') throw new TypeError('Expected instance of class which extends utils.Hash'); + _this.blockLen = _this.iHash.blockLen; + _this.outputLen = _this.iHash.outputLen; + var blockLen = _this.blockLen; + var pad = new Uint8Array(blockLen); // blockLen can be bigger than outputLen - if (_this.autoconnect) _this._connect(_this.address, Object.assign({ - autoconnect: _this.autoconnect, - reconnect: _this.reconnect, - reconnect_interval: _this.reconnect_interval, - max_reconnects: _this.max_reconnects - }, _this.rest_options)); - return _this; - } - /** - * Connects to a defined server if not connected already. - * @method - * @return {Undefined} - */ + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (var i = 0; i < pad.length; i++) pad[i] ^= 0x36; - (0, _createClass2["default"])(CommonClient, [{ - key: "connect", - value: function connect() { - if (this.socket) return; + _this.iHash.update(pad); // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone - this._connect(this.address, Object.assign({ - autoconnect: this.autoconnect, - reconnect: this.reconnect, - reconnect_interval: this.reconnect_interval, - max_reconnects: this.max_reconnects - }, this.rest_options)); - } - /** - * Calls a registered RPC method on server. - * @method - * @param {String} method - RPC method name - * @param {Object|Array} params - optional method parameters - * @param {Number} timeout - RPC reply timeout value - * @param {Object} ws_opts - options passed to ws - * @return {Promise} - */ - }, { - key: "call", - value: function call(method, params, timeout, ws_opts) { - var _this2 = this; + _this.oHash = hash.create(); // Undo internal XOR && apply outer XOR - if (!ws_opts && "object" === (0, _typeof2["default"])(timeout)) { - ws_opts = timeout; - timeout = null; - } + for (var _i2 = 0; _i2 < pad.length; _i2++) pad[_i2] ^= 0x36 ^ 0x5c; - return new Promise(function (resolve, reject) { - if (!_this2.ready) return reject(new Error("socket not ready")); + _this.oHash.update(pad); - var rpc_id = _this2.generate_request_id(method, params); + pad.fill(0); + return _this; + } - var message = { - jsonrpc: "2.0", - method: method, - params: params || null, - id: rpc_id - }; + _createClass(HMAC, [{ + key: "update", + value: function update(buf) { + assert$2.exists(this); + this.iHash.update(buf); + return this; + } + }, { + key: "digestInto", + value: function digestInto(out) { + assert$2.exists(this); + assert$2.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + }, { + key: "digest", + value: function digest() { + var out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + }, { + key: "_cloneInto", + value: function _cloneInto(to) { + // Create new instance without calling constructor since key already in state and we don't know it. + to || (to = Object.create(Object.getPrototypeOf(this), {})); + var oHash = this.oHash, + iHash = this.iHash, + finished = this.finished, + destroyed = this.destroyed, + blockLen = this.blockLen, + outputLen = this.outputLen; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + }, { + key: "destroy", + value: function destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }]); - _this2.socket.send(JSON.stringify(message), ws_opts, function (error) { - if (error) return reject(error); - _this2.queue[rpc_id] = { - promise: [resolve, reject] - }; + return HMAC; + }(Hash); + /** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - message key + * @param message - message data + */ - if (timeout) { - _this2.queue[rpc_id].timeout = setTimeout(function () { - delete _this2.queue[rpc_id]; - reject(new Error("reply timeout")); - }, timeout); - } - }); - }); - } - /** - * Logins with the other side of the connection. - * @method - * @param {Object} params - Login credentials object - * @return {Promise} - */ - }, { - key: "login", - value: function () { - var _login = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { - var resp; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.call("rpc.login", params); + var hmac = function hmac(hash, key, message) { + return new HMAC(hash, key).update(message).digest(); + }; - case 2: - resp = _context.sent; + hmac.create = function (hash, key) { + return new HMAC(hash, key); + }; - if (resp) { - _context.next = 5; - break; - } + var _0n = BigInt(0); - throw new Error("authentication failed"); + var _1n = BigInt(1); - case 5: - return _context.abrupt("return", resp); + var _2n = BigInt(2); - case 6: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); + var _3n = BigInt(3); - function login(_x) { - return _login.apply(this, arguments); - } + var _8n = BigInt(8); - return login; - }() - /** - * Fetches a list of client's methods registered on server. - * @method - * @return {Array} - */ + var CURVE = Object.freeze({ + a: _0n, + b: BigInt(7), + P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + h: _1n, + Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), + Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee') + }); - }, { - key: "listMethods", - value: function () { - var _listMethods = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this.call("__listMethods"); + var divNearest = function divNearest(a, b) { + return (a + b / _2n) / b; + }; - case 2: - return _context2.abrupt("return", _context2.sent); + var endo = { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + splitScalar: function splitScalar(k) { + var n = CURVE.n; + var a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); + var b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); + var a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); + var b2 = a1; + var POW_2_128 = BigInt('0x100000000000000000000000000000000'); + var c1 = divNearest(b2 * k, n); + var c2 = divNearest(-b1 * k, n); + var k1 = mod(k - c1 * a1 - c2 * a2, n); + var k2 = mod(-c1 * b1 - c2 * b2, n); + var k1neg = k1 > POW_2_128; + var k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; - case 3: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); + } - function listMethods() { - return _listMethods.apply(this, arguments); - } + return { + k1neg: k1neg, + k1: k1, + k2neg: k2neg, + k2: k2 + }; + } + }; + var fieldLen = 32; + var groupLen = 32; + var hashLen = 32; + var compressedLen = fieldLen + 1; + var uncompressedLen = 2 * fieldLen + 1; - return listMethods; - }() - /** - * Sends a JSON-RPC 2.0 notification to server. - * @method - * @param {String} method - RPC method name - * @param {Object} params - optional method parameters - * @return {Promise} - */ + function weierstrass(x) { + var a = CURVE.a, + b = CURVE.b; + var x2 = mod(x * x); + var x3 = mod(x2 * x); + return mod(x3 + a * x + b); + } - }, { - key: "notify", - value: function notify(method, params) { - var _this3 = this; + var USE_ENDOMORPHISM = CURVE.a === _0n; - return new Promise(function (resolve, reject) { - if (!_this3.ready) return reject(new Error("socket not ready")); - var message = { - jsonrpc: "2.0", - method: method, - params: params || null - }; + var ShaError = /*#__PURE__*/function (_Error) { + _inherits(ShaError, _Error); - _this3.socket.send(JSON.stringify(message), function (error) { - if (error) return reject(error); - resolve(); - }); - }); - } - /** - * Subscribes for a defined event. - * @method - * @param {String|Array} event - event name - * @return {Undefined} - * @throws {Error} - */ + var _super = _createSuper(ShaError); - }, { - key: "subscribe", - value: function () { - var _subscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(event) { - var result; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - if (typeof event === "string") event = [event]; - _context3.next = 3; - return this.call("rpc.on", event); + function ShaError(message) { + _classCallCheck(this, ShaError); - case 3: - result = _context3.sent; + return _super.call(this, message); + } - if (!(typeof event === "string" && result[event] !== "ok")) { - _context3.next = 6; - break; - } + return _createClass(ShaError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - throw new Error("Failed subscribing to an event '" + event + "' with: " + result[event]); + function assertJacPoint(other) { + if (!(other instanceof JacobianPoint)) throw new TypeError('JacobianPoint expected'); + } - case 6: - return _context3.abrupt("return", result); + var JacobianPoint = /*#__PURE__*/function () { + function JacobianPoint(x, y, z) { + _classCallCheck(this, JacobianPoint); - case 7: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + this.x = x; + this.y = y; + this.z = z; + } - function subscribe(_x2) { - return _subscribe.apply(this, arguments); + _createClass(JacobianPoint, [{ + key: "equals", + value: function equals(other) { + assertJacPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + var Z1Z1 = mod(Z1 * Z1); + var Z2Z2 = mod(Z2 * Z2); + var U1 = mod(X1 * Z2Z2); + var U2 = mod(X2 * Z1Z1); + var S1 = mod(mod(Y1 * Z2) * Z2Z2); + var S2 = mod(mod(Y2 * Z1) * Z1Z1); + return U1 === U2 && S1 === S2; + } + }, { + key: "negate", + value: function negate() { + return new JacobianPoint(this.x, mod(-this.y), this.z); + } + }, { + key: "double", + value: function double() { + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var A = mod(X1 * X1); + var B = mod(Y1 * Y1); + var C = mod(B * B); + var x1b = X1 + B; + var D = mod(_2n * (mod(x1b * x1b) - A - C)); + var E = mod(_3n * A); + var F = mod(E * E); + var X3 = mod(F - _2n * D); + var Y3 = mod(E * (D - X3) - _8n * C); + var Z3 = mod(_2n * Y1 * Z1); + return new JacobianPoint(X3, Y3, Z3); + } + }, { + key: "add", + value: function add(other) { + assertJacPoint(other); + var X1 = this.x, + Y1 = this.y, + Z1 = this.z; + var X2 = other.x, + Y2 = other.y, + Z2 = other.z; + if (X2 === _0n || Y2 === _0n) return this; + if (X1 === _0n || Y1 === _0n) return other; + var Z1Z1 = mod(Z1 * Z1); + var Z2Z2 = mod(Z2 * Z2); + var U1 = mod(X1 * Z2Z2); + var U2 = mod(X2 * Z1Z1); + var S1 = mod(mod(Y1 * Z2) * Z2Z2); + var S2 = mod(mod(Y2 * Z1) * Z1Z1); + var H = mod(U2 - U1); + var r = mod(S2 - S1); + + if (H === _0n) { + if (r === _0n) { + return this["double"](); + } else { + return JacobianPoint.ZERO; } + } - return subscribe; - }() - /** - * Unsubscribes from a defined event. - * @method - * @param {String|Array} event - event name - * @return {Undefined} - * @throws {Error} - */ + var HH = mod(H * H); + var HHH = mod(H * HH); + var V = mod(U1 * HH); + var X3 = mod(r * r - HHH - _2n * V); + var Y3 = mod(r * (V - X3) - S1 * HHH); + var Z3 = mod(Z1 * Z2 * H); + return new JacobianPoint(X3, Y3, Z3); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiplyUnsafe", + value: function multiplyUnsafe(scalar) { + var P0 = JacobianPoint.ZERO; + if (typeof scalar === 'bigint' && scalar === _0n) return P0; + var n = normalizeScalar(scalar); + if (n === _1n) return this; + + if (!USE_ENDOMORPHISM) { + var p = P0; + + var _d = this; + + while (n > _0n) { + if (n & _1n) p = p.add(_d); + _d = _d["double"](); + n >>= _1n; + } - }, { - key: "unsubscribe", - value: function () { - var _unsubscribe = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(event) { - var result; - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (typeof event === "string") event = [event]; - _context4.next = 3; - return this.call("rpc.off", event); + return p; + } - case 3: - result = _context4.sent; + var _endo$splitScalar = endo.splitScalar(n), + k1neg = _endo$splitScalar.k1neg, + k1 = _endo$splitScalar.k1, + k2neg = _endo$splitScalar.k2neg, + k2 = _endo$splitScalar.k2; - if (!(typeof event === "string" && result[event] !== "ok")) { - _context4.next = 6; - break; - } + var k1p = P0; + var k2p = P0; + var d = this; - throw new Error("Failed unsubscribing from an event with: " + result); + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) k1p = k1p.add(d); + if (k2 & _1n) k2p = k2p.add(d); + d = d["double"](); + k1 >>= _1n; + k2 >>= _1n; + } - case 6: - return _context4.abrupt("return", result); + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + return k1p.add(k2p); + } + }, { + key: "precomputeWindow", + value: function precomputeWindow(W) { + var windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; + var points = []; + var p = this; + var base = p; - case 7: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); + for (var window = 0; window < windows; window++) { + base = p; + points.push(base); - function unsubscribe(_x3) { - return _unsubscribe.apply(this, arguments); + for (var i = 1; i < Math.pow(2, W - 1); i++) { + base = base.add(p); + points.push(base); } - return unsubscribe; - }() - /** - * Closes a WebSocket connection gracefully. - * @method - * @param {Number} code - socket close code - * @param {String} data - optional data to be sent before closing - * @return {Undefined} - */ + p = base["double"](); + } - }, { - key: "close", - value: function close(code, data) { - this.socket.close(code || 1000, data); + return points; + } + }, { + key: "wNAF", + value: function wNAF(n, affinePoint) { + if (!affinePoint && this.equals(JacobianPoint.BASE)) affinePoint = Point.BASE; + var W = affinePoint && affinePoint._WINDOW_SIZE || 1; + + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); } - /** - * Connection/Message handler. - * @method - * @private - * @param {String} address - WebSocket API address - * @param {Object} options - ws options object - * @return {Undefined} - */ - }, { - key: "_connect", - value: function _connect(address, options) { - var _this4 = this; + var precomputes = affinePoint && pointPrecomputes.get(affinePoint); - clearTimeout(this.reconnect_timer_id); - this.socket = this.webSocketFactory(address, options); - this.socket.addEventListener("open", function () { - _this4.ready = true; + if (!precomputes) { + precomputes = this.precomputeWindow(W); - _this4.emit("open"); + if (affinePoint && W !== 1) { + precomputes = JacobianPoint.normalizeZ(precomputes); + pointPrecomputes.set(affinePoint, precomputes); + } + } - _this4.current_reconnects = 0; - }); - this.socket.addEventListener("message", function (_ref) { - var message = _ref.data; - if (message instanceof ArrayBuffer) message = Buffer$1.from(message).toString(); + var p = JacobianPoint.ZERO; + var f = JacobianPoint.BASE; + var windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); + var windowSize = Math.pow(2, W - 1); + var mask = BigInt(Math.pow(2, W) - 1); + var maxNumber = Math.pow(2, W); + var shiftBy = BigInt(W); - try { - message = JSON.parse(message); - } catch (error) { - return; - } // check if any listeners are attached and forward event + for (var window = 0; window < windows; window++) { + var offset = window * windowSize; + var wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } - if (message.notification && _this4.listeners(message.notification).length) { - if (!Object.keys(message.params).length) return _this4.emit(message.notification); - var args = [message.notification]; - if (message.params.constructor === Object) args.push(message.params);else // using for-loop instead of unshift/spread because performance is better - for (var i = 0; i < message.params.length; i++) { - args.push(message.params[i]); - } // run as microtask so that pending queue messages are resolved first - // eslint-disable-next-line prefer-spread + var offset1 = offset; + var offset2 = offset + Math.abs(wbits) - 1; + var cond1 = window % 2 !== 0; + var cond2 = wbits < 0; - return Promise.resolve().then(function () { - _this4.emit.apply(_this4, args); - }); - } + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } - if (!_this4.queue[message.id]) { - // general JSON RPC 2.0 events - if (message.method && message.params) { - // run as microtask so that pending queue messages are resolved first - return Promise.resolve().then(function () { - _this4.emit(message.method, message.params); - }); - } + return { + p: p, + f: f + }; + } + }, { + key: "multiply", + value: function multiply(scalar, affinePoint) { + var n = normalizeScalar(scalar); + var point; + var fake; - return; - } // reject early since server's response is invalid + if (USE_ENDOMORPHISM) { + var _endo$splitScalar3 = endo.splitScalar(n), + k1neg = _endo$splitScalar3.k1neg, + k1 = _endo$splitScalar3.k1, + k2neg = _endo$splitScalar3.k2neg, + k2 = _endo$splitScalar3.k2; + + var _this$wNAF2 = this.wNAF(k1, affinePoint), + k1p = _this$wNAF2.p, + f1p = _this$wNAF2.f; + var _this$wNAF4 = this.wNAF(k2, affinePoint), + k2p = _this$wNAF4.p, + f2p = _this$wNAF4.f; - if ("error" in message === "result" in message) _this4.queue[message.id].promise[1](new Error("Server response malformed. Response must include either \"result\"" + " or \"error\", but not both.")); - if (_this4.queue[message.id].timeout) clearTimeout(_this4.queue[message.id].timeout); - if (message.error) _this4.queue[message.id].promise[1](message.error);else _this4.queue[message.id].promise[0](message.result); - delete _this4.queue[message.id]; - }); - this.socket.addEventListener("error", function (error) { - return _this4.emit("error", error); - }); - this.socket.addEventListener("close", function (_ref2) { - var code = _ref2.code, - reason = _ref2.reason; - if (_this4.ready) // Delay close event until internal state is updated - setTimeout(function () { - return _this4.emit("close", code, reason); - }, 0); - _this4.ready = false; - _this4.socket = undefined; - if (code === 1000) return; - _this4.current_reconnects++; - if (_this4.reconnect && (_this4.max_reconnects > _this4.current_reconnects || _this4.max_reconnects === 0)) _this4.reconnect_timer_id = setTimeout(function () { - return _this4._connect(address, options); - }, _this4.reconnect_interval); - }); + k1p = constTimeNegate(k1neg, k1p); + k2p = constTimeNegate(k2neg, k2p); + k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + var _this$wNAF6 = this.wNAF(n, affinePoint), + p = _this$wNAF6.p, + f = _this$wNAF6.f; + + point = p; + fake = f; } - }]); - return CommonClient; - }(_eventemitter.EventEmitter); - exports["default"] = CommonClient; - })(client); + return JacobianPoint.normalizeZ([point, fake])[0]; + } + }, { + key: "toAffine", + value: function toAffine(invZ) { + var x = this.x, + y = this.y, + z = this.z; + var is0 = this.equals(JacobianPoint.ZERO); + if (invZ == null) invZ = is0 ? _8n : invert(z); + var iz1 = invZ; + var iz2 = mod(iz1 * iz1); + var iz3 = mod(iz2 * iz1); + var ax = mod(x * iz2); + var ay = mod(y * iz3); + var zz = mod(z * iz1); + if (is0) return Point.ZERO; + if (zz !== _1n) throw new Error('invZ was invalid'); + return new Point(ax, ay); + } + }], [{ + key: "fromAffine", + value: function fromAffine(p) { + if (!(p instanceof Point)) { + throw new TypeError('JacobianPoint#fromAffine: expected Point'); + } - var RpcWebSocketCommonClient = /*@__PURE__*/getDefaultExportFromCjs(client); + if (p.equals(Point.ZERO)) return JacobianPoint.ZERO; + return new JacobianPoint(p.x, p.y, _1n); + } + }, { + key: "toAffineBatch", + value: function toAffineBatch(points) { + var toInv = invertBatch(points.map(function (p) { + return p.z; + })); + return points.map(function (p, i) { + return p.toAffine(toInv[i]); + }); + } + }, { + key: "normalizeZ", + value: function normalizeZ(points) { + return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + } + }]); - var websocket_browser = {}; + return JacobianPoint; + }(); - /** - * WebSocket implements a browser-side WebSocket specification. - * @module Client - */ + JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); + JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); - (function (exports) { + function constTimeNegate(condition, item) { + var neg = item.negate(); + return condition ? neg : item; + } - var _interopRequireDefault = interopRequireDefault.exports; - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports["default"] = _default; + var pointPrecomputes = new WeakMap(); + var Point = /*#__PURE__*/function () { + function Point(x, y) { + _classCallCheck(this, Point); - var _classCallCheck2 = _interopRequireDefault(requireClassCallCheck()); + this.x = x; + this.y = y; + } - var _createClass2 = _interopRequireDefault(requireCreateClass()); + _createClass(Point, [{ + key: "_setWindowSize", + value: function _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes["delete"](this); + } + }, { + key: "hasEvenY", + value: function hasEvenY() { + return this.y % _2n === _0n; + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + return hexToBytes(this.toHex(isCompressed)); + } + }, { + key: "toHex", + value: function toHex() { + var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var x = numTo32bStr(this.x); - var _inherits2 = _interopRequireDefault(requireInherits()); + if (isCompressed) { + var prefix = this.hasEvenY() ? '02' : '03'; + return "".concat(prefix).concat(x); + } else { + return "04".concat(x).concat(numTo32bStr(this.y)); + } + } + }, { + key: "toHexX", + value: function toHexX() { + return this.toHex(true).slice(2); + } + }, { + key: "toRawX", + value: function toRawX() { + return this.toRawBytes(true).slice(1); + } + }, { + key: "assertValidity", + value: function assertValidity() { + var msg = 'Point is not on elliptic curve'; + var x = this.x, + y = this.y; + if (!isValidFieldElement(x) || !isValidFieldElement(y)) throw new Error(msg); + var left = mod(y * y); + var right = weierstrass(x); + if (mod(left - right) !== _0n) throw new Error(msg); + } + }, { + key: "equals", + value: function equals(other) { + return this.x === other.x && this.y === other.y; + } + }, { + key: "negate", + value: function negate() { + return new Point(this.x, mod(-this.y)); + } + }, { + key: "double", + value: function double() { + return JacobianPoint.fromAffine(this)["double"]().toAffine(); + } + }, { + key: "add", + value: function add(other) { + return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); + } + }, { + key: "subtract", + value: function subtract(other) { + return this.add(other.negate()); + } + }, { + key: "multiply", + value: function multiply(scalar) { + return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } + }, { + key: "multiplyAndAddUnsafe", + value: function multiplyAndAddUnsafe(Q, a, b) { + var P = JacobianPoint.fromAffine(this); + var aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); + var bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); + var sum = aP.add(bQ); + return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + } + }], [{ + key: "fromCompressedHex", + value: function fromCompressedHex(bytes) { + var isShort = bytes.length === 32; + var x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); + if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); + var y2 = weierstrass(x); + var y = sqrtMod(y2); + var isYOdd = (y & _1n) === _1n; - var _possibleConstructorReturn2 = _interopRequireDefault(requirePossibleConstructorReturn()); + if (isShort) { + if (isYOdd) y = mod(-y); + } else { + var isFirstByteOdd = (bytes[0] & 1) === 1; + if (isFirstByteOdd !== isYOdd) y = mod(-y); + } - var _getPrototypeOf2 = _interopRequireDefault(requireGetPrototypeOf()); + var point = new Point(x, y); + point.assertValidity(); + return point; + } + }, { + key: "fromUncompressedHex", + value: function fromUncompressedHex(bytes) { + var x = bytesToNumber(bytes.subarray(1, fieldLen + 1)); + var y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1)); + var point = new Point(x, y); + point.assertValidity(); + return point; + } + }, { + key: "fromHex", + value: function fromHex(hex) { + var bytes = ensureBytes(hex); + var len = bytes.length; + var header = bytes[0]; + if (len === fieldLen) return this.fromCompressedHex(bytes); - var _eventemitter = requireEventemitter3(); + if (len === compressedLen && (header === 0x02 || header === 0x03)) { + return this.fromCompressedHex(bytes); + } - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); + if (len === uncompressedLen && header === 0x04) return this.fromUncompressedHex(bytes); + throw new Error("Point.fromHex: received invalid point. Expected 32-".concat(compressedLen, " compressed bytes or ").concat(uncompressedLen, " uncompressed bytes, not ").concat(len)); + } + }, { + key: "fromPrivateKey", + value: function fromPrivateKey(privateKey) { + return Point.BASE.multiply(normalizePrivateKey(privateKey)); + } + }, { + key: "fromSignature", + value: function fromSignature(msgHash, signature, recovery) { + var _normalizeSignature = normalizeSignature(signature), + r = _normalizeSignature.r, + s = _normalizeSignature.s; - return function _createSuperInternal() { - var Super = (0, _getPrototypeOf2["default"])(Derived), - result; + if (![0, 1, 2, 3].includes(recovery)) throw new Error('Cannot recover: invalid recovery bit'); + var h = truncateHash(ensureBytes(msgHash)); + var n = CURVE.n; + var radj = recovery === 2 || recovery === 3 ? r + n : r; + var rinv = invert(radj, n); + var u1 = mod(-h * rinv, n); + var u2 = mod(s * rinv, n); + var prefix = recovery & 1 ? '03' : '02'; + var R = Point.fromHex(prefix + numTo32bStr(radj)); + var Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) throw new Error('Cannot recover signature: point at infinify'); + Q.assertValidity(); + return Q; + } + }]); - if (hasNativeReflectConstruct) { - var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } + return Point; + }(); + Point.BASE = new Point(CURVE.Gx, CURVE.Gy); + Point.ZERO = new Point(_0n, _0n); - return (0, _possibleConstructorReturn2["default"])(this, result); - }; + function sliceDER(s) { + return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; + } + + function parseDERInt(data) { + if (data.length < 2 || data[0] !== 0x02) { + throw new Error("Invalid signature integer tag: ".concat(bytesToHex(data))); } - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; + var len = data[1]; + var res = data.subarray(2, len + 2); - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } + if (!len || res.length !== len) { + throw new Error("Invalid signature integer: wrong length"); + } + + if (res[0] === 0x00 && res[1] <= 0x7f) { + throw new Error('Invalid signature integer: trailing length'); } - var WebSocketBrowserImpl = /*#__PURE__*/function (_EventEmitter) { - (0, _inherits2["default"])(WebSocketBrowserImpl, _EventEmitter); + return { + data: bytesToNumber(res), + left: data.subarray(len + 2) + }; + } - var _super = _createSuper(WebSocketBrowserImpl); - /** Instantiate a WebSocket class - * @constructor - * @param {String} address - url to a websocket server - * @param {(Object)} options - websocket options - * @param {(String|Array)} protocols - a list of protocols - * @return {WebSocketBrowserImpl} - returns a WebSocket instance - */ + function parseDERSignature(data) { + if (data.length < 2 || data[0] != 0x30) { + throw new Error("Invalid signature tag: ".concat(bytesToHex(data))); + } + if (data[1] !== data.length - 2) { + throw new Error('Invalid signature: incorrect length'); + } - function WebSocketBrowserImpl(address, options, protocols) { - var _this; + var _parseDERInt = parseDERInt(data.subarray(2)), + r = _parseDERInt.data, + sBytes = _parseDERInt.left; - (0, _classCallCheck2["default"])(this, WebSocketBrowserImpl); - _this = _super.call(this); - _this.socket = new window.WebSocket(address, protocols); + var _parseDERInt2 = parseDERInt(sBytes), + s = _parseDERInt2.data, + rBytesLeft = _parseDERInt2.left; - _this.socket.onopen = function () { - return _this.emit("open"); - }; + if (rBytesLeft.length) { + throw new Error("Invalid signature: left bytes after parsing: ".concat(bytesToHex(rBytesLeft))); + } - _this.socket.onmessage = function (event) { - return _this.emit("message", event.data); - }; + return { + r: r, + s: s + }; + } - _this.socket.onerror = function (error) { - return _this.emit("error", error); - }; + var Signature = /*#__PURE__*/function () { + function Signature(r, s) { + _classCallCheck(this, Signature); - _this.socket.onclose = function (event) { - _this.emit("close", event.code, event.reason); - }; + this.r = r; + this.s = s; + this.assertValidity(); + } - return _this; + _createClass(Signature, [{ + key: "assertValidity", + value: function assertValidity() { + var r = this.r, + s = this.s; + if (!isWithinCurveOrder(r)) throw new Error('Invalid Signature: r must be 0 < r < n'); + if (!isWithinCurveOrder(s)) throw new Error('Invalid Signature: s must be 0 < s < n'); } - /** - * Sends data through a websocket connection - * @method - * @param {(String|Object)} data - data to be sent via websocket - * @param {Object} optionsOrCallback - ws options - * @param {Function} callback - a callback called once the data is sent - * @return {Undefined} - */ - - - (0, _createClass2["default"])(WebSocketBrowserImpl, [{ - key: "send", - value: function send(data, optionsOrCallback, callback) { - var cb = callback || optionsOrCallback; + }, { + key: "hasHighS", + value: function hasHighS() { + var HALF = CURVE.n >> _1n; + return this.s > HALF; + } + }, { + key: "normalizeS", + value: function normalizeS() { + return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this; + } + }, { + key: "toDERRawBytes", + value: function toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + }, { + key: "toDERHex", + value: function toDERHex() { + var sHex = sliceDER(numberToHexUnpadded(this.s)); + var rHex = sliceDER(numberToHexUnpadded(this.r)); + var sHexL = sHex.length / 2; + var rHexL = rHex.length / 2; + var sLen = numberToHexUnpadded(sHexL); + var rLen = numberToHexUnpadded(rHexL); + var length = numberToHexUnpadded(rHexL + sHexL + 4); + return "30".concat(length, "02").concat(rLen).concat(rHex, "02").concat(sLen).concat(sHex); + } + }, { + key: "toRawBytes", + value: function toRawBytes() { + return this.toDERRawBytes(); + } + }, { + key: "toHex", + value: function toHex() { + return this.toDERHex(); + } + }, { + key: "toCompactRawBytes", + value: function toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + }, { + key: "toCompactHex", + value: function toCompactHex() { + return numTo32bStr(this.r) + numTo32bStr(this.s); + } + }], [{ + key: "fromCompact", + value: function fromCompact(hex) { + var arr = hex instanceof Uint8Array; + var name = 'Signature.fromCompact'; + if (typeof hex !== 'string' && !arr) throw new TypeError("".concat(name, ": Expected string or Uint8Array")); + var str = arr ? bytesToHex(hex) : hex; + if (str.length !== 128) throw new Error("".concat(name, ": Expected 64-byte hex")); + return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + } + }, { + key: "fromDER", + value: function fromDER(hex) { + var arr = hex instanceof Uint8Array; + if (typeof hex !== 'string' && !arr) throw new TypeError("Signature.fromDER: Expected string or Uint8Array"); - try { - this.socket.send(data); - cb(); - } catch (error) { - cb(error); - } - } - /** - * Closes an underlying socket - * @method - * @param {Number} code - status code explaining why the connection is being closed - * @param {String} reason - a description why the connection is closing - * @return {Undefined} - * @throws {Error} - */ + var _parseDERSignature = parseDERSignature(arr ? hex : hexToBytes(hex)), + r = _parseDERSignature.r, + s = _parseDERSignature.s; - }, { - key: "close", - value: function close(code, reason) { - this.socket.close(code, reason); - } - }, { - key: "addEventListener", - value: function addEventListener(type, listener, options) { - this.socket.addEventListener(type, listener, options); - } - }]); - return WebSocketBrowserImpl; - }(_eventemitter.EventEmitter); - /** - * factory method for common WebSocket instance - * @method - * @param {String} address - url to a websocket server - * @param {(Object)} options - websocket options - * @return {Undefined} - */ + return new Signature(r, s); + } + }, { + key: "fromHex", + value: function fromHex(hex) { + return this.fromDER(hex); + } + }]); + return Signature; + }(); - function _default(address, options) { - return new WebSocketBrowserImpl(address, options); + function concatBytes() { + for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { + arrays[_key] = arguments[_key]; } - })(websocket_browser); - var createRpc = /*@__PURE__*/getDefaultExportFromCjs(websocket_browser); + if (!arrays.every(function (b) { + return b instanceof Uint8Array; + })) throw new Error('Uint8Array list expected'); + if (arrays.length === 1) return arrays[0]; + var length = arrays.reduce(function (a, arr) { + return a + arr.length; + }, 0); + var result = new Uint8Array(length); - var SHA3_PI = [], - SHA3_ROTL = [], - _SHA3_IOTA = []; + for (var i = 0, pad = 0; i < arrays.length; i++) { + var arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } - var _0n$1 = BigInt(0); + return result; + } - var _1n$1 = BigInt(1); + var hexes = Array.from({ + length: 256 + }, function (v, i) { + return i.toString(16).padStart(2, '0'); + }); - var _2n$1 = BigInt(2); + function bytesToHex(uint8a) { + if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + var hex = ''; - var _7n = BigInt(7); + for (var i = 0; i < uint8a.length; i++) { + hex += hexes[uint8a[i]]; + } - var _256n = BigInt(256); + return hex; + } - var _0x71n = BigInt(0x71); + var POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); - for (var round = 0, R = _1n$1, x = 1, y = 0; round < 24; round++) { - // Pi - var _ref = [y, (2 * x + 3 * y) % 5]; - x = _ref[0]; - y = _ref[1]; - SHA3_PI.push(2 * (5 * y + x)); // Rotational + function numTo32bStr(num) { + if (typeof num !== 'bigint') throw new Error('Expected bigint'); + if (!(_0n <= num && num < POW_2_256)) throw new Error('Expected number 0 <= n < 2^256'); + return num.toString(16).padStart(64, '0'); + } - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); // Iota + function numTo32b(num) { + var b = hexToBytes(numTo32bStr(num)); + if (b.length !== 32) throw new Error('Error: expected 32 bytes'); + return b; + } - var t = _0n$1; + function numberToHexUnpadded(num) { + var hex = num.toString(16); + return hex.length & 1 ? "0".concat(hex) : hex; + } - for (var j = 0; j < 7; j++) { - R = (R << _1n$1 ^ (R >> _7n) * _0x71n) % _256n; - if (R & _2n$1) t ^= _1n$1 << (_1n$1 << BigInt(j)) - _1n$1; + function hexToNumber(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToNumber: expected string, got ' + _typeof$1(hex)); } - _SHA3_IOTA.push(t); + return BigInt("0x".concat(hex)); } - var _u64$split = u64$2.split(_SHA3_IOTA, true), - _u64$split2 = _slicedToArray(_u64$split, 2), - SHA3_IOTA_H = _u64$split2[0], - SHA3_IOTA_L = _u64$split2[1]; // Left rotation (without 0, 32, 64) + function hexToBytes(hex) { + if (typeof hex !== 'string') { + throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); + } + if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); + var array = new Uint8Array(hex.length / 2); - var rotlH = function rotlH(h, l, s) { - return s > 32 ? u64$2.rotlBH(h, l, s) : u64$2.rotlSH(h, l, s); - }; + for (var i = 0; i < array.length; i++) { + var j = i * 2; + var hexByte = hex.slice(j, j + 2); - var rotlL = function rotlL(h, l, s) { - return s > 32 ? u64$2.rotlBL(h, l, s) : u64$2.rotlSL(h, l, s); - }; // Same as keccakf1600, but allows to skip some rounds + var _byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); + array[i] = _byte; + } - function keccakP(s) { - var rounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 24; - var B = new Uint32Array(5 * 2); // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + return array; + } - for (var _round2 = 24 - rounds; _round2 < 24; _round2++) { - // Theta θ - for (var _x2 = 0; _x2 < 10; _x2++) B[_x2] = s[_x2] ^ s[_x2 + 10] ^ s[_x2 + 20] ^ s[_x2 + 30] ^ s[_x2 + 40]; + function bytesToNumber(bytes) { + return hexToNumber(bytesToHex(bytes)); + } - for (var _x4 = 0; _x4 < 10; _x4 += 2) { - var idx1 = (_x4 + 8) % 10; - var idx0 = (_x4 + 2) % 10; - var B0 = B[idx0]; - var B1 = B[idx0 + 1]; - var Th = rotlH(B0, B1, 1) ^ B[idx1]; - var Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + function ensureBytes(hex) { + return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); + } - for (var _y2 = 0; _y2 < 50; _y2 += 10) { - s[_x4 + _y2] ^= Th; - s[_x4 + _y2 + 1] ^= Tl; - } - } // Rho (ρ) and Pi (π) + function normalizeScalar(num) { + if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) return BigInt(num); + if (typeof num === 'bigint' && isWithinCurveOrder(num)) return num; + throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); + } + function mod(a) { + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var result = a % b; + return result >= _0n ? result : b + result; + } - var curH = s[2]; - var curL = s[3]; + function pow2(x, power) { + var P = CURVE.P; + var res = x; - for (var _t2 = 0; _t2 < 24; _t2++) { - var shift = SHA3_ROTL[_t2]; + while (power-- > _0n) { + res *= res; + res %= P; + } - var _Th = rotlH(curH, curL, shift); + return res; + } - var _Tl = rotlL(curH, curL, shift); + function sqrtMod(x) { + var P = CURVE.P; - var PI = SHA3_PI[_t2]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = _Th; - s[PI + 1] = _Tl; - } // Chi (χ) + var _6n = BigInt(6); + var _11n = BigInt(11); - for (var _y4 = 0; _y4 < 50; _y4 += 10) { - for (var _x6 = 0; _x6 < 10; _x6++) B[_x6] = s[_y4 + _x6]; + var _22n = BigInt(22); - for (var _x8 = 0; _x8 < 10; _x8++) s[_y4 + _x8] ^= ~B[(_x8 + 2) % 10] & B[(_x8 + 4) % 10]; - } // Iota (ι) + var _23n = BigInt(23); + var _44n = BigInt(44); - s[0] ^= SHA3_IOTA_H[_round2]; - s[1] ^= SHA3_IOTA_L[_round2]; - } + var _88n = BigInt(88); - B.fill(0); + var b2 = x * x * x % P; + var b3 = b2 * b2 * x % P; + var b6 = pow2(b3, _3n) * b3 % P; + var b9 = pow2(b6, _3n) * b3 % P; + var b11 = pow2(b9, _2n) * b2 % P; + var b22 = pow2(b11, _11n) * b11 % P; + var b44 = pow2(b22, _22n) * b22 % P; + var b88 = pow2(b44, _44n) * b44 % P; + var b176 = pow2(b88, _88n) * b88 % P; + var b220 = pow2(b176, _44n) * b44 % P; + var b223 = pow2(b220, _3n) * b3 % P; + var t1 = pow2(b223, _23n) * b22 % P; + var t2 = pow2(t1, _6n) * b2 % P; + var rt = pow2(t2, _2n); + var xc = rt * rt % P; + if (xc !== x) throw new Error('Cannot find square root'); + return rt; } - var Keccak = /*#__PURE__*/function (_Hash) { - _inherits(Keccak, _Hash); - var _super = _createSuper(Keccak); - - // NOTE: we accept arguments in bytes instead of bits here. - function Keccak(blockLen, suffix, outputLen) { - var _this; + function invert(number) { + var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var enableXOF = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var rounds = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 24; + if (number === _0n || modulo <= _0n) { + throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); + } - _classCallCheck(this, Keccak); + var a = mod(number, modulo); + var b = modulo; + var x = _0n, + u = _1n; - _this = _super.call(this); - _this.blockLen = blockLen; - _this.suffix = suffix; - _this.outputLen = outputLen; - _this.enableXOF = enableXOF; - _this.rounds = rounds; - _this.pos = 0; - _this.posOut = 0; - _this.finished = false; - _this.destroyed = false; // Can be passed from user as dkLen + while (a !== _0n) { + var q = b / a; + var r = b % a; + var m = x - u * q; + b = a, a = r, x = u, u = m; + } - assert$2.number(outputLen); // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + var gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); + } - if (0 >= _this.blockLen || _this.blockLen >= 200) throw new Error('Sha3 supports only keccak-f1600 function'); - _this.state = new Uint8Array(200); - _this.state32 = u32$1(_this.state); - return _this; - } + function invertBatch(nums) { + var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var scratch = new Array(nums.length); + var lastMultiplied = nums.reduce(function (acc, num, i) { + if (num === _0n) return acc; + scratch[i] = acc; + return mod(acc * num, p); + }, _1n); + var inverted = invert(lastMultiplied, p); + nums.reduceRight(function (acc, num, i) { + if (num === _0n) return acc; + scratch[i] = mod(acc * scratch[i], p); + return mod(acc * num, p); + }, inverted); + return scratch; + } - _createClass(Keccak, [{ - key: "keccak", - value: function keccak() { - keccakP(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; - } - }, { - key: "update", - value: function update(data) { - assert$2.exists(this); - var blockLen = this.blockLen, - state = this.state; - data = toBytes(data); - var len = data.length; + function bits2int_2(bytes) { + var delta = bytes.length * 8 - groupLen * 8; + var num = bytesToNumber(bytes); + return delta > 0 ? num >> BigInt(delta) : num; + } - for (var pos = 0; pos < len;) { - var take = Math.min(blockLen - this.pos, len - pos); + function truncateHash(hash) { + var truncateOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var h = bits2int_2(hash); + if (truncateOnly) return h; + var n = CURVE.n; + return h >= n ? h - n : h; + } - for (var i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + var _sha256Sync; - if (this.pos === blockLen) this.keccak(); - } + var _hmacSha256Sync; - return this; - } - }, { - key: "finish", - value: function finish() { - if (this.finished) return; - this.finished = true; - var state = this.state, - suffix = this.suffix, - pos = this.pos, - blockLen = this.blockLen; // Do the padding + var HmacDrbg = /*#__PURE__*/function () { + function HmacDrbg(hashLen, qByteLen) { + _classCallCheck(this, HmacDrbg); - state[pos] ^= suffix; - if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); - state[blockLen - 1] ^= 0x80; - this.keccak(); - } - }, { - key: "writeInto", - value: function writeInto(out) { - assert$2.exists(this, false); - assert$2.bytes(out); - this.finish(); - var bufferOut = this.state; - var blockLen = this.blockLen; + this.hashLen = hashLen; + this.qByteLen = qByteLen; + if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); + if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); + this.v = new Uint8Array(hashLen).fill(1); + this.k = new Uint8Array(hashLen).fill(0); + this.counter = 0; + } - for (var pos = 0, len = out.length; pos < len;) { - if (this.posOut >= blockLen) this.keccak(); - var take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; + _createClass(HmacDrbg, [{ + key: "hmac", + value: function hmac() { + for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + values[_key2] = arguments[_key2]; } - return out; + return utils.hmacSha256.apply(utils, [this.k].concat(values)); } }, { - key: "xofInto", - value: function xofInto(out) { - // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF - if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); - return this.writeInto(out); + key: "hmacSync", + value: function hmacSync() { + for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + values[_key3] = arguments[_key3]; + } + + return _hmacSha256Sync.apply(void 0, [this.k].concat(values)); } }, { - key: "xof", - value: function xof(bytes) { - assert$2.number(bytes); - return this.xofInto(new Uint8Array(bytes)); + key: "checkSync", + value: function checkSync() { + if (typeof _hmacSha256Sync !== 'function') throw new ShaError('hmacSha256Sync needs to be set'); } }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.output(out, this); - if (this.finished) throw new Error('digest() was already called'); - this.writeInto(out); - this.destroy(); - return out; + key: "incr", + value: function incr() { + if (this.counter >= 1000) throw new Error('Tried 1,000 k values for sign(), all were invalid'); + this.counter += 1; } }, { - key: "digest", - value: function digest() { - return this.digestInto(new Uint8Array(this.outputLen)); - } + key: "reseed", + value: function () { + var _reseed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var seed, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + seed = _args.length > 0 && _args[0] !== undefined ? _args[0] : new Uint8Array(); + _context.next = 3; + return this.hmac(this.v, Uint8Array.from([0x00]), seed); + + case 3: + this.k = _context.sent; + _context.next = 6; + return this.hmac(this.v); + + case 6: + this.v = _context.sent; + + if (!(seed.length === 0)) { + _context.next = 9; + break; + } + + return _context.abrupt("return"); + + case 9: + _context.next = 11; + return this.hmac(this.v, Uint8Array.from([0x01]), seed); + + case 11: + this.k = _context.sent; + _context.next = 14; + return this.hmac(this.v); + + case 14: + this.v = _context.sent; + + case 15: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + + function reseed() { + return _reseed.apply(this, arguments); + } + + return reseed; + }() }, { - key: "destroy", - value: function destroy() { - this.destroyed = true; - this.state.fill(0); + key: "reseedSync", + value: function reseedSync() { + var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Uint8Array(); + this.checkSync(); + this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); + this.v = this.hmacSync(this.v); + if (seed.length === 0) return; + this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); + this.v = this.hmacSync(this.v); } }, { - key: "_cloneInto", - value: function _cloneInto(to) { - var blockLen = this.blockLen, - suffix = this.suffix, - outputLen = this.outputLen, - rounds = this.rounds, - enableXOF = this.enableXOF; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; // Suffix can change in cSHAKE - - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } - }]); + key: "generate", + value: function () { + var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var len, out, sl; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + this.incr(); + len = 0; + out = []; - return Keccak; - }(Hash); + case 3: + if (!(len < this.qByteLen)) { + _context2.next = 12; + break; + } - var gen = function gen(suffix, blockLen, outputLen) { - return wrapConstructor(function () { - return new Keccak(blockLen, suffix, outputLen); - }); - }; + _context2.next = 6; + return this.hmac(this.v); - gen(0x06, 144, 224 / 8); - /** - * SHA3-256 hash function - * @param message - that would be hashed - */ + case 6: + this.v = _context2.sent; + sl = this.v.slice(); + out.push(sl); + len += this.v.length; + _context2.next = 3; + break; - gen(0x06, 136, 256 / 8); - gen(0x06, 104, 384 / 8); - gen(0x06, 72, 512 / 8); - gen(0x01, 144, 224 / 8); - /** - * keccak-256 hash function. Different from SHA3-256. - * @param message - that would be hashed - */ + case 12: + return _context2.abrupt("return", concatBytes.apply(void 0, out)); - var keccak_256 = gen(0x01, 136, 256 / 8); - gen(0x01, 104, 384 / 8); - gen(0x01, 72, 512 / 8); + case 13: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); - var genShake = function genShake(suffix, blockLen, outputLen) { - return wrapConstructorWithOpts(function () { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true); - }); - }; + function generate() { + return _generate.apply(this, arguments); + } - genShake(0x1f, 168, 128 / 8); - genShake(0x1f, 136, 256 / 8); + return generate; + }() + }, { + key: "generateSync", + value: function generateSync() { + this.checkSync(); + this.incr(); + var len = 0; + var out = []; - var HMAC = /*#__PURE__*/function (_Hash) { - _inherits(HMAC, _Hash); + while (len < this.qByteLen) { + this.v = this.hmacSync(this.v); + var sl = this.v.slice(); + out.push(sl); + len += this.v.length; + } - var _super = _createSuper(HMAC); + return concatBytes.apply(void 0, out); + } + }]); - function HMAC(hash, _key) { - var _this; + return HmacDrbg; + }(); - _classCallCheck(this, HMAC); + function isWithinCurveOrder(num) { + return _0n < num && num < CURVE.n; + } - _this = _super.call(this); - _this.finished = false; - _this.destroyed = false; - assert$2.hash(hash); - var key = toBytes(_key); - _this.iHash = hash.create(); - if (typeof _this.iHash.update !== 'function') throw new TypeError('Expected instance of class which extends utils.Hash'); - _this.blockLen = _this.iHash.blockLen; - _this.outputLen = _this.iHash.outputLen; - var blockLen = _this.blockLen; - var pad = new Uint8Array(blockLen); // blockLen can be bigger than outputLen + function isValidFieldElement(num) { + return _0n < num && num < CURVE.P; + } - pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + function kmdToSig(kBytes, m, d) { + var lowS = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var n = CURVE.n; + var k = truncateHash(kBytes, true); + if (!isWithinCurveOrder(k)) return; + var kinv = invert(k, n); + var q = Point.BASE.multiply(k); + var r = mod(q.x, n); + if (r === _0n) return; + var s = mod(kinv * mod(m + d * r, n), n); + if (s === _0n) return; + var sig = new Signature(r, s); + var recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); - for (var i = 0; i < pad.length; i++) pad[i] ^= 0x36; + if (lowS && sig.hasHighS()) { + sig = sig.normalizeS(); + recovery ^= 1; + } - _this.iHash.update(pad); // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone + return { + sig: sig, + recovery: recovery + }; + } + function normalizePrivateKey(key) { + var num; - _this.oHash = hash.create(); // Undo internal XOR && apply outer XOR + if (typeof key === 'bigint') { + num = key; + } else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { + num = BigInt(key); + } else if (typeof key === 'string') { + if (key.length !== 2 * groupLen) throw new Error('Expected 32 bytes of private key'); + num = hexToNumber(key); + } else if (key instanceof Uint8Array) { + if (key.length !== groupLen) throw new Error('Expected 32 bytes of private key'); + num = bytesToNumber(key); + } else { + throw new TypeError('Expected valid private key'); + } - for (var _i2 = 0; _i2 < pad.length; _i2++) pad[_i2] ^= 0x36 ^ 0x5c; + if (!isWithinCurveOrder(num)) throw new Error('Expected private key: 0 < key < n'); + return num; + } - _this.oHash.update(pad); + function normalizeSignature(signature) { + if (signature instanceof Signature) { + signature.assertValidity(); + return signature; + } - pad.fill(0); - return _this; + try { + return Signature.fromDER(signature); + } catch (error) { + return Signature.fromCompact(signature); } + } - _createClass(HMAC, [{ - key: "update", - value: function update(buf) { - assert$2.exists(this); - this.iHash.update(buf); - return this; - } - }, { - key: "digestInto", - value: function digestInto(out) { - assert$2.exists(this); - assert$2.bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - }, { - key: "digest", - value: function digest() { - var out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - }, { - key: "_cloneInto", - value: function _cloneInto(to) { - // Create new instance without calling constructor since key already in state and we don't know it. - to || (to = Object.create(Object.getPrototypeOf(this), {})); - var oHash = this.oHash, - iHash = this.iHash, - finished = this.finished, - destroyed = this.destroyed, - blockLen = this.blockLen, - outputLen = this.outputLen; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - }, { - key: "destroy", - value: function destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }]); + function getPublicKey$1(privateKey) { + var isCompressed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } - return HMAC; - }(Hash); - /** - * HMAC: RFC2104 message authentication code. - * @param hash - function that would be used e.g. sha256 - * @param key - message key - * @param message - message data - */ + function bits2int(bytes) { + var slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes; + return bytesToNumber(slice); + } + function bits2octets(bytes) { + var z1 = bits2int(bytes); + var z2 = mod(z1, CURVE.n); + return int2octets(z2 < _0n ? z1 : z2); + } - var hmac = function hmac(hash, key, message) { - return new HMAC(hash, key).update(message).digest(); - }; + function int2octets(num) { + return numTo32b(num); + } - hmac.create = function (hash, key) { - return new HMAC(hash, key); - }; + function initSigArgs(msgHash, privateKey, extraEntropy) { + if (msgHash == null) throw new Error("sign: expected valid message hash, not \"".concat(msgHash, "\"")); + var h1 = ensureBytes(msgHash); + var d = normalizePrivateKey(privateKey); + var seedArgs = [int2octets(d), bits2octets(h1)]; - var _0n = BigInt(0); + if (extraEntropy != null) { + if (extraEntropy === true) extraEntropy = utils.randomBytes(fieldLen); + var e = ensureBytes(extraEntropy); + if (e.length !== fieldLen) throw new Error("sign: Expected ".concat(fieldLen, " bytes of extra data")); + seedArgs.push(e); + } - var _1n = BigInt(1); + var seed = concatBytes.apply(void 0, seedArgs); + var m = bits2int(h1); + return { + seed: seed, + m: m, + d: d + }; + } - var _2n = BigInt(2); + function finalizeSig(recSig, opts) { + var sig = recSig.sig, + recovery = recSig.recovery; - var _3n = BigInt(3); + var _Object$assign = Object.assign({ + canonical: true, + der: true + }, opts), + der = _Object$assign.der, + recovered = _Object$assign.recovered; - var _8n = BigInt(8); + var hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); + return recovered ? [hashed, recovery] : hashed; + } - var CURVE = Object.freeze({ - a: _0n, - b: BigInt(7), - P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), - n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), - h: _1n, - Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), - Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee') - }); + function signSync(msgHash, privKey) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var divNearest = function divNearest(a, b) { - return (a + b / _2n) / b; - }; + var _initSigArgs = initSigArgs(msgHash, privKey, opts.extraEntropy), + seed = _initSigArgs.seed, + m = _initSigArgs.m, + d = _initSigArgs.d; - var endo = { - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), - splitScalar: function splitScalar(k) { - var n = CURVE.n; - var a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); - var b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); - var a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); - var b2 = a1; - var POW_2_128 = BigInt('0x100000000000000000000000000000000'); - var c1 = divNearest(b2 * k, n); - var c2 = divNearest(-b1 * k, n); - var k1 = mod(k - c1 * a1 - c2 * a2, n); - var k2 = mod(-c1 * b1 - c2 * b2, n); - var k1neg = k1 > POW_2_128; - var k2neg = k2 > POW_2_128; - if (k1neg) k1 = n - k1; - if (k2neg) k2 = n - k2; + var drbg = new HmacDrbg(hashLen, groupLen); + drbg.reseedSync(seed); + var sig; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error('splitScalarEndo: Endomorphism failed, k=' + k); - } + while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical))) drbg.reseedSync(); - return { - k1neg: k1neg, - k1: k1, - k2neg: k2neg, - k2: k2 - }; - } + return finalizeSig(sig, opts); + } + + Point.BASE._setWindowSize(8); + + var crypto$1 = { + node: nodeCrypto, + web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined }; - var fieldLen = 32; - var groupLen = 32; - var hashLen = 32; - var compressedLen = fieldLen + 1; - var uncompressedLen = 2 * fieldLen + 1; + var TAGGED_HASH_PREFIXES = {}; + var utils = { + bytesToHex: bytesToHex, + hexToBytes: hexToBytes, + concatBytes: concatBytes, + mod: mod, + invert: invert, + isValidPrivateKey: function isValidPrivateKey(privateKey) { + try { + normalizePrivateKey(privateKey); + return true; + } catch (error) { + return false; + } + }, + _bigintTo32Bytes: numTo32b, + _normalizePrivateKey: normalizePrivateKey, + hashToPrivateKey: function hashToPrivateKey(hash) { + hash = ensureBytes(hash); + var minLen = groupLen + 8; - function weierstrass(x) { - var a = CURVE.a, - b = CURVE.b; - var x2 = mod(x * x); - var x3 = mod(x2 * x); - return mod(x3 + a * x + b); - } + if (hash.length < minLen || hash.length > 1024) { + throw new Error("Expected valid bytes of private key as per FIPS 186"); + } - var USE_ENDOMORPHISM = CURVE.a === _0n; + var num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; - var ShaError = /*#__PURE__*/function (_Error) { - _inherits(ShaError, _Error); + return numTo32b(num); + }, + randomBytes: function randomBytes() { + var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; - var _super = _createSuper(ShaError); + if (crypto$1.web) { + return crypto$1.web.getRandomValues(new Uint8Array(bytesLength)); + } else if (crypto$1.node) { + var randomBytes = crypto$1.node.randomBytes; + return Uint8Array.from(randomBytes(bytesLength)); + } else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: function randomPrivateKey() { + return utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)); + }, + precompute: function precompute() { + var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; + var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point.BASE; + var cached = point === Point.BASE ? point : new Point(point.x, point.y); - function ShaError(message) { - _classCallCheck(this, ShaError); + cached._setWindowSize(windowSize); - return _super.call(this, message); - } + cached.multiply(_3n); + return cached; + }, + sha256: function () { + var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var _len4, + messages, + _key4, + buffer, + createHash, + hash, + _args4 = arguments; - return _createClass(ShaError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + for (_len4 = _args4.length, messages = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + messages[_key4] = _args4[_key4]; + } - function assertJacPoint(other) { - if (!(other instanceof JacobianPoint)) throw new TypeError('JacobianPoint expected'); - } + if (!crypto$1.web) { + _context4.next = 8; + break; + } - var JacobianPoint = /*#__PURE__*/function () { - function JacobianPoint(x, y, z) { - _classCallCheck(this, JacobianPoint); + _context4.next = 4; + return crypto$1.web.subtle.digest('SHA-256', concatBytes.apply(void 0, messages)); - this.x = x; - this.y = y; - this.z = z; - } + case 4: + buffer = _context4.sent; + return _context4.abrupt("return", new Uint8Array(buffer)); - _createClass(JacobianPoint, [{ - key: "equals", - value: function equals(other) { - assertJacPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - var Z1Z1 = mod(Z1 * Z1); - var Z2Z2 = mod(Z2 * Z2); - var U1 = mod(X1 * Z2Z2); - var U2 = mod(X2 * Z1Z1); - var S1 = mod(mod(Y1 * Z2) * Z2Z2); - var S2 = mod(mod(Y2 * Z1) * Z1Z1); - return U1 === U2 && S1 === S2; - } - }, { - key: "negate", - value: function negate() { - return new JacobianPoint(this.x, mod(-this.y), this.z); - } - }, { - key: "double", - value: function double() { - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var A = mod(X1 * X1); - var B = mod(Y1 * Y1); - var C = mod(B * B); - var x1b = X1 + B; - var D = mod(_2n * (mod(x1b * x1b) - A - C)); - var E = mod(_3n * A); - var F = mod(E * E); - var X3 = mod(F - _2n * D); - var Y3 = mod(E * (D - X3) - _8n * C); - var Z3 = mod(_2n * Y1 * Z1); - return new JacobianPoint(X3, Y3, Z3); - } - }, { - key: "add", - value: function add(other) { - assertJacPoint(other); - var X1 = this.x, - Y1 = this.y, - Z1 = this.z; - var X2 = other.x, - Y2 = other.y, - Z2 = other.z; - if (X2 === _0n || Y2 === _0n) return this; - if (X1 === _0n || Y1 === _0n) return other; - var Z1Z1 = mod(Z1 * Z1); - var Z2Z2 = mod(Z2 * Z2); - var U1 = mod(X1 * Z2Z2); - var U2 = mod(X2 * Z1Z1); - var S1 = mod(mod(Y1 * Z2) * Z2Z2); - var S2 = mod(mod(Y2 * Z1) * Z1Z1); - var H = mod(U2 - U1); - var r = mod(S2 - S1); + case 8: + if (!crypto$1.node) { + _context4.next = 15; + break; + } - if (H === _0n) { - if (r === _0n) { - return this["double"](); - } else { - return JacobianPoint.ZERO; + createHash = crypto$1.node.createHash; + hash = createHash('sha256'); + messages.forEach(function (m) { + return hash.update(m); + }); + return _context4.abrupt("return", Uint8Array.from(hash.digest())); + + case 15: + throw new Error("The environment doesn't have sha256 function"); + + case 16: + case "end": + return _context4.stop(); } - } + }, _callee4); + })); - var HH = mod(H * H); - var HHH = mod(H * HH); - var V = mod(U1 * HH); - var X3 = mod(r * r - HHH - _2n * V); - var Y3 = mod(r * (V - X3) - S1 * HHH); - var Z3 = mod(Z1 * Z2 * H); - return new JacobianPoint(X3, Y3, Z3); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); + function sha256() { + return _sha.apply(this, arguments); } - }, { - key: "multiplyUnsafe", - value: function multiplyUnsafe(scalar) { - var P0 = JacobianPoint.ZERO; - if (typeof scalar === 'bigint' && scalar === _0n) return P0; - var n = normalizeScalar(scalar); - if (n === _1n) return this; - if (!USE_ENDOMORPHISM) { - var p = P0; + return sha256; + }(), + hmacSha256: function () { + var _hmacSha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) { + var _len5, + messages, + _key5, + ckey, + message, + buffer, + createHmac, + hash, + _args5 = arguments; - var _d = this; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + for (_len5 = _args5.length, messages = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + messages[_key5 - 1] = _args5[_key5]; + } - while (n > _0n) { - if (n & _1n) p = p.add(_d); - _d = _d["double"](); - n >>= _1n; - } + if (!crypto$1.web) { + _context5.next = 12; + break; + } - return p; - } + _context5.next = 4; + return crypto$1.web.subtle.importKey('raw', key, { + name: 'HMAC', + hash: { + name: 'SHA-256' + } + }, false, ['sign']); - var _endo$splitScalar = endo.splitScalar(n), - k1neg = _endo$splitScalar.k1neg, - k1 = _endo$splitScalar.k1, - k2neg = _endo$splitScalar.k2neg, - k2 = _endo$splitScalar.k2; + case 4: + ckey = _context5.sent; + message = concatBytes.apply(void 0, messages); + _context5.next = 8; + return crypto$1.web.subtle.sign('HMAC', ckey, message); - var k1p = P0; - var k2p = P0; - var d = this; + case 8: + buffer = _context5.sent; + return _context5.abrupt("return", new Uint8Array(buffer)); - while (k1 > _0n || k2 > _0n) { - if (k1 & _1n) k1p = k1p.add(d); - if (k2 & _1n) k2p = k2p.add(d); - d = d["double"](); - k1 >>= _1n; - k2 >>= _1n; - } + case 12: + if (!crypto$1.node) { + _context5.next = 19; + break; + } - if (k1neg) k1p = k1p.negate(); - if (k2neg) k2p = k2p.negate(); - k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); - return k1p.add(k2p); - } - }, { - key: "precomputeWindow", - value: function precomputeWindow(W) { - var windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; - var points = []; - var p = this; - var base = p; + createHmac = crypto$1.node.createHmac; + hash = createHmac('sha256', key); + messages.forEach(function (m) { + return hash.update(m); + }); + return _context5.abrupt("return", Uint8Array.from(hash.digest())); - for (var window = 0; window < windows; window++) { - base = p; - points.push(base); + case 19: + throw new Error("The environment doesn't have hmac-sha256 function"); - for (var i = 1; i < Math.pow(2, W - 1); i++) { - base = base.add(p); - points.push(base); + case 20: + case "end": + return _context5.stop(); } + }, _callee5); + })); - p = base["double"](); - } - - return points; + function hmacSha256(_x9) { + return _hmacSha.apply(this, arguments); } - }, { - key: "wNAF", - value: function wNAF(n, affinePoint) { - if (!affinePoint && this.equals(JacobianPoint.BASE)) affinePoint = Point.BASE; - var W = affinePoint && affinePoint._WINDOW_SIZE || 1; - - if (256 % W) { - throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); - } - var precomputes = affinePoint && pointPrecomputes.get(affinePoint); + return hmacSha256; + }(), + sha256Sync: undefined, + hmacSha256Sync: undefined, + taggedHash: function () { + var _taggedHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(tag) { + var tagP, + tagH, + _len6, + messages, + _key6, + _args6 = arguments; - if (!precomputes) { - precomputes = this.precomputeWindow(W); + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + tagP = TAGGED_HASH_PREFIXES[tag]; - if (affinePoint && W !== 1) { - precomputes = JacobianPoint.normalizeZ(precomputes); - pointPrecomputes.set(affinePoint, precomputes); - } - } + if (!(tagP === undefined)) { + _context6.next = 7; + break; + } - var p = JacobianPoint.ZERO; - var f = JacobianPoint.BASE; - var windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W); - var windowSize = Math.pow(2, W - 1); - var mask = BigInt(Math.pow(2, W) - 1); - var maxNumber = Math.pow(2, W); - var shiftBy = BigInt(W); + _context6.next = 4; + return utils.sha256(Uint8Array.from(tag, function (c) { + return c.charCodeAt(0); + })); - for (var window = 0; window < windows; window++) { - var offset = window * windowSize; - var wbits = Number(n & mask); - n >>= shiftBy; + case 4: + tagH = _context6.sent; + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n; - } + case 7: + for (_len6 = _args6.length, messages = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + messages[_key6 - 1] = _args6[_key6]; + } - var offset1 = offset; - var offset2 = offset + Math.abs(wbits) - 1; - var cond1 = window % 2 !== 0; - var cond2 = wbits < 0; + return _context6.abrupt("return", utils.sha256.apply(utils, [tagP].concat(messages))); - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); + case 9: + case "end": + return _context6.stop(); } - } + }, _callee6); + })); - return { - p: p, - f: f - }; + function taggedHash(_x10) { + return _taggedHash.apply(this, arguments); } - }, { - key: "multiply", - value: function multiply(scalar, affinePoint) { - var n = normalizeScalar(scalar); - var point; - var fake; - - if (USE_ENDOMORPHISM) { - var _endo$splitScalar3 = endo.splitScalar(n), - k1neg = _endo$splitScalar3.k1neg, - k1 = _endo$splitScalar3.k1, - k2neg = _endo$splitScalar3.k2neg, - k2 = _endo$splitScalar3.k2; - var _this$wNAF2 = this.wNAF(k1, affinePoint), - k1p = _this$wNAF2.p, - f1p = _this$wNAF2.f; + return taggedHash; + }(), + taggedHashSync: function taggedHashSync(tag) { + if (typeof _sha256Sync !== 'function') throw new ShaError('sha256Sync is undefined, you need to set it'); + var tagP = TAGGED_HASH_PREFIXES[tag]; - var _this$wNAF4 = this.wNAF(k2, affinePoint), - k2p = _this$wNAF4.p, - f2p = _this$wNAF4.f; + if (tagP === undefined) { + var tagH = _sha256Sync(Uint8Array.from(tag, function (c) { + return c.charCodeAt(0); + })); - k1p = constTimeNegate(k1neg, k1p); - k2p = constTimeNegate(k2neg, k2p); - k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - var _this$wNAF6 = this.wNAF(n, affinePoint), - p = _this$wNAF6.p, - f = _this$wNAF6.f; + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } - point = p; - fake = f; - } + for (var _len7 = arguments.length, messages = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + messages[_key7 - 1] = arguments[_key7]; + } - return JacobianPoint.normalizeZ([point, fake])[0]; + return _sha256Sync.apply(void 0, [tagP].concat(messages)); + }, + _JacobianPoint: JacobianPoint + }; + Object.defineProperties(utils, { + sha256Sync: { + configurable: false, + get: function get() { + return _sha256Sync; + }, + set: function set(val) { + if (!_sha256Sync) _sha256Sync = val; } - }, { - key: "toAffine", - value: function toAffine(invZ) { - var x = this.x, - y = this.y, - z = this.z; - var is0 = this.equals(JacobianPoint.ZERO); - if (invZ == null) invZ = is0 ? _8n : invert(z); - var iz1 = invZ; - var iz2 = mod(iz1 * iz1); - var iz3 = mod(iz2 * iz1); - var ax = mod(x * iz2); - var ay = mod(y * iz3); - var zz = mod(z * iz1); - if (is0) return Point.ZERO; - if (zz !== _1n) throw new Error('invZ was invalid'); - return new Point(ax, ay); + }, + hmacSha256Sync: { + configurable: false, + get: function get() { + return _hmacSha256Sync; + }, + set: function set(val) { + if (!_hmacSha256Sync) _hmacSha256Sync = val; } - }], [{ - key: "fromAffine", - value: function fromAffine(p) { - if (!(p instanceof Point)) { - throw new TypeError('JacobianPoint#fromAffine: expected Point'); - } + } + }); + + var _excluded = ["commitment"], + _excluded2 = ["encoding"], + _excluded3 = ["commitment"], + _excluded4 = ["commitment"]; + /** + * A 64 byte secret key, the first 32 bytes of which is the + * private scalar and the last 32 bytes is the public key. + * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ + */ + + utils$1.sha512Sync = function () { + var _ed25519$utils; + + return sha512((_ed25519$utils = utils$1).concatBytes.apply(_ed25519$utils, arguments)); + }; + + var generatePrivateKey = utils$1.randomPrivateKey; + + var generateKeypair = function generateKeypair() { + var privateScalar = utils$1.randomPrivateKey(); + var publicKey = getPublicKey(privateScalar); + var secretKey = new Uint8Array(64); + secretKey.set(privateScalar); + secretKey.set(publicKey, 32); + return { + publicKey: publicKey, + secretKey: secretKey + }; + }; + + var getPublicKey = sync.getPublicKey; + + function _isOnCurve(publicKey) { + try { + Point$1.fromHex(publicKey, true + /* strict */ + ); + return true; + } catch (_unused) { + return false; + } + } + + var _sign = function sign(message, secretKey) { + return sync.sign(message, secretKey.slice(0, 32)); + }; + + var verify = sync.verify; + + var toBuffer = function toBuffer(arr) { + if (Buffer$1.isBuffer(arr)) { + return arr; + } else if (arr instanceof Uint8Array) { + return Buffer$1.from(arr.buffer, arr.byteOffset, arr.byteLength); + } else { + return Buffer$1.from(arr); + } + }; // Class wrapping a plain object - if (p.equals(Point.ZERO)) return JacobianPoint.ZERO; - return new JacobianPoint(p.x, p.y, _1n); + + var Struct = /*#__PURE__*/function () { + function Struct(properties) { + _classCallCheck(this, Struct); + + Object.assign(this, properties); + } + + _createClass(Struct, [{ + key: "encode", + value: function encode() { + return Buffer$1.from(serialize_1(SOLANA_SCHEMA, this)); } - }, { - key: "toAffineBatch", - value: function toAffineBatch(points) { - var toInv = invertBatch(points.map(function (p) { - return p.z; - })); - return points.map(function (p, i) { - return p.toAffine(toInv[i]); - }); + }], [{ + key: "decode", + value: function decode(data) { + return deserialize_1(SOLANA_SCHEMA, this, data); } }, { - key: "normalizeZ", - value: function normalizeZ(points) { - return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); + key: "decodeUnchecked", + value: function decodeUnchecked(data) { + return deserializeUnchecked_1(SOLANA_SCHEMA, this, data); } }]); - return JacobianPoint; - }(); + return Struct; + }(); // Class representing a Rust-compatible enum, since enums are only strings or + // numbers in pure JS - JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n); - JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n); - function constTimeNegate(condition, item) { - var neg = item.negate(); - return condition ? neg : item; - } + var Enum = /*#__PURE__*/function (_Struct) { + _inherits(Enum, _Struct); - var pointPrecomputes = new WeakMap(); - var Point = /*#__PURE__*/function () { - function Point(x, y) { - _classCallCheck(this, Point); + var _super = _createSuper(Enum); - this.x = x; - this.y = y; - } + function Enum(properties) { + var _this; - _createClass(Point, [{ - key: "_setWindowSize", - value: function _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes["delete"](this); - } - }, { - key: "hasEvenY", - value: function hasEvenY() { - return this.y % _2n === _0n; - } - }, { - key: "toRawBytes", - value: function toRawBytes() { - var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return hexToBytes(this.toHex(isCompressed)); - } - }, { - key: "toHex", - value: function toHex() { - var isCompressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var x = numTo32bStr(this.x); + _classCallCheck(this, Enum); - if (isCompressed) { - var prefix = this.hasEvenY() ? '02' : '03'; - return "".concat(prefix).concat(x); - } else { - return "04".concat(x).concat(numTo32bStr(this.y)); - } - } - }, { - key: "toHexX", - value: function toHexX() { - return this.toHex(true).slice(2); - } - }, { - key: "toRawX", - value: function toRawX() { - return this.toRawBytes(true).slice(1); - } - }, { - key: "assertValidity", - value: function assertValidity() { - var msg = 'Point is not on elliptic curve'; - var x = this.x, - y = this.y; - if (!isValidFieldElement(x) || !isValidFieldElement(y)) throw new Error(msg); - var left = mod(y * y); - var right = weierstrass(x); - if (mod(left - right) !== _0n) throw new Error(msg); - } - }, { - key: "equals", - value: function equals(other) { - return this.x === other.x && this.y === other.y; - } - }, { - key: "negate", - value: function negate() { - return new Point(this.x, mod(-this.y)); - } - }, { - key: "double", - value: function double() { - return JacobianPoint.fromAffine(this)["double"]().toAffine(); - } - }, { - key: "add", - value: function add(other) { - return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); - } - }, { - key: "subtract", - value: function subtract(other) { - return this.add(other.negate()); - } - }, { - key: "multiply", - value: function multiply(scalar) { - return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); - } - }, { - key: "multiplyAndAddUnsafe", - value: function multiplyAndAddUnsafe(Q, a, b) { - var P = JacobianPoint.fromAffine(this); - var aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a); - var bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b); - var sum = aP.add(bQ); - return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine(); + _this = _super.call(this, properties); + _this["enum"] = ''; + + if (Object.keys(properties).length !== 1) { + throw new Error('Enum can only take single value'); } - }], [{ - key: "fromCompressedHex", - value: function fromCompressedHex(bytes) { - var isShort = bytes.length === 32; - var x = bytesToNumber(isShort ? bytes : bytes.subarray(1)); - if (!isValidFieldElement(x)) throw new Error('Point is not on curve'); - var y2 = weierstrass(x); - var y = sqrtMod(y2); - var isYOdd = (y & _1n) === _1n; - if (isShort) { - if (isYOdd) y = mod(-y); - } else { - var isFirstByteOdd = (bytes[0] & 1) === 1; - if (isFirstByteOdd !== isYOdd) y = mod(-y); - } + Object.keys(properties).map(function (key) { + _this["enum"] = key; + }); + return _this; + } - var point = new Point(x, y); - point.assertValidity(); - return point; - } - }, { - key: "fromUncompressedHex", - value: function fromUncompressedHex(bytes) { - var x = bytesToNumber(bytes.subarray(1, fieldLen + 1)); - var y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1)); - var point = new Point(x, y); - point.assertValidity(); - return point; - } - }, { - key: "fromHex", - value: function fromHex(hex) { - var bytes = ensureBytes(hex); - var len = bytes.length; - var header = bytes[0]; - if (len === fieldLen) return this.fromCompressedHex(bytes); + return _createClass(Enum); + }(Struct); - if (len === compressedLen && (header === 0x02 || header === 0x03)) { - return this.fromCompressedHex(bytes); - } + var SOLANA_SCHEMA = new Map(); - if (len === uncompressedLen && header === 0x04) return this.fromUncompressedHex(bytes); - throw new Error("Point.fromHex: received invalid point. Expected 32-".concat(compressedLen, " compressed bytes or ").concat(uncompressedLen, " uncompressed bytes, not ").concat(len)); - } - }, { - key: "fromPrivateKey", - value: function fromPrivateKey(privateKey) { - return Point.BASE.multiply(normalizePrivateKey(privateKey)); - } - }, { - key: "fromSignature", - value: function fromSignature(msgHash, signature, recovery) { - var _normalizeSignature = normalizeSignature(signature), - r = _normalizeSignature.r, - s = _normalizeSignature.s; + var _Symbol$toStringTag; + /** + * Maximum length of derived pubkey seed + */ - if (![0, 1, 2, 3].includes(recovery)) throw new Error('Cannot recover: invalid recovery bit'); - var h = truncateHash(ensureBytes(msgHash)); - var n = CURVE.n; - var radj = recovery === 2 || recovery === 3 ? r + n : r; - var rinv = invert(radj, n); - var u1 = mod(-h * rinv, n); - var u2 = mod(s * rinv, n); - var prefix = recovery & 1 ? '03' : '02'; - var R = Point.fromHex(prefix + numTo32bStr(radj)); - var Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) throw new Error('Cannot recover signature: point at infinify'); - Q.assertValidity(); - return Q; - } - }]); - return Point; - }(); - Point.BASE = new Point(CURVE.Gx, CURVE.Gy); - Point.ZERO = new Point(_0n, _0n); + var MAX_SEED_LENGTH = 32; + /** + * Size of public key in bytes + */ - function sliceDER(s) { - return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s; - } + var PUBLIC_KEY_LENGTH = 32; + /** + * Value to be converted into public key + */ - function parseDERInt(data) { - if (data.length < 2 || data[0] !== 0x02) { - throw new Error("Invalid signature integer tag: ".concat(bytesToHex(data))); - } + function isPublicKeyData(value) { + return value._bn !== undefined; + } // local counter used by PublicKey.unique() - var len = data[1]; - var res = data.subarray(2, len + 2); - if (!len || res.length !== len) { - throw new Error("Invalid signature integer: wrong length"); - } + var uniquePublicKeyCounter = 1; + /** + * A public key + */ - if (res[0] === 0x00 && res[1] <= 0x7f) { - throw new Error('Invalid signature integer: trailing length'); - } + _Symbol$toStringTag = Symbol.toStringTag; - return { - data: bytesToNumber(res), - left: data.subarray(len + 2) - }; - } + var PublicKey = /*#__PURE__*/function (_Struct2, _Symbol$toStringTag2) { + _inherits(PublicKey, _Struct2); - function parseDERSignature(data) { - if (data.length < 2 || data[0] != 0x30) { - throw new Error("Invalid signature tag: ".concat(bytesToHex(data))); - } + var _super2 = _createSuper(PublicKey); - if (data[1] !== data.length - 2) { - throw new Error('Invalid signature: incorrect length'); - } + /** @internal */ - var _parseDERInt = parseDERInt(data.subarray(2)), - r = _parseDERInt.data, - sBytes = _parseDERInt.left; + /** + * Create a new PublicKey object + * @param value ed25519 public key as buffer or base-58 encoded string + */ + function PublicKey(value) { + var _this2; - var _parseDERInt2 = parseDERInt(sBytes), - s = _parseDERInt2.data, - rBytesLeft = _parseDERInt2.left; + _classCallCheck(this, PublicKey); - if (rBytesLeft.length) { - throw new Error("Invalid signature: left bytes after parsing: ".concat(bytesToHex(rBytesLeft))); - } + _this2 = _super2.call(this, {}); + _this2._bn = void 0; - return { - r: r, - s: s - }; - } + if (isPublicKeyData(value)) { + _this2._bn = value._bn; + } else { + if (typeof value === 'string') { + // assume base 58 encoding by default + var decoded = bs58$3.decode(value); - var Signature = /*#__PURE__*/function () { - function Signature(r, s) { - _classCallCheck(this, Signature); + if (decoded.length != PUBLIC_KEY_LENGTH) { + throw new Error("Invalid public key input"); + } - this.r = r; - this.s = s; - this.assertValidity(); - } + _this2._bn = new BN$1(decoded); + } else { + _this2._bn = new BN$1(value); + } - _createClass(Signature, [{ - key: "assertValidity", - value: function assertValidity() { - var r = this.r, - s = this.s; - if (!isWithinCurveOrder(r)) throw new Error('Invalid Signature: r must be 0 < r < n'); - if (!isWithinCurveOrder(s)) throw new Error('Invalid Signature: s must be 0 < s < n'); - } - }, { - key: "hasHighS", - value: function hasHighS() { - var HALF = CURVE.n >> _1n; - return this.s > HALF; + if (_this2._bn.byteLength() > PUBLIC_KEY_LENGTH) { + throw new Error("Invalid public key input"); + } } - }, { - key: "normalizeS", - value: function normalizeS() { - return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this; + + return _this2; + } + /** + * Returns a unique PublicKey for tests and benchmarks using a counter + */ + + + _createClass(PublicKey, [{ + key: "equals", + value: + /** + * Default public key value. The base58-encoded string representation is all ones (as seen below) + * The underlying BN number is 32 bytes that are all zeros + */ + + /** + * Checks if two publicKeys are equal + */ + function equals(publicKey) { + return this._bn.eq(publicKey._bn); } + /** + * Return the base-58 representation of the public key + */ + }, { - key: "toDERRawBytes", - value: function toDERRawBytes() { - return hexToBytes(this.toDERHex()); + key: "toBase58", + value: function toBase58() { + return bs58$3.encode(this.toBytes()); } }, { - key: "toDERHex", - value: function toDERHex() { - var sHex = sliceDER(numberToHexUnpadded(this.s)); - var rHex = sliceDER(numberToHexUnpadded(this.r)); - var sHexL = sHex.length / 2; - var rHexL = rHex.length / 2; - var sLen = numberToHexUnpadded(sHexL); - var rLen = numberToHexUnpadded(rHexL); - var length = numberToHexUnpadded(rHexL + sHexL + 4); - return "30".concat(length, "02").concat(rLen).concat(rHex, "02").concat(sLen).concat(sHex); + key: "toJSON", + value: function toJSON() { + return this.toBase58(); } + /** + * Return the byte array representation of the public key in big endian + */ + }, { - key: "toRawBytes", - value: function toRawBytes() { - return this.toDERRawBytes(); + key: "toBytes", + value: function toBytes() { + var buf = this.toBuffer(); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } + /** + * Return the Buffer representation of the public key in big endian + */ + }, { - key: "toHex", - value: function toHex() { - return this.toDERHex(); + key: "toBuffer", + value: function toBuffer() { + var b = this._bn.toArrayLike(Buffer$1); + + if (b.length === PUBLIC_KEY_LENGTH) { + return b; + } + + var zeroPad = Buffer$1.alloc(32); + b.copy(zeroPad, 32 - b.length); + return zeroPad; } }, { - key: "toCompactRawBytes", - value: function toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); + key: _Symbol$toStringTag2, + get: function get() { + return "PublicKey(".concat(this.toString(), ")"); } + /** + * Return the base-58 representation of the public key + */ + }, { - key: "toCompactHex", - value: function toCompactHex() { - return numTo32bStr(this.r) + numTo32bStr(this.s); + key: "toString", + value: function toString() { + return this.toBase58(); } + /** + * Derive a public key from another key, a seed, and a program ID. + * The program ID will also serve as the owner of the public key, giving + * it permission to write data to the account. + */ + + /* eslint-disable require-await */ + }], [{ - key: "fromCompact", - value: function fromCompact(hex) { - var arr = hex instanceof Uint8Array; - var name = 'Signature.fromCompact'; - if (typeof hex !== 'string' && !arr) throw new TypeError("".concat(name, ": Expected string or Uint8Array")); - var str = arr ? bytesToHex(hex) : hex; - if (str.length !== 128) throw new Error("".concat(name, ": Expected 64-byte hex")); - return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128))); + key: "unique", + value: function unique() { + var key = new PublicKey(uniquePublicKeyCounter); + uniquePublicKeyCounter += 1; + return new PublicKey(key.toBuffer()); } }, { - key: "fromDER", - value: function fromDER(hex) { - var arr = hex instanceof Uint8Array; - if (typeof hex !== 'string' && !arr) throw new TypeError("Signature.fromDER: Expected string or Uint8Array"); + key: "createWithSeed", + value: function () { + var _createWithSeed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(fromPublicKey, seed, programId) { + var buffer, publicKeyBytes; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + buffer = Buffer$1.concat([fromPublicKey.toBuffer(), Buffer$1.from(seed), programId.toBuffer()]); + publicKeyBytes = sha256(buffer); + return _context.abrupt("return", new PublicKey(publicKeyBytes)); - var _parseDERSignature = parseDERSignature(arr ? hex : hexToBytes(hex)), - r = _parseDERSignature.r, - s = _parseDERSignature.s; + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); - return new Signature(r, s); - } - }, { - key: "fromHex", - value: function fromHex(hex) { - return this.fromDER(hex); - } - }]); + function createWithSeed(_x, _x2, _x3) { + return _createWithSeed.apply(this, arguments); + } - return Signature; - }(); + return createWithSeed; + }() + /** + * Derive a program address from seeds and a program ID. + */ - function concatBytes() { - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } + /* eslint-disable require-await */ + + }, { + key: "createProgramAddressSync", + value: function createProgramAddressSync(seeds, programId) { + var buffer = Buffer$1.alloc(0); + seeds.forEach(function (seed) { + if (seed.length > MAX_SEED_LENGTH) { + throw new TypeError("Max seed length exceeded"); + } - if (!arrays.every(function (b) { - return b instanceof Uint8Array; - })) throw new Error('Uint8Array list expected'); - if (arrays.length === 1) return arrays[0]; - var length = arrays.reduce(function (a, arr) { - return a + arr.length; - }, 0); - var result = new Uint8Array(length); + buffer = Buffer$1.concat([buffer, toBuffer(seed)]); + }); + buffer = Buffer$1.concat([buffer, programId.toBuffer(), Buffer$1.from('ProgramDerivedAddress')]); + var publicKeyBytes = sha256(buffer); - for (var i = 0, pad = 0; i < arrays.length; i++) { - var arr = arrays[i]; - result.set(arr, pad); - pad += arr.length; - } + if (_isOnCurve(publicKeyBytes)) { + throw new Error("Invalid seeds, address must fall off the curve"); + } - return result; - } + return new PublicKey(publicKeyBytes); + } + /** + * Async version of createProgramAddressSync + * For backwards compatibility + * + * @deprecated Use {@link createProgramAddressSync} instead + */ - var hexes = Array.from({ - length: 256 - }, function (v, i) { - return i.toString(16).padStart(2, '0'); - }); + /* eslint-disable require-await */ - function bytesToHex(uint8a) { - if (!(uint8a instanceof Uint8Array)) throw new Error('Expected Uint8Array'); - var hex = ''; + }, { + key: "createProgramAddress", + value: function () { + var _createProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(seeds, programId) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", this.createProgramAddressSync(seeds, programId)); - for (var i = 0; i < uint8a.length; i++) { - hex += hexes[uint8a[i]]; - } + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); - return hex; - } + function createProgramAddress(_x4, _x5) { + return _createProgramAddress.apply(this, arguments); + } - var POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); + return createProgramAddress; + }() + /** + * Find a valid program address + * + * Valid program addresses must fall off the ed25519 curve. This function + * iterates a nonce until it finds one that when combined with the seeds + * results in a valid program address. + */ - function numTo32bStr(num) { - if (typeof num !== 'bigint') throw new Error('Expected bigint'); - if (!(_0n <= num && num < POW_2_256)) throw new Error('Expected number 0 <= n < 2^256'); - return num.toString(16).padStart(64, '0'); - } + }, { + key: "findProgramAddressSync", + value: function findProgramAddressSync(seeds, programId) { + var nonce = 255; + var address; - function numTo32b(num) { - var b = hexToBytes(numTo32bStr(num)); - if (b.length !== 32) throw new Error('Error: expected 32 bytes'); - return b; - } + while (nonce != 0) { + try { + var seedsWithNonce = seeds.concat(Buffer$1.from([nonce])); + address = this.createProgramAddressSync(seedsWithNonce, programId); + } catch (err) { + if (err instanceof TypeError) { + throw err; + } - function numberToHexUnpadded(num) { - var hex = num.toString(16); - return hex.length & 1 ? "0".concat(hex) : hex; - } + nonce--; + continue; + } - function hexToNumber(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToNumber: expected string, got ' + _typeof$1(hex)); - } + return [address, nonce]; + } - return BigInt("0x".concat(hex)); - } + throw new Error("Unable to find a viable program address nonce"); + } + /** + * Async version of findProgramAddressSync + * For backwards compatibility + * + * @deprecated Use {@link findProgramAddressSync} instead + */ - function hexToBytes(hex) { - if (typeof hex !== 'string') { - throw new TypeError('hexToBytes: expected string, got ' + _typeof$1(hex)); - } + }, { + key: "findProgramAddress", + value: function () { + var _findProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(seeds, programId) { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + return _context3.abrupt("return", this.findProgramAddressSync(seeds, programId)); - if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex' + hex.length); - var array = new Uint8Array(hex.length / 2); + case 1: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); - for (var i = 0; i < array.length; i++) { - var j = i * 2; - var hexByte = hex.slice(j, j + 2); + function findProgramAddress(_x6, _x7) { + return _findProgramAddress.apply(this, arguments); + } - var _byte = Number.parseInt(hexByte, 16); + return findProgramAddress; + }() + /** + * Check that a pubkey is on the ed25519 curve. + */ - if (Number.isNaN(_byte) || _byte < 0) throw new Error('Invalid byte sequence'); - array[i] = _byte; - } + }, { + key: "isOnCurve", + value: function isOnCurve(pubkeyData) { + var pubkey = new PublicKey(pubkeyData); + return _isOnCurve(pubkey.toBytes()); + } + }]); - return array; - } + return PublicKey; + }(Struct, _Symbol$toStringTag); - function bytesToNumber(bytes) { - return hexToNumber(bytesToHex(bytes)); - } + PublicKey["default"] = new PublicKey('11111111111111111111111111111111'); + SOLANA_SCHEMA.set(PublicKey, { + kind: 'struct', + fields: [['_bn', 'u256']] + }); + /** + * An account key pair (public and secret keys). + * + * @deprecated since v1.10.0, please use {@link Keypair} instead. + */ - function ensureBytes(hex) { - return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex); - } + var Account = /*#__PURE__*/function () { + /** @internal */ - function normalizeScalar(num) { - if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0) return BigInt(num); - if (typeof num === 'bigint' && isWithinCurveOrder(num)) return num; - throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n'); - } + /** @internal */ - function mod(a) { - var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var result = a % b; - return result >= _0n ? result : b + result; - } + /** + * Create a new Account object + * + * If the secretKey parameter is not provided a new key pair is randomly + * created for the account + * + * @param secretKey Secret key for the account + */ + function Account(secretKey) { + _classCallCheck(this, Account); - function pow2(x, power) { - var P = CURVE.P; - var res = x; + this._publicKey = void 0; + this._secretKey = void 0; - while (power-- > _0n) { - res *= res; - res %= P; - } + if (secretKey) { + var secretKeyBuffer = toBuffer(secretKey); - return res; - } + if (secretKey.length !== 64) { + throw new Error('bad secret key size'); + } - function sqrtMod(x) { - var P = CURVE.P; + this._publicKey = secretKeyBuffer.slice(32, 64); + this._secretKey = secretKeyBuffer.slice(0, 32); + } else { + this._secretKey = toBuffer(generatePrivateKey()); + this._publicKey = toBuffer(getPublicKey(this._secretKey)); + } + } + /** + * The public key for this account + */ - var _6n = BigInt(6); - var _11n = BigInt(11); + _createClass(Account, [{ + key: "publicKey", + get: function get() { + return new PublicKey(this._publicKey); + } + /** + * The **unencrypted** secret key for this account. The first 32 bytes + * is the private scalar and the last 32 bytes is the public key. + * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ + */ - var _22n = BigInt(22); + }, { + key: "secretKey", + get: function get() { + return Buffer$1.concat([this._secretKey, this._publicKey], 64); + } + }]); - var _23n = BigInt(23); + return Account; + }(); - var _44n = BigInt(44); + var BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111'); + /** + * Maximum over-the-wire size of a Transaction + * + * 1280 is IPv6 minimum MTU + * 40 bytes is the size of the IPv6 header + * 8 bytes is the size of the fragment header + */ - var _88n = BigInt(88); + var PACKET_DATA_SIZE = 1280 - 40 - 8; + var VERSION_PREFIX_MASK = 0x7f; + var SIGNATURE_LENGTH_IN_BYTES = 64; - var b2 = x * x * x % P; - var b3 = b2 * b2 * x % P; - var b6 = pow2(b3, _3n) * b3 % P; - var b9 = pow2(b6, _3n) * b3 % P; - var b11 = pow2(b9, _2n) * b2 % P; - var b22 = pow2(b11, _11n) * b11 % P; - var b44 = pow2(b22, _22n) * b22 % P; - var b88 = pow2(b44, _44n) * b44 % P; - var b176 = pow2(b88, _88n) * b88 % P; - var b220 = pow2(b176, _44n) * b44 % P; - var b223 = pow2(b220, _3n) * b3 % P; - var t1 = pow2(b223, _23n) * b22 % P; - var t2 = pow2(t1, _6n) * b2 % P; - var rt = pow2(t2, _2n); - var xc = rt * rt % P; - if (xc !== x) throw new Error('Cannot find square root'); - return rt; - } + var TransactionExpiredBlockheightExceededError = /*#__PURE__*/function (_Error) { + _inherits(TransactionExpiredBlockheightExceededError, _Error); - function invert(number) { - var modulo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; + var _super3 = _createSuper(TransactionExpiredBlockheightExceededError); - if (number === _0n || modulo <= _0n) { - throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo)); - } + function TransactionExpiredBlockheightExceededError(signature) { + var _this3; - var a = mod(number, modulo); - var b = modulo; - var x = _0n, - u = _1n; + _classCallCheck(this, TransactionExpiredBlockheightExceededError); - while (a !== _0n) { - var q = b / a; - var r = b % a; - var m = x - u * q; - b = a, a = r, x = u, u = m; + _this3 = _super3.call(this, "Signature ".concat(signature, " has expired: block height exceeded.")); + _this3.signature = void 0; + _this3.signature = signature; + return _this3; } - var gcd = b; - if (gcd !== _1n) throw new Error('invert: does not exist'); - return mod(x, modulo); - } - - function invertBatch(nums) { - var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : CURVE.P; - var scratch = new Array(nums.length); - var lastMultiplied = nums.reduce(function (acc, num, i) { - if (num === _0n) return acc; - scratch[i] = acc; - return mod(acc * num, p); - }, _1n); - var inverted = invert(lastMultiplied, p); - nums.reduceRight(function (acc, num, i) { - if (num === _0n) return acc; - scratch[i] = mod(acc * scratch[i], p); - return mod(acc * num, p); - }, inverted); - return scratch; - } + return _createClass(TransactionExpiredBlockheightExceededError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - function bits2int_2(bytes) { - var delta = bytes.length * 8 - groupLen * 8; - var num = bytesToNumber(bytes); - return delta > 0 ? num >> BigInt(delta) : num; - } + Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', { + value: 'TransactionExpiredBlockheightExceededError' + }); - function truncateHash(hash) { - var truncateOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var h = bits2int_2(hash); - if (truncateOnly) return h; - var n = CURVE.n; - return h >= n ? h - n : h; - } + var TransactionExpiredTimeoutError = /*#__PURE__*/function (_Error2) { + _inherits(TransactionExpiredTimeoutError, _Error2); - var _sha256Sync; + var _super4 = _createSuper(TransactionExpiredTimeoutError); - var _hmacSha256Sync; + function TransactionExpiredTimeoutError(signature, timeoutSeconds) { + var _this4; - var HmacDrbg = /*#__PURE__*/function () { - function HmacDrbg(hashLen, qByteLen) { - _classCallCheck(this, HmacDrbg); + _classCallCheck(this, TransactionExpiredTimeoutError); - this.hashLen = hashLen; - this.qByteLen = qByteLen; - if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number'); - if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number'); - this.v = new Uint8Array(hashLen).fill(1); - this.k = new Uint8Array(hashLen).fill(0); - this.counter = 0; + _this4 = _super4.call(this, "Transaction was not confirmed in ".concat(timeoutSeconds.toFixed(2), " seconds. It is ") + 'unknown if it succeeded or failed. Check signature ' + "".concat(signature, " using the Solana Explorer or CLI tools.")); + _this4.signature = void 0; + _this4.signature = signature; + return _this4; } - _createClass(HmacDrbg, [{ - key: "hmac", - value: function hmac() { - for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - values[_key2] = arguments[_key2]; - } + return _createClass(TransactionExpiredTimeoutError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - return utils.hmacSha256.apply(utils, [this.k].concat(values)); - } - }, { - key: "hmacSync", - value: function hmacSync() { - for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - values[_key3] = arguments[_key3]; - } + Object.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', { + value: 'TransactionExpiredTimeoutError' + }); - return _hmacSha256Sync.apply(void 0, [this.k].concat(values)); - } - }, { - key: "checkSync", - value: function checkSync() { - if (typeof _hmacSha256Sync !== 'function') throw new ShaError('hmacSha256Sync needs to be set'); - } - }, { - key: "incr", - value: function incr() { - if (this.counter >= 1000) throw new Error('Tried 1,000 k values for sign(), all were invalid'); - this.counter += 1; - } - }, { - key: "reseed", - value: function () { - var _reseed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { - var seed, - _args = arguments; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - seed = _args.length > 0 && _args[0] !== undefined ? _args[0] : new Uint8Array(); - _context.next = 3; - return this.hmac(this.v, Uint8Array.from([0x00]), seed); + var TransactionExpiredNonceInvalidError = /*#__PURE__*/function (_Error3) { + _inherits(TransactionExpiredNonceInvalidError, _Error3); - case 3: - this.k = _context.sent; - _context.next = 6; - return this.hmac(this.v); + var _super5 = _createSuper(TransactionExpiredNonceInvalidError); - case 6: - this.v = _context.sent; + function TransactionExpiredNonceInvalidError(signature) { + var _this5; - if (!(seed.length === 0)) { - _context.next = 9; - break; - } + _classCallCheck(this, TransactionExpiredNonceInvalidError); - return _context.abrupt("return"); + _this5 = _super5.call(this, "Signature ".concat(signature, " has expired: the nonce is no longer valid.")); + _this5.signature = void 0; + _this5.signature = signature; + return _this5; + } - case 9: - _context.next = 11; - return this.hmac(this.v, Uint8Array.from([0x01]), seed); + return _createClass(TransactionExpiredNonceInvalidError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - case 11: - this.k = _context.sent; - _context.next = 14; - return this.hmac(this.v); + Object.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', { + value: 'TransactionExpiredNonceInvalidError' + }); - case 14: - this.v = _context.sent; + var MessageAccountKeys = /*#__PURE__*/function () { + function MessageAccountKeys(staticAccountKeys, accountKeysFromLookups) { + _classCallCheck(this, MessageAccountKeys); - case 15: - case "end": - return _context.stop(); - } - }, _callee, this); - })); + this.staticAccountKeys = void 0; + this.accountKeysFromLookups = void 0; + this.staticAccountKeys = staticAccountKeys; + this.accountKeysFromLookups = accountKeysFromLookups; + } - function reseed() { - return _reseed.apply(this, arguments); + _createClass(MessageAccountKeys, [{ + key: "keySegments", + value: function keySegments() { + var keySegments = [this.staticAccountKeys]; + + if (this.accountKeysFromLookups) { + keySegments.push(this.accountKeysFromLookups.writable); + keySegments.push(this.accountKeysFromLookups.readonly); } - return reseed; - }() - }, { - key: "reseedSync", - value: function reseedSync() { - var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Uint8Array(); - this.checkSync(); - this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed); - this.v = this.hmacSync(this.v); - if (seed.length === 0) return; - this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed); - this.v = this.hmacSync(this.v); + return keySegments; } }, { - key: "generate", - value: function () { - var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { - var len, out, sl; - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - this.incr(); - len = 0; - out = []; - - case 3: - if (!(len < this.qByteLen)) { - _context2.next = 12; - break; - } - - _context2.next = 6; - return this.hmac(this.v); - - case 6: - this.v = _context2.sent; - sl = this.v.slice(); - out.push(sl); - len += this.v.length; - _context2.next = 3; - break; + key: "get", + value: function get(index) { + var _iterator = _createForOfIteratorHelper(this.keySegments()), + _step; - case 12: - return _context2.abrupt("return", concatBytes.apply(void 0, out)); + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var keySegment = _step.value; - case 13: - case "end": - return _context2.stop(); + if (index < keySegment.length) { + return keySegment[index]; + } else { + index -= keySegment.length; } - }, _callee2, this); - })); - - function generate() { - return _generate.apply(this, arguments); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - return generate; - }() + return; + } }, { - key: "generateSync", - value: function generateSync() { - this.checkSync(); - this.incr(); - var len = 0; - var out = []; + key: "length", + get: function get() { + return this.keySegments().flat().length; + } + }, { + key: "compileInstructions", + value: function compileInstructions(instructions) { + // Bail early if any account indexes would overflow a u8 + var U8_MAX = 255; - while (len < this.qByteLen) { - this.v = this.hmacSync(this.v); - var sl = this.v.slice(); - out.push(sl); - len += this.v.length; + if (this.length > U8_MAX + 1) { + throw new Error('Account index overflow encountered during compilation'); } - return concatBytes.apply(void 0, out); + var keyIndexMap = new Map(); + this.keySegments().flat().forEach(function (key, index) { + keyIndexMap.set(key.toBase58(), index); + }); + + var findKeyIndex = function findKeyIndex(key) { + var keyIndex = keyIndexMap.get(key.toBase58()); + if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation'); + return keyIndex; + }; + + return instructions.map(function (instruction) { + return { + programIdIndex: findKeyIndex(instruction.programId), + accountKeyIndexes: instruction.keys.map(function (meta) { + return findKeyIndex(meta.pubkey); + }), + data: instruction.data + }; + }); } }]); - return HmacDrbg; + return MessageAccountKeys; }(); + /** + * Layout for a public key + */ - function isWithinCurveOrder(num) { - return _0n < num && num < CURVE.n; - } - function isValidFieldElement(num) { - return _0n < num && num < CURVE.P; - } + var publicKey = function publicKey() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'publicKey'; + return blob$1(32, property); + }; + /** + * Layout for a signature + */ - function kmdToSig(kBytes, m, d) { - var lowS = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; - var n = CURVE.n; - var k = truncateHash(kBytes, true); - if (!isWithinCurveOrder(k)) return; - var kinv = invert(k, n); - var q = Point.BASE.multiply(k); - var r = mod(q.x, n); - if (r === _0n) return; - var s = mod(kinv * mod(m + d * r, n), n); - if (s === _0n) return; - var sig = new Signature(r, s); - var recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n); - if (lowS && sig.hasHighS()) { - sig = sig.normalizeS(); - recovery ^= 1; - } + var signature = function signature() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'signature'; + return blob$1(64, property); + }; + /** + * Layout for a Rust String type + */ - return { - sig: sig, - recovery: recovery - }; - } - function normalizePrivateKey(key) { - var num; + var rustString = function rustString() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'string'; + var rsl = struct([u32('length'), u32('lengthPadding'), blob$1(offset$1(u32(), -8), 'chars')], property); - if (typeof key === 'bigint') { - num = key; - } else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) { - num = BigInt(key); - } else if (typeof key === 'string') { - if (key.length !== 2 * groupLen) throw new Error('Expected 32 bytes of private key'); - num = hexToNumber(key); - } else if (key instanceof Uint8Array) { - if (key.length !== groupLen) throw new Error('Expected 32 bytes of private key'); - num = bytesToNumber(key); - } else { - throw new TypeError('Expected valid private key'); - } + var _decode = rsl.decode.bind(rsl); - if (!isWithinCurveOrder(num)) throw new Error('Expected private key: 0 < key < n'); - return num; - } + var _encode = rsl.encode.bind(rsl); - function normalizeSignature(signature) { - if (signature instanceof Signature) { - signature.assertValidity(); - return signature; - } + var rslShim = rsl; - try { - return Signature.fromDER(signature); - } catch (error) { - return Signature.fromCompact(signature); - } - } + rslShim.decode = function (b, offset) { + var data = _decode(b, offset); - function getPublicKey$1(privateKey) { - var isCompressed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } + return data['chars'].toString(); + }; - function bits2int(bytes) { - var slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes; - return bytesToNumber(slice); - } + rslShim.encode = function (str, b, offset) { + var data = { + chars: Buffer$1.from(str, 'utf8') + }; + return _encode(data, b, offset); + }; - function bits2octets(bytes) { - var z1 = bits2int(bytes); - var z2 = mod(z1, CURVE.n); - return int2octets(z2 < _0n ? z1 : z2); - } + rslShim.alloc = function (str) { + return u32().span + u32().span + Buffer$1.from(str, 'utf8').length; + }; - function int2octets(num) { - return numTo32b(num); - } + return rslShim; + }; + /** + * Layout for an Authorized object + */ - function initSigArgs(msgHash, privateKey, extraEntropy) { - if (msgHash == null) throw new Error("sign: expected valid message hash, not \"".concat(msgHash, "\"")); - var h1 = ensureBytes(msgHash); - var d = normalizePrivateKey(privateKey); - var seedArgs = [int2octets(d), bits2octets(h1)]; - if (extraEntropy != null) { - if (extraEntropy === true) extraEntropy = utils.randomBytes(fieldLen); - var e = ensureBytes(extraEntropy); - if (e.length !== fieldLen) throw new Error("sign: Expected ".concat(fieldLen, " bytes of extra data")); - seedArgs.push(e); - } + var authorized = function authorized() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'authorized'; + return struct([publicKey('staker'), publicKey('withdrawer')], property); + }; + /** + * Layout for a Lockup object + */ - var seed = concatBytes.apply(void 0, seedArgs); - var m = bits2int(h1); - return { - seed: seed, - m: m, - d: d - }; - } - function finalizeSig(recSig, opts) { - var sig = recSig.sig, - recovery = recSig.recovery; + var lockup = function lockup() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'lockup'; + return struct([ns64('unixTimestamp'), ns64('epoch'), publicKey('custodian')], property); + }; + /** + * Layout for a VoteInit object + */ - var _Object$assign = Object.assign({ - canonical: true, - der: true - }, opts), - der = _Object$assign.der, - recovered = _Object$assign.recovered; - var hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes(); - return recovered ? [hashed, recovery] : hashed; - } + var voteInit = function voteInit() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteInit'; + return struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), u8('commission')], property); + }; + /** + * Layout for a VoteAuthorizeWithSeedArgs object + */ - function signSync(msgHash, privKey) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var _initSigArgs = initSigArgs(msgHash, privKey, opts.extraEntropy), - seed = _initSigArgs.seed, - m = _initSigArgs.m, - d = _initSigArgs.d; + var voteAuthorizeWithSeedArgs = function voteAuthorizeWithSeedArgs() { + var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteAuthorizeWithSeedArgs'; + return struct([u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property); + }; - var drbg = new HmacDrbg(hashLen, groupLen); - drbg.reseedSync(seed); - var sig; + function getAlloc(type, fields) { + var getItemAlloc = function getItemAlloc(item) { + if (item.span >= 0) { + return item.span; + } else if (typeof item.alloc === 'function') { + return item.alloc(fields[item.property]); + } else if ('count' in item && 'elementLayout' in item) { + var field = fields[item.property]; - while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical))) drbg.reseedSync(); + if (Array.isArray(field)) { + return field.length * getItemAlloc(item.elementLayout); + } + } else if ('fields' in item) { + // This is a `Structure` whose size needs to be recursively measured. + return getAlloc({ + layout: item + }, fields[item.property]); + } // Couldn't determine allocated size of layout - return finalizeSig(sig, opts); + + return 0; + }; + + var alloc = 0; + type.layout.fields.forEach(function (item) { + alloc += getItemAlloc(item); + }); + return alloc; } - Point.BASE._setWindowSize(8); + function decodeLength(bytes) { + var len = 0; + var size = 0; - var crypto$1 = { - node: nodeCrypto, - web: (typeof self === "undefined" ? "undefined" : _typeof$1(self)) === 'object' && 'crypto' in self ? self.crypto : undefined - }; - var TAGGED_HASH_PREFIXES = {}; - var utils = { - bytesToHex: bytesToHex, - hexToBytes: hexToBytes, - concatBytes: concatBytes, - mod: mod, - invert: invert, - isValidPrivateKey: function isValidPrivateKey(privateKey) { - try { - normalizePrivateKey(privateKey); - return true; - } catch (error) { - return false; - } - }, - _bigintTo32Bytes: numTo32b, - _normalizePrivateKey: normalizePrivateKey, - hashToPrivateKey: function hashToPrivateKey(hash) { - hash = ensureBytes(hash); - var minLen = groupLen + 8; + for (;;) { + var elem = bytes.shift(); + len |= (elem & 0x7f) << size * 7; + size += 1; - if (hash.length < minLen || hash.length > 1024) { - throw new Error("Expected valid bytes of private key as per FIPS 186"); + if ((elem & 0x80) === 0) { + break; } + } - var num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n; + return len; + } - return numTo32b(num); - }, - randomBytes: function randomBytes() { - var bytesLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32; + function encodeLength(bytes, len) { + var rem_len = len; - if (crypto$1.web) { - return crypto$1.web.getRandomValues(new Uint8Array(bytesLength)); - } else if (crypto$1.node) { - var randomBytes = crypto$1.node.randomBytes; - return Uint8Array.from(randomBytes(bytesLength)); + for (;;) { + var elem = rem_len & 0x7f; + rem_len >>= 7; + + if (rem_len == 0) { + bytes.push(elem); + break; } else { - throw new Error("The environment doesn't have randomBytes function"); + elem |= 0x80; + bytes.push(elem); } - }, - randomPrivateKey: function randomPrivateKey() { - return utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)); - }, - precompute: function precompute() { - var windowSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; - var point = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Point.BASE; - var cached = point === Point.BASE ? point : new Point(point.x, point.y); - - cached._setWindowSize(windowSize); - - cached.multiply(_3n); - return cached; - }, - sha256: function () { - var _sha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { - var _len4, - messages, - _key4, - buffer, - createHash, - hash, - _args4 = arguments; - - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - for (_len4 = _args4.length, messages = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - messages[_key4] = _args4[_key4]; - } + } + } - if (!crypto$1.web) { - _context4.next = 8; - break; - } + function assert(condition, message) { + if (!condition) { + throw new Error(message || 'Assertion failed'); + } + } - _context4.next = 4; - return crypto$1.web.subtle.digest('SHA-256', concatBytes.apply(void 0, messages)); + var CompiledKeys = /*#__PURE__*/function () { + function CompiledKeys(payer, keyMetaMap) { + _classCallCheck(this, CompiledKeys); - case 4: - buffer = _context4.sent; - return _context4.abrupt("return", new Uint8Array(buffer)); + this.payer = void 0; + this.keyMetaMap = void 0; + this.payer = payer; + this.keyMetaMap = keyMetaMap; + } - case 8: - if (!crypto$1.node) { - _context4.next = 15; - break; - } + _createClass(CompiledKeys, [{ + key: "getMessageComponents", + value: function getMessageComponents() { + var mapEntries = _toConsumableArray(this.keyMetaMap.entries()); - createHash = crypto$1.node.createHash; - hash = createHash('sha256'); - messages.forEach(function (m) { - return hash.update(m); - }); - return _context4.abrupt("return", Uint8Array.from(hash.digest())); + assert(mapEntries.length <= 256, 'Max static account keys length exceeded'); + var writableSigners = mapEntries.filter(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + meta = _ref2[1]; - case 15: - throw new Error("The environment doesn't have sha256 function"); + return meta.isSigner && meta.isWritable; + }); + var readonlySigners = mapEntries.filter(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + meta = _ref4[1]; - case 16: - case "end": - return _context4.stop(); - } - }, _callee4); - })); + return meta.isSigner && !meta.isWritable; + }); + var writableNonSigners = mapEntries.filter(function (_ref5) { + var _ref6 = _slicedToArray(_ref5, 2), + meta = _ref6[1]; - function sha256() { - return _sha.apply(this, arguments); - } + return !meta.isSigner && meta.isWritable; + }); + var readonlyNonSigners = mapEntries.filter(function (_ref7) { + var _ref8 = _slicedToArray(_ref7, 2), + meta = _ref8[1]; - return sha256; - }(), - hmacSha256: function () { - var _hmacSha = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) { - var _len5, - messages, - _key5, - ckey, - message, - buffer, - createHmac, - hash, - _args5 = arguments; + return !meta.isSigner && !meta.isWritable; + }); + var header = { + numRequiredSignatures: writableSigners.length + readonlySigners.length, + numReadonlySignedAccounts: readonlySigners.length, + numReadonlyUnsignedAccounts: readonlyNonSigners.length + }; // sanity checks - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - for (_len5 = _args5.length, messages = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - messages[_key5 - 1] = _args5[_key5]; - } + { + assert(writableSigners.length > 0, 'Expected at least one writable signer key'); - if (!crypto$1.web) { - _context5.next = 12; - break; - } + var _writableSigners$2 = _slicedToArray(writableSigners[0], 1), + payerAddress = _writableSigners$2[0]; - _context5.next = 4; - return crypto$1.web.subtle.importKey('raw', key, { - name: 'HMAC', - hash: { - name: 'SHA-256' - } - }, false, ['sign']); + assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer'); + } + var staticAccountKeys = [].concat(_toConsumableArray(writableSigners.map(function (_ref9) { + var _ref10 = _slicedToArray(_ref9, 1), + address = _ref10[0]; - case 4: - ckey = _context5.sent; - message = concatBytes.apply(void 0, messages); - _context5.next = 8; - return crypto$1.web.subtle.sign('HMAC', ckey, message); + return new PublicKey(address); + })), _toConsumableArray(readonlySigners.map(function (_ref11) { + var _ref12 = _slicedToArray(_ref11, 1), + address = _ref12[0]; - case 8: - buffer = _context5.sent; - return _context5.abrupt("return", new Uint8Array(buffer)); + return new PublicKey(address); + })), _toConsumableArray(writableNonSigners.map(function (_ref13) { + var _ref14 = _slicedToArray(_ref13, 1), + address = _ref14[0]; - case 12: - if (!crypto$1.node) { - _context5.next = 19; - break; - } + return new PublicKey(address); + })), _toConsumableArray(readonlyNonSigners.map(function (_ref15) { + var _ref16 = _slicedToArray(_ref15, 1), + address = _ref16[0]; - createHmac = crypto$1.node.createHmac; - hash = createHmac('sha256', key); - messages.forEach(function (m) { - return hash.update(m); - }); - return _context5.abrupt("return", Uint8Array.from(hash.digest())); + return new PublicKey(address); + }))); + return [header, staticAccountKeys]; + } + }, { + key: "extractTableLookup", + value: function extractTableLookup(lookupTable) { + var _this$drainKeysFoundI = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { + return !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable; + }), + _this$drainKeysFoundI2 = _slicedToArray(_this$drainKeysFoundI, 2), + writableIndexes = _this$drainKeysFoundI2[0], + drainedWritableKeys = _this$drainKeysFoundI2[1]; - case 19: - throw new Error("The environment doesn't have hmac-sha256 function"); + var _this$drainKeysFoundI3 = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { + return !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable; + }), + _this$drainKeysFoundI4 = _slicedToArray(_this$drainKeysFoundI3, 2), + readonlyIndexes = _this$drainKeysFoundI4[0], + drainedReadonlyKeys = _this$drainKeysFoundI4[1]; // Don't extract lookup if no keys were found - case 20: - case "end": - return _context5.stop(); - } - }, _callee5); - })); - function hmacSha256(_x9) { - return _hmacSha.apply(this, arguments); + if (writableIndexes.length === 0 && readonlyIndexes.length === 0) { + return; + } + + return [{ + accountKey: lookupTable.key, + writableIndexes: writableIndexes, + readonlyIndexes: readonlyIndexes + }, { + writable: drainedWritableKeys, + readonly: drainedReadonlyKeys + }]; } + /** @internal */ - return hmacSha256; - }(), - sha256Sync: undefined, - hmacSha256Sync: undefined, - taggedHash: function () { - var _taggedHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(tag) { - var tagP, - tagH, - _len6, - messages, - _key6, - _args6 = arguments; + }, { + key: "drainKeysFoundInLookupTable", + value: function drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) { + var _this6 = this; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { - case 0: - tagP = TAGGED_HASH_PREFIXES[tag]; + var lookupTableIndexes = new Array(); + var drainedKeys = new Array(); - if (!(tagP === undefined)) { - _context6.next = 7; - break; - } + var _iterator2 = _createForOfIteratorHelper(this.keyMetaMap.entries()), + _step2; - _context6.next = 4; - return utils.sha256(Uint8Array.from(tag, function (c) { - return c.charCodeAt(0); - })); + try { + var _loop = function _loop() { + var _step2$value = _slicedToArray(_step2.value, 2), + address = _step2$value[0], + keyMeta = _step2$value[1]; - case 4: - tagH = _context6.sent; - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; + if (keyMetaFilter(keyMeta)) { + var key = new PublicKey(address); + var lookupTableIndex = lookupTableEntries.findIndex(function (entry) { + return entry.equals(key); + }); - case 7: - for (_len6 = _args6.length, messages = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { - messages[_key6 - 1] = _args6[_key6]; - } + if (lookupTableIndex >= 0) { + assert(lookupTableIndex < 256, 'Max lookup table index exceeded'); + lookupTableIndexes.push(lookupTableIndex); + drainedKeys.push(key); - return _context6.abrupt("return", utils.sha256.apply(utils, [tagP].concat(messages))); + _this6.keyMetaMap["delete"](address); + } + } + }; - case 9: - case "end": - return _context6.stop(); + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + _loop(); } - }, _callee6); - })); + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } - function taggedHash(_x10) { - return _taggedHash.apply(this, arguments); + return [lookupTableIndexes, drainedKeys]; } + }], [{ + key: "compile", + value: function compile(instructions, payer) { + var keyMetaMap = new Map(); - return taggedHash; - }(), - taggedHashSync: function taggedHashSync(tag) { - if (typeof _sha256Sync !== 'function') throw new ShaError('sha256Sync is undefined, you need to set it'); - var tagP = TAGGED_HASH_PREFIXES[tag]; + var getOrInsertDefault = function getOrInsertDefault(pubkey) { + var address = pubkey.toBase58(); + var keyMeta = keyMetaMap.get(address); - if (tagP === undefined) { - var tagH = _sha256Sync(Uint8Array.from(tag, function (c) { - return c.charCodeAt(0); - })); + if (keyMeta === undefined) { + keyMeta = { + isSigner: false, + isWritable: false, + isInvoked: false + }; + keyMetaMap.set(address, keyMeta); + } - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } + return keyMeta; + }; - for (var _len7 = arguments.length, messages = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { - messages[_key7 - 1] = arguments[_key7]; - } + var payerKeyMeta = getOrInsertDefault(payer); + payerKeyMeta.isSigner = true; + payerKeyMeta.isWritable = true; - return _sha256Sync.apply(void 0, [tagP].concat(messages)); - }, - _JacobianPoint: JacobianPoint - }; - Object.defineProperties(utils, { - sha256Sync: { - configurable: false, - get: function get() { - return _sha256Sync; - }, - set: function set(val) { - if (!_sha256Sync) _sha256Sync = val; - } - }, - hmacSha256Sync: { - configurable: false, - get: function get() { - return _hmacSha256Sync; - }, - set: function set(val) { - if (!_hmacSha256Sync) _hmacSha256Sync = val; - } - } - }); + var _iterator3 = _createForOfIteratorHelper(instructions), + _step3; - var _excluded = ["commitment"], - _excluded2 = ["encoding"], - _excluded3 = ["commitment"], - _excluded4 = ["commitment"]; - /** - * A 64 byte secret key, the first 32 bytes of which is the - * private scalar and the last 32 bytes is the public key. - * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ - */ + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var ix = _step3.value; + getOrInsertDefault(ix.programId).isInvoked = true; - utils$1.sha512Sync = function () { - var _ed25519$utils; + var _iterator4 = _createForOfIteratorHelper(ix.keys), + _step4; - return sha512((_ed25519$utils = utils$1).concatBytes.apply(_ed25519$utils, arguments)); - }; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var accountMeta = _step4.value; + var keyMeta = getOrInsertDefault(accountMeta.pubkey); + keyMeta.isSigner || (keyMeta.isSigner = accountMeta.isSigner); + keyMeta.isWritable || (keyMeta.isWritable = accountMeta.isWritable); + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } - var generatePrivateKey = utils$1.randomPrivateKey; + return new CompiledKeys(payer, keyMetaMap); + } + }]); - var generateKeypair = function generateKeypair() { - var privateScalar = utils$1.randomPrivateKey(); - var publicKey = getPublicKey(privateScalar); - var secretKey = new Uint8Array(64); - secretKey.set(privateScalar); - secretKey.set(publicKey, 32); - return { - publicKey: publicKey, - secretKey: secretKey - }; - }; + return CompiledKeys; + }(); + /** + * An instruction to execute by a program + * + * @property {number} programIdIndex + * @property {number[]} accounts + * @property {string} data + */ - var getPublicKey = sync.getPublicKey; + /** + * List of instructions to be processed atomically + */ - function _isOnCurve(publicKey) { - try { - Point$1.fromHex(publicKey, true - /* strict */ - ); - return true; - } catch (_unused) { - return false; - } - } - var _sign = function sign(message, secretKey) { - return sync.sign(message, secretKey.slice(0, 32)); - }; + var Message = /*#__PURE__*/function () { + function Message(args) { + var _this7 = this; - var verify = sync.verify; + _classCallCheck(this, Message); - var toBuffer = function toBuffer(arr) { - if (Buffer$1.isBuffer(arr)) { - return arr; - } else if (arr instanceof Uint8Array) { - return Buffer$1.from(arr.buffer, arr.byteOffset, arr.byteLength); - } else { - return Buffer$1.from(arr); + this.header = void 0; + this.accountKeys = void 0; + this.recentBlockhash = void 0; + this.instructions = void 0; + this.indexToProgramIds = new Map(); + this.header = args.header; + this.accountKeys = args.accountKeys.map(function (account) { + return new PublicKey(account); + }); + this.recentBlockhash = args.recentBlockhash; + this.instructions = args.instructions; + this.instructions.forEach(function (ix) { + return _this7.indexToProgramIds.set(ix.programIdIndex, _this7.accountKeys[ix.programIdIndex]); + }); } - }; // Class wrapping a plain object + _createClass(Message, [{ + key: "version", + get: function get() { + return 'legacy'; + } + }, { + key: "staticAccountKeys", + get: function get() { + return this.accountKeys; + } + }, { + key: "compiledInstructions", + get: function get() { + return this.instructions.map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accounts, + data: bs58$3.decode(ix.data) + }; + }); + } + }, { + key: "addressTableLookups", + get: function get() { + return []; + } + }, { + key: "getAccountKeys", + value: function getAccountKeys() { + return new MessageAccountKeys(this.staticAccountKeys); + } + }, { + key: "isAccountSigner", + value: function isAccountSigner(index) { + return index < this.header.numRequiredSignatures; + } + }, { + key: "isAccountWritable", + value: function isAccountWritable(index) { + var numSignedAccounts = this.header.numRequiredSignatures; - var Struct = /*#__PURE__*/function () { - function Struct(properties) { - _classCallCheck(this, Struct); - - Object.assign(this, properties); - } - - _createClass(Struct, [{ - key: "encode", - value: function encode() { - return Buffer$1.from(serialize_1(SOLANA_SCHEMA, this)); + if (index >= this.header.numRequiredSignatures) { + var unsignedAccountIndex = index - numSignedAccounts; + var numUnsignedAccounts = this.accountKeys.length - numSignedAccounts; + var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; + return unsignedAccountIndex < numWritableUnsignedAccounts; + } else { + var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; + return index < numWritableSignedAccounts; + } } - }], [{ - key: "decode", - value: function decode(data) { - return deserialize_1(SOLANA_SCHEMA, this, data); + }, { + key: "isProgramId", + value: function isProgramId(index) { + return this.indexToProgramIds.has(index); } }, { - key: "decodeUnchecked", - value: function decodeUnchecked(data) { - return deserializeUnchecked_1(SOLANA_SCHEMA, this, data); + key: "programIds", + value: function programIds() { + return _toConsumableArray(this.indexToProgramIds.values()); } - }]); + }, { + key: "nonProgramIds", + value: function nonProgramIds() { + var _this8 = this; - return Struct; - }(); // Class representing a Rust-compatible enum, since enums are only strings or - // numbers in pure JS + return this.accountKeys.filter(function (_, index) { + return !_this8.isProgramId(index); + }); + } + }, { + key: "serialize", + value: function serialize() { + var numKeys = this.accountKeys.length; + var keyCount = []; + encodeLength(keyCount, numKeys); + var instructions = this.instructions.map(function (instruction) { + var accounts = instruction.accounts, + programIdIndex = instruction.programIdIndex; + var data = Array.from(bs58$3.decode(instruction.data)); + var keyIndicesCount = []; + encodeLength(keyIndicesCount, accounts.length); + var dataCount = []; + encodeLength(dataCount, data.length); + return { + programIdIndex: programIdIndex, + keyIndicesCount: Buffer$1.from(keyIndicesCount), + keyIndices: accounts, + dataLength: Buffer$1.from(dataCount), + data: data + }; + }); + var instructionCount = []; + encodeLength(instructionCount, instructions.length); + var instructionBuffer = Buffer$1.alloc(PACKET_DATA_SIZE); + Buffer$1.from(instructionCount).copy(instructionBuffer); + var instructionBufferLength = instructionCount.length; + instructions.forEach(function (instruction) { + var instructionLayout = struct([u8('programIdIndex'), blob$1(instruction.keyIndicesCount.length, 'keyIndicesCount'), seq$1(u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), blob$1(instruction.dataLength.length, 'dataLength'), seq$1(u8('userdatum'), instruction.data.length, 'data')]); + var length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength); + instructionBufferLength += length; + }); + instructionBuffer = instructionBuffer.slice(0, instructionBufferLength); + var signDataLayout = struct([blob$1(1, 'numRequiredSignatures'), blob$1(1, 'numReadonlySignedAccounts'), blob$1(1, 'numReadonlyUnsignedAccounts'), blob$1(keyCount.length, 'keyCount'), seq$1(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]); + var transaction = { + numRequiredSignatures: Buffer$1.from([this.header.numRequiredSignatures]), + numReadonlySignedAccounts: Buffer$1.from([this.header.numReadonlySignedAccounts]), + numReadonlyUnsignedAccounts: Buffer$1.from([this.header.numReadonlyUnsignedAccounts]), + keyCount: Buffer$1.from(keyCount), + keys: this.accountKeys.map(function (key) { + return toBuffer(key.toBytes()); + }), + recentBlockhash: bs58$3.decode(this.recentBlockhash) + }; + var signData = Buffer$1.alloc(2048); + var length = signDataLayout.encode(transaction, signData); + instructionBuffer.copy(signData, length); + return signData.slice(0, length + instructionBuffer.length); + } + /** + * Decode a compiled message into a Message object. + */ + }], [{ + key: "compile", + value: function compile(args) { + var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); - var Enum = /*#__PURE__*/function (_Struct) { - _inherits(Enum, _Struct); + var _compiledKeys$getMess = compiledKeys.getMessageComponents(), + _compiledKeys$getMess2 = _slicedToArray(_compiledKeys$getMess, 2), + header = _compiledKeys$getMess2[0], + staticAccountKeys = _compiledKeys$getMess2[1]; - var _super = _createSuper(Enum); + var accountKeys = new MessageAccountKeys(staticAccountKeys); + var instructions = accountKeys.compileInstructions(args.instructions).map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accounts: ix.accountKeyIndexes, + data: bs58$3.encode(ix.data) + }; + }); + return new Message({ + header: header, + accountKeys: staticAccountKeys, + recentBlockhash: args.recentBlockhash, + instructions: instructions + }); + } + }, { + key: "from", + value: function from(buffer) { + // Slice up wire data + var byteArray = _toConsumableArray(buffer); - function Enum(properties) { - var _this; + var numRequiredSignatures = byteArray.shift(); - _classCallCheck(this, Enum); + if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) { + throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()'); + } - _this = _super.call(this, properties); - _this["enum"] = ''; + var numReadonlySignedAccounts = byteArray.shift(); + var numReadonlyUnsignedAccounts = byteArray.shift(); + var accountCount = decodeLength(byteArray); + var accountKeys = []; - if (Object.keys(properties).length !== 1) { - throw new Error('Enum can only take single value'); - } + for (var i = 0; i < accountCount; i++) { + var account = byteArray.slice(0, PUBLIC_KEY_LENGTH); + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + accountKeys.push(new PublicKey(Buffer$1.from(account))); + } - Object.keys(properties).map(function (key) { - _this["enum"] = key; - }); - return _this; - } + var recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH); + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + var instructionCount = decodeLength(byteArray); + var instructions = []; - return _createClass(Enum); - }(Struct); + for (var _i2 = 0; _i2 < instructionCount; _i2++) { + var programIdIndex = byteArray.shift(); - var SOLANA_SCHEMA = new Map(); + var _accountCount = decodeLength(byteArray); + + var accounts = byteArray.slice(0, _accountCount); + byteArray = byteArray.slice(_accountCount); + var dataLength = decodeLength(byteArray); + var dataSlice = byteArray.slice(0, dataLength); + var data = bs58$3.encode(Buffer$1.from(dataSlice)); + byteArray = byteArray.slice(dataLength); + instructions.push({ + programIdIndex: programIdIndex, + accounts: accounts, + data: data + }); + } + + var messageArgs = { + header: { + numRequiredSignatures: numRequiredSignatures, + numReadonlySignedAccounts: numReadonlySignedAccounts, + numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts + }, + recentBlockhash: bs58$3.encode(Buffer$1.from(recentBlockhash)), + accountKeys: accountKeys, + instructions: instructions + }; + return new Message(messageArgs); + } + }]); - var _Symbol$toStringTag; + return Message; + }(); /** - * Maximum length of derived pubkey seed + * Message constructor arguments */ - var MAX_SEED_LENGTH = 32; - /** - * Size of public key in bytes - */ + var MessageV0 = /*#__PURE__*/function () { + function MessageV0(args) { + _classCallCheck(this, MessageV0); - var PUBLIC_KEY_LENGTH = 32; - /** - * Value to be converted into public key - */ + this.header = void 0; + this.staticAccountKeys = void 0; + this.recentBlockhash = void 0; + this.compiledInstructions = void 0; + this.addressTableLookups = void 0; + this.header = args.header; + this.staticAccountKeys = args.staticAccountKeys; + this.recentBlockhash = args.recentBlockhash; + this.compiledInstructions = args.compiledInstructions; + this.addressTableLookups = args.addressTableLookups; + } - function isPublicKeyData(value) { - return value._bn !== undefined; - } // local counter used by PublicKey.unique() + _createClass(MessageV0, [{ + key: "version", + get: function get() { + return 0; + } + }, { + key: "numAccountKeysFromLookups", + get: function get() { + var count = 0; + var _iterator5 = _createForOfIteratorHelper(this.addressTableLookups), + _step5; - var uniquePublicKeyCounter = 1; - /** - * A public key - */ + try { + for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { + var lookup = _step5.value; + count += lookup.readonlyIndexes.length + lookup.writableIndexes.length; + } + } catch (err) { + _iterator5.e(err); + } finally { + _iterator5.f(); + } - _Symbol$toStringTag = Symbol.toStringTag; + return count; + } + }, { + key: "getAccountKeys", + value: function getAccountKeys(args) { + var accountKeysFromLookups; - var PublicKey = /*#__PURE__*/function (_Struct2, _Symbol$toStringTag2) { - _inherits(PublicKey, _Struct2); + if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) { + if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) { + throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups'); + } - var _super2 = _createSuper(PublicKey); + accountKeysFromLookups = args.accountKeysFromLookups; + } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) { + accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts); + } else if (this.addressTableLookups.length > 0) { + throw new Error('Failed to get account keys because address table lookups were not resolved'); + } - /** @internal */ + return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups); + } + }, { + key: "isAccountSigner", + value: function isAccountSigner(index) { + return index < this.header.numRequiredSignatures; + } + }, { + key: "isAccountWritable", + value: function isAccountWritable(index) { + var numSignedAccounts = this.header.numRequiredSignatures; + var numStaticAccountKeys = this.staticAccountKeys.length; - /** - * Create a new PublicKey object - * @param value ed25519 public key as buffer or base-58 encoded string - */ - function PublicKey(value) { - var _this2; + if (index >= numStaticAccountKeys) { + var lookupAccountKeysIndex = index - numStaticAccountKeys; + var numWritableLookupAccountKeys = this.addressTableLookups.reduce(function (count, lookup) { + return count + lookup.writableIndexes.length; + }, 0); + return lookupAccountKeysIndex < numWritableLookupAccountKeys; + } else if (index >= this.header.numRequiredSignatures) { + var unsignedAccountIndex = index - numSignedAccounts; + var numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts; + var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; + return unsignedAccountIndex < numWritableUnsignedAccounts; + } else { + var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; + return index < numWritableSignedAccounts; + } + } + }, { + key: "resolveAddressTableLookups", + value: function resolveAddressTableLookups(addressLookupTableAccounts) { + var accountKeysFromLookups = { + writable: [], + readonly: [] + }; - _classCallCheck(this, PublicKey); + var _iterator6 = _createForOfIteratorHelper(this.addressTableLookups), + _step6; - _this2 = _super2.call(this, {}); - _this2._bn = void 0; + try { + var _loop2 = function _loop2() { + var tableLookup = _step6.value; + var tableAccount = addressLookupTableAccounts.find(function (account) { + return account.key.equals(tableLookup.accountKey); + }); - if (isPublicKeyData(value)) { - _this2._bn = value._bn; - } else { - if (typeof value === 'string') { - // assume base 58 encoding by default - var decoded = bs58$1.decode(value); + if (!tableAccount) { + throw new Error("Failed to find address lookup table account for table key ".concat(tableLookup.accountKey.toBase58())); + } - if (decoded.length != PUBLIC_KEY_LENGTH) { - throw new Error("Invalid public key input"); - } + var _iterator7 = _createForOfIteratorHelper(tableLookup.writableIndexes), + _step7; - _this2._bn = new BN$1(decoded); - } else { - _this2._bn = new BN$1(value); - } + try { + for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { + var index = _step7.value; - if (_this2._bn.byteLength() > PUBLIC_KEY_LENGTH) { - throw new Error("Invalid public key input"); - } - } + if (index < tableAccount.state.addresses.length) { + accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]); + } else { + throw new Error("Failed to find address for index ".concat(index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); + } + } + } catch (err) { + _iterator7.e(err); + } finally { + _iterator7.f(); + } - return _this2; - } - /** - * Returns a unique PublicKey for tests and benchmarks using a counter - */ + var _iterator8 = _createForOfIteratorHelper(tableLookup.readonlyIndexes), + _step8; + try { + for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { + var _index = _step8.value; - _createClass(PublicKey, [{ - key: "equals", - value: - /** - * Default public key value. The base58-encoded string representation is all ones (as seen below) - * The underlying BN number is 32 bytes that are all zeros - */ + if (_index < tableAccount.state.addresses.length) { + accountKeysFromLookups.readonly.push(tableAccount.state.addresses[_index]); + } else { + throw new Error("Failed to find address for index ".concat(_index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); + } + } + } catch (err) { + _iterator8.e(err); + } finally { + _iterator8.f(); + } + }; - /** - * Checks if two publicKeys are equal - */ - function equals(publicKey) { - return this._bn.eq(publicKey._bn); - } - /** - * Return the base-58 representation of the public key - */ + for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { + _loop2(); + } + } catch (err) { + _iterator6.e(err); + } finally { + _iterator6.f(); + } - }, { - key: "toBase58", - value: function toBase58() { - return bs58$1.encode(this.toBytes()); + return accountKeysFromLookups; } }, { - key: "toJSON", - value: function toJSON() { - return this.toBase58(); + key: "serialize", + value: function serialize() { + var encodedStaticAccountKeysLength = Array(); + encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length); + var serializedInstructions = this.serializeInstructions(); + var encodedInstructionsLength = Array(); + encodeLength(encodedInstructionsLength, this.compiledInstructions.length); + var serializedAddressTableLookups = this.serializeAddressTableLookups(); + var encodedAddressTableLookupsLength = Array(); + encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length); + var messageLayout = struct([u8('prefix'), struct([u8('numRequiredSignatures'), u8('numReadonlySignedAccounts'), u8('numReadonlyUnsignedAccounts')], 'header'), blob$1(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), seq$1(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), blob$1(encodedInstructionsLength.length, 'instructionsLength'), blob$1(serializedInstructions.length, 'serializedInstructions'), blob$1(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), blob$1(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]); + var serializedMessage = new Uint8Array(PACKET_DATA_SIZE); + var MESSAGE_VERSION_0_PREFIX = 1 << 7; + var serializedMessageLength = messageLayout.encode({ + prefix: MESSAGE_VERSION_0_PREFIX, + header: this.header, + staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength), + staticAccountKeys: this.staticAccountKeys.map(function (key) { + return key.toBytes(); + }), + recentBlockhash: bs58$3.decode(this.recentBlockhash), + instructionsLength: new Uint8Array(encodedInstructionsLength), + serializedInstructions: serializedInstructions, + addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength), + serializedAddressTableLookups: serializedAddressTableLookups + }, serializedMessage); + return serializedMessage.slice(0, serializedMessageLength); } - /** - * Return the byte array representation of the public key in big endian - */ - }, { - key: "toBytes", - value: function toBytes() { - var buf = this.toBuffer(); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - /** - * Return the Buffer representation of the public key in big endian - */ + key: "serializeInstructions", + value: function serializeInstructions() { + var serializedLength = 0; + var serializedInstructions = new Uint8Array(PACKET_DATA_SIZE); - }, { - key: "toBuffer", - value: function toBuffer() { - var b = this._bn.toArrayLike(Buffer$1); + var _iterator9 = _createForOfIteratorHelper(this.compiledInstructions), + _step9; - if (b.length === PUBLIC_KEY_LENGTH) { - return b; + try { + for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { + var instruction = _step9.value; + var encodedAccountKeyIndexesLength = Array(); + encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length); + var encodedDataLength = Array(); + encodeLength(encodedDataLength, instruction.data.length); + var instructionLayout = struct([u8('programIdIndex'), blob$1(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), seq$1(u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), blob$1(encodedDataLength.length, 'encodedDataLength'), blob$1(instruction.data.length, 'data')]); + serializedLength += instructionLayout.encode({ + programIdIndex: instruction.programIdIndex, + encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength), + accountKeyIndexes: instruction.accountKeyIndexes, + encodedDataLength: new Uint8Array(encodedDataLength), + data: instruction.data + }, serializedInstructions, serializedLength); + } + } catch (err) { + _iterator9.e(err); + } finally { + _iterator9.f(); } - var zeroPad = Buffer$1.alloc(32); - b.copy(zeroPad, 32 - b.length); - return zeroPad; + return serializedInstructions.slice(0, serializedLength); } }, { - key: _Symbol$toStringTag2, - get: function get() { - return "PublicKey(".concat(this.toString(), ")"); - } - /** - * Return the base-58 representation of the public key - */ + key: "serializeAddressTableLookups", + value: function serializeAddressTableLookups() { + var serializedLength = 0; + var serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE); - }, { - key: "toString", - value: function toString() { - return this.toBase58(); - } - /** - * Derive a public key from another key, a seed, and a program ID. - * The program ID will also serve as the owner of the public key, giving - * it permission to write data to the account. - */ + var _iterator10 = _createForOfIteratorHelper(this.addressTableLookups), + _step10; - /* eslint-disable require-await */ + try { + for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { + var lookup = _step10.value; + var encodedWritableIndexesLength = Array(); + encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length); + var encodedReadonlyIndexesLength = Array(); + encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length); + var addressTableLookupLayout = struct([publicKey('accountKey'), blob$1(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), seq$1(u8(), lookup.writableIndexes.length, 'writableIndexes'), blob$1(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), seq$1(u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]); + serializedLength += addressTableLookupLayout.encode({ + accountKey: lookup.accountKey.toBytes(), + encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength), + writableIndexes: lookup.writableIndexes, + encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength), + readonlyIndexes: lookup.readonlyIndexes + }, serializedAddressTableLookups, serializedLength); + } + } catch (err) { + _iterator10.e(err); + } finally { + _iterator10.f(); + } - }], [{ - key: "unique", - value: function unique() { - var key = new PublicKey(uniquePublicKeyCounter); - uniquePublicKeyCounter += 1; - return new PublicKey(key.toBuffer()); + return serializedAddressTableLookups.slice(0, serializedLength); } - }, { - key: "createWithSeed", - value: function () { - var _createWithSeed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(fromPublicKey, seed, programId) { - var buffer, publicKeyBytes; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - buffer = Buffer$1.concat([fromPublicKey.toBuffer(), Buffer$1.from(seed), programId.toBuffer()]); - publicKeyBytes = sha256(buffer); - return _context.abrupt("return", new PublicKey(publicKeyBytes)); + }], [{ + key: "compile", + value: function compile(args) { + var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); + var addressTableLookups = new Array(); + var accountKeysFromLookups = { + writable: new Array(), + readonly: new Array() + }; + var lookupTableAccounts = args.addressLookupTableAccounts || []; - case 3: - case "end": - return _context.stop(); - } - }, _callee); - })); + var _iterator11 = _createForOfIteratorHelper(lookupTableAccounts), + _step11; - function createWithSeed(_x, _x2, _x3) { - return _createWithSeed.apply(this, arguments); - } + try { + for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { + var lookupTable = _step11.value; + var extractResult = compiledKeys.extractTableLookup(lookupTable); - return createWithSeed; - }() - /** - * Derive a program address from seeds and a program ID. - */ + if (extractResult !== undefined) { + var _accountKeysFromLooku, _accountKeysFromLooku2; - /* eslint-disable require-await */ + var _extractResult2 = _slicedToArray(extractResult, 2), + addressTableLookup = _extractResult2[0], + _extractResult$2 = _extractResult2[1], + writable = _extractResult$2.writable, + readonly = _extractResult$2.readonly; - }, { - key: "createProgramAddressSync", - value: function createProgramAddressSync(seeds, programId) { - var buffer = Buffer$1.alloc(0); - seeds.forEach(function (seed) { - if (seed.length > MAX_SEED_LENGTH) { - throw new TypeError("Max seed length exceeded"); - } + addressTableLookups.push(addressTableLookup); - buffer = Buffer$1.concat([buffer, toBuffer(seed)]); - }); - buffer = Buffer$1.concat([buffer, programId.toBuffer(), Buffer$1.from('ProgramDerivedAddress')]); - var publicKeyBytes = sha256(buffer); + (_accountKeysFromLooku = accountKeysFromLookups.writable).push.apply(_accountKeysFromLooku, _toConsumableArray(writable)); - if (_isOnCurve(publicKeyBytes)) { - throw new Error("Invalid seeds, address must fall off the curve"); + (_accountKeysFromLooku2 = accountKeysFromLookups.readonly).push.apply(_accountKeysFromLooku2, _toConsumableArray(readonly)); + } + } + } catch (err) { + _iterator11.e(err); + } finally { + _iterator11.f(); } - return new PublicKey(publicKeyBytes); - } - /** - * Async version of createProgramAddressSync - * For backwards compatibility - * - * @deprecated Use {@link createProgramAddressSync} instead - */ - - /* eslint-disable require-await */ + var _compiledKeys$getMess3 = compiledKeys.getMessageComponents(), + _compiledKeys$getMess4 = _slicedToArray(_compiledKeys$getMess3, 2), + header = _compiledKeys$getMess4[0], + staticAccountKeys = _compiledKeys$getMess4[1]; + var accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups); + var compiledInstructions = accountKeys.compileInstructions(args.instructions); + return new MessageV0({ + header: header, + staticAccountKeys: staticAccountKeys, + recentBlockhash: args.recentBlockhash, + compiledInstructions: compiledInstructions, + addressTableLookups: addressTableLookups + }); + } }, { - key: "createProgramAddress", - value: function () { - var _createProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(seeds, programId) { - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - return _context2.abrupt("return", this.createProgramAddressSync(seeds, programId)); + key: "deserialize", + value: function deserialize(serializedMessage) { + var byteArray = _toConsumableArray(serializedMessage); - case 1: - case "end": - return _context2.stop(); - } - }, _callee2, this); - })); + var prefix = byteArray.shift(); + var maskedPrefix = prefix & VERSION_PREFIX_MASK; + assert(prefix !== maskedPrefix, "Expected versioned message but received legacy message"); + var version = maskedPrefix; + assert(version === 0, "Expected versioned message with version 0 but found version ".concat(version)); + var header = { + numRequiredSignatures: byteArray.shift(), + numReadonlySignedAccounts: byteArray.shift(), + numReadonlyUnsignedAccounts: byteArray.shift() + }; + var staticAccountKeys = []; + var staticAccountKeysLength = decodeLength(byteArray); - function createProgramAddress(_x4, _x5) { - return _createProgramAddress.apply(this, arguments); + for (var i = 0; i < staticAccountKeysLength; i++) { + staticAccountKeys.push(new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH))); } - return createProgramAddress; - }() - /** - * Find a valid program address - * - * Valid program addresses must fall off the ed25519 curve. This function - * iterates a nonce until it finds one that when combined with the seeds - * results in a valid program address. - */ - - }, { - key: "findProgramAddressSync", - value: function findProgramAddressSync(seeds, programId) { - var nonce = 255; - var address; - - while (nonce != 0) { - try { - var seedsWithNonce = seeds.concat(Buffer$1.from([nonce])); - address = this.createProgramAddressSync(seedsWithNonce, programId); - } catch (err) { - if (err instanceof TypeError) { - throw err; - } + var recentBlockhash = bs58$3.encode(byteArray.splice(0, PUBLIC_KEY_LENGTH)); + var instructionCount = decodeLength(byteArray); + var compiledInstructions = []; - nonce--; - continue; - } + for (var _i4 = 0; _i4 < instructionCount; _i4++) { + var programIdIndex = byteArray.shift(); + var accountKeyIndexesLength = decodeLength(byteArray); + var accountKeyIndexes = byteArray.splice(0, accountKeyIndexesLength); + var dataLength = decodeLength(byteArray); + var data = new Uint8Array(byteArray.splice(0, dataLength)); + compiledInstructions.push({ + programIdIndex: programIdIndex, + accountKeyIndexes: accountKeyIndexes, + data: data + }); + } - return [address, nonce]; + var addressTableLookupsCount = decodeLength(byteArray); + var addressTableLookups = []; + + for (var _i6 = 0; _i6 < addressTableLookupsCount; _i6++) { + var accountKey = new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH)); + var writableIndexesLength = decodeLength(byteArray); + var writableIndexes = byteArray.splice(0, writableIndexesLength); + var readonlyIndexesLength = decodeLength(byteArray); + var readonlyIndexes = byteArray.splice(0, readonlyIndexesLength); + addressTableLookups.push({ + accountKey: accountKey, + writableIndexes: writableIndexes, + readonlyIndexes: readonlyIndexes + }); } - throw new Error("Unable to find a viable program address nonce"); + return new MessageV0({ + header: header, + staticAccountKeys: staticAccountKeys, + recentBlockhash: recentBlockhash, + compiledInstructions: compiledInstructions, + addressTableLookups: addressTableLookups + }); } - /** - * Async version of findProgramAddressSync - * For backwards compatibility - * - * @deprecated Use {@link findProgramAddressSync} instead - */ + }]); - }, { - key: "findProgramAddress", - value: function () { - var _findProgramAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(seeds, programId) { - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) switch (_context3.prev = _context3.next) { - case 0: - return _context3.abrupt("return", this.findProgramAddressSync(seeds, programId)); + return MessageV0; + }(); // eslint-disable-next-line no-redeclare - case 1: - case "end": - return _context3.stop(); - } - }, _callee3, this); - })); - function findProgramAddress(_x6, _x7) { - return _findProgramAddress.apply(this, arguments); - } + var VersionedMessage = { + deserializeMessageVersion: function deserializeMessageVersion(serializedMessage) { + var prefix = serializedMessage[0]; + var maskedPrefix = prefix & VERSION_PREFIX_MASK; // if the highest bit of the prefix is not set, the message is not versioned - return findProgramAddress; - }() - /** - * Check that a pubkey is on the ed25519 curve. - */ + if (maskedPrefix === prefix) { + return 'legacy'; + } // the lower 7 bits of the prefix indicate the message version - }, { - key: "isOnCurve", - value: function isOnCurve(pubkeyData) { - var pubkey = new PublicKey(pubkeyData); - return _isOnCurve(pubkey.toBytes()); + + return maskedPrefix; + }, + deserialize: function deserialize(serializedMessage) { + var version = VersionedMessage.deserializeMessageVersion(serializedMessage); + + if (version === 'legacy') { + return Message.from(serializedMessage); } - }]); - return PublicKey; - }(Struct, _Symbol$toStringTag); + if (version === 0) { + return MessageV0.deserialize(serializedMessage); + } else { + throw new Error("Transaction message version ".concat(version, " deserialization is not supported")); + } + } + }; + /** + * Transaction signature as base-58 encoded string + */ - PublicKey["default"] = new PublicKey('11111111111111111111111111111111'); - SOLANA_SCHEMA.set(PublicKey, { - kind: 'struct', - fields: [['_bn', 'u256']] - }); + var TransactionStatus; /** - * An account key pair (public and secret keys). - * - * @deprecated since v1.10.0, please use {@link Keypair} instead. + * Default (empty) signature */ - var Account = /*#__PURE__*/function () { - /** @internal */ + (function (TransactionStatus) { + TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"] = 0] = "BLOCKHEIGHT_EXCEEDED"; + TransactionStatus[TransactionStatus["PROCESSED"] = 1] = "PROCESSED"; + TransactionStatus[TransactionStatus["TIMED_OUT"] = 2] = "TIMED_OUT"; + TransactionStatus[TransactionStatus["NONCE_INVALID"] = 3] = "NONCE_INVALID"; + })(TransactionStatus || (TransactionStatus = {})); - /** @internal */ + var DEFAULT_SIGNATURE = Buffer$1.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0); + /** + * Account metadata used to define instructions + */ + + /** + * Transaction Instruction class + */ + var TransactionInstruction = /*#__PURE__*/function () { /** - * Create a new Account object - * - * If the secretKey parameter is not provided a new key pair is randomly - * created for the account - * - * @param secretKey Secret key for the account + * Public keys to include in this transaction + * Boolean represents whether this pubkey needs to sign the transaction */ - function Account(secretKey) { - _classCallCheck(this, Account); - this._publicKey = void 0; - this._secretKey = void 0; + /** + * Program Id to execute + */ - if (secretKey) { - var secretKeyBuffer = toBuffer(secretKey); + /** + * Program input + */ + function TransactionInstruction(opts) { + _classCallCheck(this, TransactionInstruction); - if (secretKey.length !== 64) { - throw new Error('bad secret key size'); - } + this.keys = void 0; + this.programId = void 0; + this.data = Buffer$1.alloc(0); + this.programId = opts.programId; + this.keys = opts.keys; - this._publicKey = secretKeyBuffer.slice(32, 64); - this._secretKey = secretKeyBuffer.slice(0, 32); - } else { - this._secretKey = toBuffer(generatePrivateKey()); - this._publicKey = toBuffer(getPublicKey(this._secretKey)); + if (opts.data) { + this.data = opts.data; } } /** - * The public key for this account + * @internal */ - _createClass(Account, [{ - key: "publicKey", - get: function get() { - return new PublicKey(this._publicKey); - } - /** - * The **unencrypted** secret key for this account. The first 32 bytes - * is the private scalar and the last 32 bytes is the public key. - * Read more: https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ - */ - - }, { - key: "secretKey", - get: function get() { - return Buffer$1.concat([this._secretKey, this._publicKey], 64); + _createClass(TransactionInstruction, [{ + key: "toJSON", + value: function toJSON() { + return { + keys: this.keys.map(function (_ref17) { + var pubkey = _ref17.pubkey, + isSigner = _ref17.isSigner, + isWritable = _ref17.isWritable; + return { + pubkey: pubkey.toJSON(), + isSigner: isSigner, + isWritable: isWritable + }; + }), + programId: this.programId.toJSON(), + data: _toConsumableArray(this.data) + }; } }]); - return Account; + return TransactionInstruction; }(); - - var BPF_LOADER_DEPRECATED_PROGRAM_ID = new PublicKey('BPFLoader1111111111111111111111111111111111'); /** - * Maximum over-the-wire size of a Transaction - * - * 1280 is IPv6 minimum MTU - * 40 bytes is the size of the IPv6 header - * 8 bytes is the size of the fragment header + * Pair of signature and corresponding public key */ - var PACKET_DATA_SIZE = 1280 - 40 - 8; - var VERSION_PREFIX_MASK = 0x7f; - var SIGNATURE_LENGTH_IN_BYTES = 64; - - var TransactionExpiredBlockheightExceededError = /*#__PURE__*/function (_Error) { - _inherits(TransactionExpiredBlockheightExceededError, _Error); - - var _super3 = _createSuper(TransactionExpiredBlockheightExceededError); - - function TransactionExpiredBlockheightExceededError(signature) { - var _this3; - - _classCallCheck(this, TransactionExpiredBlockheightExceededError); - - _this3 = _super3.call(this, "Signature ".concat(signature, " has expired: block height exceeded.")); - _this3.signature = void 0; - _this3.signature = signature; - return _this3; - } - - return _createClass(TransactionExpiredBlockheightExceededError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); - - Object.defineProperty(TransactionExpiredBlockheightExceededError.prototype, 'name', { - value: 'TransactionExpiredBlockheightExceededError' - }); - - var TransactionExpiredTimeoutError = /*#__PURE__*/function (_Error2) { - _inherits(TransactionExpiredTimeoutError, _Error2); - - var _super4 = _createSuper(TransactionExpiredTimeoutError); + /** + * Transaction class + */ - function TransactionExpiredTimeoutError(signature, timeoutSeconds) { - var _this4; - _classCallCheck(this, TransactionExpiredTimeoutError); + var Transaction = /*#__PURE__*/function () { + /** + * The transaction fee payer + */ - _this4 = _super4.call(this, "Transaction was not confirmed in ".concat(timeoutSeconds.toFixed(2), " seconds. It is ") + 'unknown if it succeeded or failed. Check signature ' + "".concat(signature, " using the Solana Explorer or CLI tools.")); - _this4.signature = void 0; - _this4.signature = signature; - return _this4; - } + /** + * Construct an empty Transaction + */ + function Transaction(opts) { + _classCallCheck(this, Transaction); - return _createClass(TransactionExpiredTimeoutError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); + this.signatures = []; + this.feePayer = void 0; + this.instructions = []; + this.recentBlockhash = void 0; + this.lastValidBlockHeight = void 0; + this.nonceInfo = void 0; + this.minNonceContextSlot = void 0; + this._message = void 0; + this._json = void 0; - Object.defineProperty(TransactionExpiredTimeoutError.prototype, 'name', { - value: 'TransactionExpiredTimeoutError' - }); + if (!opts) { + return; + } - var TransactionExpiredNonceInvalidError = /*#__PURE__*/function (_Error3) { - _inherits(TransactionExpiredNonceInvalidError, _Error3); + if (opts.feePayer) { + this.feePayer = opts.feePayer; + } - var _super5 = _createSuper(TransactionExpiredNonceInvalidError); + if (opts.signatures) { + this.signatures = opts.signatures; + } - function TransactionExpiredNonceInvalidError(signature) { - var _this5; + if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) { + var minContextSlot = opts.minContextSlot, + nonceInfo = opts.nonceInfo; + this.minNonceContextSlot = minContextSlot; + this.nonceInfo = nonceInfo; + } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) { + var blockhash = opts.blockhash, + lastValidBlockHeight = opts.lastValidBlockHeight; + this.recentBlockhash = blockhash; + this.lastValidBlockHeight = lastValidBlockHeight; + } else { + var recentBlockhash = opts.recentBlockhash, + _nonceInfo = opts.nonceInfo; - _classCallCheck(this, TransactionExpiredNonceInvalidError); + if (_nonceInfo) { + this.nonceInfo = _nonceInfo; + } - _this5 = _super5.call(this, "Signature ".concat(signature, " has expired: the nonce is no longer valid.")); - _this5.signature = void 0; - _this5.signature = signature; - return _this5; + this.recentBlockhash = recentBlockhash; + } } + /** + * @internal + */ - return _createClass(TransactionExpiredNonceInvalidError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); - - Object.defineProperty(TransactionExpiredNonceInvalidError.prototype, 'name', { - value: 'TransactionExpiredNonceInvalidError' - }); - - var MessageAccountKeys = /*#__PURE__*/function () { - function MessageAccountKeys(staticAccountKeys, accountKeysFromLookups) { - _classCallCheck(this, MessageAccountKeys); - - this.staticAccountKeys = void 0; - this.accountKeysFromLookups = void 0; - this.staticAccountKeys = staticAccountKeys; - this.accountKeysFromLookups = accountKeysFromLookups; - } - _createClass(MessageAccountKeys, [{ - key: "keySegments", - value: function keySegments() { - var keySegments = [this.staticAccountKeys]; + _createClass(Transaction, [{ + key: "signature", + get: + /** + * Signatures for the transaction. Typically created by invoking the + * `sign()` method + */ - if (this.accountKeysFromLookups) { - keySegments.push(this.accountKeysFromLookups.writable); - keySegments.push(this.accountKeysFromLookups.readonly); + /** + * The first (payer) Transaction signature + */ + function get() { + if (this.signatures.length > 0) { + return this.signatures[0].signature; } - return keySegments; + return null; } }, { - key: "get", - value: function get(index) { - var _iterator = _createForOfIteratorHelper(this.keySegments()), - _step; + key: "toJSON", + value: function toJSON() { + return { + recentBlockhash: this.recentBlockhash || null, + feePayer: this.feePayer ? this.feePayer.toJSON() : null, + nonceInfo: this.nonceInfo ? { + nonce: this.nonceInfo.nonce, + nonceInstruction: this.nonceInfo.nonceInstruction.toJSON() + } : null, + instructions: this.instructions.map(function (instruction) { + return instruction.toJSON(); + }), + signers: this.signatures.map(function (_ref18) { + var publicKey = _ref18.publicKey; + return publicKey.toJSON(); + }) + }; + } + /** + * Add one or more instructions to this Transaction + */ - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var keySegment = _step.value; + }, { + key: "add", + value: function add() { + var _this9 = this; - if (index < keySegment.length) { - return keySegment[index]; - } else { - index -= keySegment.length; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) { + items[_key] = arguments[_key]; } - return; - } - }, { - key: "length", - get: function get() { - return this.keySegments().flat().length; - } - }, { - key: "compileInstructions", - value: function compileInstructions(instructions) { - // Bail early if any account indexes would overflow a u8 - var U8_MAX = 255; - - if (this.length > U8_MAX + 1) { - throw new Error('Account index overflow encountered during compilation'); + if (items.length === 0) { + throw new Error('No instructions'); } - var keyIndexMap = new Map(); - this.keySegments().flat().forEach(function (key, index) { - keyIndexMap.set(key.toBase58(), index); + items.forEach(function (item) { + if ('instructions' in item) { + _this9.instructions = _this9.instructions.concat(item.instructions); + } else if ('data' in item && 'programId' in item && 'keys' in item) { + _this9.instructions.push(item); + } else { + _this9.instructions.push(new TransactionInstruction(item)); + } }); + return this; + } + /** + * Compile transaction data + */ - var findKeyIndex = function findKeyIndex(key) { - var keyIndex = keyIndexMap.get(key.toBase58()); - if (keyIndex === undefined) throw new Error('Encountered an unknown instruction account key during compilation'); - return keyIndex; - }; + }, { + key: "compileMessage", + value: function compileMessage() { + if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) { + return this._message; + } - return instructions.map(function (instruction) { - return { - programIdIndex: findKeyIndex(instruction.programId), - accountKeyIndexes: instruction.keys.map(function (meta) { - return findKeyIndex(meta.pubkey); - }), - data: instruction.data - }; - }); - } - }]); + var recentBlockhash; + var instructions; - return MessageAccountKeys; - }(); - /** - * Layout for a public key - */ + if (this.nonceInfo) { + recentBlockhash = this.nonceInfo.nonce; + if (this.instructions[0] != this.nonceInfo.nonceInstruction) { + instructions = [this.nonceInfo.nonceInstruction].concat(_toConsumableArray(this.instructions)); + } else { + instructions = this.instructions; + } + } else { + recentBlockhash = this.recentBlockhash; + instructions = this.instructions; + } - var publicKey = function publicKey() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'publicKey'; - return blob$1(32, property); - }; - /** - * Layout for a signature - */ + if (!recentBlockhash) { + throw new Error('Transaction recentBlockhash required'); + } + if (instructions.length < 1) { + console.warn('No instructions provided'); + } - var signature = function signature() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'signature'; - return blob$1(64, property); - }; - /** - * Layout for a Rust String type - */ + var feePayer; + + if (this.feePayer) { + feePayer = this.feePayer; + } else if (this.signatures.length > 0 && this.signatures[0].publicKey) { + // Use implicit fee payer + feePayer = this.signatures[0].publicKey; + } else { + throw new Error('Transaction fee payer required'); + } + for (var i = 0; i < instructions.length; i++) { + if (instructions[i].programId === undefined) { + throw new Error("Transaction instruction index ".concat(i, " has undefined program id")); + } + } - var rustString = function rustString() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'string'; - var rsl = struct([u32('length'), u32('lengthPadding'), blob$1(offset$1(u32(), -8), 'chars')], property); + var programIds = []; + var accountMetas = []; + instructions.forEach(function (instruction) { + instruction.keys.forEach(function (accountMeta) { + accountMetas.push(_objectSpread2({}, accountMeta)); + }); + var programId = instruction.programId.toString(); - var _decode = rsl.decode.bind(rsl); + if (!programIds.includes(programId)) { + programIds.push(programId); + } + }); // Append programID account metas - var _encode = rsl.encode.bind(rsl); + programIds.forEach(function (programId) { + accountMetas.push({ + pubkey: new PublicKey(programId), + isSigner: false, + isWritable: false + }); + }); // Cull duplicate account metas - var rslShim = rsl; + var uniqueMetas = []; + accountMetas.forEach(function (accountMeta) { + var pubkeyString = accountMeta.pubkey.toString(); + var uniqueIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.toString() === pubkeyString; + }); - rslShim.decode = function (b, offset) { - var data = _decode(b, offset); + if (uniqueIndex > -1) { + uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable; + uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner; + } else { + uniqueMetas.push(accountMeta); + } + }); // Sort. Prioritizing first by signer, then by writable - return data['chars'].toString(); - }; + uniqueMetas.sort(function (x, y) { + if (x.isSigner !== y.isSigner) { + // Signers always come before non-signers + return x.isSigner ? -1 : 1; + } - rslShim.encode = function (str, b, offset) { - var data = { - chars: Buffer$1.from(str, 'utf8') - }; - return _encode(data, b, offset); - }; + if (x.isWritable !== y.isWritable) { + // Writable accounts always come before read-only accounts + return x.isWritable ? -1 : 1; + } // Otherwise, sort by pubkey, stringwise. - rslShim.alloc = function (str) { - return u32().span + u32().span + Buffer$1.from(str, 'utf8').length; - }; - return rslShim; - }; - /** - * Layout for an Authorized object - */ + return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58()); + }); // Move fee payer to the front + var feePayerIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.equals(feePayer); + }); - var authorized = function authorized() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'authorized'; - return struct([publicKey('staker'), publicKey('withdrawer')], property); - }; - /** - * Layout for a Lockup object - */ + if (feePayerIndex > -1) { + var _uniqueMetas$splice3 = uniqueMetas.splice(feePayerIndex, 1), + _uniqueMetas$splice4 = _slicedToArray(_uniqueMetas$splice3, 1), + payerMeta = _uniqueMetas$splice4[0]; + payerMeta.isSigner = true; + payerMeta.isWritable = true; + uniqueMetas.unshift(payerMeta); + } else { + uniqueMetas.unshift({ + pubkey: feePayer, + isSigner: true, + isWritable: true + }); + } // Disallow unknown signers - var lockup = function lockup() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'lockup'; - return struct([ns64('unixTimestamp'), ns64('epoch'), publicKey('custodian')], property); - }; - /** - * Layout for a VoteInit object - */ + var _iterator12 = _createForOfIteratorHelper(this.signatures), + _step12; - var voteInit = function voteInit() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteInit'; - return struct([publicKey('nodePubkey'), publicKey('authorizedVoter'), publicKey('authorizedWithdrawer'), u8('commission')], property); - }; - /** - * Layout for a VoteAuthorizeWithSeedArgs object - */ + try { + var _loop3 = function _loop3() { + var signature = _step12.value; + var uniqueIndex = uniqueMetas.findIndex(function (x) { + return x.pubkey.equals(signature.publicKey); + }); + if (uniqueIndex > -1) { + if (!uniqueMetas[uniqueIndex].isSigner) { + uniqueMetas[uniqueIndex].isSigner = true; + console.warn('Transaction references a signature that is unnecessary, ' + 'only the fee payer and instruction signer accounts should sign a transaction. ' + 'This behavior is deprecated and will throw an error in the next major version release.'); + } + } else { + throw new Error("unknown signer: ".concat(signature.publicKey.toString())); + } + }; - var voteAuthorizeWithSeedArgs = function voteAuthorizeWithSeedArgs() { - var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'voteAuthorizeWithSeedArgs'; - return struct([u32('voteAuthorizationType'), publicKey('currentAuthorityDerivedKeyOwnerPubkey'), rustString('currentAuthorityDerivedKeySeed'), publicKey('newAuthorized')], property); - }; + for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { + _loop3(); + } + } catch (err) { + _iterator12.e(err); + } finally { + _iterator12.f(); + } - function getAlloc(type, fields) { - var getItemAlloc = function getItemAlloc(item) { - if (item.span >= 0) { - return item.span; - } else if (typeof item.alloc === 'function') { - return item.alloc(fields[item.property]); - } else if ('count' in item && 'elementLayout' in item) { - var field = fields[item.property]; + var numRequiredSignatures = 0; + var numReadonlySignedAccounts = 0; + var numReadonlyUnsignedAccounts = 0; // Split out signing from non-signing keys and count header values - if (Array.isArray(field)) { - return field.length * getItemAlloc(item.elementLayout); - } - } else if ('fields' in item) { - // This is a `Structure` whose size needs to be recursively measured. - return getAlloc({ - layout: item - }, fields[item.property]); - } // Couldn't determine allocated size of layout + var signedKeys = []; + var unsignedKeys = []; + uniqueMetas.forEach(function (_ref19) { + var pubkey = _ref19.pubkey, + isSigner = _ref19.isSigner, + isWritable = _ref19.isWritable; + if (isSigner) { + signedKeys.push(pubkey.toString()); + numRequiredSignatures += 1; - return 0; - }; + if (!isWritable) { + numReadonlySignedAccounts += 1; + } + } else { + unsignedKeys.push(pubkey.toString()); - var alloc = 0; - type.layout.fields.forEach(function (item) { - alloc += getItemAlloc(item); - }); - return alloc; - } + if (!isWritable) { + numReadonlyUnsignedAccounts += 1; + } + } + }); + var accountKeys = signedKeys.concat(unsignedKeys); + var compiledInstructions = instructions.map(function (instruction) { + var data = instruction.data, + programId = instruction.programId; + return { + programIdIndex: accountKeys.indexOf(programId.toString()), + accounts: instruction.keys.map(function (meta) { + return accountKeys.indexOf(meta.pubkey.toString()); + }), + data: bs58$3.encode(data) + }; + }); + compiledInstructions.forEach(function (instruction) { + assert(instruction.programIdIndex >= 0); + instruction.accounts.forEach(function (keyIndex) { + return assert(keyIndex >= 0); + }); + }); + return new Message({ + header: { + numRequiredSignatures: numRequiredSignatures, + numReadonlySignedAccounts: numReadonlySignedAccounts, + numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts + }, + accountKeys: accountKeys, + recentBlockhash: recentBlockhash, + instructions: compiledInstructions + }); + } + /** + * @internal + */ - function decodeLength(bytes) { - var len = 0; - var size = 0; + }, { + key: "_compile", + value: function _compile() { + var message = this.compileMessage(); + var signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures); - for (;;) { - var elem = bytes.shift(); - len |= (elem & 0x7f) << size * 7; - size += 1; + if (this.signatures.length === signedKeys.length) { + var valid = this.signatures.every(function (pair, index) { + return signedKeys[index].equals(pair.publicKey); + }); + if (valid) return message; + } - if ((elem & 0x80) === 0) { - break; + this.signatures = signedKeys.map(function (publicKey) { + return { + signature: null, + publicKey: publicKey + }; + }); + return message; } - } + /** + * Get a buffer of the Transaction data that need to be covered by signatures + */ - return len; - } + }, { + key: "serializeMessage", + value: function serializeMessage() { + return this._compile().serialize(); + } + /** + * Get the estimated fee associated with a transaction + */ - function encodeLength(bytes, len) { - var rem_len = len; + }, { + key: "getEstimatedFee", + value: function () { + var _getEstimatedFee = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(connection) { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return connection.getFeeForMessage(this.compileMessage()); - for (;;) { - var elem = rem_len & 0x7f; - rem_len >>= 7; + case 2: + return _context4.abrupt("return", _context4.sent.value); - if (rem_len == 0) { - bytes.push(elem); - break; - } else { - elem |= 0x80; - bytes.push(elem); - } - } - } + case 3: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); - function assert(condition, message) { - if (!condition) { - throw new Error(message || 'Assertion failed'); - } - } + function getEstimatedFee(_x8) { + return _getEstimatedFee.apply(this, arguments); + } - var CompiledKeys = /*#__PURE__*/function () { - function CompiledKeys(payer, keyMetaMap) { - _classCallCheck(this, CompiledKeys); + return getEstimatedFee; + }() + /** + * Specify the public keys which will be used to sign the Transaction. + * The first signer will be used as the transaction fee payer account. + * + * Signatures can be added with either `partialSign` or `addSignature` + * + * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be + * specified and it can be set in the Transaction constructor or with the + * `feePayer` property. + */ - this.payer = void 0; - this.keyMetaMap = void 0; - this.payer = payer; - this.keyMetaMap = keyMetaMap; - } + }, { + key: "setSigners", + value: function setSigners() { + for (var _len2 = arguments.length, signers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + signers[_key2] = arguments[_key2]; + } - _createClass(CompiledKeys, [{ - key: "getMessageComponents", - value: function getMessageComponents() { - var mapEntries = _toConsumableArray(this.keyMetaMap.entries()); + if (signers.length === 0) { + throw new Error('No signers'); + } - assert(mapEntries.length <= 256, 'Max static account keys length exceeded'); - var writableSigners = mapEntries.filter(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - meta = _ref2[1]; + var seen = new Set(); + this.signatures = signers.filter(function (publicKey) { + var key = publicKey.toString(); - return meta.isSigner && meta.isWritable; + if (seen.has(key)) { + return false; + } else { + seen.add(key); + return true; + } + }).map(function (publicKey) { + return { + signature: null, + publicKey: publicKey + }; }); - var readonlySigners = mapEntries.filter(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - meta = _ref4[1]; + } + /** + * Sign the Transaction with the specified signers. Multiple signatures may + * be applied to a Transaction. The first signature is considered "primary" + * and is used identify and confirm transactions. + * + * If the Transaction `feePayer` is not set, the first signer will be used + * as the transaction fee payer account. + * + * Transaction fields should not be modified after the first call to `sign`, + * as doing so may invalidate the signature and cause the Transaction to be + * rejected. + * + * The Transaction must be assigned a valid `recentBlockhash` before invoking this method + */ - return meta.isSigner && !meta.isWritable; - }); - var writableNonSigners = mapEntries.filter(function (_ref5) { - var _ref6 = _slicedToArray(_ref5, 2), - meta = _ref6[1]; + }, { + key: "sign", + value: function sign() { + for (var _len3 = arguments.length, signers = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + signers[_key3] = arguments[_key3]; + } - return !meta.isSigner && meta.isWritable; - }); - var readonlyNonSigners = mapEntries.filter(function (_ref7) { - var _ref8 = _slicedToArray(_ref7, 2), - meta = _ref8[1]; + if (signers.length === 0) { + throw new Error('No signers'); + } // Dedupe signers - return !meta.isSigner && !meta.isWritable; - }); - var header = { - numRequiredSignatures: writableSigners.length + readonlySigners.length, - numReadonlySignedAccounts: readonlySigners.length, - numReadonlyUnsignedAccounts: readonlyNonSigners.length - }; // sanity checks - { - assert(writableSigners.length > 0, 'Expected at least one writable signer key'); + var seen = new Set(); + var uniqueSigners = []; - var _writableSigners$2 = _slicedToArray(writableSigners[0], 1), - payerAddress = _writableSigners$2[0]; + for (var _i7 = 0, _signers = signers; _i7 < _signers.length; _i7++) { + var signer = _signers[_i7]; + var key = signer.publicKey.toString(); - assert(payerAddress === this.payer.toBase58(), 'Expected first writable signer key to be the fee payer'); + if (seen.has(key)) { + continue; + } else { + seen.add(key); + uniqueSigners.push(signer); + } } - var staticAccountKeys = [].concat(_toConsumableArray(writableSigners.map(function (_ref9) { - var _ref10 = _slicedToArray(_ref9, 1), - address = _ref10[0]; - - return new PublicKey(address); - })), _toConsumableArray(readonlySigners.map(function (_ref11) { - var _ref12 = _slicedToArray(_ref11, 1), - address = _ref12[0]; - return new PublicKey(address); - })), _toConsumableArray(writableNonSigners.map(function (_ref13) { - var _ref14 = _slicedToArray(_ref13, 1), - address = _ref14[0]; + this.signatures = uniqueSigners.map(function (signer) { + return { + signature: null, + publicKey: signer.publicKey + }; + }); - return new PublicKey(address); - })), _toConsumableArray(readonlyNonSigners.map(function (_ref15) { - var _ref16 = _slicedToArray(_ref15, 1), - address = _ref16[0]; + var message = this._compile(); - return new PublicKey(address); - }))); - return [header, staticAccountKeys]; + this._partialSign.apply(this, [message].concat(uniqueSigners)); } + /** + * Partially sign a transaction with the specified accounts. All accounts must + * correspond to either the fee payer or a signer account in the transaction + * instructions. + * + * All the caveats from the `sign` method apply to `partialSign` + */ + }, { - key: "extractTableLookup", - value: function extractTableLookup(lookupTable) { - var _this$drainKeysFoundI = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { - return !keyMeta.isSigner && !keyMeta.isInvoked && keyMeta.isWritable; - }), - _this$drainKeysFoundI2 = _slicedToArray(_this$drainKeysFoundI, 2), - writableIndexes = _this$drainKeysFoundI2[0], - drainedWritableKeys = _this$drainKeysFoundI2[1]; + key: "partialSign", + value: function partialSign() { + for (var _len4 = arguments.length, signers = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + signers[_key4] = arguments[_key4]; + } - var _this$drainKeysFoundI3 = this.drainKeysFoundInLookupTable(lookupTable.state.addresses, function (keyMeta) { - return !keyMeta.isSigner && !keyMeta.isInvoked && !keyMeta.isWritable; - }), - _this$drainKeysFoundI4 = _slicedToArray(_this$drainKeysFoundI3, 2), - readonlyIndexes = _this$drainKeysFoundI4[0], - drainedReadonlyKeys = _this$drainKeysFoundI4[1]; // Don't extract lookup if no keys were found + if (signers.length === 0) { + throw new Error('No signers'); + } // Dedupe signers - if (writableIndexes.length === 0 && readonlyIndexes.length === 0) { - return; + var seen = new Set(); + var uniqueSigners = []; + + for (var _i8 = 0, _signers2 = signers; _i8 < _signers2.length; _i8++) { + var signer = _signers2[_i8]; + var key = signer.publicKey.toString(); + + if (seen.has(key)) { + continue; + } else { + seen.add(key); + uniqueSigners.push(signer); + } } - return [{ - accountKey: lookupTable.key, - writableIndexes: writableIndexes, - readonlyIndexes: readonlyIndexes - }, { - writable: drainedWritableKeys, - readonly: drainedReadonlyKeys - }]; + var message = this._compile(); + + this._partialSign.apply(this, [message].concat(uniqueSigners)); } - /** @internal */ + /** + * @internal + */ }, { - key: "drainKeysFoundInLookupTable", - value: function drainKeysFoundInLookupTable(lookupTableEntries, keyMetaFilter) { - var _this6 = this; - - var lookupTableIndexes = new Array(); - var drainedKeys = new Array(); - - var _iterator2 = _createForOfIteratorHelper(this.keyMetaMap.entries()), - _step2; + key: "_partialSign", + value: function _partialSign(message) { + var _this10 = this; - try { - var _loop = function _loop() { - var _step2$value = _slicedToArray(_step2.value, 2), - address = _step2$value[0], - keyMeta = _step2$value[1]; + var signData = message.serialize(); - if (keyMetaFilter(keyMeta)) { - var key = new PublicKey(address); - var lookupTableIndex = lookupTableEntries.findIndex(function (entry) { - return entry.equals(key); - }); + for (var _len5 = arguments.length, signers = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + signers[_key5 - 1] = arguments[_key5]; + } - if (lookupTableIndex >= 0) { - assert(lookupTableIndex < 256, 'Max lookup table index exceeded'); - lookupTableIndexes.push(lookupTableIndex); - drainedKeys.push(key); + signers.forEach(function (signer) { + var signature = _sign(signData, signer.secretKey); - _this6.keyMetaMap["delete"](address); - } - } - }; + _this10._addSignature(signer.publicKey, toBuffer(signature)); + }); + } + /** + * Add an externally created signature to a transaction. The public key + * must correspond to either the fee payer or a signer account in the transaction + * instructions. + */ - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - _loop(); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } + }, { + key: "addSignature", + value: function addSignature(pubkey, signature) { + this._compile(); // Ensure signatures array is populated - return [lookupTableIndexes, drainedKeys]; + + this._addSignature(pubkey, signature); } - }], [{ - key: "compile", - value: function compile(instructions, payer) { - var keyMetaMap = new Map(); + /** + * @internal + */ - var getOrInsertDefault = function getOrInsertDefault(pubkey) { - var address = pubkey.toBase58(); - var keyMeta = keyMetaMap.get(address); + }, { + key: "_addSignature", + value: function _addSignature(pubkey, signature) { + assert(signature.length === 64); + var index = this.signatures.findIndex(function (sigpair) { + return pubkey.equals(sigpair.publicKey); + }); - if (keyMeta === undefined) { - keyMeta = { - isSigner: false, - isWritable: false, - isInvoked: false - }; - keyMetaMap.set(address, keyMeta); - } + if (index < 0) { + throw new Error("unknown signer: ".concat(pubkey.toString())); + } - return keyMeta; - }; + this.signatures[index].signature = Buffer$1.from(signature); + } + /** + * Verify signatures of a Transaction + * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one. + * If no boolean is provided, we expect a fully signed Transaction by default. + */ - var payerKeyMeta = getOrInsertDefault(payer); - payerKeyMeta.isSigner = true; - payerKeyMeta.isWritable = true; + }, { + key: "verifySignatures", + value: function verifySignatures(requireAllSignatures) { + return this._verifySignatures(this.serializeMessage(), requireAllSignatures === undefined ? true : requireAllSignatures); + } + /** + * @internal + */ - var _iterator3 = _createForOfIteratorHelper(instructions), - _step3; + }, { + key: "_verifySignatures", + value: function _verifySignatures(signData, requireAllSignatures) { + var _iterator13 = _createForOfIteratorHelper(this.signatures), + _step13; try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var ix = _step3.value; - getOrInsertDefault(ix.programId).isInvoked = true; - - var _iterator4 = _createForOfIteratorHelper(ix.keys), - _step4; + for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { + var _step13$value2 = _step13.value, + _signature = _step13$value2.signature, + _publicKey = _step13$value2.publicKey; - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var accountMeta = _step4.value; - var keyMeta = getOrInsertDefault(accountMeta.pubkey); - keyMeta.isSigner || (keyMeta.isSigner = accountMeta.isSigner); - keyMeta.isWritable || (keyMeta.isWritable = accountMeta.isWritable); + if (_signature === null) { + if (requireAllSignatures) { + return false; + } + } else { + if (!verify(_signature, signData, _publicKey.toBytes())) { + return false; } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); } } } catch (err) { - _iterator3.e(err); + _iterator13.e(err); } finally { - _iterator3.f(); + _iterator13.f(); } - return new CompiledKeys(payer, keyMetaMap); + return true; } - }]); - - return CompiledKeys; - }(); - /** - * An instruction to execute by a program - * - * @property {number} programIdIndex - * @property {number[]} accounts - * @property {string} data - */ - - /** - * List of instructions to be processed atomically - */ - + /** + * Serialize the Transaction in the wire format. + */ - var Message = /*#__PURE__*/function () { - function Message(args) { - var _this7 = this; + }, { + key: "serialize", + value: function serialize(config) { + var _Object$assign = Object.assign({ + requireAllSignatures: true, + verifySignatures: true + }, config), + requireAllSignatures = _Object$assign.requireAllSignatures, + verifySignatures = _Object$assign.verifySignatures; - _classCallCheck(this, Message); + var signData = this.serializeMessage(); - this.header = void 0; - this.accountKeys = void 0; - this.recentBlockhash = void 0; - this.instructions = void 0; - this.indexToProgramIds = new Map(); - this.header = args.header; - this.accountKeys = args.accountKeys.map(function (account) { - return new PublicKey(account); - }); - this.recentBlockhash = args.recentBlockhash; - this.instructions = args.instructions; - this.instructions.forEach(function (ix) { - return _this7.indexToProgramIds.set(ix.programIdIndex, _this7.accountKeys[ix.programIdIndex]); - }); - } + if (verifySignatures && !this._verifySignatures(signData, requireAllSignatures)) { + throw new Error('Signature verification failed'); + } - _createClass(Message, [{ - key: "version", - get: function get() { - return 'legacy'; + return this._serialize(signData); } + /** + * @internal + */ + }, { - key: "staticAccountKeys", - get: function get() { - return this.accountKeys; + key: "_serialize", + value: function _serialize(signData) { + var signatures = this.signatures; + var signatureCount = []; + encodeLength(signatureCount, signatures.length); + var transactionLength = signatureCount.length + signatures.length * 64 + signData.length; + var wireTransaction = Buffer$1.alloc(transactionLength); + assert(signatures.length < 256); + Buffer$1.from(signatureCount).copy(wireTransaction, 0); + signatures.forEach(function (_ref20, index) { + var signature = _ref20.signature; + + if (signature !== null) { + assert(signature.length === 64, "signature has invalid length"); + Buffer$1.from(signature).copy(wireTransaction, signatureCount.length + index * 64); + } + }); + signData.copy(wireTransaction, signatureCount.length + signatures.length * 64); + assert(wireTransaction.length <= PACKET_DATA_SIZE, "Transaction too large: ".concat(wireTransaction.length, " > ").concat(PACKET_DATA_SIZE)); + return wireTransaction; } + /** + * Deprecated method + * @internal + */ + }, { - key: "compiledInstructions", + key: "keys", get: function get() { - return this.instructions.map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accountKeyIndexes: ix.accounts, - data: bs58$1.decode(ix.data) - }; + assert(this.instructions.length === 1); + return this.instructions[0].keys.map(function (keyObj) { + return keyObj.pubkey; }); } + /** + * Deprecated method + * @internal + */ + }, { - key: "addressTableLookups", + key: "programId", get: function get() { - return []; - } - }, { - key: "getAccountKeys", - value: function getAccountKeys() { - return new MessageAccountKeys(this.staticAccountKeys); + assert(this.instructions.length === 1); + return this.instructions[0].programId; } + /** + * Deprecated method + * @internal + */ + }, { - key: "isAccountSigner", - value: function isAccountSigner(index) { - return index < this.header.numRequiredSignatures; + key: "data", + get: function get() { + assert(this.instructions.length === 1); + return this.instructions[0].data; } - }, { - key: "isAccountWritable", - value: function isAccountWritable(index) { - var numSignedAccounts = this.header.numRequiredSignatures; + /** + * Parse a wire transaction into a Transaction object. + */ - if (index >= this.header.numRequiredSignatures) { - var unsignedAccountIndex = index - numSignedAccounts; - var numUnsignedAccounts = this.accountKeys.length - numSignedAccounts; - var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; - return unsignedAccountIndex < numWritableUnsignedAccounts; - } else { - var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; - return index < numWritableSignedAccounts; + }], [{ + key: "from", + value: function from(buffer) { + // Slice up wire data + var byteArray = _toConsumableArray(buffer); + + var signatureCount = decodeLength(byteArray); + var signatures = []; + + for (var i = 0; i < signatureCount; i++) { + var _signature2 = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES); + + byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES); + signatures.push(bs58$3.encode(Buffer$1.from(_signature2))); } - } - }, { - key: "isProgramId", - value: function isProgramId(index) { - return this.indexToProgramIds.has(index); - } - }, { - key: "programIds", - value: function programIds() { - return _toConsumableArray(this.indexToProgramIds.values()); - } - }, { - key: "nonProgramIds", - value: function nonProgramIds() { - var _this8 = this; - return this.accountKeys.filter(function (_, index) { - return !_this8.isProgramId(index); - }); - } - }, { - key: "serialize", - value: function serialize() { - var numKeys = this.accountKeys.length; - var keyCount = []; - encodeLength(keyCount, numKeys); - var instructions = this.instructions.map(function (instruction) { - var accounts = instruction.accounts, - programIdIndex = instruction.programIdIndex; - var data = Array.from(bs58$1.decode(instruction.data)); - var keyIndicesCount = []; - encodeLength(keyIndicesCount, accounts.length); - var dataCount = []; - encodeLength(dataCount, data.length); - return { - programIdIndex: programIdIndex, - keyIndicesCount: Buffer$1.from(keyIndicesCount), - keyIndices: accounts, - dataLength: Buffer$1.from(dataCount), - data: data - }; - }); - var instructionCount = []; - encodeLength(instructionCount, instructions.length); - var instructionBuffer = Buffer$1.alloc(PACKET_DATA_SIZE); - Buffer$1.from(instructionCount).copy(instructionBuffer); - var instructionBufferLength = instructionCount.length; - instructions.forEach(function (instruction) { - var instructionLayout = struct([u8('programIdIndex'), blob$1(instruction.keyIndicesCount.length, 'keyIndicesCount'), seq$1(u8('keyIndex'), instruction.keyIndices.length, 'keyIndices'), blob$1(instruction.dataLength.length, 'dataLength'), seq$1(u8('userdatum'), instruction.data.length, 'data')]); - var length = instructionLayout.encode(instruction, instructionBuffer, instructionBufferLength); - instructionBufferLength += length; - }); - instructionBuffer = instructionBuffer.slice(0, instructionBufferLength); - var signDataLayout = struct([blob$1(1, 'numRequiredSignatures'), blob$1(1, 'numReadonlySignedAccounts'), blob$1(1, 'numReadonlyUnsignedAccounts'), blob$1(keyCount.length, 'keyCount'), seq$1(publicKey('key'), numKeys, 'keys'), publicKey('recentBlockhash')]); - var transaction = { - numRequiredSignatures: Buffer$1.from([this.header.numRequiredSignatures]), - numReadonlySignedAccounts: Buffer$1.from([this.header.numReadonlySignedAccounts]), - numReadonlyUnsignedAccounts: Buffer$1.from([this.header.numReadonlyUnsignedAccounts]), - keyCount: Buffer$1.from(keyCount), - keys: this.accountKeys.map(function (key) { - return toBuffer(key.toBytes()); - }), - recentBlockhash: bs58$1.decode(this.recentBlockhash) - }; - var signData = Buffer$1.alloc(2048); - var length = signDataLayout.encode(transaction, signData); - instructionBuffer.copy(signData, length); - return signData.slice(0, length + instructionBuffer.length); + return Transaction.populate(Message.from(byteArray), signatures); } /** - * Decode a compiled message into a Message object. + * Populate Transaction object from message and signatures */ - }], [{ - key: "compile", - value: function compile(args) { - var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); + }, { + key: "populate", + value: function populate(message) { + var signatures = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var transaction = new Transaction(); + transaction.recentBlockhash = message.recentBlockhash; - var _compiledKeys$getMess = compiledKeys.getMessageComponents(), - _compiledKeys$getMess2 = _slicedToArray(_compiledKeys$getMess, 2), - header = _compiledKeys$getMess2[0], - staticAccountKeys = _compiledKeys$getMess2[1]; + if (message.header.numRequiredSignatures > 0) { + transaction.feePayer = message.accountKeys[0]; + } - var accountKeys = new MessageAccountKeys(staticAccountKeys); - var instructions = accountKeys.compileInstructions(args.instructions).map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accounts: ix.accountKeyIndexes, - data: bs58$1.encode(ix.data) + signatures.forEach(function (signature, index) { + var sigPubkeyPair = { + signature: signature == bs58$3.encode(DEFAULT_SIGNATURE) ? null : bs58$3.decode(signature), + publicKey: message.accountKeys[index] }; + transaction.signatures.push(sigPubkeyPair); }); - return new Message({ - header: header, - accountKeys: staticAccountKeys, - recentBlockhash: args.recentBlockhash, - instructions: instructions + message.instructions.forEach(function (instruction) { + var keys = instruction.accounts.map(function (account) { + var pubkey = message.accountKeys[account]; + return { + pubkey: pubkey, + isSigner: transaction.signatures.some(function (keyObj) { + return keyObj.publicKey.toString() === pubkey.toString(); + }) || message.isAccountSigner(account), + isWritable: message.isAccountWritable(account) + }; + }); + transaction.instructions.push(new TransactionInstruction({ + keys: keys, + programId: message.accountKeys[instruction.programIdIndex], + data: bs58$3.decode(instruction.data) + })); }); + transaction._message = message; + transaction._json = transaction.toJSON(); + return transaction; } - }, { - key: "from", - value: function from(buffer) { - // Slice up wire data - var byteArray = _toConsumableArray(buffer); + }]); - var numRequiredSignatures = byteArray.shift(); + return Transaction; + }(); - if (numRequiredSignatures !== (numRequiredSignatures & VERSION_PREFIX_MASK)) { - throw new Error('Versioned messages must be deserialized with VersionedMessage.deserialize()'); - } + var TransactionMessage = /*#__PURE__*/function () { + function TransactionMessage(args) { + _classCallCheck(this, TransactionMessage); - var numReadonlySignedAccounts = byteArray.shift(); - var numReadonlyUnsignedAccounts = byteArray.shift(); - var accountCount = decodeLength(byteArray); - var accountKeys = []; + this.payerKey = void 0; + this.instructions = void 0; + this.recentBlockhash = void 0; + this.payerKey = args.payerKey; + this.instructions = args.instructions; + this.recentBlockhash = args.recentBlockhash; + } - for (var i = 0; i < accountCount; i++) { - var account = byteArray.slice(0, PUBLIC_KEY_LENGTH); - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - accountKeys.push(new PublicKey(Buffer$1.from(account))); + _createClass(TransactionMessage, [{ + key: "compileToLegacyMessage", + value: function compileToLegacyMessage() { + return Message.compile({ + payerKey: this.payerKey, + recentBlockhash: this.recentBlockhash, + instructions: this.instructions + }); + } + }, { + key: "compileToV0Message", + value: function compileToV0Message(addressLookupTableAccounts) { + return MessageV0.compile({ + payerKey: this.payerKey, + recentBlockhash: this.recentBlockhash, + instructions: this.instructions, + addressLookupTableAccounts: addressLookupTableAccounts + }); + } + }], [{ + key: "decompile", + value: function decompile(message, args) { + var header = message.header, + compiledInstructions = message.compiledInstructions, + recentBlockhash = message.recentBlockhash; + var numRequiredSignatures = header.numRequiredSignatures, + numReadonlySignedAccounts = header.numReadonlySignedAccounts, + numReadonlyUnsignedAccounts = header.numReadonlyUnsignedAccounts; + var numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts; + assert(numWritableSignedAccounts > 0, 'Message header is invalid'); + var numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts; + assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid'); + var accountKeys = message.getAccountKeys(args); + var payerKey = accountKeys.get(0); + + if (payerKey === undefined) { + throw new Error('Failed to decompile message because no account keys were found'); } - var recentBlockhash = byteArray.slice(0, PUBLIC_KEY_LENGTH); - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - var instructionCount = decodeLength(byteArray); var instructions = []; - for (var _i2 = 0; _i2 < instructionCount; _i2++) { - var programIdIndex = byteArray.shift(); + var _iterator14 = _createForOfIteratorHelper(compiledInstructions), + _step14; - var _accountCount = decodeLength(byteArray); + try { + for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { + var compiledIx = _step14.value; + var keys = []; - var accounts = byteArray.slice(0, _accountCount); - byteArray = byteArray.slice(_accountCount); - var dataLength = decodeLength(byteArray); - var dataSlice = byteArray.slice(0, dataLength); - var data = bs58$1.encode(Buffer$1.from(dataSlice)); - byteArray = byteArray.slice(dataLength); - instructions.push({ - programIdIndex: programIdIndex, - accounts: accounts, - data: data - }); + var _iterator15 = _createForOfIteratorHelper(compiledIx.accountKeyIndexes), + _step15; + + try { + for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { + var keyIndex = _step15.value; + var pubkey = accountKeys.get(keyIndex); + + if (pubkey === undefined) { + throw new Error("Failed to find key for account key index ".concat(keyIndex)); + } + + var isSigner = keyIndex < numRequiredSignatures; + var isWritable = void 0; + + if (isSigner) { + isWritable = keyIndex < numWritableSignedAccounts; + } else if (keyIndex < accountKeys.staticAccountKeys.length) { + isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts; + } else { + isWritable = keyIndex - accountKeys.staticAccountKeys.length < // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above + accountKeys.accountKeysFromLookups.writable.length; + } + + keys.push({ + pubkey: pubkey, + isSigner: keyIndex < header.numRequiredSignatures, + isWritable: isWritable + }); + } + } catch (err) { + _iterator15.e(err); + } finally { + _iterator15.f(); + } + + var programId = accountKeys.get(compiledIx.programIdIndex); + + if (programId === undefined) { + throw new Error("Failed to find program id for program id index ".concat(compiledIx.programIdIndex)); + } + + instructions.push(new TransactionInstruction({ + programId: programId, + data: toBuffer(compiledIx.data), + keys: keys + })); + } + } catch (err) { + _iterator14.e(err); + } finally { + _iterator14.f(); } - var messageArgs = { - header: { - numRequiredSignatures: numRequiredSignatures, - numReadonlySignedAccounts: numReadonlySignedAccounts, - numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts - }, - recentBlockhash: bs58$1.encode(Buffer$1.from(recentBlockhash)), - accountKeys: accountKeys, - instructions: instructions - }; - return new Message(messageArgs); + return new TransactionMessage({ + payerKey: payerKey, + instructions: instructions, + recentBlockhash: recentBlockhash + }); } }]); - return Message; + return TransactionMessage; }(); /** - * Message constructor arguments + * Versioned transaction class */ - var MessageV0 = /*#__PURE__*/function () { - function MessageV0(args) { - _classCallCheck(this, MessageV0); + var VersionedTransaction = /*#__PURE__*/function () { + function VersionedTransaction(message, signatures) { + _classCallCheck(this, VersionedTransaction); - this.header = void 0; - this.staticAccountKeys = void 0; - this.recentBlockhash = void 0; - this.compiledInstructions = void 0; - this.addressTableLookups = void 0; - this.header = args.header; - this.staticAccountKeys = args.staticAccountKeys; - this.recentBlockhash = args.recentBlockhash; - this.compiledInstructions = args.compiledInstructions; - this.addressTableLookups = args.addressTableLookups; + this.signatures = void 0; + this.message = void 0; + + if (signatures !== undefined) { + assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures'); + this.signatures = signatures; + } else { + var defaultSignatures = []; + + for (var i = 0; i < message.header.numRequiredSignatures; i++) { + defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES)); + } + + this.signatures = defaultSignatures; + } + + this.message = message; } - _createClass(MessageV0, [{ + _createClass(VersionedTransaction, [{ key: "version", get: function get() { - return 0; + return this.message.version; } }, { - key: "numAccountKeysFromLookups", - get: function get() { - var count = 0; + key: "serialize", + value: function serialize() { + var serializedMessage = this.message.serialize(); + var encodedSignaturesLength = Array(); + encodeLength(encodedSignaturesLength, this.signatures.length); + var transactionLayout = struct([blob$1(encodedSignaturesLength.length, 'encodedSignaturesLength'), seq$1(signature(), this.signatures.length, 'signatures'), blob$1(serializedMessage.length, 'serializedMessage')]); + var serializedTransaction = new Uint8Array(2048); + var serializedTransactionLength = transactionLayout.encode({ + encodedSignaturesLength: new Uint8Array(encodedSignaturesLength), + signatures: this.signatures, + serializedMessage: serializedMessage + }, serializedTransaction); + return serializedTransaction.slice(0, serializedTransactionLength); + } + }, { + key: "sign", + value: function sign(signers) { + var _this11 = this; - var _iterator5 = _createForOfIteratorHelper(this.addressTableLookups), - _step5; + var messageData = this.message.serialize(); + var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + + var _iterator16 = _createForOfIteratorHelper(signers), + _step16; try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var lookup = _step5.value; - count += lookup.readonlyIndexes.length + lookup.writableIndexes.length; + var _loop4 = function _loop4() { + var signer = _step16.value; + var signerIndex = signerPubkeys.findIndex(function (pubkey) { + return pubkey.equals(signer.publicKey); + }); + assert(signerIndex >= 0, "Cannot sign with non signer key ".concat(signer.publicKey.toBase58())); + _this11.signatures[signerIndex] = _sign(messageData, signer.secretKey); + }; + + for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { + _loop4(); } } catch (err) { - _iterator5.e(err); + _iterator16.e(err); } finally { - _iterator5.f(); + _iterator16.f(); } - - return count; } }, { - key: "getAccountKeys", - value: function getAccountKeys(args) { - var accountKeysFromLookups; + key: "addSignature", + value: function addSignature(publicKey, signature) { + assert(signature.byteLength === 64, 'Signature must be 64 bytes long'); + var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + var signerIndex = signerPubkeys.findIndex(function (pubkey) { + return pubkey.equals(publicKey); + }); + assert(signerIndex >= 0, "Can not add signature; `".concat(publicKey.toBase58(), "` is not required to sign this transaction")); + this.signatures[signerIndex] = signature; + } + }], [{ + key: "deserialize", + value: function deserialize(serializedTransaction) { + var byteArray = _toConsumableArray(serializedTransaction); - if (args && 'accountKeysFromLookups' in args && args.accountKeysFromLookups) { - if (this.numAccountKeysFromLookups != args.accountKeysFromLookups.writable.length + args.accountKeysFromLookups.readonly.length) { - throw new Error('Failed to get account keys because of a mismatch in the number of account keys from lookups'); - } + var signatures = []; + var signaturesLength = decodeLength(byteArray); - accountKeysFromLookups = args.accountKeysFromLookups; - } else if (args && 'addressLookupTableAccounts' in args && args.addressLookupTableAccounts) { - accountKeysFromLookups = this.resolveAddressTableLookups(args.addressLookupTableAccounts); - } else if (this.addressTableLookups.length > 0) { - throw new Error('Failed to get account keys because address table lookups were not resolved'); + for (var i = 0; i < signaturesLength; i++) { + signatures.push(new Uint8Array(byteArray.splice(0, SIGNATURE_LENGTH_IN_BYTES))); } - return new MessageAccountKeys(this.staticAccountKeys, accountKeysFromLookups); - } - }, { - key: "isAccountSigner", - value: function isAccountSigner(index) { - return index < this.header.numRequiredSignatures; + var message = VersionedMessage.deserialize(new Uint8Array(byteArray)); + return new VersionedTransaction(message, signatures); } - }, { - key: "isAccountWritable", - value: function isAccountWritable(index) { - var numSignedAccounts = this.header.numRequiredSignatures; - var numStaticAccountKeys = this.staticAccountKeys.length; + }]); - if (index >= numStaticAccountKeys) { - var lookupAccountKeysIndex = index - numStaticAccountKeys; - var numWritableLookupAccountKeys = this.addressTableLookups.reduce(function (count, lookup) { - return count + lookup.writableIndexes.length; - }, 0); - return lookupAccountKeysIndex < numWritableLookupAccountKeys; - } else if (index >= this.header.numRequiredSignatures) { - var unsignedAccountIndex = index - numSignedAccounts; - var numUnsignedAccounts = numStaticAccountKeys - numSignedAccounts; - var numWritableUnsignedAccounts = numUnsignedAccounts - this.header.numReadonlyUnsignedAccounts; - return unsignedAccountIndex < numWritableUnsignedAccounts; - } else { - var numWritableSignedAccounts = numSignedAccounts - this.header.numReadonlySignedAccounts; - return index < numWritableSignedAccounts; - } - } - }, { - key: "resolveAddressTableLookups", - value: function resolveAddressTableLookups(addressLookupTableAccounts) { - var accountKeysFromLookups = { - writable: [], - readonly: [] - }; + return VersionedTransaction; + }(); - var _iterator6 = _createForOfIteratorHelper(this.addressTableLookups), - _step6; + var SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111'); + var SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111'); + var SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111'); + var SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111'); + var SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111'); + var SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111'); + var SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111'); + var SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111'); + var SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111'); + /** + * Sign, send and confirm a transaction. + * + * If `commitment` option is not specified, defaults to 'max' commitment. + * + * @param {Connection} connection + * @param {Transaction} transaction + * @param {Array} signers + * @param {ConfirmOptions} [options] + * @returns {Promise} + */ - try { - var _loop2 = function _loop2() { - var tableLookup = _step6.value; - var tableAccount = addressLookupTableAccounts.find(function (account) { - return account.key.equals(tableLookup.accountKey); - }); + function sendAndConfirmTransaction(_x9, _x10, _x11, _x12) { + return _sendAndConfirmTransaction.apply(this, arguments); + } // zzz - if (!tableAccount) { - throw new Error("Failed to find address lookup table account for table key ".concat(tableLookup.accountKey.toBase58())); + + function _sendAndConfirmTransaction() { + _sendAndConfirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee108(connection, transaction, signers, options) { + var sendOptions, signature, status, nonceInstruction, nonceAccountPubkey; + return _regeneratorRuntime().wrap(function _callee108$(_context108) { + while (1) switch (_context108.prev = _context108.next) { + case 0: + sendOptions = options && { + skipPreflight: options.skipPreflight, + preflightCommitment: options.preflightCommitment || options.commitment, + maxRetries: options.maxRetries, + minContextSlot: options.minContextSlot + }; + _context108.next = 3; + return connection.sendTransaction(transaction, signers, sendOptions); + + case 3: + signature = _context108.sent; + + if (!(transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null)) { + _context108.next = 10; + break; } - var _iterator7 = _createForOfIteratorHelper(tableLookup.writableIndexes), - _step7; + _context108.next = 7; + return connection.confirmTransaction({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + signature: signature, + blockhash: transaction.recentBlockhash, + lastValidBlockHeight: transaction.lastValidBlockHeight + }, options && options.commitment); - try { - for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { - var index = _step7.value; + case 7: + status = _context108.sent.value; + _context108.next = 22; + break; - if (index < tableAccount.state.addresses.length) { - accountKeysFromLookups.writable.push(tableAccount.state.addresses[index]); - } else { - throw new Error("Failed to find address for index ".concat(index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); - } - } - } catch (err) { - _iterator7.e(err); - } finally { - _iterator7.f(); + case 10: + if (!(transaction.minNonceContextSlot != null && transaction.nonceInfo != null)) { + _context108.next = 18; + break; } - var _iterator8 = _createForOfIteratorHelper(tableLookup.readonlyIndexes), - _step8; + nonceInstruction = transaction.nonceInfo.nonceInstruction; + nonceAccountPubkey = nonceInstruction.keys[0].pubkey; + _context108.next = 15; + return connection.confirmTransaction({ + abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, + minContextSlot: transaction.minNonceContextSlot, + nonceAccountPubkey: nonceAccountPubkey, + nonceValue: transaction.nonceInfo.nonce, + signature: signature + }, options && options.commitment); - try { - for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { - var _index = _step8.value; + case 15: + status = _context108.sent.value; + _context108.next = 22; + break; - if (_index < tableAccount.state.addresses.length) { - accountKeysFromLookups.readonly.push(tableAccount.state.addresses[_index]); - } else { - throw new Error("Failed to find address for index ".concat(_index, " in address lookup table ").concat(tableLookup.accountKey.toBase58())); - } - } - } catch (err) { - _iterator8.e(err); - } finally { - _iterator8.f(); + case 18: + if ((options === null || options === void 0 ? void 0 : options.abortSignal) != null) { + console.warn('sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' + 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' + 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.'); } - }; - for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { - _loop2(); - } - } catch (err) { - _iterator6.e(err); - } finally { - _iterator6.f(); + _context108.next = 21; + return connection.confirmTransaction(signature, options && options.commitment); + + case 21: + status = _context108.sent.value; + + case 22: + if (!status.err) { + _context108.next = 24; + break; + } + + throw new Error("Transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + + case 24: + return _context108.abrupt("return", signature); + + case 25: + case "end": + return _context108.stop(); } + }, _callee108); + })); + return _sendAndConfirmTransaction.apply(this, arguments); + } - return accountKeysFromLookups; - } - }, { - key: "serialize", - value: function serialize() { - var encodedStaticAccountKeysLength = Array(); - encodeLength(encodedStaticAccountKeysLength, this.staticAccountKeys.length); - var serializedInstructions = this.serializeInstructions(); - var encodedInstructionsLength = Array(); - encodeLength(encodedInstructionsLength, this.compiledInstructions.length); - var serializedAddressTableLookups = this.serializeAddressTableLookups(); - var encodedAddressTableLookupsLength = Array(); - encodeLength(encodedAddressTableLookupsLength, this.addressTableLookups.length); - var messageLayout = struct([u8('prefix'), struct([u8('numRequiredSignatures'), u8('numReadonlySignedAccounts'), u8('numReadonlyUnsignedAccounts')], 'header'), blob$1(encodedStaticAccountKeysLength.length, 'staticAccountKeysLength'), seq$1(publicKey(), this.staticAccountKeys.length, 'staticAccountKeys'), publicKey('recentBlockhash'), blob$1(encodedInstructionsLength.length, 'instructionsLength'), blob$1(serializedInstructions.length, 'serializedInstructions'), blob$1(encodedAddressTableLookupsLength.length, 'addressTableLookupsLength'), blob$1(serializedAddressTableLookups.length, 'serializedAddressTableLookups')]); - var serializedMessage = new Uint8Array(PACKET_DATA_SIZE); - var MESSAGE_VERSION_0_PREFIX = 1 << 7; - var serializedMessageLength = messageLayout.encode({ - prefix: MESSAGE_VERSION_0_PREFIX, - header: this.header, - staticAccountKeysLength: new Uint8Array(encodedStaticAccountKeysLength), - staticAccountKeys: this.staticAccountKeys.map(function (key) { - return key.toBytes(); - }), - recentBlockhash: bs58$1.decode(this.recentBlockhash), - instructionsLength: new Uint8Array(encodedInstructionsLength), - serializedInstructions: serializedInstructions, - addressTableLookupsLength: new Uint8Array(encodedAddressTableLookupsLength), - serializedAddressTableLookups: serializedAddressTableLookups - }, serializedMessage); - return serializedMessage.slice(0, serializedMessageLength); + function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + /** + * Populate a buffer of instruction data using an InstructionType + * @internal + */ + + + function encodeData(type, fields) { + var allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields); + var data = Buffer$1.alloc(allocLength); + var layoutFields = Object.assign({ + instruction: type.index + }, fields); + type.layout.encode(layoutFields, data); + return data; + } + /** + * Decode instruction data buffer using an InstructionType + * @internal + */ + + + function decodeData$1(type, buffer) { + var data; + + try { + data = type.layout.decode(buffer); + } catch (err) { + throw new Error('invalid instruction; ' + err); + } + + if (data.instruction !== type.index) { + throw new Error("invalid instruction; instruction index mismatch ".concat(data.instruction, " != ").concat(type.index)); + } + + return data; + } + /** + * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11 + * + * @internal + */ + + + var FeeCalculatorLayout = nu64$1('lamportsPerSignature'); + /** + * Calculator for transaction fees. + * + * @deprecated Deprecated since Solana v1.8.0. + */ + + /** + * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32 + * + * @internal + */ + + var NonceAccountLayout = struct([u32('version'), u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), struct([FeeCalculatorLayout], 'feeCalculator')]); + var NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span; + /** + * A durable nonce is a 32 byte value encoded as a base58 string. + */ + + /** + * NonceAccount class + */ + + var NonceAccount = /*#__PURE__*/function () { + /** + * @internal + */ + function NonceAccount(args) { + _classCallCheck(this, NonceAccount); + + this.authorizedPubkey = void 0; + this.nonce = void 0; + this.feeCalculator = void 0; + this.authorizedPubkey = args.authorizedPubkey; + this.nonce = args.nonce; + this.feeCalculator = args.feeCalculator; + } + /** + * Deserialize NonceAccount from the account data. + * + * @param buffer account data + * @return NonceAccount + */ + + + _createClass(NonceAccount, null, [{ + key: "fromAccountData", + value: function fromAccountData(buffer) { + var nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0); + return new NonceAccount({ + authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey), + nonce: new PublicKey(nonceAccount.nonce).toString(), + feeCalculator: nonceAccount.feeCalculator + }); } - }, { - key: "serializeInstructions", - value: function serializeInstructions() { - var serializedLength = 0; - var serializedInstructions = new Uint8Array(PACKET_DATA_SIZE); + }]); + + return NonceAccount; + }(); + + var encodeDecode = function encodeDecode(layout) { + var decode = layout.decode.bind(layout); + var encode = layout.encode.bind(layout); + return { + decode: decode, + encode: encode + }; + }; + + var bigInt = function bigInt(length) { + return function (property) { + var layout = blob$1(length, property); + + var _encodeDecode = encodeDecode(layout), + encode = _encodeDecode.encode, + decode = _encodeDecode.decode; + + var bigIntLayout = layout; + + bigIntLayout.decode = function (buffer, offset) { + var src = decode(buffer, offset); + return toBigIntLE_1(Buffer$1.from(src)); + }; + + bigIntLayout.encode = function (bigInt, buffer, offset) { + var src = toBufferLE_1(bigInt, length); + return encode(src, buffer, offset); + }; + + return bigIntLayout; + }; + }; + + var u64 = bigInt(8); + /** + * Create account system transaction params + */ + + /** + * System Instruction class + */ + + var SystemInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function SystemInstruction() { + _classCallCheck(this, SystemInstruction); + } + /** + * Decode a system instruction and retrieve the instruction type. + */ - var _iterator9 = _createForOfIteratorHelper(this.compiledInstructions), - _step9; - try { - for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { - var instruction = _step9.value; - var encodedAccountKeyIndexesLength = Array(); - encodeLength(encodedAccountKeyIndexesLength, instruction.accountKeyIndexes.length); - var encodedDataLength = Array(); - encodeLength(encodedDataLength, instruction.data.length); - var instructionLayout = struct([u8('programIdIndex'), blob$1(encodedAccountKeyIndexesLength.length, 'encodedAccountKeyIndexesLength'), seq$1(u8(), instruction.accountKeyIndexes.length, 'accountKeyIndexes'), blob$1(encodedDataLength.length, 'encodedDataLength'), blob$1(instruction.data.length, 'data')]); - serializedLength += instructionLayout.encode({ - programIdIndex: instruction.programIdIndex, - encodedAccountKeyIndexesLength: new Uint8Array(encodedAccountKeyIndexesLength), - accountKeyIndexes: instruction.accountKeyIndexes, - encodedDataLength: new Uint8Array(encodedDataLength), - data: instruction.data - }, serializedInstructions, serializedLength); + _createClass(SystemInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; + + for (var _i9 = 0, _Object$entries = Object.entries(SYSTEM_INSTRUCTION_LAYOUTS); _i9 < _Object$entries.length; _i9++) { + var _Object$entries$_i2 = _slicedToArray(_Object$entries[_i9], 2), + ixType = _Object$entries$_i2[0], + layout = _Object$entries$_i2[1]; + + if (layout.index == typeIndex) { + type = ixType; + break; } - } catch (err) { - _iterator9.e(err); - } finally { - _iterator9.f(); } - return serializedInstructions.slice(0, serializedLength); + if (!type) { + throw new Error('Instruction type incorrect; not a SystemInstruction'); + } + + return type; } - }, { - key: "serializeAddressTableLookups", - value: function serializeAddressTableLookups() { - var serializedLength = 0; - var serializedAddressTableLookups = new Uint8Array(PACKET_DATA_SIZE); + /** + * Decode a create account system instruction and retrieve the instruction params. + */ - var _iterator10 = _createForOfIteratorHelper(this.addressTableLookups), - _step10; + }, { + key: "decodeCreateAccount", + value: function decodeCreateAccount(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - try { - for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { - var lookup = _step10.value; - var encodedWritableIndexesLength = Array(); - encodeLength(encodedWritableIndexesLength, lookup.writableIndexes.length); - var encodedReadonlyIndexesLength = Array(); - encodeLength(encodedReadonlyIndexesLength, lookup.readonlyIndexes.length); - var addressTableLookupLayout = struct([publicKey('accountKey'), blob$1(encodedWritableIndexesLength.length, 'encodedWritableIndexesLength'), seq$1(u8(), lookup.writableIndexes.length, 'writableIndexes'), blob$1(encodedReadonlyIndexesLength.length, 'encodedReadonlyIndexesLength'), seq$1(u8(), lookup.readonlyIndexes.length, 'readonlyIndexes')]); - serializedLength += addressTableLookupLayout.encode({ - accountKey: lookup.accountKey.toBytes(), - encodedWritableIndexesLength: new Uint8Array(encodedWritableIndexesLength), - writableIndexes: lookup.writableIndexes, - encodedReadonlyIndexesLength: new Uint8Array(encodedReadonlyIndexesLength), - readonlyIndexes: lookup.readonlyIndexes - }, serializedAddressTableLookups, serializedLength); - } - } catch (err) { - _iterator10.e(err); - } finally { - _iterator10.f(); - } + var _decodeData$ = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data), + lamports = _decodeData$.lamports, + space = _decodeData$.space, + programId = _decodeData$.programId; - return serializedAddressTableLookups.slice(0, serializedLength); + return { + fromPubkey: instruction.keys[0].pubkey, + newAccountPubkey: instruction.keys[1].pubkey, + lamports: lamports, + space: space, + programId: new PublicKey(programId) + }; } - }], [{ - key: "compile", - value: function compile(args) { - var compiledKeys = CompiledKeys.compile(args.instructions, args.payerKey); - var addressTableLookups = new Array(); - var accountKeysFromLookups = { - writable: new Array(), - readonly: new Array() + /** + * Decode a transfer system instruction and retrieve the instruction params. + */ + + }, { + key: "decodeTransfer", + value: function decodeTransfer(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); + + var _decodeData$2 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data), + lamports = _decodeData$2.lamports; + + return { + fromPubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + lamports: lamports }; - var lookupTableAccounts = args.addressLookupTableAccounts || []; + } + /** + * Decode a transfer with seed system instruction and retrieve the instruction params. + */ - var _iterator11 = _createForOfIteratorHelper(lookupTableAccounts), - _step11; + }, { + key: "decodeTransferWithSeed", + value: function decodeTransferWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - try { - for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { - var lookupTable = _step11.value; - var extractResult = compiledKeys.extractTableLookup(lookupTable); + var _decodeData$3 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data), + lamports = _decodeData$3.lamports, + seed = _decodeData$3.seed, + programId = _decodeData$3.programId; - if (extractResult !== undefined) { - var _accountKeysFromLooku, _accountKeysFromLooku2; + return { + fromPubkey: instruction.keys[0].pubkey, + basePubkey: instruction.keys[1].pubkey, + toPubkey: instruction.keys[2].pubkey, + lamports: lamports, + seed: seed, + programId: new PublicKey(programId) + }; + } + /** + * Decode an allocate system instruction and retrieve the instruction params. + */ - var _extractResult2 = _slicedToArray(extractResult, 2), - addressTableLookup = _extractResult2[0], - _extractResult$2 = _extractResult2[1], - writable = _extractResult$2.writable, - readonly = _extractResult$2.readonly; + }, { + key: "decodeAllocate", + value: function decodeAllocate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - addressTableLookups.push(addressTableLookup); + var _decodeData$4 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data), + space = _decodeData$4.space; - (_accountKeysFromLooku = accountKeysFromLookups.writable).push.apply(_accountKeysFromLooku, _toConsumableArray(writable)); + return { + accountPubkey: instruction.keys[0].pubkey, + space: space + }; + } + /** + * Decode an allocate with seed system instruction and retrieve the instruction params. + */ - (_accountKeysFromLooku2 = accountKeysFromLookups.readonly).push.apply(_accountKeysFromLooku2, _toConsumableArray(readonly)); - } - } - } catch (err) { - _iterator11.e(err); - } finally { - _iterator11.f(); - } + }, { + key: "decodeAllocateWithSeed", + value: function decodeAllocateWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var _compiledKeys$getMess3 = compiledKeys.getMessageComponents(), - _compiledKeys$getMess4 = _slicedToArray(_compiledKeys$getMess3, 2), - header = _compiledKeys$getMess4[0], - staticAccountKeys = _compiledKeys$getMess4[1]; + var _decodeData$5 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data), + base = _decodeData$5.base, + seed = _decodeData$5.seed, + space = _decodeData$5.space, + programId = _decodeData$5.programId; - var accountKeys = new MessageAccountKeys(staticAccountKeys, accountKeysFromLookups); - var compiledInstructions = accountKeys.compileInstructions(args.instructions); - return new MessageV0({ - header: header, - staticAccountKeys: staticAccountKeys, - recentBlockhash: args.recentBlockhash, - compiledInstructions: compiledInstructions, - addressTableLookups: addressTableLookups - }); + return { + accountPubkey: instruction.keys[0].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + space: space, + programId: new PublicKey(programId) + }; } + /** + * Decode an assign system instruction and retrieve the instruction params. + */ + }, { - key: "deserialize", - value: function deserialize(serializedMessage) { - var byteArray = _toConsumableArray(serializedMessage); + key: "decodeAssign", + value: function decodeAssign(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var prefix = byteArray.shift(); - var maskedPrefix = prefix & VERSION_PREFIX_MASK; - assert(prefix !== maskedPrefix, "Expected versioned message but received legacy message"); - var version = maskedPrefix; - assert(version === 0, "Expected versioned message with version 0 but found version ".concat(version)); - var header = { - numRequiredSignatures: byteArray.shift(), - numReadonlySignedAccounts: byteArray.shift(), - numReadonlyUnsignedAccounts: byteArray.shift() + var _decodeData$6 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data), + programId = _decodeData$6.programId; + + return { + accountPubkey: instruction.keys[0].pubkey, + programId: new PublicKey(programId) }; - var staticAccountKeys = []; - var staticAccountKeysLength = decodeLength(byteArray); + } + /** + * Decode an assign with seed system instruction and retrieve the instruction params. + */ - for (var i = 0; i < staticAccountKeysLength; i++) { - staticAccountKeys.push(new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH))); - } + }, { + key: "decodeAssignWithSeed", + value: function decodeAssignWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 1); - var recentBlockhash = bs58$1.encode(byteArray.splice(0, PUBLIC_KEY_LENGTH)); - var instructionCount = decodeLength(byteArray); - var compiledInstructions = []; + var _decodeData$7 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data), + base = _decodeData$7.base, + seed = _decodeData$7.seed, + programId = _decodeData$7.programId; - for (var _i4 = 0; _i4 < instructionCount; _i4++) { - var programIdIndex = byteArray.shift(); - var accountKeyIndexesLength = decodeLength(byteArray); - var accountKeyIndexes = byteArray.splice(0, accountKeyIndexesLength); - var dataLength = decodeLength(byteArray); - var data = new Uint8Array(byteArray.splice(0, dataLength)); - compiledInstructions.push({ - programIdIndex: programIdIndex, - accountKeyIndexes: accountKeyIndexes, - data: data - }); - } + return { + accountPubkey: instruction.keys[0].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + programId: new PublicKey(programId) + }; + } + /** + * Decode a create account with seed system instruction and retrieve the instruction params. + */ - var addressTableLookupsCount = decodeLength(byteArray); - var addressTableLookups = []; + }, { + key: "decodeCreateWithSeed", + value: function decodeCreateWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - for (var _i6 = 0; _i6 < addressTableLookupsCount; _i6++) { - var accountKey = new PublicKey(byteArray.splice(0, PUBLIC_KEY_LENGTH)); - var writableIndexesLength = decodeLength(byteArray); - var writableIndexes = byteArray.splice(0, writableIndexesLength); - var readonlyIndexesLength = decodeLength(byteArray); - var readonlyIndexes = byteArray.splice(0, readonlyIndexesLength); - addressTableLookups.push({ - accountKey: accountKey, - writableIndexes: writableIndexes, - readonlyIndexes: readonlyIndexes - }); - } + var _decodeData$8 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data), + base = _decodeData$8.base, + seed = _decodeData$8.seed, + lamports = _decodeData$8.lamports, + space = _decodeData$8.space, + programId = _decodeData$8.programId; - return new MessageV0({ - header: header, - staticAccountKeys: staticAccountKeys, - recentBlockhash: recentBlockhash, - compiledInstructions: compiledInstructions, - addressTableLookups: addressTableLookups - }); + return { + fromPubkey: instruction.keys[0].pubkey, + newAccountPubkey: instruction.keys[1].pubkey, + basePubkey: new PublicKey(base), + seed: seed, + lamports: lamports, + space: space, + programId: new PublicKey(programId) + }; } - }]); + /** + * Decode a nonce initialize system instruction and retrieve the instruction params. + */ - return MessageV0; - }(); // eslint-disable-next-line no-redeclare + }, { + key: "decodeNonceInitialize", + value: function decodeNonceInitialize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + var _decodeData$9 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data), + authorized = _decodeData$9.authorized; - var VersionedMessage = { - deserializeMessageVersion: function deserializeMessageVersion(serializedMessage) { - var prefix = serializedMessage[0]; - var maskedPrefix = prefix & VERSION_PREFIX_MASK; // if the highest bit of the prefix is not set, the message is not versioned + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: new PublicKey(authorized) + }; + } + /** + * Decode a nonce advance system instruction and retrieve the instruction params. + */ - if (maskedPrefix === prefix) { - return 'legacy'; - } // the lower 7 bits of the prefix indicate the message version + }, { + key: "decodeNonceAdvance", + value: function decodeNonceAdvance(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data); + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey + }; + } + /** + * Decode a nonce withdraw system instruction and retrieve the instruction params. + */ + }, { + key: "decodeNonceWithdraw", + value: function decodeNonceWithdraw(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 5); - return maskedPrefix; - }, - deserialize: function deserialize(serializedMessage) { - var version = VersionedMessage.deserializeMessageVersion(serializedMessage); + var _decodeData$10 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data), + lamports = _decodeData$10.lamports; - if (version === 'legacy') { - return Message.from(serializedMessage); + return { + noncePubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey, + lamports: lamports + }; } + /** + * Decode a nonce authorize system instruction and retrieve the instruction params. + */ - if (version === 0) { - return MessageV0.deserialize(serializedMessage); - } else { - throw new Error("Transaction message version ".concat(version, " deserialization is not supported")); + }, { + key: "decodeNonceAuthorize", + value: function decodeNonceAuthorize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); + + var _decodeData$11 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data), + authorized = _decodeData$11.authorized; + + return { + noncePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[1].pubkey, + newAuthorizedPubkey: new PublicKey(authorized) + }; } - } - }; - /** - * Transaction signature as base-58 encoded string - */ + /** + * @internal + */ - var TransactionStatus; - /** - * Default (empty) signature - */ + }, { + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(SystemProgram.programId)) { + throw new Error('invalid instruction; programId is not SystemProgram'); + } + } + /** + * @internal + */ - (function (TransactionStatus) { - TransactionStatus[TransactionStatus["BLOCKHEIGHT_EXCEEDED"] = 0] = "BLOCKHEIGHT_EXCEEDED"; - TransactionStatus[TransactionStatus["PROCESSED"] = 1] = "PROCESSED"; - TransactionStatus[TransactionStatus["TIMED_OUT"] = 2] = "TIMED_OUT"; - TransactionStatus[TransactionStatus["NONCE_INVALID"] = 3] = "NONCE_INVALID"; - })(TransactionStatus || (TransactionStatus = {})); + }, { + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); + } + } + }]); - var DEFAULT_SIGNATURE = Buffer$1.alloc(SIGNATURE_LENGTH_IN_BYTES).fill(0); + return SystemInstruction; + }(); /** - * Account metadata used to define instructions + * An enumeration of valid SystemInstructionType's */ /** - * Transaction Instruction class + * An enumeration of valid system InstructionType's + * @internal */ - var TransactionInstruction = /*#__PURE__*/function () { - /** - * Public keys to include in this transaction - * Boolean represents whether this pubkey needs to sign the transaction - */ + var SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({ + Create: { + index: 0, + layout: struct([u32('instruction'), ns64('lamports'), ns64('space'), publicKey('programId')]) + }, + Assign: { + index: 1, + layout: struct([u32('instruction'), publicKey('programId')]) + }, + Transfer: { + index: 2, + layout: struct([u32('instruction'), u64('lamports')]) + }, + CreateWithSeed: { + index: 3, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('lamports'), ns64('space'), publicKey('programId')]) + }, + AdvanceNonceAccount: { + index: 4, + layout: struct([u32('instruction')]) + }, + WithdrawNonceAccount: { + index: 5, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + InitializeNonceAccount: { + index: 6, + layout: struct([u32('instruction'), publicKey('authorized')]) + }, + AuthorizeNonceAccount: { + index: 7, + layout: struct([u32('instruction'), publicKey('authorized')]) + }, + Allocate: { + index: 8, + layout: struct([u32('instruction'), ns64('space')]) + }, + AllocateWithSeed: { + index: 9, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('space'), publicKey('programId')]) + }, + AssignWithSeed: { + index: 10, + layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')]) + }, + TransferWithSeed: { + index: 11, + layout: struct([u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')]) + }, + UpgradeNonceAccount: { + index: 12, + layout: struct([u32('instruction')]) + } + }); + /** + * Factory class for transactions to interact with the System program + */ + + var SystemProgram = /*#__PURE__*/function () { /** - * Program Id to execute + * @internal */ - + function SystemProgram() { + _classCallCheck(this, SystemProgram); + } /** - * Program input + * Public key that identifies the System program */ - function TransactionInstruction(opts) { - _classCallCheck(this, TransactionInstruction); - - this.keys = void 0; - this.programId = void 0; - this.data = Buffer$1.alloc(0); - this.programId = opts.programId; - this.keys = opts.keys; - if (opts.data) { - this.data = opts.data; - } - } /** - * @internal + * Generate a transaction instruction that creates a new account */ - _createClass(TransactionInstruction, [{ - key: "toJSON", - value: function toJSON() { - return { - keys: this.keys.map(function (_ref17) { - var pubkey = _ref17.pubkey, - isSigner = _ref17.isSigner, - isWritable = _ref17.isWritable; - return { - pubkey: pubkey.toJSON(), - isSigner: isSigner, - isWritable: isWritable - }; - }), - programId: this.programId.toJSON(), - data: _toConsumableArray(this.data) - }; + _createClass(SystemProgram, null, [{ + key: "createAccount", + value: function createAccount(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.Create; + var data = encodeData(type, { + lamports: params.lamports, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.newAccountPubkey, + isSigner: true, + isWritable: true + }], + programId: this.programId, + data: data + }); } - }]); - - return TransactionInstruction; - }(); - /** - * Pair of signature and corresponding public key - */ + /** + * Generate a transaction instruction that transfers lamports from one account to another + */ - /** - * Transaction class - */ + }, { + key: "transfer", + value: function transfer(params) { + var data; + var keys; + if ('basePubkey' in params) { + var _type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed; + data = encodeData(_type, { + lamports: BigInt(params.lamports), + seed: params.seed, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.fromPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }]; + } else { + var _type2 = SYSTEM_INSTRUCTION_LAYOUTS.Transfer; + data = encodeData(_type2, { + lamports: BigInt(params.lamports) + }); + keys = [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }]; + } - var Transaction = /*#__PURE__*/function () { - /** - * The transaction fee payer - */ + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that assigns an account to a program + */ - /** - * Construct an empty Transaction - */ - function Transaction(opts) { - _classCallCheck(this, Transaction); + }, { + key: "assign", + value: function assign(params) { + var data; + var keys; - this.signatures = []; - this.feePayer = void 0; - this.instructions = []; - this.recentBlockhash = void 0; - this.lastValidBlockHeight = void 0; - this.nonceInfo = void 0; - this.minNonceContextSlot = void 0; - this._message = void 0; - this._json = void 0; + if ('basePubkey' in params) { + var _type3 = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed; + data = encodeData(_type3, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }]; + } else { + var _type4 = SYSTEM_INSTRUCTION_LAYOUTS.Assign; + data = encodeData(_type4, { + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: true, + isWritable: true + }]; + } - if (!opts) { - return; + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); } + /** + * Generate a transaction instruction that creates a new account at + * an address generated with `from`, a seed, and programId + */ - if (opts.feePayer) { - this.feePayer = opts.feePayer; - } + }, { + key: "createAccountWithSeed", + value: function createAccountWithSeed(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed; + var data = encodeData(type, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + lamports: params.lamports, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + var keys = [{ + pubkey: params.fromPubkey, + isSigner: true, + isWritable: true + }, { + pubkey: params.newAccountPubkey, + isSigner: false, + isWritable: true + }]; - if (opts.signatures) { - this.signatures = opts.signatures; + if (params.basePubkey != params.fromPubkey) { + keys.push({ + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }); + } + + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data + }); } + /** + * Generate a transaction that creates a new Nonce account + */ - if (Object.prototype.hasOwnProperty.call(opts, 'nonceInfo')) { - var minContextSlot = opts.minContextSlot, - nonceInfo = opts.nonceInfo; - this.minNonceContextSlot = minContextSlot; - this.nonceInfo = nonceInfo; - } else if (Object.prototype.hasOwnProperty.call(opts, 'lastValidBlockHeight')) { - var blockhash = opts.blockhash, - lastValidBlockHeight = opts.lastValidBlockHeight; - this.recentBlockhash = blockhash; - this.lastValidBlockHeight = lastValidBlockHeight; - } else { - var recentBlockhash = opts.recentBlockhash, - _nonceInfo = opts.nonceInfo; + }, { + key: "createNonceAccount", + value: function createNonceAccount(params) { + var transaction = new Transaction(); - if (_nonceInfo) { - this.nonceInfo = _nonceInfo; + if ('basePubkey' in params && 'seed' in params) { + transaction.add(SystemProgram.createAccountWithSeed({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.noncePubkey, + basePubkey: params.basePubkey, + seed: params.seed, + lamports: params.lamports, + space: NONCE_ACCOUNT_LENGTH, + programId: this.programId + })); + } else { + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.noncePubkey, + lamports: params.lamports, + space: NONCE_ACCOUNT_LENGTH, + programId: this.programId + })); } - this.recentBlockhash = recentBlockhash; + var initParams = { + noncePubkey: params.noncePubkey, + authorizedPubkey: params.authorizedPubkey + }; + transaction.add(this.nonceInitialize(initParams)); + return transaction; } - } - /** - * @internal - */ - - - _createClass(Transaction, [{ - key: "signature", - get: /** - * Signatures for the transaction. Typically created by invoking the - * `sign()` method + * Generate an instruction to initialize a Nonce account */ + }, { + key: "nonceInitialize", + value: function nonceInitialize(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount; + var data = encodeData(type, { + authorized: toBuffer(params.authorizedPubkey.toBuffer()) + }); + var instructionData = { + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); + } /** - * The first (payer) Transaction signature + * Generate an instruction to advance the nonce in a Nonce account */ - function get() { - if (this.signatures.length > 0) { - return this.signatures[0].signature; - } - return null; - } }, { - key: "toJSON", - value: function toJSON() { - return { - recentBlockhash: this.recentBlockhash || null, - feePayer: this.feePayer ? this.feePayer.toJSON() : null, - nonceInfo: this.nonceInfo ? { - nonce: this.nonceInfo.nonce, - nonceInstruction: this.nonceInfo.nonceInstruction.toJSON() - } : null, - instructions: this.instructions.map(function (instruction) { - return instruction.toJSON(); - }), - signers: this.signatures.map(function (_ref18) { - var publicKey = _ref18.publicKey; - return publicKey.toJSON(); - }) + key: "nonceAdvance", + value: function nonceAdvance(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount; + var data = encodeData(type); + var instructionData = { + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data }; + return new TransactionInstruction(instructionData); } /** - * Add one or more instructions to this Transaction + * Generate a transaction instruction that withdraws lamports from a Nonce account */ }, { - key: "add", - value: function add() { - var _this9 = this; + key: "nonceWithdraw", + value: function nonceWithdraw(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount; + var data = encodeData(type, { + lamports: params.lamports + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that authorizes a new PublicKey as the authority + * on a Nonce account. + */ - for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) { - items[_key] = arguments[_key]; - } + }, { + key: "nonceAuthorize", + value: function nonceAuthorize(params) { + var type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount; + var data = encodeData(type, { + authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()) + }); + return new TransactionInstruction({ + keys: [{ + pubkey: params.noncePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction instruction that allocates space in an account without funding + */ - if (items.length === 0) { - throw new Error('No instructions'); + }, { + key: "allocate", + value: function allocate(params) { + var data; + var keys; + + if ('basePubkey' in params) { + var _type5 = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed; + data = encodeData(_type5, { + base: toBuffer(params.basePubkey.toBuffer()), + seed: params.seed, + space: params.space, + programId: toBuffer(params.programId.toBuffer()) + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: params.basePubkey, + isSigner: true, + isWritable: false + }]; + } else { + var _type6 = SYSTEM_INSTRUCTION_LAYOUTS.Allocate; + data = encodeData(_type6, { + space: params.space + }); + keys = [{ + pubkey: params.accountPubkey, + isSigner: true, + isWritable: true + }]; } - items.forEach(function (item) { - if ('instructions' in item) { - _this9.instructions = _this9.instructions.concat(item.instructions); - } else if ('data' in item && 'programId' in item && 'keys' in item) { - _this9.instructions.push(item); - } else { - _this9.instructions.push(new TransactionInstruction(item)); - } + return new TransactionInstruction({ + keys: keys, + programId: this.programId, + data: data }); - return this; + } + }]); + + return SystemProgram; + }(); + + SystemProgram.programId = new PublicKey('11111111111111111111111111111111'); // Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the + // rest of the Transaction fields + // + // TODO: replace 300 with a proper constant for the size of the other + // Transaction fields + + var CHUNK_SIZE = PACKET_DATA_SIZE - 300; + /** + * Program loader interface + */ + + var Loader = /*#__PURE__*/function () { + /** + * @internal + */ + function Loader() { + _classCallCheck(this, Loader); + } + /** + * Amount of program data placed in each load Transaction + */ + + /** + * Minimum number of signatures required to load a program not including + * retries + * + * Can be used to calculate transaction fees + */ + + + _createClass(Loader, null, [{ + key: "getMinNumSignatures", + value: function getMinNumSignatures(dataLength) { + return 2 * ( // Every transaction requires two signatures (payer + program) + Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction + 1) // Add one for Finalize transaction + ; } /** - * Compile transaction data + * Loads a generic program + * + * @param connection The connection to use + * @param payer System account that pays to load the program + * @param program Account to load the program into + * @param programId Public key that identifies the loader + * @param data Program octets + * @return true if program was loaded successfully, false if program was already loaded */ }, { - key: "compileMessage", - value: function compileMessage() { - if (this._message && JSON.stringify(this.toJSON()) === JSON.stringify(this._json)) { - return this._message; - } + key: "load", + value: function () { + var _load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(connection, payer, program, programId, data) { + var balanceNeeded, programInfo, transaction, dataLayout, chunkSize, offset, array, transactions, bytes, _data, _transaction, REQUESTS_PER_SECOND, _dataLayout, _data2, _transaction2; - var recentBlockhash; - var instructions; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return connection.getMinimumBalanceForRentExemption(data.length); - if (this.nonceInfo) { - recentBlockhash = this.nonceInfo.nonce; + case 2: + balanceNeeded = _context5.sent; + _context5.next = 5; + return connection.getAccountInfo(program.publicKey, 'confirmed'); - if (this.instructions[0] != this.nonceInfo.nonceInstruction) { - instructions = [this.nonceInfo.nonceInstruction].concat(_toConsumableArray(this.instructions)); - } else { - instructions = this.instructions; - } - } else { - recentBlockhash = this.recentBlockhash; - instructions = this.instructions; - } + case 5: + programInfo = _context5.sent; + transaction = null; - if (!recentBlockhash) { - throw new Error('Transaction recentBlockhash required'); - } + if (!(programInfo !== null)) { + _context5.next = 16; + break; + } - if (instructions.length < 1) { - console.warn('No instructions provided'); - } + if (!programInfo.executable) { + _context5.next = 11; + break; + } - var feePayer; + console.error('Program load failed, account is already executable'); + return _context5.abrupt("return", false); - if (this.feePayer) { - feePayer = this.feePayer; - } else if (this.signatures.length > 0 && this.signatures[0].publicKey) { - // Use implicit fee payer - feePayer = this.signatures[0].publicKey; - } else { - throw new Error('Transaction fee payer required'); - } + case 11: + if (programInfo.data.length !== data.length) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.allocate({ + accountPubkey: program.publicKey, + space: data.length + })); + } - for (var i = 0; i < instructions.length; i++) { - if (instructions[i].programId === undefined) { - throw new Error("Transaction instruction index ".concat(i, " has undefined program id")); - } - } + if (!programInfo.owner.equals(programId)) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.assign({ + accountPubkey: program.publicKey, + programId: programId + })); + } - var programIds = []; - var accountMetas = []; - instructions.forEach(function (instruction) { - instruction.keys.forEach(function (accountMeta) { - accountMetas.push(_objectSpread2({}, accountMeta)); - }); - var programId = instruction.programId.toString(); + if (programInfo.lamports < balanceNeeded) { + transaction = transaction || new Transaction(); + transaction.add(SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: program.publicKey, + lamports: balanceNeeded - programInfo.lamports + })); + } - if (!programIds.includes(programId)) { - programIds.push(programId); - } - }); // Append programID account metas + _context5.next = 17; + break; - programIds.forEach(function (programId) { - accountMetas.push({ - pubkey: new PublicKey(programId), - isSigner: false, - isWritable: false - }); - }); // Cull duplicate account metas + case 16: + transaction = new Transaction().add(SystemProgram.createAccount({ + fromPubkey: payer.publicKey, + newAccountPubkey: program.publicKey, + lamports: balanceNeeded > 0 ? balanceNeeded : 1, + space: data.length, + programId: programId + })); - var uniqueMetas = []; - accountMetas.forEach(function (accountMeta) { - var pubkeyString = accountMeta.pubkey.toString(); - var uniqueIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.toString() === pubkeyString; - }); + case 17: + if (!(transaction !== null)) { + _context5.next = 20; + break; + } - if (uniqueIndex > -1) { - uniqueMetas[uniqueIndex].isWritable = uniqueMetas[uniqueIndex].isWritable || accountMeta.isWritable; - uniqueMetas[uniqueIndex].isSigner = uniqueMetas[uniqueIndex].isSigner || accountMeta.isSigner; - } else { - uniqueMetas.push(accountMeta); - } - }); // Sort. Prioritizing first by signer, then by writable + _context5.next = 20; + return sendAndConfirmTransaction(connection, transaction, [payer, program], { + commitment: 'confirmed' + }); - uniqueMetas.sort(function (x, y) { - if (x.isSigner !== y.isSigner) { - // Signers always come before non-signers - return x.isSigner ? -1 : 1; - } + case 20: + dataLayout = struct([u32('instruction'), u32('offset'), u32('bytesLength'), u32('bytesLengthPadding'), seq$1(u8('byte'), offset$1(u32(), -8), 'bytes')]); + chunkSize = Loader.chunkSize; + offset = 0; + array = data; + transactions = []; - if (x.isWritable !== y.isWritable) { - // Writable accounts always come before read-only accounts - return x.isWritable ? -1 : 1; - } // Otherwise, sort by pubkey, stringwise. + case 25: + if (!(array.length > 0)) { + _context5.next = 39; + break; + } + bytes = array.slice(0, chunkSize); + _data = Buffer$1.alloc(chunkSize + 16); + dataLayout.encode({ + instruction: 0, + // Load instruction + offset: offset, + bytes: bytes, + bytesLength: 0, + bytesLengthPadding: 0 + }, _data); + _transaction = new Transaction().add({ + keys: [{ + pubkey: program.publicKey, + isSigner: true, + isWritable: true + }], + programId: programId, + data: _data + }); + transactions.push(sendAndConfirmTransaction(connection, _transaction, [payer, program], { + commitment: 'confirmed' + })); // Delay between sends in an attempt to reduce rate limit errors - return x.pubkey.toBase58().localeCompare(y.pubkey.toBase58()); - }); // Move fee payer to the front + if (!connection._rpcEndpoint.includes('solana.com')) { + _context5.next = 35; + break; + } - var feePayerIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.equals(feePayer); - }); + REQUESTS_PER_SECOND = 4; + _context5.next = 35; + return sleep(1000 / REQUESTS_PER_SECOND); - if (feePayerIndex > -1) { - var _uniqueMetas$splice3 = uniqueMetas.splice(feePayerIndex, 1), - _uniqueMetas$splice4 = _slicedToArray(_uniqueMetas$splice3, 1), - payerMeta = _uniqueMetas$splice4[0]; + case 35: + offset += chunkSize; + array = array.slice(chunkSize); + _context5.next = 25; + break; - payerMeta.isSigner = true; - payerMeta.isWritable = true; - uniqueMetas.unshift(payerMeta); - } else { - uniqueMetas.unshift({ - pubkey: feePayer, - isSigner: true, - isWritable: true - }); - } // Disallow unknown signers + case 39: + _context5.next = 41; + return Promise.all(transactions); + case 41: + _dataLayout = struct([u32('instruction')]); + _data2 = Buffer$1.alloc(_dataLayout.span); - var _iterator12 = _createForOfIteratorHelper(this.signatures), - _step12; + _dataLayout.encode({ + instruction: 1 // Finalize instruction - try { - var _loop3 = function _loop3() { - var signature = _step12.value; - var uniqueIndex = uniqueMetas.findIndex(function (x) { - return x.pubkey.equals(signature.publicKey); - }); + }, _data2); - if (uniqueIndex > -1) { - if (!uniqueMetas[uniqueIndex].isSigner) { - uniqueMetas[uniqueIndex].isSigner = true; - console.warn('Transaction references a signature that is unnecessary, ' + 'only the fee payer and instruction signer accounts should sign a transaction. ' + 'This behavior is deprecated and will throw an error in the next major version release.'); - } - } else { - throw new Error("unknown signer: ".concat(signature.publicKey.toString())); + _transaction2 = new Transaction().add({ + keys: [{ + pubkey: program.publicKey, + isSigner: true, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: programId, + data: _data2 + }); + _context5.next = 47; + return sendAndConfirmTransaction(connection, _transaction2, [payer, program], { + commitment: 'confirmed' + }); + + case 47: + return _context5.abrupt("return", true); + + case 48: + case "end": + return _context5.stop(); } - }; + }, _callee5); + })); - for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { - _loop3(); - } - } catch (err) { - _iterator12.e(err); - } finally { - _iterator12.f(); + function load(_x13, _x14, _x15, _x16, _x17) { + return _load.apply(this, arguments); } - var numRequiredSignatures = 0; - var numReadonlySignedAccounts = 0; - var numReadonlyUnsignedAccounts = 0; // Split out signing from non-signing keys and count header values + return load; + }() + }]); - var signedKeys = []; - var unsignedKeys = []; - uniqueMetas.forEach(function (_ref19) { - var pubkey = _ref19.pubkey, - isSigner = _ref19.isSigner, - isWritable = _ref19.isWritable; + return Loader; + }(); - if (isSigner) { - signedKeys.push(pubkey.toString()); - numRequiredSignatures += 1; + Loader.chunkSize = CHUNK_SIZE; + var BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111'); + /** + * Factory class for transactions to interact with a program loader + */ - if (!isWritable) { - numReadonlySignedAccounts += 1; - } - } else { - unsignedKeys.push(pubkey.toString()); + var BpfLoader = /*#__PURE__*/function () { + function BpfLoader() { + _classCallCheck(this, BpfLoader); + } - if (!isWritable) { - numReadonlyUnsignedAccounts += 1; - } - } - }); - var accountKeys = signedKeys.concat(unsignedKeys); - var compiledInstructions = instructions.map(function (instruction) { - var data = instruction.data, - programId = instruction.programId; - return { - programIdIndex: accountKeys.indexOf(programId.toString()), - accounts: instruction.keys.map(function (meta) { - return accountKeys.indexOf(meta.pubkey.toString()); - }), - data: bs58$1.encode(data) - }; - }); - compiledInstructions.forEach(function (instruction) { - assert(instruction.programIdIndex >= 0); - instruction.accounts.forEach(function (keyIndex) { - return assert(keyIndex >= 0); - }); - }); - return new Message({ - header: { - numRequiredSignatures: numRequiredSignatures, - numReadonlySignedAccounts: numReadonlySignedAccounts, - numReadonlyUnsignedAccounts: numReadonlyUnsignedAccounts - }, - accountKeys: accountKeys, - recentBlockhash: recentBlockhash, - instructions: compiledInstructions - }); - } + _createClass(BpfLoader, null, [{ + key: "getMinNumSignatures", + value: /** - * @internal + * Minimum number of signatures required to load a program not including + * retries + * + * Can be used to calculate transaction fees */ - - }, { - key: "_compile", - value: function _compile() { - var message = this.compileMessage(); - var signedKeys = message.accountKeys.slice(0, message.header.numRequiredSignatures); - - if (this.signatures.length === signedKeys.length) { - var valid = this.signatures.every(function (pair, index) { - return signedKeys[index].equals(pair.publicKey); - }); - if (valid) return message; - } - - this.signatures = signedKeys.map(function (publicKey) { - return { - signature: null, - publicKey: publicKey - }; - }); - return message; + function getMinNumSignatures(dataLength) { + return Loader.getMinNumSignatures(dataLength); } /** - * Get a buffer of the Transaction data that need to be covered by signatures + * Load a SBF program + * + * @param connection The connection to use + * @param payer Account that will pay program loading fees + * @param program Account to load the program into + * @param elf The entire ELF containing the SBF program + * @param loaderProgramId The program id of the BPF loader to use + * @return true if program was loaded successfully, false if program was already loaded */ }, { - key: "serializeMessage", - value: function serializeMessage() { - return this._compile().serialize(); + key: "load", + value: function load(connection, payer, program, elf, loaderProgramId) { + return Loader.load(connection, payer, program, loaderProgramId, elf); } - /** - * Get the estimated fee associated with a transaction - */ + }]); - }, { - key: "getEstimatedFee", - value: function () { - var _getEstimatedFee = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(connection) { - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return connection.getFeeForMessage(this.compileMessage()); + return BpfLoader; + }(); - case 2: - return _context4.abrupt("return", _context4.sent.value); + var objToString = Object.prototype.toString; - case 3: - case "end": - return _context4.stop(); - } - }, _callee4, this); - })); + var objKeys = Object.keys || function (obj) { + var keys = []; - function getEstimatedFee(_x8) { - return _getEstimatedFee.apply(this, arguments); - } + for (var name in obj) { + keys.push(name); + } - return getEstimatedFee; - }() - /** - * Specify the public keys which will be used to sign the Transaction. - * The first signer will be used as the transaction fee payer account. - * - * Signatures can be added with either `partialSign` or `addSignature` - * - * @deprecated Deprecated since v0.84.0. Only the fee payer needs to be - * specified and it can be set in the Transaction constructor or with the - * `feePayer` property. - */ + return keys; + }; - }, { - key: "setSigners", - value: function setSigners() { - for (var _len2 = arguments.length, signers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - signers[_key2] = arguments[_key2]; - } + function stringify(val, isArrayProp) { + var i, max, str, keys, key, propVal, toStr; - if (signers.length === 0) { - throw new Error('No signers'); - } + if (val === true) { + return "true"; + } - var seen = new Set(); - this.signatures = signers.filter(function (publicKey) { - var key = publicKey.toString(); + if (val === false) { + return "false"; + } - if (seen.has(key)) { - return false; - } else { - seen.add(key); - return true; - } - }).map(function (publicKey) { - return { - signature: null, - publicKey: publicKey - }; - }); - } - /** - * Sign the Transaction with the specified signers. Multiple signatures may - * be applied to a Transaction. The first signature is considered "primary" - * and is used identify and confirm transactions. - * - * If the Transaction `feePayer` is not set, the first signer will be used - * as the transaction fee payer account. - * - * Transaction fields should not be modified after the first call to `sign`, - * as doing so may invalidate the signature and cause the Transaction to be - * rejected. - * - * The Transaction must be assigned a valid `recentBlockhash` before invoking this method - */ + switch (_typeof$1(val)) { + case "object": + if (val === null) { + return null; + } else if (val.toJSON && typeof val.toJSON === "function") { + return stringify(val.toJSON(), isArrayProp); + } else { + toStr = objToString.call(val); - }, { - key: "sign", - value: function sign() { - for (var _len3 = arguments.length, signers = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - signers[_key3] = arguments[_key3]; - } + if (toStr === "[object Array]") { + str = '['; + max = val.length - 1; + + for (i = 0; i < max; i++) { + str += stringify(val[i], true) + ','; + } + + if (max > -1) { + str += stringify(val[i], true); + } + + return str + ']'; + } else if (toStr === "[object Object]") { + // only object is left + keys = objKeys(val).sort(); + max = keys.length; + str = ""; + i = 0; - if (signers.length === 0) { - throw new Error('No signers'); - } // Dedupe signers + while (i < max) { + key = keys[i]; + propVal = stringify(val[key], false); + if (propVal !== undefined) { + if (str) { + str += ','; + } - var seen = new Set(); - var uniqueSigners = []; + str += JSON.stringify(key) + ':' + propVal; + } - for (var _i7 = 0, _signers = signers; _i7 < _signers.length; _i7++) { - var signer = _signers[_i7]; - var key = signer.publicKey.toString(); + i++; + } - if (seen.has(key)) { - continue; + return '{' + str + '}'; } else { - seen.add(key); - uniqueSigners.push(signer); + return JSON.stringify(val); } } - this.signatures = uniqueSigners.map(function (signer) { - return { - signature: null, - publicKey: signer.publicKey - }; - }); + case "function": + case "undefined": + return isArrayProp ? null : undefined; - var message = this._compile(); + case "string": + return JSON.stringify(val); - this._partialSign.apply(this, [message].concat(uniqueSigners)); - } - /** - * Partially sign a transaction with the specified accounts. All accounts must - * correspond to either the fee payer or a signer account in the transaction - * instructions. - * - * All the caveats from the `sign` method apply to `partialSign` - */ + default: + return isFinite(val) ? val : null; + } + } - }, { - key: "partialSign", - value: function partialSign() { - for (var _len4 = arguments.length, signers = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - signers[_key4] = arguments[_key4]; - } + var fastStableStringify = function fastStableStringify(val) { + var returnVal = stringify(val, false); - if (signers.length === 0) { - throw new Error('No signers'); - } // Dedupe signers + if (returnVal !== undefined) { + return '' + returnVal; + } + }; + var fastStableStringify$1 = fastStableStringify; + var MINIMUM_SLOT_PER_EPOCH = 32; // Returns the number of trailing zeros in the binary representation of self. - var seen = new Set(); - var uniqueSigners = []; + function trailingZeros(n) { + var trailingZeros = 0; - for (var _i8 = 0, _signers2 = signers; _i8 < _signers2.length; _i8++) { - var signer = _signers2[_i8]; - var key = signer.publicKey.toString(); + while (n > 1) { + n /= 2; + trailingZeros++; + } - if (seen.has(key)) { - continue; - } else { - seen.add(key); - uniqueSigners.push(signer); - } - } + return trailingZeros; + } // Returns the smallest power of two greater than or equal to n - var message = this._compile(); - this._partialSign.apply(this, [message].concat(uniqueSigners)); - } - /** - * @internal - */ + function nextPowerOfTwo(n) { + if (n === 0) return 1; + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; + n |= n >> 32; + return n + 1; + } + /** + * Epoch schedule + * (see https://docs.solana.com/terminology#epoch) + * Can be retrieved with the {@link Connection.getEpochSchedule} method + */ - }, { - key: "_partialSign", - value: function _partialSign(message) { - var _this10 = this; - var signData = message.serialize(); + var EpochSchedule = /*#__PURE__*/function () { + /** The maximum number of slots in each epoch */ - for (var _len5 = arguments.length, signers = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - signers[_key5 - 1] = arguments[_key5]; - } + /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */ - signers.forEach(function (signer) { - var signature = _sign(signData, signer.secretKey); + /** Indicates whether epochs start short and grow */ - _this10._addSignature(signer.publicKey, toBuffer(signature)); - }); - } - /** - * Add an externally created signature to a transaction. The public key - * must correspond to either the fee payer or a signer account in the transaction - * instructions. - */ + /** The first epoch with `slotsPerEpoch` slots */ - }, { - key: "addSignature", - value: function addSignature(pubkey, signature) { - this._compile(); // Ensure signatures array is populated + /** The first slot of `firstNormalEpoch` */ + function EpochSchedule(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) { + _classCallCheck(this, EpochSchedule); + this.slotsPerEpoch = void 0; + this.leaderScheduleSlotOffset = void 0; + this.warmup = void 0; + this.firstNormalEpoch = void 0; + this.firstNormalSlot = void 0; + this.slotsPerEpoch = slotsPerEpoch; + this.leaderScheduleSlotOffset = leaderScheduleSlotOffset; + this.warmup = warmup; + this.firstNormalEpoch = firstNormalEpoch; + this.firstNormalSlot = firstNormalSlot; + } - this._addSignature(pubkey, signature); + _createClass(EpochSchedule, [{ + key: "getEpoch", + value: function getEpoch(slot) { + return this.getEpochAndSlotIndex(slot)[0]; } - /** - * @internal - */ - }, { - key: "_addSignature", - value: function _addSignature(pubkey, signature) { - assert(signature.length === 64); - var index = this.signatures.findIndex(function (sigpair) { - return pubkey.equals(sigpair.publicKey); - }); + key: "getEpochAndSlotIndex", + value: function getEpochAndSlotIndex(slot) { + if (slot < this.firstNormalSlot) { + var epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1; + var epochLen = this.getSlotsInEpoch(epoch); + var slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH); + return [epoch, slotIndex]; + } else { + var normalSlotIndex = slot - this.firstNormalSlot; + var normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch); - if (index < 0) { - throw new Error("unknown signer: ".concat(pubkey.toString())); - } + var _epoch = this.firstNormalEpoch + normalEpochIndex; - this.signatures[index].signature = Buffer$1.from(signature); - } - /** - * Verify signatures of a Transaction - * Optional parameter specifies if we're expecting a fully signed Transaction or a partially signed one. - * If no boolean is provided, we expect a fully signed Transaction by default. - */ + var _slotIndex = normalSlotIndex % this.slotsPerEpoch; + return [_epoch, _slotIndex]; + } + } }, { - key: "verifySignatures", - value: function verifySignatures(requireAllSignatures) { - return this._verifySignatures(this.serializeMessage(), requireAllSignatures === undefined ? true : requireAllSignatures); + key: "getFirstSlotInEpoch", + value: function getFirstSlotInEpoch(epoch) { + if (epoch <= this.firstNormalEpoch) { + return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH; + } else { + return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot; + } } - /** - * @internal - */ - }, { - key: "_verifySignatures", - value: function _verifySignatures(signData, requireAllSignatures) { - var _iterator13 = _createForOfIteratorHelper(this.signatures), - _step13; - - try { - for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { - var _step13$value2 = _step13.value, - _signature = _step13$value2.signature, - _publicKey = _step13$value2.publicKey; - - if (_signature === null) { - if (requireAllSignatures) { - return false; - } - } else { - if (!verify(_signature, signData, _publicKey.toBytes())) { - return false; - } - } - } - } catch (err) { - _iterator13.e(err); - } finally { - _iterator13.f(); + key: "getLastSlotInEpoch", + value: function getLastSlotInEpoch(epoch) { + return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1; + } + }, { + key: "getSlotsInEpoch", + value: function getSlotsInEpoch(epoch) { + if (epoch < this.firstNormalEpoch) { + return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH)); + } else { + return this.slotsPerEpoch; } - - return true; } - /** - * Serialize the Transaction in the wire format. - */ + }]); - }, { - key: "serialize", - value: function serialize(config) { - var _Object$assign = Object.assign({ - requireAllSignatures: true, - verifySignatures: true - }, config), - requireAllSignatures = _Object$assign.requireAllSignatures, - verifySignatures = _Object$assign.verifySignatures; + return EpochSchedule; + }(); - var signData = this.serializeMessage(); + var SendTransactionError = /*#__PURE__*/function (_Error4) { + _inherits(SendTransactionError, _Error4); - if (verifySignatures && !this._verifySignatures(signData, requireAllSignatures)) { - throw new Error('Signature verification failed'); - } + var _super6 = _createSuper(SendTransactionError); - return this._serialize(signData); - } - /** - * @internal - */ + function SendTransactionError(message, logs) { + var _this12; - }, { - key: "_serialize", - value: function _serialize(signData) { - var signatures = this.signatures; - var signatureCount = []; - encodeLength(signatureCount, signatures.length); - var transactionLength = signatureCount.length + signatures.length * 64 + signData.length; - var wireTransaction = Buffer$1.alloc(transactionLength); - assert(signatures.length < 256); - Buffer$1.from(signatureCount).copy(wireTransaction, 0); - signatures.forEach(function (_ref20, index) { - var signature = _ref20.signature; + _classCallCheck(this, SendTransactionError); - if (signature !== null) { - assert(signature.length === 64, "signature has invalid length"); - Buffer$1.from(signature).copy(wireTransaction, signatureCount.length + index * 64); - } - }); - signData.copy(wireTransaction, signatureCount.length + signatures.length * 64); - assert(wireTransaction.length <= PACKET_DATA_SIZE, "Transaction too large: ".concat(wireTransaction.length, " > ").concat(PACKET_DATA_SIZE)); - return wireTransaction; - } - /** - * Deprecated method - * @internal - */ + _this12 = _super6.call(this, message); + _this12.logs = void 0; + _this12.logs = logs; + return _this12; + } - }, { - key: "keys", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].keys.map(function (keyObj) { - return keyObj.pubkey; - }); - } - /** - * Deprecated method - * @internal - */ + return _createClass(SendTransactionError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); // Keep in sync with client/src/rpc_custom_errors.rs + // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - }, { - key: "programId", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].programId; - } - /** - * Deprecated method - * @internal - */ - }, { - key: "data", - get: function get() { - assert(this.instructions.length === 1); - return this.instructions[0].data; - } - /** - * Parse a wire transaction into a Transaction object. - */ + var SolanaJSONRPCErrorCode = { + JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001, + JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002, + JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003, + JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004, + JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005, + JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006, + JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007, + JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008, + JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009, + JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010, + JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011, + JSON_RPC_SCAN_ERROR: -32012, + JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013, + JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014, + JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015, + JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016 + }; - }], [{ - key: "from", - value: function from(buffer) { - // Slice up wire data - var byteArray = _toConsumableArray(buffer); + var SolanaJSONRPCError = /*#__PURE__*/function (_Error5) { + _inherits(SolanaJSONRPCError, _Error5); - var signatureCount = decodeLength(byteArray); - var signatures = []; + var _super7 = _createSuper(SolanaJSONRPCError); - for (var i = 0; i < signatureCount; i++) { - var _signature2 = byteArray.slice(0, SIGNATURE_LENGTH_IN_BYTES); + function SolanaJSONRPCError(_ref21, customMessage) { + var _this13; - byteArray = byteArray.slice(SIGNATURE_LENGTH_IN_BYTES); - signatures.push(bs58$1.encode(Buffer$1.from(_signature2))); - } + var code = _ref21.code, + message = _ref21.message, + data = _ref21.data; - return Transaction.populate(Message.from(byteArray), signatures); - } - /** - * Populate Transaction object from message and signatures - */ + _classCallCheck(this, SolanaJSONRPCError); - }, { - key: "populate", - value: function populate(message) { - var signatures = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var transaction = new Transaction(); - transaction.recentBlockhash = message.recentBlockhash; + _this13 = _super7.call(this, customMessage != null ? "".concat(customMessage, ": ").concat(message) : message); + _this13.code = void 0; + _this13.data = void 0; + _this13.code = code; + _this13.data = data; + _this13.name = 'SolanaJSONRPCError'; + return _this13; + } - if (message.header.numRequiredSignatures > 0) { - transaction.feePayer = message.accountKeys[0]; - } + return _createClass(SolanaJSONRPCError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - signatures.forEach(function (signature, index) { - var sigPubkeyPair = { - signature: signature == bs58$1.encode(DEFAULT_SIGNATURE) ? null : bs58$1.decode(signature), - publicKey: message.accountKeys[index] - }; - transaction.signatures.push(sigPubkeyPair); - }); - message.instructions.forEach(function (instruction) { - var keys = instruction.accounts.map(function (account) { - var pubkey = message.accountKeys[account]; - return { - pubkey: pubkey, - isSigner: transaction.signatures.some(function (keyObj) { - return keyObj.publicKey.toString() === pubkey.toString(); - }) || message.isAccountSigner(account), - isWritable: message.isAccountWritable(account) - }; - }); - transaction.instructions.push(new TransactionInstruction({ - keys: keys, - programId: message.accountKeys[instruction.programIdIndex], - data: bs58$1.decode(instruction.data) - })); - }); - transaction._message = message; - transaction._json = transaction.toJSON(); - return transaction; - } - }]); + var fetchImpl = globalThis.fetch; - return Transaction; - }(); + var RpcWebSocketClient = /*#__PURE__*/function (_RpcWebSocketCommonCl) { + _inherits(RpcWebSocketClient, _RpcWebSocketCommonCl); - var TransactionMessage = /*#__PURE__*/function () { - function TransactionMessage(args) { - _classCallCheck(this, TransactionMessage); + var _super8 = _createSuper(RpcWebSocketClient); - this.payerKey = void 0; - this.instructions = void 0; - this.recentBlockhash = void 0; - this.payerKey = args.payerKey; - this.instructions = args.instructions; - this.recentBlockhash = args.recentBlockhash; - } + function RpcWebSocketClient(address, options, generate_request_id) { + var _this14; - _createClass(TransactionMessage, [{ - key: "compileToLegacyMessage", - value: function compileToLegacyMessage() { - return Message.compile({ - payerKey: this.payerKey, - recentBlockhash: this.recentBlockhash, - instructions: this.instructions - }); - } - }, { - key: "compileToV0Message", - value: function compileToV0Message(addressLookupTableAccounts) { - return MessageV0.compile({ - payerKey: this.payerKey, - recentBlockhash: this.recentBlockhash, - instructions: this.instructions, - addressLookupTableAccounts: addressLookupTableAccounts - }); - } - }], [{ - key: "decompile", - value: function decompile(message, args) { - var header = message.header, - compiledInstructions = message.compiledInstructions, - recentBlockhash = message.recentBlockhash; - var numRequiredSignatures = header.numRequiredSignatures, - numReadonlySignedAccounts = header.numReadonlySignedAccounts, - numReadonlyUnsignedAccounts = header.numReadonlyUnsignedAccounts; - var numWritableSignedAccounts = numRequiredSignatures - numReadonlySignedAccounts; - assert(numWritableSignedAccounts > 0, 'Message header is invalid'); - var numWritableUnsignedAccounts = message.staticAccountKeys.length - numRequiredSignatures - numReadonlyUnsignedAccounts; - assert(numWritableUnsignedAccounts >= 0, 'Message header is invalid'); - var accountKeys = message.getAccountKeys(args); - var payerKey = accountKeys.get(0); + _classCallCheck(this, RpcWebSocketClient); - if (payerKey === undefined) { - throw new Error('Failed to decompile message because no account keys were found'); - } + var webSocketFactory = function webSocketFactory(url) { + var rpc = createRpc(url, _objectSpread2({ + autoconnect: true, + max_reconnects: 5, + reconnect: true, + reconnect_interval: 1000 + }, options)); - var instructions = []; + if ('socket' in rpc) { + _this14.underlyingSocket = rpc.socket; + } else { + _this14.underlyingSocket = rpc; + } - var _iterator14 = _createForOfIteratorHelper(compiledInstructions), - _step14; + return rpc; + }; - try { - for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { - var compiledIx = _step14.value; - var keys = []; + _this14 = _super8.call(this, webSocketFactory, address, options, generate_request_id); + _this14.underlyingSocket = void 0; + return _this14; + } - var _iterator15 = _createForOfIteratorHelper(compiledIx.accountKeyIndexes), - _step15; + _createClass(RpcWebSocketClient, [{ + key: "call", + value: function call() { + var _this$underlyingSocke; - try { - for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { - var keyIndex = _step15.value; - var pubkey = accountKeys.get(keyIndex); + var readyState = (_this$underlyingSocke = this.underlyingSocket) === null || _this$underlyingSocke === void 0 ? void 0 : _this$underlyingSocke.readyState; - if (pubkey === undefined) { - throw new Error("Failed to find key for account key index ".concat(keyIndex)); - } + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } - var isSigner = keyIndex < numRequiredSignatures; - var isWritable = void 0; + if (readyState === 1 + /* WebSocket.OPEN */ + ) { + var _get2; - if (isSigner) { - isWritable = keyIndex < numWritableSignedAccounts; - } else if (keyIndex < accountKeys.staticAccountKeys.length) { - isWritable = keyIndex - numRequiredSignatures < numWritableUnsignedAccounts; - } else { - isWritable = keyIndex - accountKeys.staticAccountKeys.length < // accountKeysFromLookups cannot be undefined because we already found a pubkey for this index above - accountKeys.accountKeysFromLookups.writable.length; - } + return (_get2 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "call", this)).call.apply(_get2, [this].concat(args)); + } - keys.push({ - pubkey: pubkey, - isSigner: keyIndex < header.numRequiredSignatures, - isWritable: isWritable - }); - } - } catch (err) { - _iterator15.e(err); - } finally { - _iterator15.f(); - } + return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); + } + }, { + key: "notify", + value: function notify() { + var _this$underlyingSocke2; - var programId = accountKeys.get(compiledIx.programIdIndex); + var readyState = (_this$underlyingSocke2 = this.underlyingSocket) === null || _this$underlyingSocke2 === void 0 ? void 0 : _this$underlyingSocke2.readyState; - if (programId === undefined) { - throw new Error("Failed to find program id for program id index ".concat(compiledIx.programIdIndex)); - } + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } - instructions.push(new TransactionInstruction({ - programId: programId, - data: toBuffer(compiledIx.data), - keys: keys - })); - } - } catch (err) { - _iterator14.e(err); - } finally { - _iterator14.f(); + if (readyState === 1 + /* WebSocket.OPEN */ + ) { + var _get3; + + return (_get3 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "notify", this)).call.apply(_get3, [this].concat(args)); } - return new TransactionMessage({ - payerKey: payerKey, - instructions: instructions, - recentBlockhash: recentBlockhash - }); + return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); } }]); - return TransactionMessage; - }(); + return RpcWebSocketClient; + }(RpcWebSocketCommonClient); // TODO: These constants should be removed in favor of reading them out of a + // Syscall account + /** - * Versioned transaction class + * @internal */ - var VersionedTransaction = /*#__PURE__*/function () { - function VersionedTransaction(message, signatures) { - _classCallCheck(this, VersionedTransaction); + var NUM_TICKS_PER_SECOND = 160; + /** + * @internal + */ - this.signatures = void 0; - this.message = void 0; + var DEFAULT_TICKS_PER_SLOT = 64; + /** + * @internal + */ - if (signatures !== undefined) { - assert(signatures.length === message.header.numRequiredSignatures, 'Expected signatures length to be equal to the number of required signatures'); - this.signatures = signatures; - } else { - var defaultSignatures = []; + var NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT; + /** + * @internal + */ - for (var i = 0; i < message.header.numRequiredSignatures; i++) { - defaultSignatures.push(new Uint8Array(SIGNATURE_LENGTH_IN_BYTES)); - } + var MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND; + /** + * @internal + */ - this.signatures = defaultSignatures; - } + /** + * Decode account data buffer using an AccountType + * @internal + */ - this.message = message; + function decodeData(type, data) { + var decoded; + + try { + decoded = type.layout.decode(data); + } catch (err) { + throw new Error('invalid instruction; ' + err); } - _createClass(VersionedTransaction, [{ - key: "version", - get: function get() { - return this.message.version; - } - }, { - key: "serialize", - value: function serialize() { - var serializedMessage = this.message.serialize(); - var encodedSignaturesLength = Array(); - encodeLength(encodedSignaturesLength, this.signatures.length); - var transactionLayout = struct([blob$1(encodedSignaturesLength.length, 'encodedSignaturesLength'), seq$1(signature(), this.signatures.length, 'signatures'), blob$1(serializedMessage.length, 'serializedMessage')]); - var serializedTransaction = new Uint8Array(2048); - var serializedTransactionLength = transactionLayout.encode({ - encodedSignaturesLength: new Uint8Array(encodedSignaturesLength), - signatures: this.signatures, - serializedMessage: serializedMessage - }, serializedTransaction); - return serializedTransaction.slice(0, serializedTransactionLength); - } - }, { - key: "sign", - value: function sign(signers) { - var _this11 = this; + if (decoded.typeIndex !== type.index) { + throw new Error("invalid account data; account type mismatch ".concat(decoded.typeIndex, " != ").concat(type.index)); + } - var messageData = this.message.serialize(); - var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); + return decoded; + } /// The serialized size of lookup table metadata - var _iterator16 = _createForOfIteratorHelper(signers), - _step16; - try { - var _loop4 = function _loop4() { - var signer = _step16.value; - var signerIndex = signerPubkeys.findIndex(function (pubkey) { - return pubkey.equals(signer.publicKey); - }); - assert(signerIndex >= 0, "Cannot sign with non signer key ".concat(signer.publicKey.toBase58())); - _this11.signatures[signerIndex] = _sign(messageData, signer.secretKey); - }; + var LOOKUP_TABLE_META_SIZE = 56; - for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { - _loop4(); - } - } catch (err) { - _iterator16.e(err); - } finally { - _iterator16.f(); - } - } - }, { - key: "addSignature", - value: function addSignature(publicKey, signature) { - assert(signature.byteLength === 64, 'Signature must be 64 bytes long'); - var signerPubkeys = this.message.staticAccountKeys.slice(0, this.message.header.numRequiredSignatures); - var signerIndex = signerPubkeys.findIndex(function (pubkey) { - return pubkey.equals(publicKey); - }); - assert(signerIndex >= 0, "Can not add signature; `".concat(publicKey.toBase58(), "` is not required to sign this transaction")); - this.signatures[signerIndex] = signature; + var AddressLookupTableAccount = /*#__PURE__*/function () { + function AddressLookupTableAccount(args) { + _classCallCheck(this, AddressLookupTableAccount); + + this.key = void 0; + this.state = void 0; + this.key = args.key; + this.state = args.state; + } + + _createClass(AddressLookupTableAccount, [{ + key: "isActive", + value: function isActive() { + var U64_MAX = BigInt('0xffffffffffffffff'); + return this.state.deactivationSlot === U64_MAX; } }], [{ key: "deserialize", - value: function deserialize(serializedTransaction) { - var byteArray = _toConsumableArray(serializedTransaction); - - var signatures = []; - var signaturesLength = decodeLength(byteArray); + value: function deserialize(accountData) { + var meta = decodeData(LookupTableMetaLayout, accountData); + var serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE; + assert(serializedAddressesLen >= 0, 'lookup table is invalid'); + assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid'); + var numSerializedAddresses = serializedAddressesLen / 32; - for (var i = 0; i < signaturesLength; i++) { - signatures.push(new Uint8Array(byteArray.splice(0, SIGNATURE_LENGTH_IN_BYTES))); - } + var _BufferLayout$struct$ = struct([seq$1(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE)), + addresses = _BufferLayout$struct$.addresses; - var message = VersionedMessage.deserialize(new Uint8Array(byteArray)); - return new VersionedTransaction(message, signatures); + return { + deactivationSlot: meta.deactivationSlot, + lastExtendedSlot: meta.lastExtendedSlot, + lastExtendedSlotStartIndex: meta.lastExtendedStartIndex, + authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined, + addresses: addresses.map(function (address) { + return new PublicKey(address); + }) + }; } }]); - return VersionedTransaction; + return AddressLookupTableAccount; }(); - var SYSVAR_CLOCK_PUBKEY = new PublicKey('SysvarC1ock11111111111111111111111111111111'); - var SYSVAR_EPOCH_SCHEDULE_PUBKEY = new PublicKey('SysvarEpochSchedu1e111111111111111111111111'); - var SYSVAR_INSTRUCTIONS_PUBKEY = new PublicKey('Sysvar1nstructions1111111111111111111111111'); - var SYSVAR_RECENT_BLOCKHASHES_PUBKEY = new PublicKey('SysvarRecentB1ockHashes11111111111111111111'); - var SYSVAR_RENT_PUBKEY = new PublicKey('SysvarRent111111111111111111111111111111111'); - var SYSVAR_REWARDS_PUBKEY = new PublicKey('SysvarRewards111111111111111111111111111111'); - var SYSVAR_SLOT_HASHES_PUBKEY = new PublicKey('SysvarS1otHashes111111111111111111111111111'); - var SYSVAR_SLOT_HISTORY_PUBKEY = new PublicKey('SysvarS1otHistory11111111111111111111111111'); - var SYSVAR_STAKE_HISTORY_PUBKEY = new PublicKey('SysvarStakeHistory1111111111111111111111111'); - /** - * Sign, send and confirm a transaction. - * - * If `commitment` option is not specified, defaults to 'max' commitment. - * - * @param {Connection} connection - * @param {Transaction} transaction - * @param {Array} signers - * @param {ConfirmOptions} [options] - * @returns {Promise} - */ - - function sendAndConfirmTransaction(_x9, _x10, _x11, _x12) { - return _sendAndConfirmTransaction.apply(this, arguments); - } // zzz + var LookupTableMetaLayout = { + index: 1, + layout: struct([u32('typeIndex'), u64('deactivationSlot'), nu64$1('lastExtendedSlot'), u8('lastExtendedStartIndex'), u8(), // option + seq$1(publicKey(), offset$1(u8(), -1), 'authority')]) + }; + var URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i; + function makeWebsocketUrl(endpoint) { + var matches = endpoint.match(URL_RE); - function _sendAndConfirmTransaction() { - _sendAndConfirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee108(connection, transaction, signers, options) { - var sendOptions, signature, status, nonceInstruction, nonceAccountPubkey; - return _regeneratorRuntime().wrap(function _callee108$(_context108) { - while (1) switch (_context108.prev = _context108.next) { - case 0: - sendOptions = options && { - skipPreflight: options.skipPreflight, - preflightCommitment: options.preflightCommitment || options.commitment, - maxRetries: options.maxRetries, - minContextSlot: options.minContextSlot - }; - _context108.next = 3; - return connection.sendTransaction(transaction, signers, sendOptions); + if (matches == null) { + throw TypeError("Failed to validate endpoint URL `".concat(endpoint, "`")); + } - case 3: - signature = _context108.sent; + var _matches = _slicedToArray(matches, 4); + _matches[0]; + var // eslint-disable-line @typescript-eslint/no-unused-vars + hostish = _matches[1], + portWithColon = _matches[2], + rest = _matches[3]; - if (!(transaction.recentBlockhash != null && transaction.lastValidBlockHeight != null)) { - _context108.next = 10; - break; - } + var protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:'; + var startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10); + var websocketPort = // Only shift the port by +1 as a convention for ws(s) only if given endpoint + // is explictly specifying the endpoint port (HTTP-based RPC), assuming + // we're directly trying to connect to solana-validator's ws listening port. + // When the endpoint omits the port, we're connecting to the protocol + // default ports: http(80) or https(443) and it's assumed we're behind a reverse + // proxy which manages WebSocket upgrade and backend port redirection. + startPort == null ? '' : ":".concat(startPort + 1); + return "".concat(protocol, "//").concat(hostish).concat(websocketPort).concat(rest); + } - _context108.next = 7; - return connection.confirmTransaction({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - signature: signature, - blockhash: transaction.recentBlockhash, - lastValidBlockHeight: transaction.lastValidBlockHeight - }, options && options.commitment); + var PublicKeyFromString = coerce(instance(PublicKey), string(), function (value) { + return new PublicKey(value); + }); + var RawAccountDataResult = tuple([string(), literal('base64')]); + var BufferFromRawAccountData = coerce(instance(Buffer$1), RawAccountDataResult, function (value) { + return Buffer$1.from(value[0], 'base64'); + }); + /** + * Attempt to use a recent blockhash for up to 30 seconds + * @internal + */ - case 7: - status = _context108.sent.value; - _context108.next = 22; - break; + var BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; + /** + * HACK. + * Copied from rpc-websockets/dist/lib/client. + * Otherwise, `yarn build` fails with: + * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d + */ - case 10: - if (!(transaction.minNonceContextSlot != null && transaction.nonceInfo != null)) { - _context108.next = 18; - break; - } + /* @internal */ - nonceInstruction = transaction.nonceInfo.nonceInstruction; - nonceAccountPubkey = nonceInstruction.keys[0].pubkey; - _context108.next = 15; - return connection.confirmTransaction({ - abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, - minContextSlot: transaction.minNonceContextSlot, - nonceAccountPubkey: nonceAccountPubkey, - nonceValue: transaction.nonceInfo.nonce, - signature: signature - }, options && options.commitment); + function assertEndpointUrl(putativeUrl) { + if (/^https?:/.test(putativeUrl) === false) { + throw new TypeError('Endpoint URL must start with `http:` or `https:`.'); + } - case 15: - status = _context108.sent.value; - _context108.next = 22; - break; + return putativeUrl; + } + /** @internal */ - case 18: - if ((options === null || options === void 0 ? void 0 : options.abortSignal) != null) { - console.warn('sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was ' + 'supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` ' + 'or a combination of `nonceInfo` and `minNonceContextSlot` are abortable.'); - } - _context108.next = 21; - return connection.confirmTransaction(signature, options && options.commitment); + function extractCommitmentFromConfig(commitmentOrConfig) { + var commitment; + var config; - case 21: - status = _context108.sent.value; + if (typeof commitmentOrConfig === 'string') { + commitment = commitmentOrConfig; + } else if (commitmentOrConfig) { + var specifiedCommitment = commitmentOrConfig.commitment, + specifiedConfig = _objectWithoutProperties(commitmentOrConfig, _excluded); - case 22: - if (!status.err) { - _context108.next = 24; - break; - } + commitment = specifiedCommitment; + config = specifiedConfig; + } - throw new Error("Transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + return { + commitment: commitment, + config: config + }; + } + /** + * @internal + */ - case 24: - return _context108.abrupt("return", signature); - case 25: - case "end": - return _context108.stop(); - } - }, _callee108); - })); - return _sendAndConfirmTransaction.apply(this, arguments); + function createRpcResult(result) { + return union([type({ + jsonrpc: literal('2.0'), + id: string(), + result: result + }), type({ + jsonrpc: literal('2.0'), + id: string(), + error: type({ + code: unknown(), + message: string(), + data: optional(any()) + }) + })]); } - function sleep(ms) { - return new Promise(function (resolve) { - return setTimeout(resolve, ms); + var UnknownRpcResult = createRpcResult(unknown()); + /** + * @internal + */ + + function jsonRpcResult(schema) { + return coerce(createRpcResult(schema), UnknownRpcResult, function (value) { + if ('error' in value) { + return value; + } else { + return _objectSpread2(_objectSpread2({}, value), {}, { + result: _create(value.result, schema) + }); + } }); } /** - * Populate a buffer of instruction data using an InstructionType * @internal */ - function encodeData(type, fields) { - var allocLength = type.layout.span >= 0 ? type.layout.span : getAlloc(type, fields); - var data = Buffer$1.alloc(allocLength); - var layoutFields = Object.assign({ - instruction: type.index - }, fields); - type.layout.encode(layoutFields, data); - return data; + function jsonRpcResultAndContext(value) { + return jsonRpcResult(type({ + context: type({ + slot: number() + }), + value: value + })); } /** - * Decode instruction data buffer using an InstructionType * @internal */ - function decodeData$1(type, buffer) { - var data; + function notificationResultAndContext(value) { + return type({ + context: type({ + slot: number() + }), + value: value + }); + } + /** + * @internal + */ - try { - data = type.layout.decode(buffer); - } catch (err) { - throw new Error('invalid instruction; ' + err); - } - if (data.instruction !== type.index) { - throw new Error("invalid instruction; instruction index mismatch ".concat(data.instruction, " != ").concat(type.index)); + function versionedMessageFromResponse(version, response) { + if (version === 0) { + return new MessageV0({ + header: response.header, + staticAccountKeys: response.accountKeys.map(function (accountKey) { + return new PublicKey(accountKey); + }), + recentBlockhash: response.recentBlockhash, + compiledInstructions: response.instructions.map(function (ix) { + return { + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accounts, + data: bs58$3.decode(ix.data) + }; + }), + addressTableLookups: response.addressTableLookups + }); + } else { + return new Message(response); } - - return data; } /** - * https://github.com/solana-labs/solana/blob/90bedd7e067b5b8f3ddbb45da00a4e9cabb22c62/sdk/src/fee_calculator.rs#L7-L11 - * - * @internal + * The level of commitment desired when querying state + *
+	 *   'processed': Query the most recent block which has reached 1 confirmation by the connected node
+	 *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
+	 *   'finalized': Query the most recent block which has been finalized by the cluster
+	 * 
+ */ + + + var GetInflationGovernorResult = type({ + foundation: number(), + foundationTerm: number(), + initial: number(), + taper: number(), + terminal: number() + }); + /** + * The inflation reward for an epoch */ - - var FeeCalculatorLayout = nu64$1('lamportsPerSignature'); /** - * Calculator for transaction fees. - * - * @deprecated Deprecated since Solana v1.8.0. + * Expected JSON RPC response for the "getInflationReward" message */ + var GetInflationRewardResult = jsonRpcResult(array(nullable(type({ + epoch: number(), + effectiveSlot: number(), + amount: number(), + postBalance: number(), + commission: optional(nullable(number())) + })))); /** - * See https://github.com/solana-labs/solana/blob/0ea2843ec9cdc517572b8e62c959f41b55cf4453/sdk/src/nonce_state.rs#L29-L32 - * - * @internal + * Expected JSON RPC response for the "getRecentPrioritizationFees" message */ - var NonceAccountLayout = struct([u32('version'), u32('state'), publicKey('authorizedPubkey'), publicKey('nonce'), struct([FeeCalculatorLayout], 'feeCalculator')]); - var NONCE_ACCOUNT_LENGTH = NonceAccountLayout.span; + var GetRecentPrioritizationFeesResult = array(type({ + slot: number(), + prioritizationFee: number() + })); /** - * A durable nonce is a 32 byte value encoded as a base58 string. + * Expected JSON RPC response for the "getInflationRate" message */ + var GetInflationRateResult = type({ + total: number(), + validator: number(), + foundation: number(), + epoch: number() + }); /** - * NonceAccount class + * Information about the current epoch */ - var NonceAccount = /*#__PURE__*/function () { - /** - * @internal - */ - function NonceAccount(args) { - _classCallCheck(this, NonceAccount); - - this.authorizedPubkey = void 0; - this.nonce = void 0; - this.feeCalculator = void 0; - this.authorizedPubkey = args.authorizedPubkey; - this.nonce = args.nonce; - this.feeCalculator = args.feeCalculator; - } - /** - * Deserialize NonceAccount from the account data. - * - * @param buffer account data - * @return NonceAccount - */ - - - _createClass(NonceAccount, null, [{ - key: "fromAccountData", - value: function fromAccountData(buffer) { - var nonceAccount = NonceAccountLayout.decode(toBuffer(buffer), 0); - return new NonceAccount({ - authorizedPubkey: new PublicKey(nonceAccount.authorizedPubkey), - nonce: new PublicKey(nonceAccount.nonce).toString(), - feeCalculator: nonceAccount.feeCalculator - }); - } - }]); - - return NonceAccount; - }(); - - var encodeDecode = function encodeDecode(layout) { - var decode = layout.decode.bind(layout); - var encode = layout.encode.bind(layout); - return { - decode: decode, - encode: encode - }; - }; - - var bigInt = function bigInt(length) { - return function (property) { - var layout = blob$1(length, property); - - var _encodeDecode = encodeDecode(layout), - encode = _encodeDecode.encode, - decode = _encodeDecode.decode; - - var bigIntLayout = layout; - - bigIntLayout.decode = function (buffer, offset) { - var src = decode(buffer, offset); - return toBigIntLE_1(Buffer$1.from(src)); - }; - - bigIntLayout.encode = function (bigInt, buffer, offset) { - var src = toBufferLE_1(bigInt, length); - return encode(src, buffer, offset); - }; - - return bigIntLayout; - }; - }; - - var u64 = bigInt(8); + var GetEpochInfoResult = type({ + epoch: number(), + slotIndex: number(), + slotsInEpoch: number(), + absoluteSlot: number(), + blockHeight: optional(number()), + transactionCount: optional(number()) + }); + var GetEpochScheduleResult = type({ + slotsPerEpoch: number(), + leaderScheduleSlotOffset: number(), + warmup: _boolean(), + firstNormalEpoch: number(), + firstNormalSlot: number() + }); /** - * Create account system transaction params + * Leader schedule + * (see https://docs.solana.com/terminology#leader-schedule) */ + var GetLeaderScheduleResult = record(string(), array(number())); /** - * System Instruction class + * Transaction error or null */ - var SystemInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function SystemInstruction() { - _classCallCheck(this, SystemInstruction); - } - /** - * Decode a system instruction and retrieve the instruction type. - */ - - - _createClass(SystemInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; - - for (var _i9 = 0, _Object$entries = Object.entries(SYSTEM_INSTRUCTION_LAYOUTS); _i9 < _Object$entries.length; _i9++) { - var _Object$entries$_i2 = _slicedToArray(_Object$entries[_i9], 2), - ixType = _Object$entries$_i2[0], - layout = _Object$entries$_i2[1]; - - if (layout.index == typeIndex) { - type = ixType; - break; - } - } + var TransactionErrorResult = nullable(union([type({}), string()])); + /** + * Signature status for a transaction + */ - if (!type) { - throw new Error('Instruction type incorrect; not a SystemInstruction'); - } + var SignatureStatusResult = type({ + err: TransactionErrorResult + }); + /** + * Transaction signature received notification + */ - return type; - } - /** - * Decode a create account system instruction and retrieve the instruction params. - */ + var SignatureReceivedResult = literal('receivedSignature'); + /** + * Version info for a node + */ - }, { - key: "decodeCreateAccount", - value: function decodeCreateAccount(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + var VersionResult = type({ + 'solana-core': string(), + 'feature-set': optional(number()) + }); + var SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({ + err: nullable(union([type({}), string()])), + logs: nullable(array(string())), + accounts: optional(nullable(array(nullable(type({ + executable: _boolean(), + owner: string(), + lamports: number(), + data: array(string()), + rentEpoch: optional(number()) + }))))), + unitsConsumed: optional(number()), + returnData: optional(nullable(type({ + programId: string(), + data: tuple([string(), literal('base64')]) + }))) + })); + /** + * Expected JSON RPC response for the "getBlockProduction" message + */ - var _decodeData$ = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Create, instruction.data), - lamports = _decodeData$.lamports, - space = _decodeData$.space, - programId = _decodeData$.programId; + var BlockProductionResponseStruct = jsonRpcResultAndContext(type({ + byIdentity: record(string(), array(number())), + range: type({ + firstSlot: number(), + lastSlot: number() + }) + })); + /** + * A performance sample + */ - return { - fromPubkey: instruction.keys[0].pubkey, - newAccountPubkey: instruction.keys[1].pubkey, - lamports: lamports, - space: space, - programId: new PublicKey(programId) - }; + function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) { + var fetch = customFetch ? customFetch : fetchImpl; + var agent; + { + if (httpAgent != null) { + console.warn('You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' + 'It has been ignored; `httpAgent` is only used in Node environments.'); } - /** - * Decode a transfer system instruction and retrieve the instruction params. - */ - - }, { - key: "decodeTransfer", - value: function decodeTransfer(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + } + var fetchWithMiddleware; - var _decodeData$2 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Transfer, instruction.data), - lamports = _decodeData$2.lamports; + if (fetchMiddleware) { + fetchWithMiddleware = /*#__PURE__*/function () { + var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(info, init) { + var modifiedFetchArgs; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return new Promise(function (resolve, reject) { + try { + fetchMiddleware(info, init, function (modifiedInfo, modifiedInit) { + return resolve([modifiedInfo, modifiedInit]); + }); + } catch (error) { + reject(error); + } + }); - return { - fromPubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - lamports: lamports - }; - } - /** - * Decode a transfer with seed system instruction and retrieve the instruction params. - */ + case 2: + modifiedFetchArgs = _context6.sent; + _context6.next = 5; + return fetch.apply(void 0, _toConsumableArray(modifiedFetchArgs)); - }, { - key: "decodeTransferWithSeed", - value: function decodeTransferWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 5: + return _context6.abrupt("return", _context6.sent); - var _decodeData$3 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed, instruction.data), - lamports = _decodeData$3.lamports, - seed = _decodeData$3.seed, - programId = _decodeData$3.programId; + case 6: + case "end": + return _context6.stop(); + } + }, _callee6); + })); - return { - fromPubkey: instruction.keys[0].pubkey, - basePubkey: instruction.keys[1].pubkey, - toPubkey: instruction.keys[2].pubkey, - lamports: lamports, - seed: seed, - programId: new PublicKey(programId) + return function fetchWithMiddleware(_x18, _x19) { + return _ref22.apply(this, arguments); }; - } - /** - * Decode an allocate system instruction and retrieve the instruction params. - */ - - }, { - key: "decodeAllocate", - value: function decodeAllocate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + }(); + } - var _decodeData$4 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Allocate, instruction.data), - space = _decodeData$4.space; + var clientBrowser = new RpcClient( /*#__PURE__*/function () { + var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(request, callback) { + var options, too_many_requests_retries, res, waitTime, text; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + options = { + method: 'POST', + body: request, + agent: agent, + headers: Object.assign({ + 'Content-Type': 'application/json' + }, httpHeaders || {}, COMMON_HTTP_HEADERS) + }; + _context7.prev = 1; + too_many_requests_retries = 5; + waitTime = 500; - return { - accountPubkey: instruction.keys[0].pubkey, - space: space - }; - } - /** - * Decode an allocate with seed system instruction and retrieve the instruction params. - */ + case 4: + if (!fetchWithMiddleware) { + _context7.next = 10; + break; + } - }, { - key: "decodeAllocateWithSeed", - value: function decodeAllocateWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + _context7.next = 7; + return fetchWithMiddleware(url, options); - var _decodeData$5 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed, instruction.data), - base = _decodeData$5.base, - seed = _decodeData$5.seed, - space = _decodeData$5.space, - programId = _decodeData$5.programId; + case 7: + res = _context7.sent; + _context7.next = 13; + break; - return { - accountPubkey: instruction.keys[0].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - space: space, - programId: new PublicKey(programId) - }; - } - /** - * Decode an assign system instruction and retrieve the instruction params. - */ + case 10: + _context7.next = 12; + return fetch(url, options); - }, { - key: "decodeAssign", - value: function decodeAssign(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + case 12: + res = _context7.sent; - var _decodeData$6 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.Assign, instruction.data), - programId = _decodeData$6.programId; + case 13: + if (!(res.status !== 429 + /* Too many requests */ + )) { + _context7.next = 15; + break; + } - return { - accountPubkey: instruction.keys[0].pubkey, - programId: new PublicKey(programId) - }; - } - /** - * Decode an assign with seed system instruction and retrieve the instruction params. - */ + return _context7.abrupt("break", 26); - }, { - key: "decodeAssignWithSeed", - value: function decodeAssignWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 1); + case 15: + if (!(disableRetryOnRateLimit === true)) { + _context7.next = 17; + break; + } - var _decodeData$7 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed, instruction.data), - base = _decodeData$7.base, - seed = _decodeData$7.seed, - programId = _decodeData$7.programId; + return _context7.abrupt("break", 26); - return { - accountPubkey: instruction.keys[0].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - programId: new PublicKey(programId) - }; - } - /** - * Decode a create account with seed system instruction and retrieve the instruction params. - */ + case 17: + too_many_requests_retries -= 1; - }, { - key: "decodeCreateWithSeed", - value: function decodeCreateWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + if (!(too_many_requests_retries === 0)) { + _context7.next = 20; + break; + } - var _decodeData$8 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed, instruction.data), - base = _decodeData$8.base, - seed = _decodeData$8.seed, - lamports = _decodeData$8.lamports, - space = _decodeData$8.space, - programId = _decodeData$8.programId; + return _context7.abrupt("break", 26); - return { - fromPubkey: instruction.keys[0].pubkey, - newAccountPubkey: instruction.keys[1].pubkey, - basePubkey: new PublicKey(base), - seed: seed, - lamports: lamports, - space: space, - programId: new PublicKey(programId) - }; - } - /** - * Decode a nonce initialize system instruction and retrieve the instruction params. - */ + case 20: + console.log("Server responded with ".concat(res.status, " ").concat(res.statusText, ". Retrying after ").concat(waitTime, "ms delay...")); + _context7.next = 23; + return sleep(waitTime); - }, { - key: "decodeNonceInitialize", - value: function decodeNonceInitialize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 23: + waitTime *= 2; - var _decodeData$9 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount, instruction.data), - authorized = _decodeData$9.authorized; + case 24: + _context7.next = 4; + break; - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: new PublicKey(authorized) - }; - } - /** - * Decode a nonce advance system instruction and retrieve the instruction params. - */ + case 26: + _context7.next = 28; + return res.text(); - }, { - key: "decodeNonceAdvance", - value: function decodeNonceAdvance(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount, instruction.data); - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey - }; - } - /** - * Decode a nonce withdraw system instruction and retrieve the instruction params. - */ + case 28: + text = _context7.sent; - }, { - key: "decodeNonceWithdraw", - value: function decodeNonceWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 5); + if (res.ok) { + callback(null, text); + } else { + callback(new Error("".concat(res.status, " ").concat(res.statusText, ": ").concat(text))); + } - var _decodeData$10 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount, instruction.data), - lamports = _decodeData$10.lamports; + _context7.next = 35; + break; - return { - noncePubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey, - lamports: lamports - }; - } - /** - * Decode a nonce authorize system instruction and retrieve the instruction params. - */ + case 32: + _context7.prev = 32; + _context7.t0 = _context7["catch"](1); + if (_context7.t0 instanceof Error) callback(_context7.t0); - }, { - key: "decodeNonceAuthorize", - value: function decodeNonceAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + case 35: + case "end": + return _context7.stop(); + } + }, _callee7, null, [[1, 32]]); + })); - var _decodeData$11 = decodeData$1(SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount, instruction.data), - authorized = _decodeData$11.authorized; + return function (_x20, _x21) { + return _ref23.apply(this, arguments); + }; + }(), {}); + return clientBrowser; + } - return { - noncePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[1].pubkey, - newAuthorizedPubkey: new PublicKey(authorized) - }; - } - /** - * @internal - */ + function createRpcRequest(client) { + return function (method, args) { + return new Promise(function (resolve, reject) { + client.request(method, args, function (err, response) { + if (err) { + reject(err); + return; + } - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(SystemProgram.programId)) { - throw new Error('invalid instruction; programId is not SystemProgram'); - } - } - /** - * @internal - */ + resolve(response); + }); + }); + }; + } - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } - } - }]); + function createRpcBatchRequest(client) { + return function (requests) { + return new Promise(function (resolve, reject) { + // Do nothing if requests is empty + if (requests.length === 0) resolve([]); + var batch = requests.map(function (params) { + return client.request(params.methodName, params.args); + }); + client.request(batch, function (err, response) { + if (err) { + reject(err); + return; + } - return SystemInstruction; - }(); + resolve(response); + }); + }); + }; + } /** - * An enumeration of valid SystemInstructionType's + * Expected JSON RPC response for the "getInflationGovernor" message */ + + var GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult); /** - * An enumeration of valid system InstructionType's - * @internal + * Expected JSON RPC response for the "getInflationRate" message */ - - var SYSTEM_INSTRUCTION_LAYOUTS = Object.freeze({ - Create: { - index: 0, - layout: struct([u32('instruction'), ns64('lamports'), ns64('space'), publicKey('programId')]) - }, - Assign: { - index: 1, - layout: struct([u32('instruction'), publicKey('programId')]) - }, - Transfer: { - index: 2, - layout: struct([u32('instruction'), u64('lamports')]) - }, - CreateWithSeed: { - index: 3, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('lamports'), ns64('space'), publicKey('programId')]) - }, - AdvanceNonceAccount: { - index: 4, - layout: struct([u32('instruction')]) - }, - WithdrawNonceAccount: { - index: 5, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - InitializeNonceAccount: { - index: 6, - layout: struct([u32('instruction'), publicKey('authorized')]) - }, - AuthorizeNonceAccount: { - index: 7, - layout: struct([u32('instruction'), publicKey('authorized')]) - }, - Allocate: { - index: 8, - layout: struct([u32('instruction'), ns64('space')]) - }, - AllocateWithSeed: { - index: 9, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), ns64('space'), publicKey('programId')]) - }, - AssignWithSeed: { - index: 10, - layout: struct([u32('instruction'), publicKey('base'), rustString('seed'), publicKey('programId')]) - }, - TransferWithSeed: { - index: 11, - layout: struct([u32('instruction'), u64('lamports'), rustString('seed'), publicKey('programId')]) - }, - UpgradeNonceAccount: { - index: 12, - layout: struct([u32('instruction')]) - } - }); + var GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult); /** - * Factory class for transactions to interact with the System program + * Expected JSON RPC response for the "getRecentPrioritizationFees" message */ - var SystemProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function SystemProgram() { - _classCallCheck(this, SystemProgram); - } - /** - * Public key that identifies the System program - */ - - /** - * Generate a transaction instruction that creates a new account - */ - - - _createClass(SystemProgram, null, [{ - key: "createAccount", - value: function createAccount(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.Create; - var data = encodeData(type, { - lamports: params.lamports, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.newAccountPubkey, - isSigner: true, - isWritable: true - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that transfers lamports from one account to another - */ - - }, { - key: "transfer", - value: function transfer(params) { - var data; - var keys; - - if ('basePubkey' in params) { - var _type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed; - data = encodeData(_type, { - lamports: BigInt(params.lamports), - seed: params.seed, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.fromPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }]; - } else { - var _type2 = SYSTEM_INSTRUCTION_LAYOUTS.Transfer; - data = encodeData(_type2, { - lamports: BigInt(params.lamports) - }); - keys = [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }]; - } + var GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult); + /** + * Expected JSON RPC response for the "getEpochInfo" message + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that assigns an account to a program - */ + var GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult); + /** + * Expected JSON RPC response for the "getEpochSchedule" message + */ - }, { - key: "assign", - value: function assign(params) { - var data; - var keys; + var GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult); + /** + * Expected JSON RPC response for the "getLeaderSchedule" message + */ - if ('basePubkey' in params) { - var _type3 = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed; - data = encodeData(_type3, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }]; - } else { - var _type4 = SYSTEM_INSTRUCTION_LAYOUTS.Assign; - data = encodeData(_type4, { - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: true, - isWritable: true - }]; - } + var GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult); + /** + * Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that creates a new account at - * an address generated with `from`, a seed, and programId - */ + var SlotRpcResult = jsonRpcResult(number()); + /** + * Supply + */ - }, { - key: "createAccountWithSeed", - value: function createAccountWithSeed(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed; - var data = encodeData(type, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - lamports: params.lamports, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - var keys = [{ - pubkey: params.fromPubkey, - isSigner: true, - isWritable: true - }, { - pubkey: params.newAccountPubkey, - isSigner: false, - isWritable: true - }]; + /** + * Expected JSON RPC response for the "getSupply" message + */ - if (params.basePubkey != params.fromPubkey) { - keys.push({ - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }); - } + var GetSupplyRpcResult = jsonRpcResultAndContext(type({ + total: number(), + circulating: number(), + nonCirculating: number(), + nonCirculatingAccounts: array(PublicKeyFromString) + })); + /** + * Token amount object which returns a token amount in different formats + * for various client use cases. + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction that creates a new Nonce account - */ + /** + * Expected JSON RPC structure for token amounts + */ - }, { - key: "createNonceAccount", - value: function createNonceAccount(params) { - var transaction = new Transaction(); + var TokenAmountResult = type({ + amount: string(), + uiAmount: nullable(number()), + decimals: number(), + uiAmountString: optional(string()) + }); + /** + * Token address and balance. + */ - if ('basePubkey' in params && 'seed' in params) { - transaction.add(SystemProgram.createAccountWithSeed({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.noncePubkey, - basePubkey: params.basePubkey, - seed: params.seed, - lamports: params.lamports, - space: NONCE_ACCOUNT_LENGTH, - programId: this.programId - })); - } else { - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.noncePubkey, - lamports: params.lamports, - space: NONCE_ACCOUNT_LENGTH, - programId: this.programId - })); - } + /** + * Expected JSON RPC response for the "getTokenLargestAccounts" message + */ - var initParams = { - noncePubkey: params.noncePubkey, - authorizedPubkey: params.authorizedPubkey - }; - transaction.add(this.nonceInitialize(initParams)); - return transaction; - } - /** - * Generate an instruction to initialize a Nonce account - */ + var GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({ + address: PublicKeyFromString, + amount: string(), + uiAmount: nullable(number()), + decimals: number(), + uiAmountString: optional(string()) + }))); + /** + * Expected JSON RPC response for the "getTokenAccountsByOwner" message + */ - }, { - key: "nonceInitialize", - value: function nonceInitialize(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount; - var data = encodeData(type, { - authorized: toBuffer(params.authorizedPubkey.toBuffer()) - }); - var instructionData = { - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate an instruction to advance the nonce in a Nonce account - */ + var GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ + pubkey: PublicKeyFromString, + account: type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: BufferFromRawAccountData, + rentEpoch: number() + }) + }))); + var ParsedAccountDataResult = type({ + program: string(), + parsed: unknown(), + space: number() + }); + /** + * Expected JSON RPC response for the "getTokenAccountsByOwner" message with parsed data + */ - }, { - key: "nonceAdvance", - value: function nonceAdvance(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount; - var data = encodeData(type); - var instructionData = { - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a transaction instruction that withdraws lamports from a Nonce account - */ + var GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ + pubkey: PublicKeyFromString, + account: type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: ParsedAccountDataResult, + rentEpoch: number() + }) + }))); + /** + * Pair of an account address and its balance + */ - }, { - key: "nonceWithdraw", - value: function nonceWithdraw(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount; - var data = encodeData(type, { - lamports: params.lamports - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that authorizes a new PublicKey as the authority - * on a Nonce account. - */ + /** + * Expected JSON RPC response for the "getLargestAccounts" message + */ - }, { - key: "nonceAuthorize", - value: function nonceAuthorize(params) { - var type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount; - var data = encodeData(type, { - authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()) - }); - return new TransactionInstruction({ - keys: [{ - pubkey: params.noncePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction instruction that allocates space in an account without funding - */ + var GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({ + lamports: number(), + address: PublicKeyFromString + }))); + /** + * @internal + */ - }, { - key: "allocate", - value: function allocate(params) { - var data; - var keys; + var AccountInfoResult = type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: BufferFromRawAccountData, + rentEpoch: number() + }); + /** + * @internal + */ - if ('basePubkey' in params) { - var _type5 = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed; - data = encodeData(_type5, { - base: toBuffer(params.basePubkey.toBuffer()), - seed: params.seed, - space: params.space, - programId: toBuffer(params.programId.toBuffer()) - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: params.basePubkey, - isSigner: true, - isWritable: false - }]; - } else { - var _type6 = SYSTEM_INSTRUCTION_LAYOUTS.Allocate; - data = encodeData(_type6, { - space: params.space - }); - keys = [{ - pubkey: params.accountPubkey, - isSigner: true, - isWritable: true - }]; - } + var KeyedAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: AccountInfoResult + }); + var ParsedOrRawAccountData = coerce(union([instance(Buffer$1), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), function (value) { + if (Array.isArray(value)) { + return _create(value, BufferFromRawAccountData); + } else { + return value; + } + }); + /** + * @internal + */ - return new TransactionInstruction({ - keys: keys, - programId: this.programId, - data: data - }); - } - }]); + var ParsedAccountInfoResult = type({ + executable: _boolean(), + owner: PublicKeyFromString, + lamports: number(), + data: ParsedOrRawAccountData, + rentEpoch: number() + }); + var KeyedParsedAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: ParsedAccountInfoResult + }); + /** + * @internal + */ - return SystemProgram; - }(); + var StakeActivationResult = type({ + state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]), + active: number(), + inactive: number() + }); + /** + * Expected JSON RPC response for the "getConfirmedSignaturesForAddress2" message + */ - SystemProgram.programId = new PublicKey('11111111111111111111111111111111'); // Keep program chunks under PACKET_DATA_SIZE, leaving enough room for the - // rest of the Transaction fields - // - // TODO: replace 300 with a proper constant for the size of the other - // Transaction fields + var GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({ + signature: string(), + slot: number(), + err: TransactionErrorResult, + memo: nullable(string()), + blockTime: optional(nullable(number())) + }))); + /** + * Expected JSON RPC response for the "getSignaturesForAddress" message + */ - var CHUNK_SIZE = PACKET_DATA_SIZE - 300; + var GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({ + signature: string(), + slot: number(), + err: TransactionErrorResult, + memo: nullable(string()), + blockTime: optional(nullable(number())) + }))); + /*** + * Expected JSON RPC response for the "accountNotification" message + */ + + var AccountNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(AccountInfoResult) + }); /** - * Program loader interface + * @internal */ - var Loader = /*#__PURE__*/function () { - /** - * @internal - */ - function Loader() { - _classCallCheck(this, Loader); - } - /** - * Amount of program data placed in each load Transaction - */ + var ProgramAccountInfoResult = type({ + pubkey: PublicKeyFromString, + account: AccountInfoResult + }); + /*** + * Expected JSON RPC response for the "programNotification" message + */ - /** - * Minimum number of signatures required to load a program not including - * retries - * - * Can be used to calculate transaction fees - */ + var ProgramAccountNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(ProgramAccountInfoResult) + }); + /** + * @internal + */ + var SlotInfoResult = type({ + parent: number(), + slot: number(), + root: number() + }); + /** + * Expected JSON RPC response for the "slotNotification" message + */ - _createClass(Loader, null, [{ - key: "getMinNumSignatures", - value: function getMinNumSignatures(dataLength) { - return 2 * ( // Every transaction requires two signatures (payer + program) - Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction - 1) // Add one for Finalize transaction - ; - } - /** - * Loads a generic program - * - * @param connection The connection to use - * @param payer System account that pays to load the program - * @param program Account to load the program into - * @param programId Public key that identifies the loader - * @param data Program octets - * @return true if program was loaded successfully, false if program was already loaded - */ + var SlotNotificationResult = type({ + subscription: number(), + result: SlotInfoResult + }); + /** + * Slot updates which can be used for tracking the live progress of a cluster. + * - `"firstShredReceived"`: connected node received the first shred of a block. + * Indicates that a new block that is being produced. + * - `"completed"`: connected node has received all shreds of a block. Indicates + * a block was recently produced. + * - `"optimisticConfirmation"`: block was optimistically confirmed by the + * cluster. It is not guaranteed that an optimistic confirmation notification + * will be sent for every finalized blocks. + * - `"root"`: the connected node rooted this block. + * - `"createdBank"`: the connected node has started validating this block. + * - `"frozen"`: the connected node has validated this block. + * - `"dead"`: the connected node failed to validate this block. + */ - }, { - key: "load", - value: function () { - var _load = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(connection, payer, program, programId, data) { - var balanceNeeded, programInfo, transaction, dataLayout, chunkSize, offset, array, transactions, bytes, _data, _transaction, REQUESTS_PER_SECOND, _dataLayout, _data2, _transaction2; + /** + * @internal + */ - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) switch (_context5.prev = _context5.next) { - case 0: - _context5.next = 2; - return connection.getMinimumBalanceForRentExemption(data.length); + var SlotUpdateResult = union([type({ + type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]), + slot: number(), + timestamp: number() + }), type({ + type: literal('createdBank'), + parent: number(), + slot: number(), + timestamp: number() + }), type({ + type: literal('frozen'), + slot: number(), + timestamp: number(), + stats: type({ + numTransactionEntries: number(), + numSuccessfulTransactions: number(), + numFailedTransactions: number(), + maxTransactionsPerEntry: number() + }) + }), type({ + type: literal('dead'), + slot: number(), + timestamp: number(), + err: string() + })]); + /** + * Expected JSON RPC response for the "slotsUpdatesNotification" message + */ - case 2: - balanceNeeded = _context5.sent; - _context5.next = 5; - return connection.getAccountInfo(program.publicKey, 'confirmed'); + var SlotUpdateNotificationResult = type({ + subscription: number(), + result: SlotUpdateResult + }); + /** + * Expected JSON RPC response for the "signatureNotification" message + */ - case 5: - programInfo = _context5.sent; - transaction = null; + var SignatureNotificationResult = type({ + subscription: number(), + result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult])) + }); + /** + * Expected JSON RPC response for the "rootNotification" message + */ - if (!(programInfo !== null)) { - _context5.next = 16; - break; - } + var RootNotificationResult = type({ + subscription: number(), + result: number() + }); + var ContactInfoResult = type({ + pubkey: string(), + gossip: nullable(string()), + tpu: nullable(string()), + rpc: nullable(string()), + version: nullable(string()) + }); + var VoteAccountInfoResult = type({ + votePubkey: string(), + nodePubkey: string(), + activatedStake: number(), + epochVoteAccount: _boolean(), + epochCredits: array(tuple([number(), number(), number()])), + commission: number(), + lastVote: number(), + rootSlot: nullable(number()) + }); + /** + * Expected JSON RPC response for the "getVoteAccounts" message + */ - if (!programInfo.executable) { - _context5.next = 11; - break; - } + var GetVoteAccounts = jsonRpcResult(type({ + current: array(VoteAccountInfoResult), + delinquent: array(VoteAccountInfoResult) + })); + var ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]); + var SignatureStatusResponse = type({ + slot: number(), + confirmations: nullable(number()), + err: TransactionErrorResult, + confirmationStatus: optional(ConfirmationStatus) + }); + /** + * Expected JSON RPC response for the "getSignatureStatuses" message + */ - console.error('Program load failed, account is already executable'); - return _context5.abrupt("return", false); + var GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse))); + /** + * Expected JSON RPC response for the "getMinimumBalanceForRentExemption" message + */ - case 11: - if (programInfo.data.length !== data.length) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.allocate({ - accountPubkey: program.publicKey, - space: data.length - })); - } + var GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number()); + var AddressTableLookupStruct = type({ + accountKey: PublicKeyFromString, + writableIndexes: array(number()), + readonlyIndexes: array(number()) + }); + var ConfirmedTransactionResult = type({ + signatures: array(string()), + message: type({ + accountKeys: array(string()), + header: type({ + numRequiredSignatures: number(), + numReadonlySignedAccounts: number(), + numReadonlyUnsignedAccounts: number() + }), + instructions: array(type({ + accounts: array(number()), + data: string(), + programIdIndex: number() + })), + recentBlockhash: string(), + addressTableLookups: optional(array(AddressTableLookupStruct)) + }) + }); + var AnnotatedAccountKey = type({ + pubkey: PublicKeyFromString, + signer: _boolean(), + writable: _boolean(), + source: optional(union([literal('transaction'), literal('lookupTable')])) + }); + var ConfirmedTransactionAccountsModeResult = type({ + accountKeys: array(AnnotatedAccountKey), + signatures: array(string()) + }); + var ParsedInstructionResult = type({ + parsed: unknown(), + program: string(), + programId: PublicKeyFromString + }); + var RawInstructionResult = type({ + accounts: array(PublicKeyFromString), + data: string(), + programId: PublicKeyFromString + }); + var InstructionResult = union([RawInstructionResult, ParsedInstructionResult]); + var UnknownInstructionResult = union([type({ + parsed: unknown(), + program: string(), + programId: string() + }), type({ + accounts: array(string()), + data: string(), + programId: string() + })]); + var ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, function (value) { + if ('accounts' in value) { + return _create(value, RawInstructionResult); + } else { + return _create(value, ParsedInstructionResult); + } + }); + /** + * @internal + */ + + var ParsedConfirmedTransactionResult = type({ + signatures: array(string()), + message: type({ + accountKeys: array(AnnotatedAccountKey), + instructions: array(ParsedOrRawInstruction), + recentBlockhash: string(), + addressTableLookups: optional(nullable(array(AddressTableLookupStruct))) + }) + }); + var TokenBalanceResult = type({ + accountIndex: number(), + mint: string(), + owner: optional(string()), + uiTokenAmount: TokenAmountResult + }); + var LoadedAddressesResult = type({ + writable: array(PublicKeyFromString), + readonly: array(PublicKeyFromString) + }); + /** + * @internal + */ + + var ConfirmedTransactionMetaResult = type({ + err: TransactionErrorResult, + fee: number(), + innerInstructions: optional(nullable(array(type({ + index: number(), + instructions: array(type({ + accounts: array(number()), + data: string(), + programIdIndex: number() + })) + })))), + preBalances: array(number()), + postBalances: array(number()), + logMessages: optional(nullable(array(string()))), + preTokenBalances: optional(nullable(array(TokenBalanceResult))), + postTokenBalances: optional(nullable(array(TokenBalanceResult))), + loadedAddresses: optional(LoadedAddressesResult), + computeUnitsConsumed: optional(number()) + }); + /** + * @internal + */ + + var ParsedConfirmedTransactionMetaResult = type({ + err: TransactionErrorResult, + fee: number(), + innerInstructions: optional(nullable(array(type({ + index: number(), + instructions: array(ParsedOrRawInstruction) + })))), + preBalances: array(number()), + postBalances: array(number()), + logMessages: optional(nullable(array(string()))), + preTokenBalances: optional(nullable(array(TokenBalanceResult))), + postTokenBalances: optional(nullable(array(TokenBalanceResult))), + loadedAddresses: optional(LoadedAddressesResult), + computeUnitsConsumed: optional(number()) + }); + var TransactionVersionStruct = union([literal(0), literal('legacy')]); + /** @internal */ - if (!programInfo.owner.equals(programId)) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.assign({ - accountPubkey: program.publicKey, - programId: programId - })); - } + var RewardsResult = type({ + pubkey: string(), + lamports: number(), + postBalance: nullable(number()), + rewardType: nullable(string()), + commission: optional(nullable(number())) + }); + /** + * Expected JSON RPC response for the "getBlock" message + */ - if (programInfo.lamports < balanceNeeded) { - transaction = transaction || new Transaction(); - transaction.add(SystemProgram.transfer({ - fromPubkey: payer.publicKey, - toPubkey: program.publicKey, - lamports: balanceNeeded - programInfo.lamports - })); - } + var GetBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionResult, + meta: nullable(ConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `none` + */ - _context5.next = 17; - break; + var GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` + */ - case 16: - transaction = new Transaction().add(SystemProgram.createAccount({ - fromPubkey: payer.publicKey, - newAccountPubkey: program.publicKey, - lamports: balanceNeeded > 0 ? balanceNeeded : 1, - space: data.length, - programId: programId - })); + var GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionAccountsModeResult, + meta: nullable(ConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected parsed JSON RPC response for the "getBlock" message + */ - case 17: - if (!(transaction !== null)) { - _context5.next = 20; - break; - } + var GetParsedBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ParsedConfirmedTransactionResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` + */ - _context5.next = 20; - return sendAndConfirmTransaction(connection, transaction, [payer, program], { - commitment: 'confirmed' - }); + var GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionAccountsModeResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + version: optional(TransactionVersionStruct) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `none` + */ - case 20: - dataLayout = struct([u32('instruction'), u32('offset'), u32('bytesLength'), u32('bytesLengthPadding'), seq$1(u8('byte'), offset$1(u32(), -8), 'bytes')]); - chunkSize = Loader.chunkSize; - offset = 0; - array = data; - transactions = []; + var GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()), + blockHeight: nullable(number()) + }))); + /** + * Expected JSON RPC response for the "getConfirmedBlock" message + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead. + */ - case 25: - if (!(array.length > 0)) { - _context5.next = 39; - break; - } + var GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + transactions: array(type({ + transaction: ConfirmedTransactionResult, + meta: nullable(ConfirmedTransactionMetaResult) + })), + rewards: optional(array(RewardsResult)), + blockTime: nullable(number()) + }))); + /** + * Expected JSON RPC response for the "getBlock" message + */ - bytes = array.slice(0, chunkSize); - _data = Buffer$1.alloc(chunkSize + 16); - dataLayout.encode({ - instruction: 0, - // Load instruction - offset: offset, - bytes: bytes, - bytesLength: 0, - bytesLengthPadding: 0 - }, _data); - _transaction = new Transaction().add({ - keys: [{ - pubkey: program.publicKey, - isSigner: true, - isWritable: true - }], - programId: programId, - data: _data - }); - transactions.push(sendAndConfirmTransaction(connection, _transaction, [payer, program], { - commitment: 'confirmed' - })); // Delay between sends in an attempt to reduce rate limit errors + var GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({ + blockhash: string(), + previousBlockhash: string(), + parentSlot: number(), + signatures: array(string()), + blockTime: nullable(number()) + }))); + /** + * Expected JSON RPC response for the "getTransaction" message + */ - if (!connection._rpcEndpoint.includes('solana.com')) { - _context5.next = 35; - break; - } + var GetTransactionRpcResult = jsonRpcResult(nullable(type({ + slot: number(), + meta: ConfirmedTransactionMetaResult, + blockTime: optional(nullable(number())), + transaction: ConfirmedTransactionResult, + version: optional(TransactionVersionStruct) + }))); + /** + * Expected parsed JSON RPC response for the "getTransaction" message + */ - REQUESTS_PER_SECOND = 4; - _context5.next = 35; - return sleep(1000 / REQUESTS_PER_SECOND); + var GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({ + slot: number(), + transaction: ParsedConfirmedTransactionResult, + meta: nullable(ParsedConfirmedTransactionMetaResult), + blockTime: optional(nullable(number())), + version: optional(TransactionVersionStruct) + }))); + /** + * Expected JSON RPC response for the "getRecentBlockhash" message + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead. + */ - case 35: - offset += chunkSize; - array = array.slice(chunkSize); - _context5.next = 25; - break; + var GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(type({ + blockhash: string(), + feeCalculator: type({ + lamportsPerSignature: number() + }) + })); + /** + * Expected JSON RPC response for the "getLatestBlockhash" message + */ - case 39: - _context5.next = 41; - return Promise.all(transactions); + var GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({ + blockhash: string(), + lastValidBlockHeight: number() + })); + var PerfSampleResult = type({ + slot: number(), + numTransactions: number(), + numSlots: number(), + samplePeriodSecs: number() + }); + /* + * Expected JSON RPC response for "getRecentPerformanceSamples" message + */ - case 41: - _dataLayout = struct([u32('instruction')]); - _data2 = Buffer$1.alloc(_dataLayout.span); + var GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult)); + /** + * Expected JSON RPC response for the "getFeeCalculatorForBlockhash" message + */ - _dataLayout.encode({ - instruction: 1 // Finalize instruction + var GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({ + feeCalculator: type({ + lamportsPerSignature: number() + }) + }))); + /** + * Expected JSON RPC response for the "requestAirdrop" message + */ - }, _data2); + var RequestAirdropRpcResult = jsonRpcResult(string()); + /** + * Expected JSON RPC response for the "sendTransaction" message + */ - _transaction2 = new Transaction().add({ - keys: [{ - pubkey: program.publicKey, - isSigner: true, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: programId, - data: _data2 - }); - _context5.next = 47; - return sendAndConfirmTransaction(connection, _transaction2, [payer, program], { - commitment: 'confirmed' - }); + var SendTransactionRpcResult = jsonRpcResult(string()); + /** + * Information about the latest slot being processed by a node + */ - case 47: - return _context5.abrupt("return", true); + /** + * @internal + */ - case 48: - case "end": - return _context5.stop(); - } - }, _callee5); - })); + var LogsResult = type({ + err: TransactionErrorResult, + logs: array(string()), + signature: string() + }); + /** + * Logs result. + */ - function load(_x13, _x14, _x15, _x16, _x17) { - return _load.apply(this, arguments); - } + /** + * Expected JSON RPC response for the "logsNotification" message. + */ - return load; - }() - }]); + var LogsNotificationResult = type({ + result: notificationResultAndContext(LogsResult), + subscription: number() + }); + /** + * Filter for log subscriptions. + */ - return Loader; - }(); + /** @internal */ - Loader.chunkSize = CHUNK_SIZE; - var BPF_LOADER_PROGRAM_ID = new PublicKey('BPFLoader2111111111111111111111111111111111'); + var COMMON_HTTP_HEADERS = { + 'solana-client': "js/".concat("0.0.0-development") + }; /** - * Factory class for transactions to interact with a program loader + * A connection to a fullnode JSON RPC endpoint */ - var BpfLoader = /*#__PURE__*/function () { - function BpfLoader() { - _classCallCheck(this, BpfLoader); - } + var Connection = /*#__PURE__*/function () { + /** @internal */ - _createClass(BpfLoader, null, [{ - key: "getMinNumSignatures", - value: - /** - * Minimum number of signatures required to load a program not including - * retries - * - * Can be used to calculate transaction fees - */ - function getMinNumSignatures(dataLength) { - return Loader.getMinNumSignatures(dataLength); - } - /** - * Load a SBF program - * - * @param connection The connection to use - * @param payer Account that will pay program loading fees - * @param program Account to load the program into - * @param elf The entire ELF containing the SBF program - * @param loaderProgramId The program id of the BPF loader to use - * @return true if program was loaded successfully, false if program was already loaded - */ + /** @internal */ - }, { - key: "load", - value: function load(connection, payer, program, elf, loaderProgramId) { - return Loader.load(connection, payer, program, loaderProgramId, elf); - } - }]); + /** @internal */ - return BpfLoader; - }(); + /** @internal */ - var objToString = Object.prototype.toString; + /** @internal */ - var objKeys = Object.keys || function (obj) { - var keys = []; + /** @internal */ - for (var name in obj) { - keys.push(name); - } + /** @internal */ - return keys; - }; + /** @internal */ - function stringify(val, isArrayProp) { - var i, max, str, keys, key, propVal, toStr; + /** @internal */ - if (val === true) { - return "true"; - } + /** @internal */ - if (val === false) { - return "false"; - } + /** @internal */ - switch (_typeof$1(val)) { - case "object": - if (val === null) { - return null; - } else if (val.toJSON && typeof val.toJSON === "function") { - return stringify(val.toJSON(), isArrayProp); - } else { - toStr = objToString.call(val); + /** @internal + * A number that we increment every time an active connection closes. + * Used to determine whether the same socket connection that was open + * when an async operation started is the same one that's active when + * its continuation fires. + * + */ - if (toStr === "[object Array]") { - str = '['; - max = val.length - 1; + /** @internal */ - for (i = 0; i < max; i++) { - str += stringify(val[i], true) + ','; - } + /** @internal */ - if (max > -1) { - str += stringify(val[i], true); - } + /** @internal */ - return str + ']'; - } else if (toStr === "[object Object]") { - // only object is left - keys = objKeys(val).sort(); - max = keys.length; - str = ""; - i = 0; + /** @internal */ - while (i < max) { - key = keys[i]; - propVal = stringify(val[key], false); + /** @internal */ - if (propVal !== undefined) { - if (str) { - str += ','; - } + /** @internal */ - str += JSON.stringify(key) + ':' + propVal; - } + /** @internal */ - i++; - } + /** @internal */ - return '{' + str + '}'; - } else { - return JSON.stringify(val); - } - } + /** @internal */ - case "function": - case "undefined": - return isArrayProp ? null : undefined; + /** + * Special case. + * After a signature is processed, RPCs automatically dispose of the + * subscription on the server side. We need to track which of these + * subscriptions have been disposed in such a way, so that we know + * whether the client is dealing with a not-yet-processed signature + * (in which case we must tear down the server subscription) or an + * already-processed signature (in which case the client can simply + * clear out the subscription locally without telling the server). + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ - case "string": - return JSON.stringify(val); + /** @internal */ - default: - return isFinite(val) ? val : null; - } - } + /** + * Establish a JSON RPC connection + * + * @param endpoint URL to the fullnode JSON RPC endpoint + * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object + */ + function Connection(endpoint, _commitmentOrConfig) { + var _this15 = this; + + _classCallCheck(this, Connection); + + this._commitment = void 0; + this._confirmTransactionInitialTimeout = void 0; + this._rpcEndpoint = void 0; + this._rpcWsEndpoint = void 0; + this._rpcClient = void 0; + this._rpcRequest = void 0; + this._rpcBatchRequest = void 0; + this._rpcWebSocket = void 0; + this._rpcWebSocketConnected = false; + this._rpcWebSocketHeartbeat = null; + this._rpcWebSocketIdleTimeout = null; + this._rpcWebSocketGeneration = 0; + this._disableBlockhashCaching = false; + this._pollingBlockhash = false; + this._blockhashInfo = { + latestBlockhash: null, + lastFetch: 0, + transactionSignatures: [], + simulatedSignatures: [] + }; + this._nextClientSubscriptionId = 0; + this._subscriptionDisposeFunctionsByClientSubscriptionId = {}; + this._subscriptionHashByClientSubscriptionId = {}; + this._subscriptionStateChangeCallbacksByHash = {}; + this._subscriptionCallbacksByServerSubscriptionId = {}; + this._subscriptionsByHash = {}; + this._subscriptionsAutoDisposedByRpc = new Set(); - var fastStableStringify = function fastStableStringify(val) { - var returnVal = stringify(val, false); + this.getBlockHeight = function () { + var requestPromises = {}; + return /*#__PURE__*/function () { + var _ref24 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(commitmentOrConfig) { + var _requestPromises$requ; - if (returnVal !== undefined) { - return '' + returnVal; - } - }; + var _extractCommitmentFro, commitment, config, args, requestHash; - var fastStableStringify$1 = fastStableStringify; - var MINIMUM_SLOT_PER_EPOCH = 32; // Returns the number of trailing zeros in the binary representation of self. + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _extractCommitmentFro = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro.commitment, config = _extractCommitmentFro.config; + args = _this15._buildArgs([], commitment, undefined + /* encoding */ + , config); + requestHash = fastStableStringify$1(args); + requestPromises[requestHash] = (_requestPromises$requ = requestPromises[requestHash]) !== null && _requestPromises$requ !== void 0 ? _requestPromises$requ : _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.prev = 0; + _context8.next = 3; + return _this15._rpcRequest('getBlockHeight', args); - function trailingZeros(n) { - var trailingZeros = 0; + case 3: + unsafeRes = _context8.sent; + res = _create(unsafeRes, jsonRpcResult(number())); - while (n > 1) { - n /= 2; - trailingZeros++; - } + if (!('error' in res)) { + _context8.next = 7; + break; + } - return trailingZeros; - } // Returns the smallest power of two greater than or equal to n + throw new SolanaJSONRPCError(res.error, 'failed to get block height information'); + case 7: + return _context8.abrupt("return", res.result); - function nextPowerOfTwo(n) { - if (n === 0) return 1; - n--; - n |= n >> 1; - n |= n >> 2; - n |= n >> 4; - n |= n >> 8; - n |= n >> 16; - n |= n >> 32; - return n + 1; - } - /** - * Epoch schedule - * (see https://docs.solana.com/terminology#epoch) - * Can be retrieved with the {@link Connection.getEpochSchedule} method - */ + case 8: + _context8.prev = 8; + delete requestPromises[requestHash]; + return _context8.finish(8); + case 11: + case "end": + return _context8.stop(); + } + }, _callee8, null, [[0,, 8, 11]]); + }))(); + _context9.next = 6; + return requestPromises[requestHash]; - var EpochSchedule = /*#__PURE__*/function () { - /** The maximum number of slots in each epoch */ + case 6: + return _context9.abrupt("return", _context9.sent); - /** The number of slots before beginning of an epoch to calculate a leader schedule for that epoch */ + case 7: + case "end": + return _context9.stop(); + } + }, _callee9); + })); - /** Indicates whether epochs start short and grow */ + return function (_x22) { + return _ref24.apply(this, arguments); + }; + }(); + }(); - /** The first epoch with `slotsPerEpoch` slots */ + var wsEndpoint; + var httpHeaders; + var fetch; + var fetchMiddleware; + var disableRetryOnRateLimit; + var httpAgent; - /** The first slot of `firstNormalEpoch` */ - function EpochSchedule(slotsPerEpoch, leaderScheduleSlotOffset, warmup, firstNormalEpoch, firstNormalSlot) { - _classCallCheck(this, EpochSchedule); + if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') { + this._commitment = _commitmentOrConfig; + } else if (_commitmentOrConfig) { + this._commitment = _commitmentOrConfig.commitment; + this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout; + wsEndpoint = _commitmentOrConfig.wsEndpoint; + httpHeaders = _commitmentOrConfig.httpHeaders; + fetch = _commitmentOrConfig.fetch; + fetchMiddleware = _commitmentOrConfig.fetchMiddleware; + disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit; + httpAgent = _commitmentOrConfig.httpAgent; + } - this.slotsPerEpoch = void 0; - this.leaderScheduleSlotOffset = void 0; - this.warmup = void 0; - this.firstNormalEpoch = void 0; - this.firstNormalSlot = void 0; - this.slotsPerEpoch = slotsPerEpoch; - this.leaderScheduleSlotOffset = leaderScheduleSlotOffset; - this.warmup = warmup; - this.firstNormalEpoch = firstNormalEpoch; - this.firstNormalSlot = firstNormalSlot; - } + this._rpcEndpoint = assertEndpointUrl(endpoint); + this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint); + this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent); + this._rpcRequest = createRpcRequest(this._rpcClient); + this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient); + this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, { + autoconnect: false, + max_reconnects: Infinity + }); - _createClass(EpochSchedule, [{ - key: "getEpoch", - value: function getEpoch(slot) { - return this.getEpochAndSlotIndex(slot)[0]; - } - }, { - key: "getEpochAndSlotIndex", - value: function getEpochAndSlotIndex(slot) { - if (slot < this.firstNormalSlot) { - var epoch = trailingZeros(nextPowerOfTwo(slot + MINIMUM_SLOT_PER_EPOCH + 1)) - trailingZeros(MINIMUM_SLOT_PER_EPOCH) - 1; - var epochLen = this.getSlotsInEpoch(epoch); - var slotIndex = slot - (epochLen - MINIMUM_SLOT_PER_EPOCH); - return [epoch, slotIndex]; - } else { - var normalSlotIndex = slot - this.firstNormalSlot; - var normalEpochIndex = Math.floor(normalSlotIndex / this.slotsPerEpoch); + this._rpcWebSocket.on('open', this._wsOnOpen.bind(this)); - var _epoch = this.firstNormalEpoch + normalEpochIndex; + this._rpcWebSocket.on('error', this._wsOnError.bind(this)); - var _slotIndex = normalSlotIndex % this.slotsPerEpoch; + this._rpcWebSocket.on('close', this._wsOnClose.bind(this)); - return [_epoch, _slotIndex]; - } - } - }, { - key: "getFirstSlotInEpoch", - value: function getFirstSlotInEpoch(epoch) { - if (epoch <= this.firstNormalEpoch) { - return (Math.pow(2, epoch) - 1) * MINIMUM_SLOT_PER_EPOCH; - } else { - return (epoch - this.firstNormalEpoch) * this.slotsPerEpoch + this.firstNormalSlot; - } - } - }, { - key: "getLastSlotInEpoch", - value: function getLastSlotInEpoch(epoch) { - return this.getFirstSlotInEpoch(epoch) + this.getSlotsInEpoch(epoch) - 1; - } - }, { - key: "getSlotsInEpoch", - value: function getSlotsInEpoch(epoch) { - if (epoch < this.firstNormalEpoch) { - return Math.pow(2, epoch + trailingZeros(MINIMUM_SLOT_PER_EPOCH)); - } else { - return this.slotsPerEpoch; - } - } - }]); + this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this)); - return EpochSchedule; - }(); + this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this)); - var SendTransactionError = /*#__PURE__*/function (_Error4) { - _inherits(SendTransactionError, _Error4); + this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this)); - var _super6 = _createSuper(SendTransactionError); + this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this)); - function SendTransactionError(message, logs) { - var _this12; + this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this)); - _classCallCheck(this, SendTransactionError); + this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this)); - _this12 = _super6.call(this, message); - _this12.logs = void 0; - _this12.logs = logs; - return _this12; + this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this)); } - - return _createClass(SendTransactionError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); // Keep in sync with client/src/rpc_custom_errors.rs - // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ + /** + * The default commitment used for requests + */ - var SolanaJSONRPCErrorCode = { - JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP: -32001, - JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: -32002, - JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: -32003, - JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE: -32004, - JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY: -32005, - JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: -32006, - JSON_RPC_SERVER_ERROR_SLOT_SKIPPED: -32007, - JSON_RPC_SERVER_ERROR_NO_SNAPSHOT: -32008, - JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: -32009, - JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: -32010, - JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: -32011, - JSON_RPC_SCAN_ERROR: -32012, - JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: -32013, - JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: -32014, - JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: -32015, - JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: -32016 - }; + _createClass(Connection, [{ + key: "commitment", + get: function get() { + return this._commitment; + } + /** + * The RPC endpoint + */ - var SolanaJSONRPCError = /*#__PURE__*/function (_Error5) { - _inherits(SolanaJSONRPCError, _Error5); + }, { + key: "rpcEndpoint", + get: function get() { + return this._rpcEndpoint; + } + /** + * Fetch the balance for the specified public key, return with context + */ - var _super7 = _createSuper(SolanaJSONRPCError); + }, { + key: "getBalanceAndContext", + value: function () { + var _getBalanceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(publicKey, commitmentOrConfig) { + var _extractCommitmentFro2, commitment, config, args, unsafeRes, res; - function SolanaJSONRPCError(_ref21, customMessage) { - var _this13; + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + /** @internal */ + _extractCommitmentFro2 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro2.commitment, config = _extractCommitmentFro2.config; + args = this._buildArgs([publicKey.toBase58()], commitment, undefined + /* encoding */ + , config); + _context10.next = 4; + return this._rpcRequest('getBalance', args); - var code = _ref21.code, - message = _ref21.message, - data = _ref21.data; + case 4: + unsafeRes = _context10.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(number())); - _classCallCheck(this, SolanaJSONRPCError); + if (!('error' in res)) { + _context10.next = 8; + break; + } - _this13 = _super7.call(this, customMessage != null ? "".concat(customMessage, ": ").concat(message) : message); - _this13.code = void 0; - _this13.data = void 0; - _this13.code = code; - _this13.data = data; - _this13.name = 'SolanaJSONRPCError'; - return _this13; - } + throw new SolanaJSONRPCError(res.error, "failed to get balance for ".concat(publicKey.toBase58())); - return _createClass(SolanaJSONRPCError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); + case 8: + return _context10.abrupt("return", res.result); - var fetchImpl = globalThis.fetch; + case 9: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); - var RpcWebSocketClient = /*#__PURE__*/function (_RpcWebSocketCommonCl) { - _inherits(RpcWebSocketClient, _RpcWebSocketCommonCl); + function getBalanceAndContext(_x23, _x24) { + return _getBalanceAndContext.apply(this, arguments); + } - var _super8 = _createSuper(RpcWebSocketClient); + return getBalanceAndContext; + }() + /** + * Fetch the balance for the specified public key + */ - function RpcWebSocketClient(address, options, generate_request_id) { - var _this14; + }, { + key: "getBalance", + value: function () { + var _getBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(publicKey, commitmentOrConfig) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return this.getBalanceAndContext(publicKey, commitmentOrConfig).then(function (x) { + return x.value; + })["catch"](function (e) { + throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e); + }); - _classCallCheck(this, RpcWebSocketClient); + case 2: + return _context11.abrupt("return", _context11.sent); - var webSocketFactory = function webSocketFactory(url) { - var rpc = createRpc(url, _objectSpread2({ - autoconnect: true, - max_reconnects: 5, - reconnect: true, - reconnect_interval: 1000 - }, options)); + case 3: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); - if ('socket' in rpc) { - _this14.underlyingSocket = rpc.socket; - } else { - _this14.underlyingSocket = rpc; + function getBalance(_x25, _x26) { + return _getBalance.apply(this, arguments); } - return rpc; - }; - - _this14 = _super8.call(this, webSocketFactory, address, options, generate_request_id); - _this14.underlyingSocket = void 0; - return _this14; - } - - _createClass(RpcWebSocketClient, [{ - key: "call", - value: function call() { - var _this$underlyingSocke; + return getBalance; + }() + /** + * Fetch the estimated production time of a block + */ - var readyState = (_this$underlyingSocke = this.underlyingSocket) === null || _this$underlyingSocke === void 0 ? void 0 : _this$underlyingSocke.readyState; + }, { + key: "getBlockTime", + value: function () { + var _getBlockTime = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(slot) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return this._rpcRequest('getBlockTime', [slot]); - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } + case 2: + unsafeRes = _context12.sent; + res = _create(unsafeRes, jsonRpcResult(nullable(number()))); - if (readyState === 1 - /* WebSocket.OPEN */ - ) { - var _get2; + if (!('error' in res)) { + _context12.next = 6; + break; + } - return (_get2 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "call", this)).call.apply(_get2, [this].concat(args)); - } + throw new SolanaJSONRPCError(res.error, "failed to get block time for slot ".concat(slot)); - return Promise.reject(new Error('Tried to call a JSON-RPC method `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); - } - }, { - key: "notify", - value: function notify() { - var _this$underlyingSocke2; + case 6: + return _context12.abrupt("return", res.result); - var readyState = (_this$underlyingSocke2 = this.underlyingSocket) === null || _this$underlyingSocke2 === void 0 ? void 0 : _this$underlyingSocke2.readyState; + case 7: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); - for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; + function getBlockTime(_x27) { + return _getBlockTime.apply(this, arguments); } - if (readyState === 1 - /* WebSocket.OPEN */ - ) { - var _get3; + return getBlockTime; + }() + /** + * Fetch the lowest slot that the node has information about in its ledger. + * This value may increase over time if the node is configured to purge older ledger data + */ - return (_get3 = _get(_getPrototypeOf(RpcWebSocketClient.prototype), "notify", this)).call.apply(_get3, [this].concat(args)); - } + }, { + key: "getMinimumLedgerSlot", + value: function () { + var _getMinimumLedgerSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return this._rpcRequest('minimumLedgerSlot', []); - return Promise.reject(new Error('Tried to send a JSON-RPC notification `' + args[0] + '` but the socket was not `CONNECTING` or `OPEN` (`readyState` was ' + readyState + ')')); - } - }]); + case 2: + unsafeRes = _context13.sent; + res = _create(unsafeRes, jsonRpcResult(number())); - return RpcWebSocketClient; - }(RpcWebSocketCommonClient); // TODO: These constants should be removed in favor of reading them out of a - // Syscall account + if (!('error' in res)) { + _context13.next = 6; + break; + } - /** - * @internal - */ + throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot'); + case 6: + return _context13.abrupt("return", res.result); - var NUM_TICKS_PER_SECOND = 160; - /** - * @internal - */ + case 7: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); - var DEFAULT_TICKS_PER_SLOT = 64; - /** - * @internal - */ + function getMinimumLedgerSlot() { + return _getMinimumLedgerSlot.apply(this, arguments); + } - var NUM_SLOTS_PER_SECOND = NUM_TICKS_PER_SECOND / DEFAULT_TICKS_PER_SLOT; - /** - * @internal - */ + return getMinimumLedgerSlot; + }() + /** + * Fetch the slot of the lowest confirmed block that has not been purged from the ledger + */ - var MS_PER_SLOT = 1000 / NUM_SLOTS_PER_SECOND; - /** - * @internal - */ + }, { + key: "getFirstAvailableBlock", + value: function () { + var _getFirstAvailableBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return this._rpcRequest('getFirstAvailableBlock', []); - /** - * Decode account data buffer using an AccountType - * @internal - */ + case 2: + unsafeRes = _context14.sent; + res = _create(unsafeRes, SlotRpcResult); - function decodeData(type, data) { - var decoded; + if (!('error' in res)) { + _context14.next = 6; + break; + } - try { - decoded = type.layout.decode(data); - } catch (err) { - throw new Error('invalid instruction; ' + err); - } + throw new SolanaJSONRPCError(res.error, 'failed to get first available block'); - if (decoded.typeIndex !== type.index) { - throw new Error("invalid account data; account type mismatch ".concat(decoded.typeIndex, " != ").concat(type.index)); - } + case 6: + return _context14.abrupt("return", res.result); - return decoded; - } /// The serialized size of lookup table metadata + case 7: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function getFirstAvailableBlock() { + return _getFirstAvailableBlock.apply(this, arguments); + } - var LOOKUP_TABLE_META_SIZE = 56; + return getFirstAvailableBlock; + }() + /** + * Fetch information about the current supply + */ - var AddressLookupTableAccount = /*#__PURE__*/function () { - function AddressLookupTableAccount(args) { - _classCallCheck(this, AddressLookupTableAccount); + }, { + key: "getSupply", + value: function () { + var _getSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(config) { + var configArg, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + configArg = {}; - this.key = void 0; - this.state = void 0; - this.key = args.key; - this.state = args.state; - } + if (typeof config === 'string') { + configArg = { + commitment: config + }; + } else if (config) { + configArg = _objectSpread2(_objectSpread2({}, config), {}, { + commitment: config && config.commitment || this.commitment + }); + } else { + configArg = { + commitment: this.commitment + }; + } - _createClass(AddressLookupTableAccount, [{ - key: "isActive", - value: function isActive() { - var U64_MAX = BigInt('0xffffffffffffffff'); - return this.state.deactivationSlot === U64_MAX; - } - }], [{ - key: "deserialize", - value: function deserialize(accountData) { - var meta = decodeData(LookupTableMetaLayout, accountData); - var serializedAddressesLen = accountData.length - LOOKUP_TABLE_META_SIZE; - assert(serializedAddressesLen >= 0, 'lookup table is invalid'); - assert(serializedAddressesLen % 32 === 0, 'lookup table is invalid'); - var numSerializedAddresses = serializedAddressesLen / 32; + _context15.next = 4; + return this._rpcRequest('getSupply', [configArg]); - var _BufferLayout$struct$ = struct([seq$1(publicKey(), numSerializedAddresses, 'addresses')]).decode(accountData.slice(LOOKUP_TABLE_META_SIZE)), - addresses = _BufferLayout$struct$.addresses; + case 4: + unsafeRes = _context15.sent; + res = _create(unsafeRes, GetSupplyRpcResult); - return { - deactivationSlot: meta.deactivationSlot, - lastExtendedSlot: meta.lastExtendedSlot, - lastExtendedSlotStartIndex: meta.lastExtendedStartIndex, - authority: meta.authority.length !== 0 ? new PublicKey(meta.authority[0]) : undefined, - addresses: addresses.map(function (address) { - return new PublicKey(address); - }) - }; - } - }]); + if (!('error' in res)) { + _context15.next = 8; + break; + } - return AddressLookupTableAccount; - }(); + throw new SolanaJSONRPCError(res.error, 'failed to get supply'); - var LookupTableMetaLayout = { - index: 1, - layout: struct([u32('typeIndex'), u64('deactivationSlot'), nu64$1('lastExtendedSlot'), u8('lastExtendedStartIndex'), u8(), // option - seq$1(publicKey(), offset$1(u8(), -1), 'authority')]) - }; - var URL_RE = /^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i; + case 8: + return _context15.abrupt("return", res.result); - function makeWebsocketUrl(endpoint) { - var matches = endpoint.match(URL_RE); + case 9: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); - if (matches == null) { - throw TypeError("Failed to validate endpoint URL `".concat(endpoint, "`")); - } + function getSupply(_x28) { + return _getSupply.apply(this, arguments); + } - var _matches = _slicedToArray(matches, 4); - _matches[0]; - var // eslint-disable-line @typescript-eslint/no-unused-vars - hostish = _matches[1], - portWithColon = _matches[2], - rest = _matches[3]; + return getSupply; + }() + /** + * Fetch the current supply of a token mint + */ - var protocol = endpoint.startsWith('https:') ? 'wss:' : 'ws:'; - var startPort = portWithColon == null ? null : parseInt(portWithColon.slice(1), 10); - var websocketPort = // Only shift the port by +1 as a convention for ws(s) only if given endpoint - // is explictly specifying the endpoint port (HTTP-based RPC), assuming - // we're directly trying to connect to solana-validator's ws listening port. - // When the endpoint omits the port, we're connecting to the protocol - // default ports: http(80) or https(443) and it's assumed we're behind a reverse - // proxy which manages WebSocket upgrade and backend port redirection. - startPort == null ? '' : ":".concat(startPort + 1); - return "".concat(protocol, "//").concat(hostish).concat(websocketPort).concat(rest); - } + }, { + key: "getTokenSupply", + value: function () { + var _getTokenSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(tokenMintAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + args = this._buildArgs([tokenMintAddress.toBase58()], commitment); + _context16.next = 3; + return this._rpcRequest('getTokenSupply', args); - var PublicKeyFromString = coerce(instance(PublicKey), string(), function (value) { - return new PublicKey(value); - }); - var RawAccountDataResult = tuple([string(), literal('base64')]); - var BufferFromRawAccountData = coerce(instance(Buffer$1), RawAccountDataResult, function (value) { - return Buffer$1.from(value[0], 'base64'); - }); - /** - * Attempt to use a recent blockhash for up to 30 seconds - * @internal - */ + case 3: + unsafeRes = _context16.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); - var BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000; - /** - * HACK. - * Copied from rpc-websockets/dist/lib/client. - * Otherwise, `yarn build` fails with: - * https://gist.github.com/steveluscher/c057eca81d479ef705cdb53162f9971d - */ + if (!('error' in res)) { + _context16.next = 7; + break; + } - /* @internal */ + throw new SolanaJSONRPCError(res.error, 'failed to get token supply'); - function assertEndpointUrl(putativeUrl) { - if (/^https?:/.test(putativeUrl) === false) { - throw new TypeError('Endpoint URL must start with `http:` or `https:`.'); - } + case 7: + return _context16.abrupt("return", res.result); - return putativeUrl; - } - /** @internal */ + case 8: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getTokenSupply(_x29, _x30) { + return _getTokenSupply.apply(this, arguments); + } - function extractCommitmentFromConfig(commitmentOrConfig) { - var commitment; - var config; + return getTokenSupply; + }() + /** + * Fetch the current balance of a token account + */ - if (typeof commitmentOrConfig === 'string') { - commitment = commitmentOrConfig; - } else if (commitmentOrConfig) { - var specifiedCommitment = commitmentOrConfig.commitment, - specifiedConfig = _objectWithoutProperties(commitmentOrConfig, _excluded); + }, { + key: "getTokenAccountBalance", + value: function () { + var _getTokenAccountBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(tokenAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + args = this._buildArgs([tokenAddress.toBase58()], commitment); + _context17.next = 3; + return this._rpcRequest('getTokenAccountBalance', args); - commitment = specifiedCommitment; - config = specifiedConfig; - } + case 3: + unsafeRes = _context17.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); - return { - commitment: commitment, - config: config - }; - } - /** - * @internal - */ + if (!('error' in res)) { + _context17.next = 7; + break; + } + throw new SolanaJSONRPCError(res.error, 'failed to get token account balance'); - function createRpcResult(result) { - return union([type({ - jsonrpc: literal('2.0'), - id: string(), - result: result - }), type({ - jsonrpc: literal('2.0'), - id: string(), - error: type({ - code: unknown(), - message: string(), - data: optional(any()) - }) - })]); - } + case 7: + return _context17.abrupt("return", res.result); - var UnknownRpcResult = createRpcResult(unknown()); - /** - * @internal - */ + case 8: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); - function jsonRpcResult(schema) { - return coerce(createRpcResult(schema), UnknownRpcResult, function (value) { - if ('error' in value) { - return value; - } else { - return _objectSpread2(_objectSpread2({}, value), {}, { - result: _create(value.result, schema) - }); - } - }); - } - /** - * @internal - */ + function getTokenAccountBalance(_x31, _x32) { + return _getTokenAccountBalance.apply(this, arguments); + } + return getTokenAccountBalance; + }() + /** + * Fetch all the token accounts owned by the specified account + * + * @return {Promise}>>>} + */ - function jsonRpcResultAndContext(value) { - return jsonRpcResult(type({ - context: type({ - slot: number() - }), - value: value - })); - } - /** - * @internal - */ + }, { + key: "getTokenAccountsByOwner", + value: function () { + var _getTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(ownerAddress, filter, commitmentOrConfig) { + var _extractCommitmentFro3, commitment, config, _args, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + _extractCommitmentFro3 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro3.commitment, config = _extractCommitmentFro3.config; + _args = [ownerAddress.toBase58()]; - function notificationResultAndContext(value) { - return type({ - context: type({ - slot: number() - }), - value: value - }); - } - /** - * @internal - */ + if ('mint' in filter) { + _args.push({ + mint: filter.mint.toBase58() + }); + } else { + _args.push({ + programId: filter.programId.toBase58() + }); + } + args = this._buildArgs(_args, commitment, 'base64', config); + _context18.next = 6; + return this._rpcRequest('getTokenAccountsByOwner', args); - function versionedMessageFromResponse(version, response) { - if (version === 0) { - return new MessageV0({ - header: response.header, - staticAccountKeys: response.accountKeys.map(function (accountKey) { - return new PublicKey(accountKey); - }), - recentBlockhash: response.recentBlockhash, - compiledInstructions: response.instructions.map(function (ix) { - return { - programIdIndex: ix.programIdIndex, - accountKeyIndexes: ix.accounts, - data: bs58$1.decode(ix.data) - }; - }), - addressTableLookups: response.addressTableLookups - }); - } else { - return new Message(response); - } - } - /** - * The level of commitment desired when querying state - *
-	 *   'processed': Query the most recent block which has reached 1 confirmation by the connected node
-	 *   'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
-	 *   'finalized': Query the most recent block which has been finalized by the cluster
-	 * 
- */ + case 6: + unsafeRes = _context18.sent; + res = _create(unsafeRes, GetTokenAccountsByOwner); + if (!('error' in res)) { + _context18.next = 10; + break; + } - var GetInflationGovernorResult = type({ - foundation: number(), - foundationTerm: number(), - initial: number(), - taper: number(), - terminal: number() - }); - /** - * The inflation reward for an epoch - */ + throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); - /** - * Expected JSON RPC response for the "getInflationReward" message - */ + case 10: + return _context18.abrupt("return", res.result); - var GetInflationRewardResult = jsonRpcResult(array(nullable(type({ - epoch: number(), - effectiveSlot: number(), - amount: number(), - postBalance: number(), - commission: optional(nullable(number())) - })))); - /** - * Expected JSON RPC response for the "getRecentPrioritizationFees" message - */ + case 11: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); - var GetRecentPrioritizationFeesResult = array(type({ - slot: number(), - prioritizationFee: number() - })); - /** - * Expected JSON RPC response for the "getInflationRate" message - */ + function getTokenAccountsByOwner(_x33, _x34, _x35) { + return _getTokenAccountsByOwner.apply(this, arguments); + } - var GetInflationRateResult = type({ - total: number(), - validator: number(), - foundation: number(), - epoch: number() - }); - /** - * Information about the current epoch - */ + return getTokenAccountsByOwner; + }() + /** + * Fetch parsed token accounts owned by the specified account + * + * @return {Promise}>>>} + */ - var GetEpochInfoResult = type({ - epoch: number(), - slotIndex: number(), - slotsInEpoch: number(), - absoluteSlot: number(), - blockHeight: optional(number()), - transactionCount: optional(number()) - }); - var GetEpochScheduleResult = type({ - slotsPerEpoch: number(), - leaderScheduleSlotOffset: number(), - warmup: _boolean(), - firstNormalEpoch: number(), - firstNormalSlot: number() - }); - /** - * Leader schedule - * (see https://docs.solana.com/terminology#leader-schedule) - */ + }, { + key: "getParsedTokenAccountsByOwner", + value: function () { + var _getParsedTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(ownerAddress, filter, commitment) { + var _args, args, unsafeRes, res; - var GetLeaderScheduleResult = record(string(), array(number())); - /** - * Transaction error or null - */ + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _args = [ownerAddress.toBase58()]; - var TransactionErrorResult = nullable(union([type({}), string()])); - /** - * Signature status for a transaction - */ + if ('mint' in filter) { + _args.push({ + mint: filter.mint.toBase58() + }); + } else { + _args.push({ + programId: filter.programId.toBase58() + }); + } - var SignatureStatusResult = type({ - err: TransactionErrorResult - }); - /** - * Transaction signature received notification - */ + args = this._buildArgs(_args, commitment, 'jsonParsed'); + _context19.next = 5; + return this._rpcRequest('getTokenAccountsByOwner', args); - var SignatureReceivedResult = literal('receivedSignature'); - /** - * Version info for a node - */ + case 5: + unsafeRes = _context19.sent; + res = _create(unsafeRes, GetParsedTokenAccountsByOwner); - var VersionResult = type({ - 'solana-core': string(), - 'feature-set': optional(number()) - }); - var SimulatedTransactionResponseStruct = jsonRpcResultAndContext(type({ - err: nullable(union([type({}), string()])), - logs: nullable(array(string())), - accounts: optional(nullable(array(nullable(type({ - executable: _boolean(), - owner: string(), - lamports: number(), - data: array(string()), - rentEpoch: optional(number()) - }))))), - unitsConsumed: optional(number()), - returnData: optional(nullable(type({ - programId: string(), - data: tuple([string(), literal('base64')]) - }))) - })); - /** - * Expected JSON RPC response for the "getBlockProduction" message - */ + if (!('error' in res)) { + _context19.next = 9; + break; + } + + throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); - var BlockProductionResponseStruct = jsonRpcResultAndContext(type({ - byIdentity: record(string(), array(number())), - range: type({ - firstSlot: number(), - lastSlot: number() - }) - })); - /** - * A performance sample - */ + case 9: + return _context19.abrupt("return", res.result); - function createRpcClient(url, httpHeaders, customFetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent) { - var fetch = customFetch ? customFetch : fetchImpl; - var agent; - { - if (httpAgent != null) { - console.warn('You have supplied an `httpAgent` when creating a `Connection` in a browser environment.' + 'It has been ignored; `httpAgent` is only used in Node environments.'); - } - } - var fetchWithMiddleware; + case 10: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); - if (fetchMiddleware) { - fetchWithMiddleware = /*#__PURE__*/function () { - var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(info, init) { - var modifiedFetchArgs; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) switch (_context6.prev = _context6.next) { + function getParsedTokenAccountsByOwner(_x36, _x37, _x38) { + return _getParsedTokenAccountsByOwner.apply(this, arguments); + } + + return getParsedTokenAccountsByOwner; + }() + /** + * Fetch the 20 largest accounts with their current balances + */ + + }, { + key: "getLargestAccounts", + value: function () { + var _getLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(config) { + var arg, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { case 0: - _context6.next = 2; - return new Promise(function (resolve, reject) { - try { - fetchMiddleware(info, init, function (modifiedInfo, modifiedInit) { - return resolve([modifiedInfo, modifiedInit]); - }); - } catch (error) { - reject(error); - } + arg = _objectSpread2(_objectSpread2({}, config), {}, { + commitment: config && config.commitment || this.commitment }); + args = arg.filter || arg.commitment ? [arg] : []; + _context20.next = 4; + return this._rpcRequest('getLargestAccounts', args); - case 2: - modifiedFetchArgs = _context6.sent; - _context6.next = 5; - return fetch.apply(void 0, _toConsumableArray(modifiedFetchArgs)); + case 4: + unsafeRes = _context20.sent; + res = _create(unsafeRes, GetLargestAccountsRpcResult); - case 5: - return _context6.abrupt("return", _context6.sent); + if (!('error' in res)) { + _context20.next = 8; + break; + } - case 6: + throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts'); + + case 8: + return _context20.abrupt("return", res.result); + + case 9: case "end": - return _context6.stop(); + return _context20.stop(); } - }, _callee6); + }, _callee20, this); })); - return function fetchWithMiddleware(_x18, _x19) { - return _ref22.apply(this, arguments); - }; - }(); - } + function getLargestAccounts(_x39) { + return _getLargestAccounts.apply(this, arguments); + } - var clientBrowser = new RpcClient( /*#__PURE__*/function () { - var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(request, callback) { - var options, too_many_requests_retries, res, waitTime, text; - return _regeneratorRuntime().wrap(function _callee7$(_context7) { - while (1) switch (_context7.prev = _context7.next) { - case 0: - options = { - method: 'POST', - body: request, - agent: agent, - headers: Object.assign({ - 'Content-Type': 'application/json' - }, httpHeaders || {}, COMMON_HTTP_HEADERS) - }; - _context7.prev = 1; - too_many_requests_retries = 5; - waitTime = 500; + return getLargestAccounts; + }() + /** + * Fetch the 20 largest token accounts with their current balances + * for a given mint. + */ - case 4: - if (!fetchWithMiddleware) { - _context7.next = 10; - break; - } + }, { + key: "getTokenLargestAccounts", + value: function () { + var _getTokenLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(mintAddress, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + args = this._buildArgs([mintAddress.toBase58()], commitment); + _context21.next = 3; + return this._rpcRequest('getTokenLargestAccounts', args); - _context7.next = 7; - return fetchWithMiddleware(url, options); + case 3: + unsafeRes = _context21.sent; + res = _create(unsafeRes, GetTokenLargestAccountsResult); - case 7: - res = _context7.sent; - _context7.next = 13; - break; + if (!('error' in res)) { + _context21.next = 7; + break; + } - case 10: - _context7.next = 12; - return fetch(url, options); + throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts'); - case 12: - res = _context7.sent; + case 7: + return _context21.abrupt("return", res.result); - case 13: - if (!(res.status !== 429 - /* Too many requests */ - )) { - _context7.next = 15; - break; - } + case 8: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); - return _context7.abrupt("break", 26); + function getTokenLargestAccounts(_x40, _x41) { + return _getTokenLargestAccounts.apply(this, arguments); + } - case 15: - if (!(disableRetryOnRateLimit === true)) { - _context7.next = 17; - break; - } + return getTokenLargestAccounts; + }() + /** + * Fetch all the account info for the specified public key, return with context + */ - return _context7.abrupt("break", 26); + }, { + key: "getAccountInfoAndContext", + value: function () { + var _getAccountInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(publicKey, commitmentOrConfig) { + var _extractCommitmentFro4, commitment, config, args, unsafeRes, res; - case 17: - too_many_requests_retries -= 1; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + _extractCommitmentFro4 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro4.commitment, config = _extractCommitmentFro4.config; + args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config); + _context22.next = 4; + return this._rpcRequest('getAccountInfo', args); - if (!(too_many_requests_retries === 0)) { - _context7.next = 20; - break; - } + case 4: + unsafeRes = _context22.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult))); - return _context7.abrupt("break", 26); + if (!('error' in res)) { + _context22.next = 8; + break; + } - case 20: - console.log("Server responded with ".concat(res.status, " ").concat(res.statusText, ". Retrying after ").concat(waitTime, "ms delay...")); - _context7.next = 23; - return sleep(waitTime); + throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); - case 23: - waitTime *= 2; + case 8: + return _context22.abrupt("return", res.result); - case 24: - _context7.next = 4; - break; + case 9: + case "end": + return _context22.stop(); + } + }, _callee22, this); + })); - case 26: - _context7.next = 28; - return res.text(); + function getAccountInfoAndContext(_x42, _x43) { + return _getAccountInfoAndContext.apply(this, arguments); + } - case 28: - text = _context7.sent; + return getAccountInfoAndContext; + }() + /** + * Fetch parsed account info for the specified public key + */ - if (res.ok) { - callback(null, text); - } else { - callback(new Error("".concat(res.status, " ").concat(res.statusText, ": ").concat(text))); - } + }, { + key: "getParsedAccountInfo", + value: function () { + var _getParsedAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(publicKey, commitmentOrConfig) { + var _extractCommitmentFro5, commitment, config, args, unsafeRes, res; - _context7.next = 35; - break; + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + _extractCommitmentFro5 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro5.commitment, config = _extractCommitmentFro5.config; + args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config); + _context23.next = 4; + return this._rpcRequest('getAccountInfo', args); - case 32: - _context7.prev = 32; - _context7.t0 = _context7["catch"](1); - if (_context7.t0 instanceof Error) callback(_context7.t0); + case 4: + unsafeRes = _context23.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult))); - case 35: - case "end": - return _context7.stop(); - } - }, _callee7, null, [[1, 32]]); - })); + if (!('error' in res)) { + _context23.next = 8; + break; + } - return function (_x20, _x21) { - return _ref23.apply(this, arguments); - }; - }(), {}); - return clientBrowser; - } + throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); - function createRpcRequest(client) { - return function (method, args) { - return new Promise(function (resolve, reject) { - client.request(method, args, function (err, response) { - if (err) { - reject(err); - return; - } + case 8: + return _context23.abrupt("return", res.result); - resolve(response); - }); - }); - }; - } + case 9: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); - function createRpcBatchRequest(client) { - return function (requests) { - return new Promise(function (resolve, reject) { - // Do nothing if requests is empty - if (requests.length === 0) resolve([]); - var batch = requests.map(function (params) { - return client.request(params.methodName, params.args); - }); - client.request(batch, function (err, response) { - if (err) { - reject(err); - return; - } + function getParsedAccountInfo(_x44, _x45) { + return _getParsedAccountInfo.apply(this, arguments); + } - resolve(response); - }); - }); - }; - } - /** - * Expected JSON RPC response for the "getInflationGovernor" message - */ + return getParsedAccountInfo; + }() + /** + * Fetch all the account info for the specified public key + */ + }, { + key: "getAccountInfo", + value: function () { + var _getAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(publicKey, commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + _context24.prev = 0; + _context24.next = 3; + return this.getAccountInfoAndContext(publicKey, commitmentOrConfig); - var GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult); - /** - * Expected JSON RPC response for the "getInflationRate" message - */ + case 3: + res = _context24.sent; + return _context24.abrupt("return", res.value); - var GetInflationRateRpcResult = jsonRpcResult(GetInflationRateResult); - /** - * Expected JSON RPC response for the "getRecentPrioritizationFees" message - */ + case 7: + _context24.prev = 7; + _context24.t0 = _context24["catch"](0); + throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + _context24.t0); - var GetRecentPrioritizationFeesRpcResult = jsonRpcResult(GetRecentPrioritizationFeesResult); - /** - * Expected JSON RPC response for the "getEpochInfo" message - */ + case 10: + case "end": + return _context24.stop(); + } + }, _callee24, this, [[0, 7]]); + })); - var GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult); - /** - * Expected JSON RPC response for the "getEpochSchedule" message - */ + function getAccountInfo(_x46, _x47) { + return _getAccountInfo.apply(this, arguments); + } - var GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult); - /** - * Expected JSON RPC response for the "getLeaderSchedule" message - */ + return getAccountInfo; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + */ - var GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult); - /** - * Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages - */ + }, { + key: "getMultipleParsedAccounts", + value: function () { + var _getMultipleParsedAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(publicKeys, rawConfig) { + var _extractCommitmentFro6, commitment, config, keys, args, unsafeRes, res; - var SlotRpcResult = jsonRpcResult(number()); - /** - * Supply - */ + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + _extractCommitmentFro6 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro6.commitment, config = _extractCommitmentFro6.config; + keys = publicKeys.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs([keys], commitment, 'jsonParsed', config); + _context25.next = 5; + return this._rpcRequest('getMultipleAccounts', args); - /** - * Expected JSON RPC response for the "getSupply" message - */ + case 5: + unsafeRes = _context25.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult)))); - var GetSupplyRpcResult = jsonRpcResultAndContext(type({ - total: number(), - circulating: number(), - nonCirculating: number(), - nonCirculatingAccounts: array(PublicKeyFromString) - })); - /** - * Token amount object which returns a token amount in different formats - * for various client use cases. - */ + if (!('error' in res)) { + _context25.next = 9; + break; + } - /** - * Expected JSON RPC structure for token amounts - */ + throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); - var TokenAmountResult = type({ - amount: string(), - uiAmount: nullable(number()), - decimals: number(), - uiAmountString: optional(string()) - }); - /** - * Token address and balance. - */ + case 9: + return _context25.abrupt("return", res.result); - /** - * Expected JSON RPC response for the "getTokenLargestAccounts" message - */ + case 10: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); - var GetTokenLargestAccountsResult = jsonRpcResultAndContext(array(type({ - address: PublicKeyFromString, - amount: string(), - uiAmount: nullable(number()), - decimals: number(), - uiAmountString: optional(string()) - }))); - /** - * Expected JSON RPC response for the "getTokenAccountsByOwner" message - */ + function getMultipleParsedAccounts(_x48, _x49) { + return _getMultipleParsedAccounts.apply(this, arguments); + } - var GetTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ - pubkey: PublicKeyFromString, - account: type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: BufferFromRawAccountData, - rentEpoch: number() - }) - }))); - var ParsedAccountDataResult = type({ - program: string(), - parsed: unknown(), - space: number() - }); - /** - * Expected JSON RPC response for the "getTokenAccountsByOwner" message with parsed data - */ + return getMultipleParsedAccounts; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + */ - var GetParsedTokenAccountsByOwner = jsonRpcResultAndContext(array(type({ - pubkey: PublicKeyFromString, - account: type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: ParsedAccountDataResult, - rentEpoch: number() - }) - }))); - /** - * Pair of an account address and its balance - */ + }, { + key: "getMultipleAccountsInfoAndContext", + value: function () { + var _getMultipleAccountsInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(publicKeys, commitmentOrConfig) { + var _extractCommitmentFro7, commitment, config, keys, args, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee26$(_context26) { + while (1) switch (_context26.prev = _context26.next) { + case 0: + _extractCommitmentFro7 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro7.commitment, config = _extractCommitmentFro7.config; + keys = publicKeys.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs([keys], commitment, 'base64', config); + _context26.next = 5; + return this._rpcRequest('getMultipleAccounts', args); - /** - * Expected JSON RPC response for the "getLargestAccounts" message - */ + case 5: + unsafeRes = _context26.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult)))); - var GetLargestAccountsRpcResult = jsonRpcResultAndContext(array(type({ - lamports: number(), - address: PublicKeyFromString - }))); - /** - * @internal - */ + if (!('error' in res)) { + _context26.next = 9; + break; + } - var AccountInfoResult = type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: BufferFromRawAccountData, - rentEpoch: number() - }); - /** - * @internal - */ + throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); - var KeyedAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: AccountInfoResult - }); - var ParsedOrRawAccountData = coerce(union([instance(Buffer$1), ParsedAccountDataResult]), union([RawAccountDataResult, ParsedAccountDataResult]), function (value) { - if (Array.isArray(value)) { - return _create(value, BufferFromRawAccountData); - } else { - return value; - } - }); - /** - * @internal - */ + case 9: + return _context26.abrupt("return", res.result); - var ParsedAccountInfoResult = type({ - executable: _boolean(), - owner: PublicKeyFromString, - lamports: number(), - data: ParsedOrRawAccountData, - rentEpoch: number() - }); - var KeyedParsedAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: ParsedAccountInfoResult - }); - /** - * @internal - */ + case 10: + case "end": + return _context26.stop(); + } + }, _callee26, this); + })); - var StakeActivationResult = type({ - state: union([literal('active'), literal('inactive'), literal('activating'), literal('deactivating')]), - active: number(), - inactive: number() - }); - /** - * Expected JSON RPC response for the "getConfirmedSignaturesForAddress2" message - */ + function getMultipleAccountsInfoAndContext(_x50, _x51) { + return _getMultipleAccountsInfoAndContext.apply(this, arguments); + } - var GetConfirmedSignaturesForAddress2RpcResult = jsonRpcResult(array(type({ - signature: string(), - slot: number(), - err: TransactionErrorResult, - memo: nullable(string()), - blockTime: optional(nullable(number())) - }))); - /** - * Expected JSON RPC response for the "getSignaturesForAddress" message - */ + return getMultipleAccountsInfoAndContext; + }() + /** + * Fetch all the account info for multiple accounts specified by an array of public keys + */ - var GetSignaturesForAddressRpcResult = jsonRpcResult(array(type({ - signature: string(), - slot: number(), - err: TransactionErrorResult, - memo: nullable(string()), - blockTime: optional(nullable(number())) - }))); - /*** - * Expected JSON RPC response for the "accountNotification" message - */ + }, { + key: "getMultipleAccountsInfo", + value: function () { + var _getMultipleAccountsInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27(publicKeys, commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee27$(_context27) { + while (1) switch (_context27.prev = _context27.next) { + case 0: + _context27.next = 2; + return this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig); - var AccountNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(AccountInfoResult) - }); - /** - * @internal - */ + case 2: + res = _context27.sent; + return _context27.abrupt("return", res.value); - var ProgramAccountInfoResult = type({ - pubkey: PublicKeyFromString, - account: AccountInfoResult - }); - /*** - * Expected JSON RPC response for the "programNotification" message - */ + case 4: + case "end": + return _context27.stop(); + } + }, _callee27, this); + })); - var ProgramAccountNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(ProgramAccountInfoResult) - }); - /** - * @internal - */ + function getMultipleAccountsInfo(_x52, _x53) { + return _getMultipleAccountsInfo.apply(this, arguments); + } - var SlotInfoResult = type({ - parent: number(), - slot: number(), - root: number() - }); - /** - * Expected JSON RPC response for the "slotNotification" message - */ + return getMultipleAccountsInfo; + }() + /** + * Returns epoch activation information for a stake account that has been delegated + */ - var SlotNotificationResult = type({ - subscription: number(), - result: SlotInfoResult - }); - /** - * Slot updates which can be used for tracking the live progress of a cluster. - * - `"firstShredReceived"`: connected node received the first shred of a block. - * Indicates that a new block that is being produced. - * - `"completed"`: connected node has received all shreds of a block. Indicates - * a block was recently produced. - * - `"optimisticConfirmation"`: block was optimistically confirmed by the - * cluster. It is not guaranteed that an optimistic confirmation notification - * will be sent for every finalized blocks. - * - `"root"`: the connected node rooted this block. - * - `"createdBank"`: the connected node has started validating this block. - * - `"frozen"`: the connected node has validated this block. - * - `"dead"`: the connected node failed to validate this block. - */ + }, { + key: "getStakeActivation", + value: function () { + var _getStakeActivation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28(publicKey, commitmentOrConfig, epoch) { + var _extractCommitmentFro8, commitment, config, args, unsafeRes, res; - /** - * @internal - */ + return _regeneratorRuntime().wrap(function _callee28$(_context28) { + while (1) switch (_context28.prev = _context28.next) { + case 0: + _extractCommitmentFro8 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro8.commitment, config = _extractCommitmentFro8.config; + args = this._buildArgs([publicKey.toBase58()], commitment, undefined + /* encoding */ + , _objectSpread2(_objectSpread2({}, config), {}, { + epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch + })); + _context28.next = 4; + return this._rpcRequest('getStakeActivation', args); - var SlotUpdateResult = union([type({ - type: union([literal('firstShredReceived'), literal('completed'), literal('optimisticConfirmation'), literal('root')]), - slot: number(), - timestamp: number() - }), type({ - type: literal('createdBank'), - parent: number(), - slot: number(), - timestamp: number() - }), type({ - type: literal('frozen'), - slot: number(), - timestamp: number(), - stats: type({ - numTransactionEntries: number(), - numSuccessfulTransactions: number(), - numFailedTransactions: number(), - maxTransactionsPerEntry: number() - }) - }), type({ - type: literal('dead'), - slot: number(), - timestamp: number(), - err: string() - })]); - /** - * Expected JSON RPC response for the "slotsUpdatesNotification" message - */ + case 4: + unsafeRes = _context28.sent; + res = _create(unsafeRes, jsonRpcResult(StakeActivationResult)); - var SlotUpdateNotificationResult = type({ - subscription: number(), - result: SlotUpdateResult - }); - /** - * Expected JSON RPC response for the "signatureNotification" message - */ + if (!('error' in res)) { + _context28.next = 8; + break; + } - var SignatureNotificationResult = type({ - subscription: number(), - result: notificationResultAndContext(union([SignatureStatusResult, SignatureReceivedResult])) - }); - /** - * Expected JSON RPC response for the "rootNotification" message - */ + throw new SolanaJSONRPCError(res.error, "failed to get Stake Activation ".concat(publicKey.toBase58())); - var RootNotificationResult = type({ - subscription: number(), - result: number() - }); - var ContactInfoResult = type({ - pubkey: string(), - gossip: nullable(string()), - tpu: nullable(string()), - rpc: nullable(string()), - version: nullable(string()) - }); - var VoteAccountInfoResult = type({ - votePubkey: string(), - nodePubkey: string(), - activatedStake: number(), - epochVoteAccount: _boolean(), - epochCredits: array(tuple([number(), number(), number()])), - commission: number(), - lastVote: number(), - rootSlot: nullable(number()) - }); - /** - * Expected JSON RPC response for the "getVoteAccounts" message - */ + case 8: + return _context28.abrupt("return", res.result); - var GetVoteAccounts = jsonRpcResult(type({ - current: array(VoteAccountInfoResult), - delinquent: array(VoteAccountInfoResult) - })); - var ConfirmationStatus = union([literal('processed'), literal('confirmed'), literal('finalized')]); - var SignatureStatusResponse = type({ - slot: number(), - confirmations: nullable(number()), - err: TransactionErrorResult, - confirmationStatus: optional(ConfirmationStatus) - }); - /** - * Expected JSON RPC response for the "getSignatureStatuses" message - */ + case 9: + case "end": + return _context28.stop(); + } + }, _callee28, this); + })); - var GetSignatureStatusesRpcResult = jsonRpcResultAndContext(array(nullable(SignatureStatusResponse))); - /** - * Expected JSON RPC response for the "getMinimumBalanceForRentExemption" message - */ + function getStakeActivation(_x54, _x55, _x56) { + return _getStakeActivation.apply(this, arguments); + } - var GetMinimumBalanceForRentExemptionRpcResult = jsonRpcResult(number()); - var AddressTableLookupStruct = type({ - accountKey: PublicKeyFromString, - writableIndexes: array(number()), - readonlyIndexes: array(number()) - }); - var ConfirmedTransactionResult = type({ - signatures: array(string()), - message: type({ - accountKeys: array(string()), - header: type({ - numRequiredSignatures: number(), - numReadonlySignedAccounts: number(), - numReadonlyUnsignedAccounts: number() - }), - instructions: array(type({ - accounts: array(number()), - data: string(), - programIdIndex: number() - })), - recentBlockhash: string(), - addressTableLookups: optional(array(AddressTableLookupStruct)) - }) - }); - var AnnotatedAccountKey = type({ - pubkey: PublicKeyFromString, - signer: _boolean(), - writable: _boolean(), - source: optional(union([literal('transaction'), literal('lookupTable')])) - }); - var ConfirmedTransactionAccountsModeResult = type({ - accountKeys: array(AnnotatedAccountKey), - signatures: array(string()) - }); - var ParsedInstructionResult = type({ - parsed: unknown(), - program: string(), - programId: PublicKeyFromString - }); - var RawInstructionResult = type({ - accounts: array(PublicKeyFromString), - data: string(), - programId: PublicKeyFromString - }); - var InstructionResult = union([RawInstructionResult, ParsedInstructionResult]); - var UnknownInstructionResult = union([type({ - parsed: unknown(), - program: string(), - programId: string() - }), type({ - accounts: array(string()), - data: string(), - programId: string() - })]); - var ParsedOrRawInstruction = coerce(InstructionResult, UnknownInstructionResult, function (value) { - if ('accounts' in value) { - return _create(value, RawInstructionResult); - } else { - return _create(value, ParsedInstructionResult); - } - }); - /** - * @internal - */ + return getStakeActivation; + }() + /** + * Fetch all the accounts owned by the specified program id + * + * @return {Promise}>>} + */ - var ParsedConfirmedTransactionResult = type({ - signatures: array(string()), - message: type({ - accountKeys: array(AnnotatedAccountKey), - instructions: array(ParsedOrRawInstruction), - recentBlockhash: string(), - addressTableLookups: optional(nullable(array(AddressTableLookupStruct))) - }) - }); - var TokenBalanceResult = type({ - accountIndex: number(), - mint: string(), - owner: optional(string()), - uiTokenAmount: TokenAmountResult - }); - var LoadedAddressesResult = type({ - writable: array(PublicKeyFromString), - readonly: array(PublicKeyFromString) - }); - /** - * @internal - */ + }, { + key: "getProgramAccounts", + value: function () { + var _getProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee29(programId, configOrCommitment) { + var _extractCommitmentFro9, commitment, config, _ref26, encoding, configWithoutEncoding, args, unsafeRes, res; - var ConfirmedTransactionMetaResult = type({ - err: TransactionErrorResult, - fee: number(), - innerInstructions: optional(nullable(array(type({ - index: number(), - instructions: array(type({ - accounts: array(number()), - data: string(), - programIdIndex: number() - })) - })))), - preBalances: array(number()), - postBalances: array(number()), - logMessages: optional(nullable(array(string()))), - preTokenBalances: optional(nullable(array(TokenBalanceResult))), - postTokenBalances: optional(nullable(array(TokenBalanceResult))), - loadedAddresses: optional(LoadedAddressesResult), - computeUnitsConsumed: optional(number()) - }); - /** - * @internal - */ + return _regeneratorRuntime().wrap(function _callee29$(_context29) { + while (1) switch (_context29.prev = _context29.next) { + case 0: + _extractCommitmentFro9 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro9.commitment, config = _extractCommitmentFro9.config; + _ref26 = config || {}, encoding = _ref26.encoding, configWithoutEncoding = _objectWithoutProperties(_ref26, _excluded2); + args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', configWithoutEncoding); + _context29.next = 5; + return this._rpcRequest('getProgramAccounts', args); - var ParsedConfirmedTransactionMetaResult = type({ - err: TransactionErrorResult, - fee: number(), - innerInstructions: optional(nullable(array(type({ - index: number(), - instructions: array(ParsedOrRawInstruction) - })))), - preBalances: array(number()), - postBalances: array(number()), - logMessages: optional(nullable(array(string()))), - preTokenBalances: optional(nullable(array(TokenBalanceResult))), - postTokenBalances: optional(nullable(array(TokenBalanceResult))), - loadedAddresses: optional(LoadedAddressesResult), - computeUnitsConsumed: optional(number()) - }); - var TransactionVersionStruct = union([literal(0), literal('legacy')]); - /** @internal */ + case 5: + unsafeRes = _context29.sent; + res = _create(unsafeRes, jsonRpcResult(array(KeyedAccountInfoResult))); - var RewardsResult = type({ - pubkey: string(), - lamports: number(), - postBalance: nullable(number()), - rewardType: nullable(string()), - commission: optional(nullable(number())) - }); - /** - * Expected JSON RPC response for the "getBlock" message - */ + if (!('error' in res)) { + _context29.next = 9; + break; + } - var GetBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionResult, - meta: nullable(ConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `none` - */ + throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); - var GetNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` - */ + case 9: + return _context29.abrupt("return", res.result); - var GetAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionAccountsModeResult, - meta: nullable(ConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected parsed JSON RPC response for the "getBlock" message - */ + case 10: + case "end": + return _context29.stop(); + } + }, _callee29, this); + })); - var GetParsedBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ParsedConfirmedTransactionResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `accounts` - */ + function getProgramAccounts(_x57, _x58) { + return _getProgramAccounts.apply(this, arguments); + } - var GetParsedAccountsModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionAccountsModeResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - version: optional(TransactionVersionStruct) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected parsed JSON RPC response for the "getBlock" message when `transactionDetails` is `none` - */ + return getProgramAccounts; + }() + /** + * Fetch and parse all the accounts owned by the specified program id + * + * @return {Promise}>>} + */ - var GetParsedNoneModeBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()), - blockHeight: nullable(number()) - }))); - /** - * Expected JSON RPC response for the "getConfirmedBlock" message - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetBlockRpcResult} instead. - */ + }, { + key: "getParsedProgramAccounts", + value: function () { + var _getParsedProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee30(programId, configOrCommitment) { + var _extractCommitmentFro10, commitment, config, args, unsafeRes, res; - var GetConfirmedBlockRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - transactions: array(type({ - transaction: ConfirmedTransactionResult, - meta: nullable(ConfirmedTransactionMetaResult) - })), - rewards: optional(array(RewardsResult)), - blockTime: nullable(number()) - }))); - /** - * Expected JSON RPC response for the "getBlock" message - */ + return _regeneratorRuntime().wrap(function _callee30$(_context30) { + while (1) switch (_context30.prev = _context30.next) { + case 0: + _extractCommitmentFro10 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro10.commitment, config = _extractCommitmentFro10.config; + args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config); + _context30.next = 4; + return this._rpcRequest('getProgramAccounts', args); - var GetBlockSignaturesRpcResult = jsonRpcResult(nullable(type({ - blockhash: string(), - previousBlockhash: string(), - parentSlot: number(), - signatures: array(string()), - blockTime: nullable(number()) - }))); - /** - * Expected JSON RPC response for the "getTransaction" message - */ + case 4: + unsafeRes = _context30.sent; + res = _create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult))); - var GetTransactionRpcResult = jsonRpcResult(nullable(type({ - slot: number(), - meta: ConfirmedTransactionMetaResult, - blockTime: optional(nullable(number())), - transaction: ConfirmedTransactionResult, - version: optional(TransactionVersionStruct) - }))); - /** - * Expected parsed JSON RPC response for the "getTransaction" message - */ + if (!('error' in res)) { + _context30.next = 8; + break; + } - var GetParsedTransactionRpcResult = jsonRpcResult(nullable(type({ - slot: number(), - transaction: ParsedConfirmedTransactionResult, - meta: nullable(ParsedConfirmedTransactionMetaResult), - blockTime: optional(nullable(number())), - version: optional(TransactionVersionStruct) - }))); - /** - * Expected JSON RPC response for the "getRecentBlockhash" message - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link GetLatestBlockhashRpcResult} instead. - */ + throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); - var GetRecentBlockhashAndContextRpcResult = jsonRpcResultAndContext(type({ - blockhash: string(), - feeCalculator: type({ - lamportsPerSignature: number() - }) - })); - /** - * Expected JSON RPC response for the "getLatestBlockhash" message - */ + case 8: + return _context30.abrupt("return", res.result); - var GetLatestBlockhashRpcResult = jsonRpcResultAndContext(type({ - blockhash: string(), - lastValidBlockHeight: number() - })); - var PerfSampleResult = type({ - slot: number(), - numTransactions: number(), - numSlots: number(), - samplePeriodSecs: number() - }); - /* - * Expected JSON RPC response for "getRecentPerformanceSamples" message - */ + case 9: + case "end": + return _context30.stop(); + } + }, _callee30, this); + })); - var GetRecentPerformanceSamplesRpcResult = jsonRpcResult(array(PerfSampleResult)); - /** - * Expected JSON RPC response for the "getFeeCalculatorForBlockhash" message - */ + function getParsedProgramAccounts(_x59, _x60) { + return _getParsedProgramAccounts.apply(this, arguments); + } - var GetFeeCalculatorRpcResult = jsonRpcResultAndContext(nullable(type({ - feeCalculator: type({ - lamportsPerSignature: number() - }) - }))); - /** - * Expected JSON RPC response for the "requestAirdrop" message - */ + return getParsedProgramAccounts; + }() // eslint-disable-next-line no-dupe-class-members - var RequestAirdropRpcResult = jsonRpcResult(string()); - /** - * Expected JSON RPC response for the "sendTransaction" message - */ + }, { + key: "confirmTransaction", + value: function () { + var _confirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee31(strategy, commitment) { + var rawSignature, _config$abortSignal, config, decodedSignature; - var SendTransactionRpcResult = jsonRpcResult(string()); - /** - * Information about the latest slot being processed by a node - */ + return _regeneratorRuntime().wrap(function _callee31$(_context31) { + while (1) switch (_context31.prev = _context31.next) { + case 0: + if (!(typeof strategy == 'string')) { + _context31.next = 4; + break; + } - /** - * @internal - */ + rawSignature = strategy; + _context31.next = 8; + break; - var LogsResult = type({ - err: TransactionErrorResult, - logs: array(string()), - signature: string() - }); - /** - * Logs result. - */ + case 4: + config = strategy; - /** - * Expected JSON RPC response for the "logsNotification" message. - */ + if (!((_config$abortSignal = config.abortSignal) !== null && _config$abortSignal !== void 0 && _config$abortSignal.aborted)) { + _context31.next = 7; + break; + } - var LogsNotificationResult = type({ - result: notificationResultAndContext(LogsResult), - subscription: number() - }); - /** - * Filter for log subscriptions. - */ + return _context31.abrupt("return", Promise.reject(config.abortSignal.reason)); - /** @internal */ + case 7: + rawSignature = config.signature; - var COMMON_HTTP_HEADERS = { - 'solana-client': "js/".concat("0.0.0-development") - }; - /** - * A connection to a fullnode JSON RPC endpoint - */ + case 8: + _context31.prev = 8; + decodedSignature = bs58$3.decode(rawSignature); + _context31.next = 15; + break; - var Connection = /*#__PURE__*/function () { - /** @internal */ + case 12: + _context31.prev = 12; + _context31.t0 = _context31["catch"](8); + throw new Error('signature must be base58 encoded: ' + rawSignature); - /** @internal */ + case 15: + assert(decodedSignature.length === 64, 'signature has invalid length'); - /** @internal */ + if (!(typeof strategy === 'string')) { + _context31.next = 22; + break; + } - /** @internal */ + _context31.next = 19; + return this.confirmTransactionUsingLegacyTimeoutStrategy({ + commitment: commitment || this.commitment, + signature: rawSignature + }); - /** @internal */ + case 19: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 22: + if (!('lastValidBlockHeight' in strategy)) { + _context31.next = 28; + break; + } - /** @internal */ + _context31.next = 25; + return this.confirmTransactionUsingBlockHeightExceedanceStrategy({ + commitment: commitment || this.commitment, + strategy: strategy + }); - /** @internal */ + case 25: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 28: + _context31.next = 30; + return this.confirmTransactionUsingDurableNonceStrategy({ + commitment: commitment || this.commitment, + strategy: strategy + }); - /** @internal */ + case 30: + return _context31.abrupt("return", _context31.sent); - /** @internal */ + case 31: + case "end": + return _context31.stop(); + } + }, _callee31, this, [[8, 12]]); + })); - /** @internal - * A number that we increment every time an active connection closes. - * Used to determine whether the same socket connection that was open - * when an async operation started is the same one that's active when - * its continuation fires. - * - */ + function confirmTransaction(_x61, _x62) { + return _confirmTransaction.apply(this, arguments); + } - /** @internal */ + return confirmTransaction; + }() + }, { + key: "getCancellationPromise", + value: function getCancellationPromise(signal) { + return new Promise(function (_, reject) { + if (signal == null) { + return; + } - /** @internal */ + if (signal.aborted) { + reject(signal.reason); + } else { + signal.addEventListener('abort', function () { + reject(signal.reason); + }); + } + }); + } + }, { + key: "getTransactionConfirmationPromise", + value: function getTransactionConfirmationPromise(_ref27) { + var _this16 = this; - /** @internal */ + var commitment = _ref27.commitment, + signature = _ref27.signature; + var signatureSubscriptionId; + var disposeSignatureSubscriptionStateChangeObserver; + var done = false; + var confirmationPromise = new Promise(function (resolve, reject) { + try { + signatureSubscriptionId = _this16.onSignature(signature, function (result, context) { + signatureSubscriptionId = undefined; + var response = { + context: context, + value: result + }; + resolve({ + __type: TransactionStatus.PROCESSED, + response: response + }); + }, commitment); + var subscriptionSetupPromise = new Promise(function (resolveSubscriptionSetup) { + if (signatureSubscriptionId == null) { + resolveSubscriptionSetup(); + } else { + disposeSignatureSubscriptionStateChangeObserver = _this16._onSubscriptionStateChange(signatureSubscriptionId, function (nextState) { + if (nextState === 'subscribed') { + resolveSubscriptionSetup(); + } + }); + } + }); - /** @internal */ + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee32() { + var response, context, value; + return _regeneratorRuntime().wrap(function _callee32$(_context32) { + while (1) switch (_context32.prev = _context32.next) { + case 0: + _context32.next = 2; + return subscriptionSetupPromise; - /** @internal */ + case 2: + if (!done) { + _context32.next = 4; + break; + } - /** @internal */ + return _context32.abrupt("return"); - /** @internal */ + case 4: + _context32.next = 6; + return _this16.getSignatureStatus(signature); - /** @internal */ + case 6: + response = _context32.sent; - /** @internal */ + if (!done) { + _context32.next = 9; + break; + } - /** - * Special case. - * After a signature is processed, RPCs automatically dispose of the - * subscription on the server side. We need to track which of these - * subscriptions have been disposed in such a way, so that we know - * whether the client is dealing with a not-yet-processed signature - * (in which case we must tear down the server subscription) or an - * already-processed signature (in which case the client can simply - * clear out the subscription locally without telling the server). - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ + return _context32.abrupt("return"); - /** @internal */ + case 9: + if (!(response == null)) { + _context32.next = 11; + break; + } - /** - * Establish a JSON RPC connection - * - * @param endpoint URL to the fullnode JSON RPC endpoint - * @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object - */ - function Connection(endpoint, _commitmentOrConfig) { - var _this15 = this; + return _context32.abrupt("return"); - _classCallCheck(this, Connection); + case 11: + context = response.context, value = response.value; - this._commitment = void 0; - this._confirmTransactionInitialTimeout = void 0; - this._rpcEndpoint = void 0; - this._rpcWsEndpoint = void 0; - this._rpcClient = void 0; - this._rpcRequest = void 0; - this._rpcBatchRequest = void 0; - this._rpcWebSocket = void 0; - this._rpcWebSocketConnected = false; - this._rpcWebSocketHeartbeat = null; - this._rpcWebSocketIdleTimeout = null; - this._rpcWebSocketGeneration = 0; - this._disableBlockhashCaching = false; - this._pollingBlockhash = false; - this._blockhashInfo = { - latestBlockhash: null, - lastFetch: 0, - transactionSignatures: [], - simulatedSignatures: [] - }; - this._nextClientSubscriptionId = 0; - this._subscriptionDisposeFunctionsByClientSubscriptionId = {}; - this._subscriptionHashByClientSubscriptionId = {}; - this._subscriptionStateChangeCallbacksByHash = {}; - this._subscriptionCallbacksByServerSubscriptionId = {}; - this._subscriptionsByHash = {}; - this._subscriptionsAutoDisposedByRpc = new Set(); + if (!(value == null)) { + _context32.next = 14; + break; + } - this.getBlockHeight = function () { - var requestPromises = {}; - return /*#__PURE__*/function () { - var _ref24 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(commitmentOrConfig) { - var _requestPromises$requ; + return _context32.abrupt("return"); - var _extractCommitmentFro, commitment, config, args, requestHash; + case 14: + if (!(value !== null && value !== void 0 && value.err)) { + _context32.next = 18; + break; + } - return _regeneratorRuntime().wrap(function _callee9$(_context9) { - while (1) switch (_context9.prev = _context9.next) { - case 0: - _extractCommitmentFro = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro.commitment, config = _extractCommitmentFro.config; - args = _this15._buildArgs([], commitment, undefined - /* encoding */ - , config); - requestHash = fastStableStringify$1(args); - requestPromises[requestHash] = (_requestPromises$requ = requestPromises[requestHash]) !== null && _requestPromises$requ !== void 0 ? _requestPromises$requ : _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee8$(_context8) { - while (1) switch (_context8.prev = _context8.next) { - case 0: - _context8.prev = 0; - _context8.next = 3; - return _this15._rpcRequest('getBlockHeight', args); + reject(value.err); + _context32.next = 29; + break; - case 3: - unsafeRes = _context8.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + case 18: + _context32.t0 = commitment; + _context32.next = _context32.t0 === 'confirmed' ? 21 : _context32.t0 === 'single' ? 21 : _context32.t0 === 'singleGossip' ? 21 : _context32.t0 === 'finalized' ? 24 : _context32.t0 === 'max' ? 24 : _context32.t0 === 'root' ? 24 : _context32.t0 === 'processed' ? 27 : _context32.t0 === 'recent' ? 27 : 27; + break; - if (!('error' in res)) { - _context8.next = 7; - break; - } + case 21: + if (!(value.confirmationStatus === 'processed')) { + _context32.next = 23; + break; + } - throw new SolanaJSONRPCError(res.error, 'failed to get block height information'); + return _context32.abrupt("return"); - case 7: - return _context8.abrupt("return", res.result); + case 23: + return _context32.abrupt("break", 27); - case 8: - _context8.prev = 8; - delete requestPromises[requestHash]; - return _context8.finish(8); + case 24: + if (!(value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed')) { + _context32.next = 26; + break; + } + + return _context32.abrupt("return"); + + case 26: + return _context32.abrupt("break", 27); - case 11: - case "end": - return _context8.stop(); + case 27: + done = true; + resolve({ + __type: TransactionStatus.PROCESSED, + response: { + context: context, + value: value } - }, _callee8, null, [[0,, 8, 11]]); - }))(); - _context9.next = 6; - return requestPromises[requestHash]; + }); - case 6: - return _context9.abrupt("return", _context9.sent); + case 29: + case "end": + return _context32.stop(); + } + }, _callee32); + }))(); + } catch (err) { + reject(err); + } + }); - case 7: - case "end": - return _context9.stop(); - } - }, _callee9); - })); + var abortConfirmation = function abortConfirmation() { + if (disposeSignatureSubscriptionStateChangeObserver) { + disposeSignatureSubscriptionStateChangeObserver(); + disposeSignatureSubscriptionStateChangeObserver = undefined; + } - return function (_x22) { - return _ref24.apply(this, arguments); - }; - }(); - }(); + if (signatureSubscriptionId != null) { + _this16.removeSignatureListener(signatureSubscriptionId); - var wsEndpoint; - var httpHeaders; - var fetch; - var fetchMiddleware; - var disableRetryOnRateLimit; - var httpAgent; + signatureSubscriptionId = undefined; + } + }; - if (_commitmentOrConfig && typeof _commitmentOrConfig === 'string') { - this._commitment = _commitmentOrConfig; - } else if (_commitmentOrConfig) { - this._commitment = _commitmentOrConfig.commitment; - this._confirmTransactionInitialTimeout = _commitmentOrConfig.confirmTransactionInitialTimeout; - wsEndpoint = _commitmentOrConfig.wsEndpoint; - httpHeaders = _commitmentOrConfig.httpHeaders; - fetch = _commitmentOrConfig.fetch; - fetchMiddleware = _commitmentOrConfig.fetchMiddleware; - disableRetryOnRateLimit = _commitmentOrConfig.disableRetryOnRateLimit; - httpAgent = _commitmentOrConfig.httpAgent; + return { + abortConfirmation: abortConfirmation, + confirmationPromise: confirmationPromise + }; } + }, { + key: "confirmTransactionUsingBlockHeightExceedanceStrategy", + value: function () { + var _confirmTransactionUsingBlockHeightExceedanceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee35(_ref29) { + var _this17 = this; - this._rpcEndpoint = assertEndpointUrl(endpoint); - this._rpcWsEndpoint = wsEndpoint || makeWebsocketUrl(endpoint); - this._rpcClient = createRpcClient(endpoint, httpHeaders, fetch, fetchMiddleware, disableRetryOnRateLimit, httpAgent); - this._rpcRequest = createRpcRequest(this._rpcClient); - this._rpcBatchRequest = createRpcBatchRequest(this._rpcClient); - this._rpcWebSocket = new RpcWebSocketClient(this._rpcWsEndpoint, { - autoconnect: false, - max_reconnects: Infinity - }); + var commitment, _ref29$strategy, abortSignal, lastValidBlockHeight, signature, done, expiryPromise, _this$getTransactionC, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome; - this._rpcWebSocket.on('open', this._wsOnOpen.bind(this)); + return _regeneratorRuntime().wrap(function _callee35$(_context35) { + while (1) switch (_context35.prev = _context35.next) { + case 0: + commitment = _ref29.commitment, _ref29$strategy = _ref29.strategy, abortSignal = _ref29$strategy.abortSignal, lastValidBlockHeight = _ref29$strategy.lastValidBlockHeight, signature = _ref29$strategy.signature; + done = false; + expiryPromise = new Promise(function (resolve) { + var checkBlockHeight = /*#__PURE__*/function () { + var _ref30 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee33() { + var blockHeight; + return _regeneratorRuntime().wrap(function _callee33$(_context33) { + while (1) switch (_context33.prev = _context33.next) { + case 0: + _context33.prev = 0; + _context33.next = 3; + return _this17.getBlockHeight(commitment); - this._rpcWebSocket.on('error', this._wsOnError.bind(this)); + case 3: + blockHeight = _context33.sent; + return _context33.abrupt("return", blockHeight); - this._rpcWebSocket.on('close', this._wsOnClose.bind(this)); + case 7: + _context33.prev = 7; + _context33.t0 = _context33["catch"](0); + return _context33.abrupt("return", -1); - this._rpcWebSocket.on('accountNotification', this._wsOnAccountNotification.bind(this)); + case 10: + case "end": + return _context33.stop(); + } + }, _callee33, null, [[0, 7]]); + })); - this._rpcWebSocket.on('programNotification', this._wsOnProgramAccountNotification.bind(this)); + return function checkBlockHeight() { + return _ref30.apply(this, arguments); + }; + }(); - this._rpcWebSocket.on('slotNotification', this._wsOnSlotNotification.bind(this)); + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee34() { + var currentBlockHeight; + return _regeneratorRuntime().wrap(function _callee34$(_context34) { + while (1) switch (_context34.prev = _context34.next) { + case 0: + _context34.next = 2; + return checkBlockHeight(); - this._rpcWebSocket.on('slotsUpdatesNotification', this._wsOnSlotUpdatesNotification.bind(this)); + case 2: + currentBlockHeight = _context34.sent; - this._rpcWebSocket.on('signatureNotification', this._wsOnSignatureNotification.bind(this)); + if (!done) { + _context34.next = 5; + break; + } - this._rpcWebSocket.on('rootNotification', this._wsOnRootNotification.bind(this)); + return _context34.abrupt("return"); - this._rpcWebSocket.on('logsNotification', this._wsOnLogsNotification.bind(this)); - } - /** - * The default commitment used for requests - */ + case 5: + if (!(currentBlockHeight <= lastValidBlockHeight)) { + _context34.next = 17; + break; + } + _context34.next = 8; + return sleep(1000); - _createClass(Connection, [{ - key: "commitment", - get: function get() { - return this._commitment; - } - /** - * The RPC endpoint - */ + case 8: + if (!done) { + _context34.next = 10; + break; + } - }, { - key: "rpcEndpoint", - get: function get() { - return this._rpcEndpoint; - } - /** - * Fetch the balance for the specified public key, return with context - */ + return _context34.abrupt("return"); - }, { - key: "getBalanceAndContext", - value: function () { - var _getBalanceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(publicKey, commitmentOrConfig) { - var _extractCommitmentFro2, commitment, config, args, unsafeRes, res; + case 10: + _context34.next = 12; + return checkBlockHeight(); - return _regeneratorRuntime().wrap(function _callee10$(_context10) { - while (1) switch (_context10.prev = _context10.next) { - case 0: - /** @internal */ - _extractCommitmentFro2 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro2.commitment, config = _extractCommitmentFro2.config; - args = this._buildArgs([publicKey.toBase58()], commitment, undefined - /* encoding */ - , config); - _context10.next = 4; - return this._rpcRequest('getBalance', args); + case 12: + currentBlockHeight = _context34.sent; - case 4: - unsafeRes = _context10.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(number())); + if (!done) { + _context34.next = 15; + break; + } - if (!('error' in res)) { - _context10.next = 8; - break; - } + return _context34.abrupt("return"); - throw new SolanaJSONRPCError(res.error, "failed to get balance for ".concat(publicKey.toBase58())); + case 15: + _context34.next = 5; + break; + + case 17: + resolve({ + __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED + }); + + case 18: + case "end": + return _context34.stop(); + } + }, _callee34); + }))(); + }); + _this$getTransactionC = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC.abortConfirmation, confirmationPromise = _this$getTransactionC.confirmationPromise; + cancellationPromise = this.getCancellationPromise(abortSignal); + _context35.prev = 5; + _context35.next = 8; + return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); case 8: - return _context10.abrupt("return", res.result); + outcome = _context35.sent; - case 9: - case "end": - return _context10.stop(); - } - }, _callee10, this); - })); + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context35.next = 13; + break; + } - function getBalanceAndContext(_x23, _x24) { - return _getBalanceAndContext.apply(this, arguments); - } + result = outcome.response; + _context35.next = 14; + break; - return getBalanceAndContext; - }() - /** - * Fetch the balance for the specified public key - */ + case 13: + throw new TransactionExpiredBlockheightExceededError(signature); - }, { - key: "getBalance", - value: function () { - var _getBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(publicKey, commitmentOrConfig) { - return _regeneratorRuntime().wrap(function _callee11$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - _context11.next = 2; - return this.getBalanceAndContext(publicKey, commitmentOrConfig).then(function (x) { - return x.value; - })["catch"](function (e) { - throw new Error('failed to get balance of account ' + publicKey.toBase58() + ': ' + e); - }); + case 14: + _context35.prev = 14; + done = true; + abortConfirmation(); + return _context35.finish(14); - case 2: - return _context11.abrupt("return", _context11.sent); + case 18: + return _context35.abrupt("return", result); - case 3: + case 19: case "end": - return _context11.stop(); + return _context35.stop(); } - }, _callee11, this); + }, _callee35, this, [[5,, 14, 18]]); })); - function getBalance(_x25, _x26) { - return _getBalance.apply(this, arguments); + function confirmTransactionUsingBlockHeightExceedanceStrategy(_x63) { + return _confirmTransactionUsingBlockHeightExceedanceStrategy.apply(this, arguments); } - return getBalance; + return confirmTransactionUsingBlockHeightExceedanceStrategy; }() - /** - * Fetch the estimated production time of a block - */ - }, { - key: "getBlockTime", + key: "confirmTransactionUsingDurableNonceStrategy", value: function () { - var _getBlockTime = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(slot) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee12$(_context12) { - while (1) switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return this._rpcRequest('getBlockTime', [slot]); + var _confirmTransactionUsingDurableNonceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee38(_ref32) { + var _this18 = this; - case 2: - unsafeRes = _context12.sent; - res = _create(unsafeRes, jsonRpcResult(nullable(number()))); + var commitment, _ref32$strategy, abortSignal, minContextSlot, nonceAccountPubkey, nonceValue, signature, done, expiryPromise, _this$getTransactionC2, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome, _signatureStatus, signatureStatus, _outcome$slotInWhichN, status, commitmentForStatus, confirmationStatus; - if (!('error' in res)) { - _context12.next = 6; - break; - } + return _regeneratorRuntime().wrap(function _callee38$(_context38) { + while (1) switch (_context38.prev = _context38.next) { + case 0: + commitment = _ref32.commitment, _ref32$strategy = _ref32.strategy, abortSignal = _ref32$strategy.abortSignal, minContextSlot = _ref32$strategy.minContextSlot, nonceAccountPubkey = _ref32$strategy.nonceAccountPubkey, nonceValue = _ref32$strategy.nonceValue, signature = _ref32$strategy.signature; + done = false; + expiryPromise = new Promise(function (resolve) { + var currentNonceValue = nonceValue; + var lastCheckedSlot = null; - throw new SolanaJSONRPCError(res.error, "failed to get block time for slot ".concat(slot)); + var getCurrentNonceValue = /*#__PURE__*/function () { + var _ref33 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36() { + var _yield$_this18$getNon2, context, nonceAccount; - case 6: - return _context12.abrupt("return", res.result); + return _regeneratorRuntime().wrap(function _callee36$(_context36) { + while (1) switch (_context36.prev = _context36.next) { + case 0: + _context36.prev = 0; + _context36.next = 3; + return _this18.getNonceAndContext(nonceAccountPubkey, { + commitment: commitment, + minContextSlot: minContextSlot + }); - case 7: - case "end": - return _context12.stop(); - } - }, _callee12, this); - })); + case 3: + _yield$_this18$getNon2 = _context36.sent; + context = _yield$_this18$getNon2.context; + nonceAccount = _yield$_this18$getNon2.value; + lastCheckedSlot = context.slot; + return _context36.abrupt("return", nonceAccount === null || nonceAccount === void 0 ? void 0 : nonceAccount.nonce); - function getBlockTime(_x27) { - return _getBlockTime.apply(this, arguments); - } + case 10: + _context36.prev = 10; + _context36.t0 = _context36["catch"](0); + return _context36.abrupt("return", currentNonceValue); - return getBlockTime; - }() - /** - * Fetch the lowest slot that the node has information about in its ledger. - * This value may increase over time if the node is configured to purge older ledger data - */ + case 13: + case "end": + return _context36.stop(); + } + }, _callee36, null, [[0, 10]]); + })); - }, { - key: "getMinimumLedgerSlot", - value: function () { - var _getMinimumLedgerSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee13$(_context13) { - while (1) switch (_context13.prev = _context13.next) { - case 0: - _context13.next = 2; - return this._rpcRequest('minimumLedgerSlot', []); + return function getCurrentNonceValue() { + return _ref33.apply(this, arguments); + }; + }(); - case 2: - unsafeRes = _context13.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee37() { + return _regeneratorRuntime().wrap(function _callee37$(_context37) { + while (1) switch (_context37.prev = _context37.next) { + case 0: + _context37.next = 2; + return getCurrentNonceValue(); - if (!('error' in res)) { - _context13.next = 6; - break; - } + case 2: + currentNonceValue = _context37.sent; - throw new SolanaJSONRPCError(res.error, 'failed to get minimum ledger slot'); + if (!done) { + _context37.next = 5; + break; + } - case 6: - return _context13.abrupt("return", res.result); + return _context37.abrupt("return"); - case 7: - case "end": - return _context13.stop(); - } - }, _callee13, this); - })); + case 5: - function getMinimumLedgerSlot() { - return _getMinimumLedgerSlot.apply(this, arguments); - } + if (!(nonceValue !== currentNonceValue)) { + _context37.next = 9; + break; + } - return getMinimumLedgerSlot; - }() - /** - * Fetch the slot of the lowest confirmed block that has not been purged from the ledger - */ + resolve({ + __type: TransactionStatus.NONCE_INVALID, + slotInWhichNonceDidAdvance: lastCheckedSlot + }); + return _context37.abrupt("return"); - }, { - key: "getFirstAvailableBlock", - value: function () { - var _getFirstAvailableBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee14$(_context14) { - while (1) switch (_context14.prev = _context14.next) { - case 0: - _context14.next = 2; - return this._rpcRequest('getFirstAvailableBlock', []); + case 9: + _context37.next = 11; + return sleep(2000); - case 2: - unsafeRes = _context14.sent; - res = _create(unsafeRes, SlotRpcResult); + case 11: + if (!done) { + _context37.next = 13; + break; + } - if (!('error' in res)) { - _context14.next = 6; - break; - } + return _context37.abrupt("return"); - throw new SolanaJSONRPCError(res.error, 'failed to get first available block'); + case 13: + _context37.next = 15; + return getCurrentNonceValue(); - case 6: - return _context14.abrupt("return", res.result); + case 15: + currentNonceValue = _context37.sent; - case 7: - case "end": - return _context14.stop(); - } - }, _callee14, this); - })); + if (!done) { + _context37.next = 18; + break; + } - function getFirstAvailableBlock() { - return _getFirstAvailableBlock.apply(this, arguments); - } + return _context37.abrupt("return"); - return getFirstAvailableBlock; - }() - /** - * Fetch information about the current supply - */ + case 18: + _context37.next = 5; + break; - }, { - key: "getSupply", - value: function () { - var _getSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(config) { - var configArg, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee15$(_context15) { - while (1) switch (_context15.prev = _context15.next) { - case 0: - configArg = {}; + case 20: + case "end": + return _context37.stop(); + } + }, _callee37); + }))(); + }); + _this$getTransactionC2 = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC2.abortConfirmation, confirmationPromise = _this$getTransactionC2.confirmationPromise; + cancellationPromise = this.getCancellationPromise(abortSignal); + _context38.prev = 5; + _context38.next = 8; + return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + + case 8: + outcome = _context38.sent; - if (typeof config === 'string') { - configArg = { - commitment: config - }; - } else if (config) { - configArg = _objectSpread2(_objectSpread2({}, config), {}, { - commitment: config && config.commitment || this.commitment - }); - } else { - configArg = { - commitment: this.commitment - }; + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context38.next = 13; + break; } - _context15.next = 4; - return this._rpcRequest('getSupply', [configArg]); + result = outcome.response; + _context38.next = 47; + break; - case 4: - unsafeRes = _context15.sent; - res = _create(unsafeRes, GetSupplyRpcResult); + case 13: - if (!('error' in res)) { - _context15.next = 8; - break; - } + _context38.next = 16; + return this.getSignatureStatus(signature); - throw new SolanaJSONRPCError(res.error, 'failed to get supply'); + case 16: + status = _context38.sent; - case 8: - return _context15.abrupt("return", res.result); + if (!(status == null)) { + _context38.next = 19; + break; + } - case 9: - case "end": - return _context15.stop(); - } - }, _callee15, this); - })); + return _context38.abrupt("break", 27); - function getSupply(_x28) { - return _getSupply.apply(this, arguments); - } + case 19: + if (!(status.context.slot < ((_outcome$slotInWhichN = outcome.slotInWhichNonceDidAdvance) !== null && _outcome$slotInWhichN !== void 0 ? _outcome$slotInWhichN : minContextSlot))) { + _context38.next = 23; + break; + } - return getSupply; - }() - /** - * Fetch the current supply of a token mint - */ + _context38.next = 22; + return sleep(400); - }, { - key: "getTokenSupply", - value: function () { - var _getTokenSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(tokenMintAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee16$(_context16) { - while (1) switch (_context16.prev = _context16.next) { - case 0: - args = this._buildArgs([tokenMintAddress.toBase58()], commitment); - _context16.next = 3; - return this._rpcRequest('getTokenSupply', args); + case 22: + return _context38.abrupt("continue", 13); - case 3: - unsafeRes = _context16.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); + case 23: + signatureStatus = status; + return _context38.abrupt("break", 27); - if (!('error' in res)) { - _context16.next = 7; + case 27: + if (!((_signatureStatus = signatureStatus) !== null && _signatureStatus !== void 0 && _signatureStatus.value)) { + _context38.next = 46; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token supply'); + commitmentForStatus = commitment || 'finalized'; + confirmationStatus = signatureStatus.value.confirmationStatus; + _context38.t0 = commitmentForStatus; + _context38.next = _context38.t0 === 'processed' ? 33 : _context38.t0 === 'recent' ? 33 : _context38.t0 === 'confirmed' ? 36 : _context38.t0 === 'single' ? 36 : _context38.t0 === 'singleGossip' ? 36 : _context38.t0 === 'finalized' ? 39 : _context38.t0 === 'max' ? 39 : _context38.t0 === 'root' ? 39 : 42; + break; - case 7: - return _context16.abrupt("return", res.result); + case 33: + if (!(confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { + _context38.next = 35; + break; + } - case 8: - case "end": - return _context16.stop(); - } - }, _callee16, this); - })); + throw new TransactionExpiredNonceInvalidError(signature); - function getTokenSupply(_x29, _x30) { - return _getTokenSupply.apply(this, arguments); - } + case 35: + return _context38.abrupt("break", 43); - return getTokenSupply; - }() - /** - * Fetch the current balance of a token account - */ + case 36: + if (!(confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { + _context38.next = 38; + break; + } - }, { - key: "getTokenAccountBalance", - value: function () { - var _getTokenAccountBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(tokenAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee17$(_context17) { - while (1) switch (_context17.prev = _context17.next) { - case 0: - args = this._buildArgs([tokenAddress.toBase58()], commitment); - _context17.next = 3; - return this._rpcRequest('getTokenAccountBalance', args); + throw new TransactionExpiredNonceInvalidError(signature); - case 3: - unsafeRes = _context17.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(TokenAmountResult)); + case 38: + return _context38.abrupt("break", 43); - if (!('error' in res)) { - _context17.next = 7; + case 39: + if (!(confirmationStatus !== 'finalized')) { + _context38.next = 41; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token account balance'); + throw new TransactionExpiredNonceInvalidError(signature); - case 7: - return _context17.abrupt("return", res.result); + case 41: + return _context38.abrupt("break", 43); - case 8: + case 42: + + case 43: + result = { + context: signatureStatus.context, + value: { + err: signatureStatus.value.err + } + }; + _context38.next = 47; + break; + + case 46: + throw new TransactionExpiredNonceInvalidError(signature); + + case 47: + _context38.prev = 47; + done = true; + abortConfirmation(); + return _context38.finish(47); + + case 51: + return _context38.abrupt("return", result); + + case 52: case "end": - return _context17.stop(); + return _context38.stop(); } - }, _callee17, this); + }, _callee38, this, [[5,, 47, 51]]); })); - function getTokenAccountBalance(_x31, _x32) { - return _getTokenAccountBalance.apply(this, arguments); + function confirmTransactionUsingDurableNonceStrategy(_x64) { + return _confirmTransactionUsingDurableNonceStrategy.apply(this, arguments); } - return getTokenAccountBalance; + return confirmTransactionUsingDurableNonceStrategy; }() - /** - * Fetch all the token accounts owned by the specified account - * - * @return {Promise}>>>} - */ - }, { - key: "getTokenAccountsByOwner", + key: "confirmTransactionUsingLegacyTimeoutStrategy", value: function () { - var _getTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(ownerAddress, filter, commitmentOrConfig) { - var _extractCommitmentFro3, commitment, config, _args, args, unsafeRes, res; + var _confirmTransactionUsingLegacyTimeoutStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee39(_ref35) { + var _this19 = this; - return _regeneratorRuntime().wrap(function _callee18$(_context18) { - while (1) switch (_context18.prev = _context18.next) { + var commitment, signature, timeoutId, expiryPromise, _this$getTransactionC3, abortConfirmation, confirmationPromise, result, outcome; + + return _regeneratorRuntime().wrap(function _callee39$(_context39) { + while (1) switch (_context39.prev = _context39.next) { case 0: - _extractCommitmentFro3 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro3.commitment, config = _extractCommitmentFro3.config; - _args = [ownerAddress.toBase58()]; + commitment = _ref35.commitment, signature = _ref35.signature; + expiryPromise = new Promise(function (resolve) { + var timeoutMs = _this19._confirmTransactionInitialTimeout || 60 * 1000; - if ('mint' in filter) { - _args.push({ - mint: filter.mint.toBase58() - }); - } else { - _args.push({ - programId: filter.programId.toBase58() - }); - } + switch (commitment) { + case 'processed': + case 'recent': + case 'single': + case 'confirmed': + case 'singleGossip': + { + timeoutMs = _this19._confirmTransactionInitialTimeout || 30 * 1000; + break; + } + } - args = this._buildArgs(_args, commitment, 'base64', config); - _context18.next = 6; - return this._rpcRequest('getTokenAccountsByOwner', args); + timeoutId = setTimeout(function () { + return resolve({ + __type: TransactionStatus.TIMED_OUT, + timeoutMs: timeoutMs + }); + }, timeoutMs); + }); + _this$getTransactionC3 = this.getTransactionConfirmationPromise({ + commitment: commitment, + signature: signature + }), abortConfirmation = _this$getTransactionC3.abortConfirmation, confirmationPromise = _this$getTransactionC3.confirmationPromise; + _context39.prev = 3; + _context39.next = 6; + return Promise.race([confirmationPromise, expiryPromise]); case 6: - unsafeRes = _context18.sent; - res = _create(unsafeRes, GetTokenAccountsByOwner); + outcome = _context39.sent; - if (!('error' in res)) { - _context18.next = 10; + if (!(outcome.__type === TransactionStatus.PROCESSED)) { + _context39.next = 11; break; } - throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); - - case 10: - return _context18.abrupt("return", res.result); + result = outcome.response; + _context39.next = 12; + break; case 11: + throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000); + + case 12: + _context39.prev = 12; + clearTimeout(timeoutId); + abortConfirmation(); + return _context39.finish(12); + + case 16: + return _context39.abrupt("return", result); + + case 17: case "end": - return _context18.stop(); + return _context39.stop(); } - }, _callee18, this); + }, _callee39, this, [[3,, 12, 16]]); })); - function getTokenAccountsByOwner(_x33, _x34, _x35) { - return _getTokenAccountsByOwner.apply(this, arguments); + function confirmTransactionUsingLegacyTimeoutStrategy(_x65) { + return _confirmTransactionUsingLegacyTimeoutStrategy.apply(this, arguments); } - return getTokenAccountsByOwner; + return confirmTransactionUsingLegacyTimeoutStrategy; }() /** - * Fetch parsed token accounts owned by the specified account - * - * @return {Promise}>>>} + * Return the list of nodes that are currently participating in the cluster */ }, { - key: "getParsedTokenAccountsByOwner", + key: "getClusterNodes", value: function () { - var _getParsedTokenAccountsByOwner = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(ownerAddress, filter, commitment) { - var _args, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee19$(_context19) { - while (1) switch (_context19.prev = _context19.next) { + var _getClusterNodes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee40() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee40$(_context40) { + while (1) switch (_context40.prev = _context40.next) { case 0: - _args = [ownerAddress.toBase58()]; - - if ('mint' in filter) { - _args.push({ - mint: filter.mint.toBase58() - }); - } else { - _args.push({ - programId: filter.programId.toBase58() - }); - } - - args = this._buildArgs(_args, commitment, 'jsonParsed'); - _context19.next = 5; - return this._rpcRequest('getTokenAccountsByOwner', args); + _context40.next = 2; + return this._rpcRequest('getClusterNodes', []); - case 5: - unsafeRes = _context19.sent; - res = _create(unsafeRes, GetParsedTokenAccountsByOwner); + case 2: + unsafeRes = _context40.sent; + res = _create(unsafeRes, jsonRpcResult(array(ContactInfoResult))); if (!('error' in res)) { - _context19.next = 9; + _context40.next = 6; break; } - throw new SolanaJSONRPCError(res.error, "failed to get token accounts owned by account ".concat(ownerAddress.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes'); - case 9: - return _context19.abrupt("return", res.result); + case 6: + return _context40.abrupt("return", res.result); - case 10: + case 7: case "end": - return _context19.stop(); + return _context40.stop(); } - }, _callee19, this); + }, _callee40, this); })); - function getParsedTokenAccountsByOwner(_x36, _x37, _x38) { - return _getParsedTokenAccountsByOwner.apply(this, arguments); + function getClusterNodes() { + return _getClusterNodes.apply(this, arguments); } - return getParsedTokenAccountsByOwner; + return getClusterNodes; }() /** - * Fetch the 20 largest accounts with their current balances + * Return the list of nodes that are currently participating in the cluster */ }, { - key: "getLargestAccounts", + key: "getVoteAccounts", value: function () { - var _getLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(config) { - var arg, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee20$(_context20) { - while (1) switch (_context20.prev = _context20.next) { + var _getVoteAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee41(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee41$(_context41) { + while (1) switch (_context41.prev = _context41.next) { case 0: - arg = _objectSpread2(_objectSpread2({}, config), {}, { - commitment: config && config.commitment || this.commitment - }); - args = arg.filter || arg.commitment ? [arg] : []; - _context20.next = 4; - return this._rpcRequest('getLargestAccounts', args); + args = this._buildArgs([], commitment); + _context41.next = 3; + return this._rpcRequest('getVoteAccounts', args); - case 4: - unsafeRes = _context20.sent; - res = _create(unsafeRes, GetLargestAccountsRpcResult); + case 3: + unsafeRes = _context41.sent; + res = _create(unsafeRes, GetVoteAccounts); if (!('error' in res)) { - _context20.next = 8; + _context41.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get largest accounts'); + throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts'); - case 8: - return _context20.abrupt("return", res.result); + case 7: + return _context41.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context20.stop(); + return _context41.stop(); } - }, _callee20, this); + }, _callee41, this); })); - function getLargestAccounts(_x39) { - return _getLargestAccounts.apply(this, arguments); + function getVoteAccounts(_x66) { + return _getVoteAccounts.apply(this, arguments); } - return getLargestAccounts; + return getVoteAccounts; }() /** - * Fetch the 20 largest token accounts with their current balances - * for a given mint. + * Fetch the current slot that the node is processing */ }, { - key: "getTokenLargestAccounts", + key: "getSlot", value: function () { - var _getTokenLargestAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(mintAddress, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee21$(_context21) { - while (1) switch (_context21.prev = _context21.next) { + var _getSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee42(commitmentOrConfig) { + var _extractCommitmentFro11, commitment, config, args, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee42$(_context42) { + while (1) switch (_context42.prev = _context42.next) { case 0: - args = this._buildArgs([mintAddress.toBase58()], commitment); - _context21.next = 3; - return this._rpcRequest('getTokenLargestAccounts', args); + _extractCommitmentFro11 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro11.commitment, config = _extractCommitmentFro11.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context42.next = 4; + return this._rpcRequest('getSlot', args); - case 3: - unsafeRes = _context21.sent; - res = _create(unsafeRes, GetTokenLargestAccountsResult); + case 4: + unsafeRes = _context42.sent; + res = _create(unsafeRes, jsonRpcResult(number())); if (!('error' in res)) { - _context21.next = 7; + _context42.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get token largest accounts'); - - case 7: - return _context21.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get slot'); case 8: + return _context42.abrupt("return", res.result); + + case 9: case "end": - return _context21.stop(); + return _context42.stop(); } - }, _callee21, this); + }, _callee42, this); })); - function getTokenLargestAccounts(_x40, _x41) { - return _getTokenLargestAccounts.apply(this, arguments); + function getSlot(_x67) { + return _getSlot.apply(this, arguments); } - return getTokenLargestAccounts; + return getSlot; }() /** - * Fetch all the account info for the specified public key, return with context + * Fetch the current slot leader of the cluster */ }, { - key: "getAccountInfoAndContext", + key: "getSlotLeader", value: function () { - var _getAccountInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(publicKey, commitmentOrConfig) { - var _extractCommitmentFro4, commitment, config, args, unsafeRes, res; + var _getSlotLeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee43(commitmentOrConfig) { + var _extractCommitmentFro12, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee22$(_context22) { - while (1) switch (_context22.prev = _context22.next) { + return _regeneratorRuntime().wrap(function _callee43$(_context43) { + while (1) switch (_context43.prev = _context43.next) { case 0: - _extractCommitmentFro4 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro4.commitment, config = _extractCommitmentFro4.config; - args = this._buildArgs([publicKey.toBase58()], commitment, 'base64', config); - _context22.next = 4; - return this._rpcRequest('getAccountInfo', args); + _extractCommitmentFro12 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro12.commitment, config = _extractCommitmentFro12.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context43.next = 4; + return this._rpcRequest('getSlotLeader', args); case 4: - unsafeRes = _context22.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(AccountInfoResult))); + unsafeRes = _context43.sent; + res = _create(unsafeRes, jsonRpcResult(string())); if (!('error' in res)) { - _context22.next = 8; + _context43.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get slot leader'); case 8: - return _context22.abrupt("return", res.result); + return _context43.abrupt("return", res.result); case 9: case "end": - return _context22.stop(); + return _context43.stop(); } - }, _callee22, this); + }, _callee43, this); })); - function getAccountInfoAndContext(_x42, _x43) { - return _getAccountInfoAndContext.apply(this, arguments); + function getSlotLeader(_x68) { + return _getSlotLeader.apply(this, arguments); } - return getAccountInfoAndContext; + return getSlotLeader; }() /** - * Fetch parsed account info for the specified public key + * Fetch `limit` number of slot leaders starting from `startSlot` + * + * @param startSlot fetch slot leaders starting from this slot + * @param limit number of slot leaders to return */ }, { - key: "getParsedAccountInfo", + key: "getSlotLeaders", value: function () { - var _getParsedAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(publicKey, commitmentOrConfig) { - var _extractCommitmentFro5, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee23$(_context23) { - while (1) switch (_context23.prev = _context23.next) { + var _getSlotLeaders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee44(startSlot, limit) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee44$(_context44) { + while (1) switch (_context44.prev = _context44.next) { case 0: - _extractCommitmentFro5 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro5.commitment, config = _extractCommitmentFro5.config; - args = this._buildArgs([publicKey.toBase58()], commitment, 'jsonParsed', config); - _context23.next = 4; - return this._rpcRequest('getAccountInfo', args); + args = [startSlot, limit]; + _context44.next = 3; + return this._rpcRequest('getSlotLeaders', args); - case 4: - unsafeRes = _context23.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(ParsedAccountInfoResult))); + case 3: + unsafeRes = _context44.sent; + res = _create(unsafeRes, jsonRpcResult(array(PublicKeyFromString))); if (!('error' in res)) { - _context23.next = 8; + _context44.next = 7; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info about account ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders'); + + case 7: + return _context44.abrupt("return", res.result); case 8: - return _context23.abrupt("return", res.result); - - case 9: case "end": - return _context23.stop(); + return _context44.stop(); } - }, _callee23, this); + }, _callee44, this); })); - function getParsedAccountInfo(_x44, _x45) { - return _getParsedAccountInfo.apply(this, arguments); + function getSlotLeaders(_x69, _x70) { + return _getSlotLeaders.apply(this, arguments); } - return getParsedAccountInfo; + return getSlotLeaders; }() /** - * Fetch all the account info for the specified public key + * Fetch the current status of a signature */ }, { - key: "getAccountInfo", + key: "getSignatureStatus", value: function () { - var _getAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(publicKey, commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee24$(_context24) { - while (1) switch (_context24.prev = _context24.next) { - case 0: - _context24.prev = 0; - _context24.next = 3; - return this.getAccountInfoAndContext(publicKey, commitmentOrConfig); + var _getSignatureStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee45(signature, config) { + var _yield$this$getSignat, context, values, value; - case 3: - res = _context24.sent; - return _context24.abrupt("return", res.value); + return _regeneratorRuntime().wrap(function _callee45$(_context45) { + while (1) switch (_context45.prev = _context45.next) { + case 0: + _context45.next = 2; + return this.getSignatureStatuses([signature], config); - case 7: - _context24.prev = 7; - _context24.t0 = _context24["catch"](0); - throw new Error('failed to get info about account ' + publicKey.toBase58() + ': ' + _context24.t0); + case 2: + _yield$this$getSignat = _context45.sent; + context = _yield$this$getSignat.context; + values = _yield$this$getSignat.value; + assert(values.length === 1); + value = values[0]; + return _context45.abrupt("return", { + context: context, + value: value + }); - case 10: + case 8: case "end": - return _context24.stop(); + return _context45.stop(); } - }, _callee24, this, [[0, 7]]); + }, _callee45, this); })); - function getAccountInfo(_x46, _x47) { - return _getAccountInfo.apply(this, arguments); + function getSignatureStatus(_x71, _x72) { + return _getSignatureStatus.apply(this, arguments); } - return getAccountInfo; + return getSignatureStatus; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + * Fetch the current statuses of a batch of signatures */ }, { - key: "getMultipleParsedAccounts", + key: "getSignatureStatuses", value: function () { - var _getMultipleParsedAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(publicKeys, rawConfig) { - var _extractCommitmentFro6, commitment, config, keys, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee25$(_context25) { - while (1) switch (_context25.prev = _context25.next) { + var _getSignatureStatuses = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee46(signatures, config) { + var params, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee46$(_context46) { + while (1) switch (_context46.prev = _context46.next) { case 0: - _extractCommitmentFro6 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro6.commitment, config = _extractCommitmentFro6.config; - keys = publicKeys.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs([keys], commitment, 'jsonParsed', config); - _context25.next = 5; - return this._rpcRequest('getMultipleAccounts', args); + params = [signatures]; - case 5: - unsafeRes = _context25.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(ParsedAccountInfoResult)))); + if (config) { + params.push(config); + } + + _context46.next = 4; + return this._rpcRequest('getSignatureStatuses', params); + + case 4: + unsafeRes = _context46.sent; + res = _create(unsafeRes, GetSignatureStatusesRpcResult); if (!('error' in res)) { - _context25.next = 9; + _context46.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); + throw new SolanaJSONRPCError(res.error, 'failed to get signature status'); - case 9: - return _context25.abrupt("return", res.result); + case 8: + return _context46.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context25.stop(); + return _context46.stop(); } - }, _callee25, this); + }, _callee46, this); })); - function getMultipleParsedAccounts(_x48, _x49) { - return _getMultipleParsedAccounts.apply(this, arguments); + function getSignatureStatuses(_x73, _x74) { + return _getSignatureStatuses.apply(this, arguments); } - return getMultipleParsedAccounts; + return getSignatureStatuses; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys, return with context + * Fetch the current transaction count of the cluster */ }, { - key: "getMultipleAccountsInfoAndContext", + key: "getTransactionCount", value: function () { - var _getMultipleAccountsInfoAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(publicKeys, commitmentOrConfig) { - var _extractCommitmentFro7, commitment, config, keys, args, unsafeRes, res; + var _getTransactionCount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee47(commitmentOrConfig) { + var _extractCommitmentFro13, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee26$(_context26) { - while (1) switch (_context26.prev = _context26.next) { + return _regeneratorRuntime().wrap(function _callee47$(_context47) { + while (1) switch (_context47.prev = _context47.next) { case 0: - _extractCommitmentFro7 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro7.commitment, config = _extractCommitmentFro7.config; - keys = publicKeys.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs([keys], commitment, 'base64', config); - _context26.next = 5; - return this._rpcRequest('getMultipleAccounts', args); + _extractCommitmentFro13 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro13.commitment, config = _extractCommitmentFro13.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context47.next = 4; + return this._rpcRequest('getTransactionCount', args); - case 5: - unsafeRes = _context26.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(array(nullable(AccountInfoResult)))); + case 4: + unsafeRes = _context47.sent; + res = _create(unsafeRes, jsonRpcResult(number())); if (!('error' in res)) { - _context26.next = 9; + _context47.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get info for accounts ".concat(keys)); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction count'); - case 9: - return _context26.abrupt("return", res.result); + case 8: + return _context47.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context26.stop(); + return _context47.stop(); } - }, _callee26, this); + }, _callee47, this); })); - function getMultipleAccountsInfoAndContext(_x50, _x51) { - return _getMultipleAccountsInfoAndContext.apply(this, arguments); + function getTransactionCount(_x75) { + return _getTransactionCount.apply(this, arguments); } - return getMultipleAccountsInfoAndContext; + return getTransactionCount; }() /** - * Fetch all the account info for multiple accounts specified by an array of public keys + * Fetch the current total currency supply of the cluster in lamports + * + * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead. */ }, { - key: "getMultipleAccountsInfo", + key: "getTotalSupply", value: function () { - var _getMultipleAccountsInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27(publicKeys, commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee27$(_context27) { - while (1) switch (_context27.prev = _context27.next) { + var _getTotalSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee48(commitment) { + var result; + return _regeneratorRuntime().wrap(function _callee48$(_context48) { + while (1) switch (_context48.prev = _context48.next) { case 0: - _context27.next = 2; - return this.getMultipleAccountsInfoAndContext(publicKeys, commitmentOrConfig); + _context48.next = 2; + return this.getSupply({ + commitment: commitment, + excludeNonCirculatingAccountsList: true + }); case 2: - res = _context27.sent; - return _context27.abrupt("return", res.value); + result = _context48.sent; + return _context48.abrupt("return", result.value.total); case 4: case "end": - return _context27.stop(); + return _context48.stop(); } - }, _callee27, this); + }, _callee48, this); })); - function getMultipleAccountsInfo(_x52, _x53) { - return _getMultipleAccountsInfo.apply(this, arguments); + function getTotalSupply(_x76) { + return _getTotalSupply.apply(this, arguments); } - return getMultipleAccountsInfo; + return getTotalSupply; }() /** - * Returns epoch activation information for a stake account that has been delegated + * Fetch the cluster InflationGovernor parameters */ }, { - key: "getStakeActivation", + key: "getInflationGovernor", value: function () { - var _getStakeActivation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28(publicKey, commitmentOrConfig, epoch) { - var _extractCommitmentFro8, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee28$(_context28) { - while (1) switch (_context28.prev = _context28.next) { + var _getInflationGovernor = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee49(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee49$(_context49) { + while (1) switch (_context49.prev = _context49.next) { case 0: - _extractCommitmentFro8 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro8.commitment, config = _extractCommitmentFro8.config; - args = this._buildArgs([publicKey.toBase58()], commitment, undefined - /* encoding */ - , _objectSpread2(_objectSpread2({}, config), {}, { - epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch - })); - _context28.next = 4; - return this._rpcRequest('getStakeActivation', args); + args = this._buildArgs([], commitment); + _context49.next = 3; + return this._rpcRequest('getInflationGovernor', args); - case 4: - unsafeRes = _context28.sent; - res = _create(unsafeRes, jsonRpcResult(StakeActivationResult)); + case 3: + unsafeRes = _context49.sent; + res = _create(unsafeRes, GetInflationGovernorRpcResult); if (!('error' in res)) { - _context28.next = 8; + _context49.next = 7; break; } - throw new SolanaJSONRPCError(res.error, "failed to get Stake Activation ".concat(publicKey.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation'); - case 8: - return _context28.abrupt("return", res.result); + case 7: + return _context49.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context28.stop(); + return _context49.stop(); } - }, _callee28, this); + }, _callee49, this); })); - function getStakeActivation(_x54, _x55, _x56) { - return _getStakeActivation.apply(this, arguments); + function getInflationGovernor(_x77) { + return _getInflationGovernor.apply(this, arguments); } - return getStakeActivation; + return getInflationGovernor; }() /** - * Fetch all the accounts owned by the specified program id - * - * @return {Promise}>>} + * Fetch the inflation reward for a list of addresses for an epoch */ }, { - key: "getProgramAccounts", + key: "getInflationReward", value: function () { - var _getProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee29(programId, configOrCommitment) { - var _extractCommitmentFro9, commitment, config, _ref26, encoding, configWithoutEncoding, args, unsafeRes, res; + var _getInflationReward = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee50(addresses, epoch, commitmentOrConfig) { + var _extractCommitmentFro14, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee29$(_context29) { - while (1) switch (_context29.prev = _context29.next) { + return _regeneratorRuntime().wrap(function _callee50$(_context50) { + while (1) switch (_context50.prev = _context50.next) { case 0: - _extractCommitmentFro9 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro9.commitment, config = _extractCommitmentFro9.config; - _ref26 = config || {}, encoding = _ref26.encoding, configWithoutEncoding = _objectWithoutProperties(_ref26, _excluded2); - args = this._buildArgs([programId.toBase58()], commitment, encoding || 'base64', configWithoutEncoding); - _context29.next = 5; - return this._rpcRequest('getProgramAccounts', args); + _extractCommitmentFro14 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro14.commitment, config = _extractCommitmentFro14.config; + args = this._buildArgs([addresses.map(function (pubkey) { + return pubkey.toBase58(); + })], commitment, undefined + /* encoding */ + , _objectSpread2(_objectSpread2({}, config), {}, { + epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch + })); + _context50.next = 4; + return this._rpcRequest('getInflationReward', args); - case 5: - unsafeRes = _context29.sent; - res = _create(unsafeRes, jsonRpcResult(array(KeyedAccountInfoResult))); + case 4: + unsafeRes = _context50.sent; + res = _create(unsafeRes, GetInflationRewardResult); if (!('error' in res)) { - _context29.next = 9; + _context50.next = 8; break; } - throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward'); - case 9: - return _context29.abrupt("return", res.result); + case 8: + return _context50.abrupt("return", res.result); - case 10: + case 9: case "end": - return _context29.stop(); + return _context50.stop(); } - }, _callee29, this); + }, _callee50, this); })); - function getProgramAccounts(_x57, _x58) { - return _getProgramAccounts.apply(this, arguments); + function getInflationReward(_x78, _x79, _x80) { + return _getInflationReward.apply(this, arguments); } - return getProgramAccounts; + return getInflationReward; }() /** - * Fetch and parse all the accounts owned by the specified program id - * - * @return {Promise}>>} + * Fetch the specific inflation values for the current epoch */ }, { - key: "getParsedProgramAccounts", + key: "getInflationRate", value: function () { - var _getParsedProgramAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee30(programId, configOrCommitment) { - var _extractCommitmentFro10, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee30$(_context30) { - while (1) switch (_context30.prev = _context30.next) { + var _getInflationRate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee51() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee51$(_context51) { + while (1) switch (_context51.prev = _context51.next) { case 0: - _extractCommitmentFro10 = extractCommitmentFromConfig(configOrCommitment), commitment = _extractCommitmentFro10.commitment, config = _extractCommitmentFro10.config; - args = this._buildArgs([programId.toBase58()], commitment, 'jsonParsed', config); - _context30.next = 4; - return this._rpcRequest('getProgramAccounts', args); + _context51.next = 2; + return this._rpcRequest('getInflationRate', []); - case 4: - unsafeRes = _context30.sent; - res = _create(unsafeRes, jsonRpcResult(array(KeyedParsedAccountInfoResult))); + case 2: + unsafeRes = _context51.sent; + res = _create(unsafeRes, GetInflationRateRpcResult); if (!('error' in res)) { - _context30.next = 8; + _context51.next = 6; break; } - throw new SolanaJSONRPCError(res.error, "failed to get accounts owned by program ".concat(programId.toBase58())); + throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate'); - case 8: - return _context30.abrupt("return", res.result); + case 6: + return _context51.abrupt("return", res.result); - case 9: + case 7: case "end": - return _context30.stop(); + return _context51.stop(); } - }, _callee30, this); + }, _callee51, this); })); - function getParsedProgramAccounts(_x59, _x60) { - return _getParsedProgramAccounts.apply(this, arguments); + function getInflationRate() { + return _getInflationRate.apply(this, arguments); } - return getParsedProgramAccounts; - }() // eslint-disable-next-line no-dupe-class-members + return getInflationRate; + }() + /** + * Fetch the Epoch Info parameters + */ }, { - key: "confirmTransaction", + key: "getEpochInfo", value: function () { - var _confirmTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee31(strategy, commitment) { - var rawSignature, _config$abortSignal, config, decodedSignature; + var _getEpochInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee52(commitmentOrConfig) { + var _extractCommitmentFro15, commitment, config, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee31$(_context31) { - while (1) switch (_context31.prev = _context31.next) { + return _regeneratorRuntime().wrap(function _callee52$(_context52) { + while (1) switch (_context52.prev = _context52.next) { case 0: - if (!(typeof strategy == 'string')) { - _context31.next = 4; - break; - } - - rawSignature = strategy; - _context31.next = 8; - break; + _extractCommitmentFro15 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro15.commitment, config = _extractCommitmentFro15.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context52.next = 4; + return this._rpcRequest('getEpochInfo', args); case 4: - config = strategy; - - if (!((_config$abortSignal = config.abortSignal) !== null && _config$abortSignal !== void 0 && _config$abortSignal.aborted)) { - _context31.next = 7; - break; - } - - return _context31.abrupt("return", Promise.reject(config.abortSignal.reason)); - - case 7: - rawSignature = config.signature; - - case 8: - _context31.prev = 8; - decodedSignature = bs58$1.decode(rawSignature); - _context31.next = 15; - break; - - case 12: - _context31.prev = 12; - _context31.t0 = _context31["catch"](8); - throw new Error('signature must be base58 encoded: ' + rawSignature); - - case 15: - assert(decodedSignature.length === 64, 'signature has invalid length'); - - if (!(typeof strategy === 'string')) { - _context31.next = 22; - break; - } - - _context31.next = 19; - return this.confirmTransactionUsingLegacyTimeoutStrategy({ - commitment: commitment || this.commitment, - signature: rawSignature - }); - - case 19: - return _context31.abrupt("return", _context31.sent); + unsafeRes = _context52.sent; + res = _create(unsafeRes, GetEpochInfoRpcResult); - case 22: - if (!('lastValidBlockHeight' in strategy)) { - _context31.next = 28; + if (!('error' in res)) { + _context52.next = 8; break; - } - - _context31.next = 25; - return this.confirmTransactionUsingBlockHeightExceedanceStrategy({ - commitment: commitment || this.commitment, - strategy: strategy - }); - - case 25: - return _context31.abrupt("return", _context31.sent); - - case 28: - _context31.next = 30; - return this.confirmTransactionUsingDurableNonceStrategy({ - commitment: commitment || this.commitment, - strategy: strategy - }); - - case 30: - return _context31.abrupt("return", _context31.sent); - - case 31: - case "end": - return _context31.stop(); - } - }, _callee31, this, [[8, 12]]); - })); - - function confirmTransaction(_x61, _x62) { - return _confirmTransaction.apply(this, arguments); - } - - return confirmTransaction; - }() - }, { - key: "getCancellationPromise", - value: function getCancellationPromise(signal) { - return new Promise(function (_, reject) { - if (signal == null) { - return; - } - - if (signal.aborted) { - reject(signal.reason); - } else { - signal.addEventListener('abort', function () { - reject(signal.reason); - }); - } - }); - } - }, { - key: "getTransactionConfirmationPromise", - value: function getTransactionConfirmationPromise(_ref27) { - var _this16 = this; - - var commitment = _ref27.commitment, - signature = _ref27.signature; - var signatureSubscriptionId; - var disposeSignatureSubscriptionStateChangeObserver; - var done = false; - var confirmationPromise = new Promise(function (resolve, reject) { - try { - signatureSubscriptionId = _this16.onSignature(signature, function (result, context) { - signatureSubscriptionId = undefined; - var response = { - context: context, - value: result - }; - resolve({ - __type: TransactionStatus.PROCESSED, - response: response - }); - }, commitment); - var subscriptionSetupPromise = new Promise(function (resolveSubscriptionSetup) { - if (signatureSubscriptionId == null) { - resolveSubscriptionSetup(); - } else { - disposeSignatureSubscriptionStateChangeObserver = _this16._onSubscriptionStateChange(signatureSubscriptionId, function (nextState) { - if (nextState === 'subscribed') { - resolveSubscriptionSetup(); - } - }); - } - }); + } - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee32() { - var response, context, value; - return _regeneratorRuntime().wrap(function _callee32$(_context32) { - while (1) switch (_context32.prev = _context32.next) { - case 0: - _context32.next = 2; - return subscriptionSetupPromise; + throw new SolanaJSONRPCError(res.error, 'failed to get epoch info'); - case 2: - if (!done) { - _context32.next = 4; - break; - } + case 8: + return _context52.abrupt("return", res.result); - return _context32.abrupt("return"); + case 9: + case "end": + return _context52.stop(); + } + }, _callee52, this); + })); - case 4: - _context32.next = 6; - return _this16.getSignatureStatus(signature); + function getEpochInfo(_x81) { + return _getEpochInfo.apply(this, arguments); + } - case 6: - response = _context32.sent; + return getEpochInfo; + }() + /** + * Fetch the Epoch Schedule parameters + */ - if (!done) { - _context32.next = 9; - break; - } + }, { + key: "getEpochSchedule", + value: function () { + var _getEpochSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee53() { + var unsafeRes, res, epochSchedule; + return _regeneratorRuntime().wrap(function _callee53$(_context53) { + while (1) switch (_context53.prev = _context53.next) { + case 0: + _context53.next = 2; + return this._rpcRequest('getEpochSchedule', []); - return _context32.abrupt("return"); + case 2: + unsafeRes = _context53.sent; + res = _create(unsafeRes, GetEpochScheduleRpcResult); - case 9: - if (!(response == null)) { - _context32.next = 11; - break; - } + if (!('error' in res)) { + _context53.next = 6; + break; + } - return _context32.abrupt("return"); + throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule'); - case 11: - context = response.context, value = response.value; + case 6: + epochSchedule = res.result; + return _context53.abrupt("return", new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot)); - if (!(value == null)) { - _context32.next = 14; - break; - } + case 8: + case "end": + return _context53.stop(); + } + }, _callee53, this); + })); - return _context32.abrupt("return"); + function getEpochSchedule() { + return _getEpochSchedule.apply(this, arguments); + } - case 14: - if (!(value !== null && value !== void 0 && value.err)) { - _context32.next = 18; - break; - } + return getEpochSchedule; + }() + /** + * Fetch the leader schedule for the current epoch + * @return {Promise>} + */ - reject(value.err); - _context32.next = 29; - break; + }, { + key: "getLeaderSchedule", + value: function () { + var _getLeaderSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee54() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee54$(_context54) { + while (1) switch (_context54.prev = _context54.next) { + case 0: + _context54.next = 2; + return this._rpcRequest('getLeaderSchedule', []); - case 18: - _context32.t0 = commitment; - _context32.next = _context32.t0 === 'confirmed' ? 21 : _context32.t0 === 'single' ? 21 : _context32.t0 === 'singleGossip' ? 21 : _context32.t0 === 'finalized' ? 24 : _context32.t0 === 'max' ? 24 : _context32.t0 === 'root' ? 24 : _context32.t0 === 'processed' ? 27 : _context32.t0 === 'recent' ? 27 : 27; - break; + case 2: + unsafeRes = _context54.sent; + res = _create(unsafeRes, GetLeaderScheduleRpcResult); - case 21: - if (!(value.confirmationStatus === 'processed')) { - _context32.next = 23; - break; - } + if (!('error' in res)) { + _context54.next = 6; + break; + } - return _context32.abrupt("return"); + throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule'); - case 23: - return _context32.abrupt("break", 27); + case 6: + return _context54.abrupt("return", res.result); - case 24: - if (!(value.confirmationStatus === 'processed' || value.confirmationStatus === 'confirmed')) { - _context32.next = 26; - break; - } + case 7: + case "end": + return _context54.stop(); + } + }, _callee54, this); + })); - return _context32.abrupt("return"); + function getLeaderSchedule() { + return _getLeaderSchedule.apply(this, arguments); + } - case 26: - return _context32.abrupt("break", 27); + return getLeaderSchedule; + }() + /** + * Fetch the minimum balance needed to exempt an account of `dataLength` + * size from rent + */ - case 27: - done = true; - resolve({ - __type: TransactionStatus.PROCESSED, - response: { - context: context, - value: value - } - }); + }, { + key: "getMinimumBalanceForRentExemption", + value: function () { + var _getMinimumBalanceForRentExemption = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee55(dataLength, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee55$(_context55) { + while (1) switch (_context55.prev = _context55.next) { + case 0: + args = this._buildArgs([dataLength], commitment); + _context55.next = 3; + return this._rpcRequest('getMinimumBalanceForRentExemption', args); - case 29: - case "end": - return _context32.stop(); + case 3: + unsafeRes = _context55.sent; + res = _create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult); + + if (!('error' in res)) { + _context55.next = 8; + break; } - }, _callee32); - }))(); - } catch (err) { - reject(err); - } - }); - var abortConfirmation = function abortConfirmation() { - if (disposeSignatureSubscriptionStateChangeObserver) { - disposeSignatureSubscriptionStateChangeObserver(); - disposeSignatureSubscriptionStateChangeObserver = undefined; - } + console.warn('Unable to fetch minimum balance for rent exemption'); + return _context55.abrupt("return", 0); - if (signatureSubscriptionId != null) { - _this16.removeSignatureListener(signatureSubscriptionId); + case 8: + return _context55.abrupt("return", res.result); - signatureSubscriptionId = undefined; - } - }; + case 9: + case "end": + return _context55.stop(); + } + }, _callee55, this); + })); - return { - abortConfirmation: abortConfirmation, - confirmationPromise: confirmationPromise - }; - } - }, { - key: "confirmTransactionUsingBlockHeightExceedanceStrategy", - value: function () { - var _confirmTransactionUsingBlockHeightExceedanceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee35(_ref29) { - var _this17 = this; + function getMinimumBalanceForRentExemption(_x82, _x83) { + return _getMinimumBalanceForRentExemption.apply(this, arguments); + } - var commitment, _ref29$strategy, abortSignal, lastValidBlockHeight, signature, done, expiryPromise, _this$getTransactionC, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome; + return getMinimumBalanceForRentExemption; + }() + /** + * Fetch a recent blockhash from the cluster, return with context + * @return {Promise>} + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + */ - return _regeneratorRuntime().wrap(function _callee35$(_context35) { - while (1) switch (_context35.prev = _context35.next) { + }, { + key: "getRecentBlockhashAndContext", + value: function () { + var _getRecentBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee56(commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee56$(_context56) { + while (1) switch (_context56.prev = _context56.next) { case 0: - commitment = _ref29.commitment, _ref29$strategy = _ref29.strategy, abortSignal = _ref29$strategy.abortSignal, lastValidBlockHeight = _ref29$strategy.lastValidBlockHeight, signature = _ref29$strategy.signature; - done = false; - expiryPromise = new Promise(function (resolve) { - var checkBlockHeight = /*#__PURE__*/function () { - var _ref30 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee33() { - var blockHeight; - return _regeneratorRuntime().wrap(function _callee33$(_context33) { - while (1) switch (_context33.prev = _context33.next) { - case 0: - _context33.prev = 0; - _context33.next = 3; - return _this17.getBlockHeight(commitment); - - case 3: - blockHeight = _context33.sent; - return _context33.abrupt("return", blockHeight); - - case 7: - _context33.prev = 7; - _context33.t0 = _context33["catch"](0); - return _context33.abrupt("return", -1); + args = this._buildArgs([], commitment); + _context56.next = 3; + return this._rpcRequest('getRecentBlockhash', args); - case 10: - case "end": - return _context33.stop(); - } - }, _callee33, null, [[0, 7]]); - })); + case 3: + unsafeRes = _context56.sent; + res = _create(unsafeRes, GetRecentBlockhashAndContextRpcResult); - return function checkBlockHeight() { - return _ref30.apply(this, arguments); - }; - }(); + if (!('error' in res)) { + _context56.next = 7; + break; + } - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee34() { - var currentBlockHeight; - return _regeneratorRuntime().wrap(function _callee34$(_context34) { - while (1) switch (_context34.prev = _context34.next) { - case 0: - _context34.next = 2; - return checkBlockHeight(); + throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash'); - case 2: - currentBlockHeight = _context34.sent; + case 7: + return _context56.abrupt("return", res.result); - if (!done) { - _context34.next = 5; - break; - } + case 8: + case "end": + return _context56.stop(); + } + }, _callee56, this); + })); - return _context34.abrupt("return"); + function getRecentBlockhashAndContext(_x84) { + return _getRecentBlockhashAndContext.apply(this, arguments); + } - case 5: - if (!(currentBlockHeight <= lastValidBlockHeight)) { - _context34.next = 17; - break; - } + return getRecentBlockhashAndContext; + }() + /** + * Fetch recent performance samples + * @return {Promise>} + */ - _context34.next = 8; - return sleep(1000); + }, { + key: "getRecentPerformanceSamples", + value: function () { + var _getRecentPerformanceSamples = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee57(limit) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee57$(_context57) { + while (1) switch (_context57.prev = _context57.next) { + case 0: + _context57.next = 2; + return this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []); - case 8: - if (!done) { - _context34.next = 10; - break; - } + case 2: + unsafeRes = _context57.sent; + res = _create(unsafeRes, GetRecentPerformanceSamplesRpcResult); - return _context34.abrupt("return"); + if (!('error' in res)) { + _context57.next = 6; + break; + } - case 10: - _context34.next = 12; - return checkBlockHeight(); + throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples'); - case 12: - currentBlockHeight = _context34.sent; + case 6: + return _context57.abrupt("return", res.result); - if (!done) { - _context34.next = 15; - break; - } + case 7: + case "end": + return _context57.stop(); + } + }, _callee57, this); + })); - return _context34.abrupt("return"); + function getRecentPerformanceSamples(_x85) { + return _getRecentPerformanceSamples.apply(this, arguments); + } - case 15: - _context34.next = 5; - break; + return getRecentPerformanceSamples; + }() + /** + * Fetch the fee calculator for a recent blockhash from the cluster, return with context + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead. + */ - case 17: - resolve({ - __type: TransactionStatus.BLOCKHEIGHT_EXCEEDED - }); + }, { + key: "getFeeCalculatorForBlockhash", + value: function () { + var _getFeeCalculatorForBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee58(blockhash, commitment) { + var args, unsafeRes, res, _res$result, context, value; - case 18: - case "end": - return _context34.stop(); - } - }, _callee34); - }))(); - }); - _this$getTransactionC = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC.abortConfirmation, confirmationPromise = _this$getTransactionC.confirmationPromise; - cancellationPromise = this.getCancellationPromise(abortSignal); - _context35.prev = 5; - _context35.next = 8; - return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + return _regeneratorRuntime().wrap(function _callee58$(_context58) { + while (1) switch (_context58.prev = _context58.next) { + case 0: + args = this._buildArgs([blockhash], commitment); + _context58.next = 3; + return this._rpcRequest('getFeeCalculatorForBlockhash', args); - case 8: - outcome = _context35.sent; + case 3: + unsafeRes = _context58.sent; + res = _create(unsafeRes, GetFeeCalculatorRpcResult); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context35.next = 13; + if (!('error' in res)) { + _context58.next = 7; break; } - result = outcome.response; - _context35.next = 14; - break; - - case 13: - throw new TransactionExpiredBlockheightExceededError(signature); - - case 14: - _context35.prev = 14; - done = true; - abortConfirmation(); - return _context35.finish(14); + throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator'); - case 18: - return _context35.abrupt("return", result); + case 7: + _res$result = res.result, context = _res$result.context, value = _res$result.value; + return _context58.abrupt("return", { + context: context, + value: value !== null ? value.feeCalculator : null + }); - case 19: + case 9: case "end": - return _context35.stop(); + return _context58.stop(); } - }, _callee35, this, [[5,, 14, 18]]); + }, _callee58, this); })); - function confirmTransactionUsingBlockHeightExceedanceStrategy(_x63) { - return _confirmTransactionUsingBlockHeightExceedanceStrategy.apply(this, arguments); + function getFeeCalculatorForBlockhash(_x86, _x87) { + return _getFeeCalculatorForBlockhash.apply(this, arguments); } - return confirmTransactionUsingBlockHeightExceedanceStrategy; + return getFeeCalculatorForBlockhash; }() + /** + * Fetch the fee for a message from the cluster, return with context + */ + }, { - key: "confirmTransactionUsingDurableNonceStrategy", + key: "getFeeForMessage", value: function () { - var _confirmTransactionUsingDurableNonceStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee38(_ref32) { - var _this18 = this; - - var commitment, _ref32$strategy, abortSignal, minContextSlot, nonceAccountPubkey, nonceValue, signature, done, expiryPromise, _this$getTransactionC2, abortConfirmation, confirmationPromise, cancellationPromise, result, outcome, _signatureStatus, signatureStatus, _outcome$slotInWhichN, status, commitmentForStatus, confirmationStatus; - - return _regeneratorRuntime().wrap(function _callee38$(_context38) { - while (1) switch (_context38.prev = _context38.next) { + var _getFeeForMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee59(message, commitment) { + var wireMessage, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee59$(_context59) { + while (1) switch (_context59.prev = _context59.next) { case 0: - commitment = _ref32.commitment, _ref32$strategy = _ref32.strategy, abortSignal = _ref32$strategy.abortSignal, minContextSlot = _ref32$strategy.minContextSlot, nonceAccountPubkey = _ref32$strategy.nonceAccountPubkey, nonceValue = _ref32$strategy.nonceValue, signature = _ref32$strategy.signature; - done = false; - expiryPromise = new Promise(function (resolve) { - var currentNonceValue = nonceValue; - var lastCheckedSlot = null; - - var getCurrentNonceValue = /*#__PURE__*/function () { - var _ref33 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee36() { - var _yield$_this18$getNon2, context, nonceAccount; + wireMessage = toBuffer(message.serialize()).toString('base64'); + args = this._buildArgs([wireMessage], commitment); + _context59.next = 4; + return this._rpcRequest('getFeeForMessage', args); - return _regeneratorRuntime().wrap(function _callee36$(_context36) { - while (1) switch (_context36.prev = _context36.next) { - case 0: - _context36.prev = 0; - _context36.next = 3; - return _this18.getNonceAndContext(nonceAccountPubkey, { - commitment: commitment, - minContextSlot: minContextSlot - }); + case 4: + unsafeRes = _context59.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(nullable(number()))); - case 3: - _yield$_this18$getNon2 = _context36.sent; - context = _yield$_this18$getNon2.context; - nonceAccount = _yield$_this18$getNon2.value; - lastCheckedSlot = context.slot; - return _context36.abrupt("return", nonceAccount === null || nonceAccount === void 0 ? void 0 : nonceAccount.nonce); + if (!('error' in res)) { + _context59.next = 8; + break; + } - case 10: - _context36.prev = 10; - _context36.t0 = _context36["catch"](0); - return _context36.abrupt("return", currentNonceValue); + throw new SolanaJSONRPCError(res.error, 'failed to get fee for message'); - case 13: - case "end": - return _context36.stop(); - } - }, _callee36, null, [[0, 10]]); - })); + case 8: + if (!(res.result === null)) { + _context59.next = 10; + break; + } - return function getCurrentNonceValue() { - return _ref33.apply(this, arguments); - }; - }(); + throw new Error('invalid blockhash'); - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee37() { - return _regeneratorRuntime().wrap(function _callee37$(_context37) { - while (1) switch (_context37.prev = _context37.next) { - case 0: - _context37.next = 2; - return getCurrentNonceValue(); + case 10: + return _context59.abrupt("return", res.result); - case 2: - currentNonceValue = _context37.sent; + case 11: + case "end": + return _context59.stop(); + } + }, _callee59, this); + })); - if (!done) { - _context37.next = 5; - break; - } + function getFeeForMessage(_x88, _x89) { + return _getFeeForMessage.apply(this, arguments); + } - return _context37.abrupt("return"); + return getFeeForMessage; + }() + /** + * Fetch a list of prioritization fees from recent blocks. + */ - case 5: + }, { + key: "getRecentPrioritizationFees", + value: function () { + var _getRecentPrioritizationFees = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee60(config) { + var _config$lockedWritabl; - if (!(nonceValue !== currentNonceValue)) { - _context37.next = 9; - break; - } + var accounts, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee60$(_context60) { + while (1) switch (_context60.prev = _context60.next) { + case 0: + accounts = config === null || config === void 0 ? void 0 : (_config$lockedWritabl = config.lockedWritableAccounts) === null || _config$lockedWritabl === void 0 ? void 0 : _config$lockedWritabl.map(function (key) { + return key.toBase58(); + }); + args = this._buildArgs(accounts !== null && accounts !== void 0 && accounts.length ? [accounts] : []); + _context60.next = 4; + return this._rpcRequest('getRecentPrioritizationFees', args); - resolve({ - __type: TransactionStatus.NONCE_INVALID, - slotInWhichNonceDidAdvance: lastCheckedSlot - }); - return _context37.abrupt("return"); + case 4: + unsafeRes = _context60.sent; + res = _create(unsafeRes, GetRecentPrioritizationFeesRpcResult); - case 9: - _context37.next = 11; - return sleep(2000); + if (!('error' in res)) { + _context60.next = 8; + break; + } - case 11: - if (!done) { - _context37.next = 13; - break; - } + throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees'); - return _context37.abrupt("return"); + case 8: + return _context60.abrupt("return", res.result); - case 13: - _context37.next = 15; - return getCurrentNonceValue(); + case 9: + case "end": + return _context60.stop(); + } + }, _callee60, this); + })); - case 15: - currentNonceValue = _context37.sent; + function getRecentPrioritizationFees(_x90) { + return _getRecentPrioritizationFees.apply(this, arguments); + } - if (!done) { - _context37.next = 18; - break; - } + return getRecentPrioritizationFees; + }() + /** + * Fetch a recent blockhash from the cluster + * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + */ - return _context37.abrupt("return"); + }, { + key: "getRecentBlockhash", + value: function () { + var _getRecentBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee61(commitment) { + var res; + return _regeneratorRuntime().wrap(function _callee61$(_context61) { + while (1) switch (_context61.prev = _context61.next) { + case 0: + _context61.prev = 0; + _context61.next = 3; + return this.getRecentBlockhashAndContext(commitment); - case 18: - _context37.next = 5; - break; + case 3: + res = _context61.sent; + return _context61.abrupt("return", res.value); - case 20: - case "end": - return _context37.stop(); - } - }, _callee37); - }))(); - }); - _this$getTransactionC2 = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC2.abortConfirmation, confirmationPromise = _this$getTransactionC2.confirmationPromise; - cancellationPromise = this.getCancellationPromise(abortSignal); - _context38.prev = 5; - _context38.next = 8; - return Promise.race([cancellationPromise, confirmationPromise, expiryPromise]); + case 7: + _context61.prev = 7; + _context61.t0 = _context61["catch"](0); + throw new Error('failed to get recent blockhash: ' + _context61.t0); - case 8: - outcome = _context38.sent; + case 10: + case "end": + return _context61.stop(); + } + }, _callee61, this, [[0, 7]]); + })); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context38.next = 13; - break; - } + function getRecentBlockhash(_x91) { + return _getRecentBlockhash.apply(this, arguments); + } - result = outcome.response; - _context38.next = 47; - break; + return getRecentBlockhash; + }() + /** + * Fetch the latest blockhash from the cluster + * @return {Promise} + */ - case 13: + }, { + key: "getLatestBlockhash", + value: function () { + var _getLatestBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee62(commitmentOrConfig) { + var res; + return _regeneratorRuntime().wrap(function _callee62$(_context62) { + while (1) switch (_context62.prev = _context62.next) { + case 0: + _context62.prev = 0; + _context62.next = 3; + return this.getLatestBlockhashAndContext(commitmentOrConfig); - _context38.next = 16; - return this.getSignatureStatus(signature); + case 3: + res = _context62.sent; + return _context62.abrupt("return", res.value); - case 16: - status = _context38.sent; + case 7: + _context62.prev = 7; + _context62.t0 = _context62["catch"](0); + throw new Error('failed to get recent blockhash: ' + _context62.t0); - if (!(status == null)) { - _context38.next = 19; - break; - } + case 10: + case "end": + return _context62.stop(); + } + }, _callee62, this, [[0, 7]]); + })); - return _context38.abrupt("break", 27); + function getLatestBlockhash(_x92) { + return _getLatestBlockhash.apply(this, arguments); + } - case 19: - if (!(status.context.slot < ((_outcome$slotInWhichN = outcome.slotInWhichNonceDidAdvance) !== null && _outcome$slotInWhichN !== void 0 ? _outcome$slotInWhichN : minContextSlot))) { - _context38.next = 23; - break; - } + return getLatestBlockhash; + }() + /** + * Fetch the latest blockhash from the cluster + * @return {Promise} + */ - _context38.next = 22; - return sleep(400); + }, { + key: "getLatestBlockhashAndContext", + value: function () { + var _getLatestBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee63(commitmentOrConfig) { + var _extractCommitmentFro16, commitment, config, args, unsafeRes, res; - case 22: - return _context38.abrupt("continue", 13); + return _regeneratorRuntime().wrap(function _callee63$(_context63) { + while (1) switch (_context63.prev = _context63.next) { + case 0: + _extractCommitmentFro16 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro16.commitment, config = _extractCommitmentFro16.config; + args = this._buildArgs([], commitment, undefined + /* encoding */ + , config); + _context63.next = 4; + return this._rpcRequest('getLatestBlockhash', args); - case 23: - signatureStatus = status; - return _context38.abrupt("break", 27); + case 4: + unsafeRes = _context63.sent; + res = _create(unsafeRes, GetLatestBlockhashRpcResult); - case 27: - if (!((_signatureStatus = signatureStatus) !== null && _signatureStatus !== void 0 && _signatureStatus.value)) { - _context38.next = 46; + if (!('error' in res)) { + _context63.next = 8; break; } - commitmentForStatus = commitment || 'finalized'; - confirmationStatus = signatureStatus.value.confirmationStatus; - _context38.t0 = commitmentForStatus; - _context38.next = _context38.t0 === 'processed' ? 33 : _context38.t0 === 'recent' ? 33 : _context38.t0 === 'confirmed' ? 36 : _context38.t0 === 'single' ? 36 : _context38.t0 === 'singleGossip' ? 36 : _context38.t0 === 'finalized' ? 39 : _context38.t0 === 'max' ? 39 : _context38.t0 === 'root' ? 39 : 42; - break; + throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash'); - case 33: - if (!(confirmationStatus !== 'processed' && confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { - _context38.next = 35; - break; - } + case 8: + return _context63.abrupt("return", res.result); - throw new TransactionExpiredNonceInvalidError(signature); + case 9: + case "end": + return _context63.stop(); + } + }, _callee63, this); + })); - case 35: - return _context38.abrupt("break", 43); + function getLatestBlockhashAndContext(_x93) { + return _getLatestBlockhashAndContext.apply(this, arguments); + } - case 36: - if (!(confirmationStatus !== 'confirmed' && confirmationStatus !== 'finalized')) { - _context38.next = 38; - break; - } + return getLatestBlockhashAndContext; + }() + /** + * Fetch the node version + */ - throw new TransactionExpiredNonceInvalidError(signature); + }, { + key: "getVersion", + value: function () { + var _getVersion = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee64() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee64$(_context64) { + while (1) switch (_context64.prev = _context64.next) { + case 0: + _context64.next = 2; + return this._rpcRequest('getVersion', []); - case 38: - return _context38.abrupt("break", 43); + case 2: + unsafeRes = _context64.sent; + res = _create(unsafeRes, jsonRpcResult(VersionResult)); - case 39: - if (!(confirmationStatus !== 'finalized')) { - _context38.next = 41; + if (!('error' in res)) { + _context64.next = 6; break; } - throw new TransactionExpiredNonceInvalidError(signature); + throw new SolanaJSONRPCError(res.error, 'failed to get version'); - case 41: - return _context38.abrupt("break", 43); + case 6: + return _context64.abrupt("return", res.result); - case 42: + case 7: + case "end": + return _context64.stop(); + } + }, _callee64, this); + })); - case 43: - result = { - context: signatureStatus.context, - value: { - err: signatureStatus.value.err - } - }; - _context38.next = 47; - break; + function getVersion() { + return _getVersion.apply(this, arguments); + } - case 46: - throw new TransactionExpiredNonceInvalidError(signature); + return getVersion; + }() + /** + * Fetch the genesis hash + */ - case 47: - _context38.prev = 47; - done = true; - abortConfirmation(); - return _context38.finish(47); + }, { + key: "getGenesisHash", + value: function () { + var _getGenesisHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee65() { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee65$(_context65) { + while (1) switch (_context65.prev = _context65.next) { + case 0: + _context65.next = 2; + return this._rpcRequest('getGenesisHash', []); - case 51: - return _context38.abrupt("return", result); + case 2: + unsafeRes = _context65.sent; + res = _create(unsafeRes, jsonRpcResult(string())); - case 52: + if (!('error' in res)) { + _context65.next = 6; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash'); + + case 6: + return _context65.abrupt("return", res.result); + + case 7: case "end": - return _context38.stop(); + return _context65.stop(); } - }, _callee38, this, [[5,, 47, 51]]); + }, _callee65, this); })); - function confirmTransactionUsingDurableNonceStrategy(_x64) { - return _confirmTransactionUsingDurableNonceStrategy.apply(this, arguments); + function getGenesisHash() { + return _getGenesisHash.apply(this, arguments); } - return confirmTransactionUsingDurableNonceStrategy; + return getGenesisHash; }() + /** + * Fetch a processed block from the cluster. + * + * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by + * setting the `maxSupportedTransactionVersion` property. + */ + + /** + * Fetch a processed block from the cluster. + */ + // eslint-disable-next-line no-dupe-class-members + }, { - key: "confirmTransactionUsingLegacyTimeoutStrategy", + key: "getBlock", value: function () { - var _confirmTransactionUsingLegacyTimeoutStrategy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee39(_ref35) { - var _this19 = this; - - var commitment, signature, timeoutId, expiryPromise, _this$getTransactionC3, abortConfirmation, confirmationPromise, result, outcome; + var _getBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee66(slot, rawConfig) { + var _extractCommitmentFro17, commitment, config, args, unsafeRes, res, _res, _res2, result; - return _regeneratorRuntime().wrap(function _callee39$(_context39) { - while (1) switch (_context39.prev = _context39.next) { + return _regeneratorRuntime().wrap(function _callee66$(_context66) { + while (1) switch (_context66.prev = _context66.next) { case 0: - commitment = _ref35.commitment, signature = _ref35.signature; - expiryPromise = new Promise(function (resolve) { - var timeoutMs = _this19._confirmTransactionInitialTimeout || 60 * 1000; - - switch (commitment) { - case 'processed': - case 'recent': - case 'single': - case 'confirmed': - case 'singleGossip': - { - timeoutMs = _this19._confirmTransactionInitialTimeout || 30 * 1000; - break; - } - } + _extractCommitmentFro17 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro17.commitment, config = _extractCommitmentFro17.config; + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined + /* encoding */ + , config); + _context66.next = 4; + return this._rpcRequest('getBlock', args); - timeoutId = setTimeout(function () { - return resolve({ - __type: TransactionStatus.TIMED_OUT, - timeoutMs: timeoutMs - }); - }, timeoutMs); - }); - _this$getTransactionC3 = this.getTransactionConfirmationPromise({ - commitment: commitment, - signature: signature - }), abortConfirmation = _this$getTransactionC3.abortConfirmation, confirmationPromise = _this$getTransactionC3.confirmationPromise; - _context39.prev = 3; - _context39.next = 6; - return Promise.race([confirmationPromise, expiryPromise]); + case 4: + unsafeRes = _context66.sent; + _context66.prev = 5; + _context66.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; + _context66.next = _context66.t0 === 'accounts' ? 9 : _context66.t0 === 'none' ? 13 : 17; + break; - case 6: - outcome = _context39.sent; + case 9: + res = _create(unsafeRes, GetAccountsModeBlockRpcResult); - if (!(outcome.__type === TransactionStatus.PROCESSED)) { - _context39.next = 11; + if (!('error' in res)) { + _context66.next = 12; break; } - result = outcome.response; - _context39.next = 12; - break; - - case 11: - throw new TransactionExpiredTimeoutError(signature, outcome.timeoutMs / 1000); + throw res.error; case 12: - _context39.prev = 12; - clearTimeout(timeoutId); - abortConfirmation(); - return _context39.finish(12); + return _context66.abrupt("return", res.result); + + case 13: + _res = _create(unsafeRes, GetNoneModeBlockRpcResult); + + if (!('error' in _res)) { + _context66.next = 16; + break; + } + + throw _res.error; case 16: - return _context39.abrupt("return", result); + return _context66.abrupt("return", _res.result); case 17: + _res2 = _create(unsafeRes, GetBlockRpcResult); + + if (!('error' in _res2)) { + _context66.next = 20; + break; + } + + throw _res2.error; + + case 20: + result = _res2.result; + return _context66.abrupt("return", result ? _objectSpread2(_objectSpread2({}, result), {}, { + transactions: result.transactions.map(function (_ref36) { + var transaction = _ref36.transaction, + meta = _ref36.meta, + version = _ref36.version; + return { + meta: meta, + transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { + message: versionedMessageFromResponse(version, transaction.message) + }), + version: version + }; + }) + }) : null); + + case 22: + _context66.next = 27; + break; + + case 24: + _context66.prev = 24; + _context66.t1 = _context66["catch"](5); + throw new SolanaJSONRPCError(_context66.t1, 'failed to get confirmed block'); + + case 27: case "end": - return _context39.stop(); + return _context66.stop(); } - }, _callee39, this, [[3,, 12, 16]]); + }, _callee66, this, [[5, 24]]); })); - function confirmTransactionUsingLegacyTimeoutStrategy(_x65) { - return _confirmTransactionUsingLegacyTimeoutStrategy.apply(this, arguments); + function getBlock(_x94, _x95) { + return _getBlock.apply(this, arguments); } - return confirmTransactionUsingLegacyTimeoutStrategy; + return getBlock; }() /** - * Return the list of nodes that are currently participating in the cluster + * Fetch parsed transaction details for a confirmed or finalized block */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getClusterNodes", + key: "getParsedBlock", value: function () { - var _getClusterNodes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee40() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee40$(_context40) { - while (1) switch (_context40.prev = _context40.next) { + var _getParsedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee67(slot, rawConfig) { + var _extractCommitmentFro18, commitment, config, args, unsafeRes, res, _res3, _res4; + + return _regeneratorRuntime().wrap(function _callee67$(_context67) { + while (1) switch (_context67.prev = _context67.next) { case 0: - _context40.next = 2; - return this._rpcRequest('getClusterNodes', []); + _extractCommitmentFro18 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro18.commitment, config = _extractCommitmentFro18.config; + args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config); + _context67.next = 4; + return this._rpcRequest('getBlock', args); - case 2: - unsafeRes = _context40.sent; - res = _create(unsafeRes, jsonRpcResult(array(ContactInfoResult))); + case 4: + unsafeRes = _context67.sent; + _context67.prev = 5; + _context67.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; + _context67.next = _context67.t0 === 'accounts' ? 9 : _context67.t0 === 'none' ? 13 : 17; + break; + + case 9: + res = _create(unsafeRes, GetParsedAccountsModeBlockRpcResult); if (!('error' in res)) { - _context40.next = 6; + _context67.next = 12; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get cluster nodes'); + throw res.error; - case 6: - return _context40.abrupt("return", res.result); + case 12: + return _context67.abrupt("return", res.result); - case 7: - case "end": - return _context40.stop(); - } - }, _callee40, this); - })); + case 13: + _res3 = _create(unsafeRes, GetParsedNoneModeBlockRpcResult); - function getClusterNodes() { - return _getClusterNodes.apply(this, arguments); - } + if (!('error' in _res3)) { + _context67.next = 16; + break; + } - return getClusterNodes; - }() - /** - * Return the list of nodes that are currently participating in the cluster - */ + throw _res3.error; - }, { - key: "getVoteAccounts", - value: function () { - var _getVoteAccounts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee41(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee41$(_context41) { - while (1) switch (_context41.prev = _context41.next) { - case 0: - args = this._buildArgs([], commitment); - _context41.next = 3; - return this._rpcRequest('getVoteAccounts', args); + case 16: + return _context67.abrupt("return", _res3.result); - case 3: - unsafeRes = _context41.sent; - res = _create(unsafeRes, GetVoteAccounts); + case 17: + _res4 = _create(unsafeRes, GetParsedBlockRpcResult); - if (!('error' in res)) { - _context41.next = 7; + if (!('error' in _res4)) { + _context67.next = 20; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get vote accounts'); + throw _res4.error; - case 7: - return _context41.abrupt("return", res.result); + case 20: + return _context67.abrupt("return", _res4.result); - case 8: + case 21: + _context67.next = 26; + break; + + case 23: + _context67.prev = 23; + _context67.t1 = _context67["catch"](5); + throw new SolanaJSONRPCError(_context67.t1, 'failed to get block'); + + case 26: case "end": - return _context41.stop(); + return _context67.stop(); } - }, _callee41, this); + }, _callee67, this, [[5, 23]]); })); - function getVoteAccounts(_x66) { - return _getVoteAccounts.apply(this, arguments); + function getParsedBlock(_x96, _x97) { + return _getParsedBlock.apply(this, arguments); } - return getVoteAccounts; + return getParsedBlock; }() - /** - * Fetch the current slot that the node is processing + /* + * Returns the current block height of the node + */ + + /* + * Returns recent block production information from the current or previous epoch */ }, { - key: "getSlot", + key: "getBlockProduction", value: function () { - var _getSlot = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee42(commitmentOrConfig) { - var _extractCommitmentFro11, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee42$(_context42) { - while (1) switch (_context42.prev = _context42.next) { + var _getBlockProduction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee68(configOrCommitment) { + var extra, commitment, c, rest, args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee68$(_context68) { + while (1) switch (_context68.prev = _context68.next) { case 0: - _extractCommitmentFro11 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro11.commitment, config = _extractCommitmentFro11.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context42.next = 4; - return this._rpcRequest('getSlot', args); + if (typeof configOrCommitment === 'string') { + commitment = configOrCommitment; + } else if (configOrCommitment) { + c = configOrCommitment.commitment, rest = _objectWithoutProperties(configOrCommitment, _excluded3); + commitment = c; + extra = rest; + } + + args = this._buildArgs([], commitment, 'base64', extra); + _context68.next = 4; + return this._rpcRequest('getBlockProduction', args); case 4: - unsafeRes = _context42.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + unsafeRes = _context68.sent; + res = _create(unsafeRes, BlockProductionResponseStruct); if (!('error' in res)) { - _context42.next = 8; + _context68.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot'); + throw new SolanaJSONRPCError(res.error, 'failed to get block production information'); case 8: - return _context42.abrupt("return", res.result); + return _context68.abrupt("return", res.result); case 9: case "end": - return _context42.stop(); + return _context68.stop(); } - }, _callee42, this); + }, _callee68, this); })); - function getSlot(_x67) { - return _getSlot.apply(this, arguments); + function getBlockProduction(_x98) { + return _getBlockProduction.apply(this, arguments); } - return getSlot; + return getBlockProduction; }() /** - * Fetch the current slot leader of the cluster + * Fetch a confirmed or finalized transaction from the cluster. + * + * @deprecated Instead, call `getTransaction` using a + * `GetVersionedTransactionConfig` by setting the + * `maxSupportedTransactionVersion` property. + */ + + /** + * Fetch a confirmed or finalized transaction from the cluster. */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getSlotLeader", + key: "getTransaction", value: function () { - var _getSlotLeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee43(commitmentOrConfig) { - var _extractCommitmentFro12, commitment, config, args, unsafeRes, res; + var _getTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee69(signature, rawConfig) { + var _extractCommitmentFro19, commitment, config, args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee43$(_context43) { - while (1) switch (_context43.prev = _context43.next) { + return _regeneratorRuntime().wrap(function _callee69$(_context69) { + while (1) switch (_context69.prev = _context69.next) { case 0: - _extractCommitmentFro12 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro12.commitment, config = _extractCommitmentFro12.config; - args = this._buildArgs([], commitment, undefined + _extractCommitmentFro19 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro19.commitment, config = _extractCommitmentFro19.config; + args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined /* encoding */ , config); - _context43.next = 4; - return this._rpcRequest('getSlotLeader', args); + _context69.next = 4; + return this._rpcRequest('getTransaction', args); case 4: - unsafeRes = _context43.sent; - res = _create(unsafeRes, jsonRpcResult(string())); + unsafeRes = _context69.sent; + res = _create(unsafeRes, GetTransactionRpcResult); if (!('error' in res)) { - _context43.next = 8; + _context69.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot leader'); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 8: - return _context43.abrupt("return", res.result); - - case 9: - case "end": - return _context43.stop(); - } - }, _callee43, this); - })); - - function getSlotLeader(_x68) { - return _getSlotLeader.apply(this, arguments); - } - - return getSlotLeader; - }() - /** - * Fetch `limit` number of slot leaders starting from `startSlot` - * - * @param startSlot fetch slot leaders starting from this slot - * @param limit number of slot leaders to return - */ - - }, { - key: "getSlotLeaders", - value: function () { - var _getSlotLeaders = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee44(startSlot, limit) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee44$(_context44) { - while (1) switch (_context44.prev = _context44.next) { - case 0: - args = [startSlot, limit]; - _context44.next = 3; - return this._rpcRequest('getSlotLeaders', args); - - case 3: - unsafeRes = _context44.sent; - res = _create(unsafeRes, jsonRpcResult(array(PublicKeyFromString))); + result = res.result; - if (!('error' in res)) { - _context44.next = 7; + if (result) { + _context69.next = 11; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get slot leaders'); + return _context69.abrupt("return", result); - case 7: - return _context44.abrupt("return", res.result); + case 11: + return _context69.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { + transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { + message: versionedMessageFromResponse(result.version, result.transaction.message) + }) + })); - case 8: + case 12: case "end": - return _context44.stop(); + return _context69.stop(); } - }, _callee44, this); + }, _callee69, this); })); - function getSlotLeaders(_x69, _x70) { - return _getSlotLeaders.apply(this, arguments); + function getTransaction(_x99, _x100) { + return _getTransaction.apply(this, arguments); } - return getSlotLeaders; + return getTransaction; }() /** - * Fetch the current status of a signature + * Fetch parsed transaction details for a confirmed or finalized transaction */ }, { - key: "getSignatureStatus", + key: "getParsedTransaction", value: function () { - var _getSignatureStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee45(signature, config) { - var _yield$this$getSignat, context, values, value; - - return _regeneratorRuntime().wrap(function _callee45$(_context45) { - while (1) switch (_context45.prev = _context45.next) { - case 0: - _context45.next = 2; - return this.getSignatureStatuses([signature], config); - - case 2: - _yield$this$getSignat = _context45.sent; - context = _yield$this$getSignat.context; - values = _yield$this$getSignat.value; - assert(values.length === 1); - value = values[0]; - return _context45.abrupt("return", { - context: context, - value: value - }); - - case 8: - case "end": - return _context45.stop(); - } - }, _callee45, this); - })); - - function getSignatureStatus(_x71, _x72) { - return _getSignatureStatus.apply(this, arguments); - } - - return getSignatureStatus; - }() - /** - * Fetch the current statuses of a batch of signatures - */ + var _getParsedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee70(signature, commitmentOrConfig) { + var _extractCommitmentFro20, commitment, config, args, unsafeRes, res; - }, { - key: "getSignatureStatuses", - value: function () { - var _getSignatureStatuses = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee46(signatures, config) { - var params, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee46$(_context46) { - while (1) switch (_context46.prev = _context46.next) { + return _regeneratorRuntime().wrap(function _callee70$(_context70) { + while (1) switch (_context70.prev = _context70.next) { case 0: - params = [signatures]; - - if (config) { - params.push(config); - } - - _context46.next = 4; - return this._rpcRequest('getSignatureStatuses', params); + _extractCommitmentFro20 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro20.commitment, config = _extractCommitmentFro20.config; + args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); + _context70.next = 4; + return this._rpcRequest('getTransaction', args); case 4: - unsafeRes = _context46.sent; - res = _create(unsafeRes, GetSignatureStatusesRpcResult); + unsafeRes = _context70.sent; + res = _create(unsafeRes, GetParsedTransactionRpcResult); if (!('error' in res)) { - _context46.next = 8; + _context70.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get signature status'); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 8: - return _context46.abrupt("return", res.result); + return _context70.abrupt("return", res.result); case 9: case "end": - return _context46.stop(); + return _context70.stop(); } - }, _callee46, this); + }, _callee70, this); })); - function getSignatureStatuses(_x73, _x74) { - return _getSignatureStatuses.apply(this, arguments); + function getParsedTransaction(_x101, _x102) { + return _getParsedTransaction.apply(this, arguments); } - return getSignatureStatuses; + return getParsedTransaction; }() /** - * Fetch the current transaction count of the cluster + * Fetch parsed transaction details for a batch of confirmed transactions */ }, { - key: "getTransactionCount", + key: "getParsedTransactions", value: function () { - var _getTransactionCount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee47(commitmentOrConfig) { - var _extractCommitmentFro13, commitment, config, args, unsafeRes, res; + var _getParsedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee71(signatures, commitmentOrConfig) { + var _this20 = this; - return _regeneratorRuntime().wrap(function _callee47$(_context47) { - while (1) switch (_context47.prev = _context47.next) { + var _extractCommitmentFro21, commitment, config, batch, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee71$(_context71) { + while (1) switch (_context71.prev = _context71.next) { case 0: - _extractCommitmentFro13 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro13.commitment, config = _extractCommitmentFro13.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context47.next = 4; - return this._rpcRequest('getTransactionCount', args); + _extractCommitmentFro21 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro21.commitment, config = _extractCommitmentFro21.config; + batch = signatures.map(function (signature) { + var args = _this20._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); - case 4: - unsafeRes = _context47.sent; - res = _create(unsafeRes, jsonRpcResult(number())); + return { + methodName: 'getTransaction', + args: args + }; + }); + _context71.next = 4; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context47.next = 8; - break; - } + case 4: + unsafeRes = _context71.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetParsedTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get transaction count'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + } - case 8: - return _context47.abrupt("return", res.result); + return res.result; + }); + return _context71.abrupt("return", res); - case 9: + case 7: case "end": - return _context47.stop(); + return _context71.stop(); } - }, _callee47, this); + }, _callee71, this); })); - function getTransactionCount(_x75) { - return _getTransactionCount.apply(this, arguments); + function getParsedTransactions(_x103, _x104) { + return _getParsedTransactions.apply(this, arguments); } - return getTransactionCount; + return getParsedTransactions; }() /** - * Fetch the current total currency supply of the cluster in lamports + * Fetch transaction details for a batch of confirmed transactions. + * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}. * - * @deprecated Deprecated since v1.2.8. Please use {@link getSupply} instead. + * @deprecated Instead, call `getTransactions` using a + * `GetVersionedTransactionConfig` by setting the + * `maxSupportedTransactionVersion` property. */ - }, { - key: "getTotalSupply", - value: function () { - var _getTotalSupply = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee48(commitment) { - var result; - return _regeneratorRuntime().wrap(function _callee48$(_context48) { - while (1) switch (_context48.prev = _context48.next) { - case 0: - _context48.next = 2; - return this.getSupply({ - commitment: commitment, - excludeNonCirculatingAccountsList: true - }); - - case 2: - result = _context48.sent; - return _context48.abrupt("return", result.value.total); - - case 4: - case "end": - return _context48.stop(); - } - }, _callee48, this); - })); - - function getTotalSupply(_x76) { - return _getTotalSupply.apply(this, arguments); - } - - return getTotalSupply; - }() /** - * Fetch the cluster InflationGovernor parameters + * Fetch transaction details for a batch of confirmed transactions. + * Similar to {@link getParsedTransactions} but returns a {@link + * VersionedTransactionResponse}. */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getInflationGovernor", + key: "getTransactions", value: function () { - var _getInflationGovernor = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee49(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee49$(_context49) { - while (1) switch (_context49.prev = _context49.next) { + var _getTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee72(signatures, commitmentOrConfig) { + var _this21 = this; + + var _extractCommitmentFro22, commitment, config, batch, unsafeRes, res; + + return _regeneratorRuntime().wrap(function _callee72$(_context72) { + while (1) switch (_context72.prev = _context72.next) { case 0: - args = this._buildArgs([], commitment); - _context49.next = 3; - return this._rpcRequest('getInflationGovernor', args); + _extractCommitmentFro22 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro22.commitment, config = _extractCommitmentFro22.config; + batch = signatures.map(function (signature) { + var args = _this21._buildArgsAtLeastConfirmed([signature], commitment, undefined + /* encoding */ + , config); - case 3: - unsafeRes = _context49.sent; - res = _create(unsafeRes, GetInflationGovernorRpcResult); + return { + methodName: 'getTransaction', + args: args + }; + }); + _context72.next = 4; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context49.next = 7; - break; - } + case 4: + unsafeRes = _context72.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get inflation'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + } + + var result = res.result; + if (!result) return result; + return _objectSpread2(_objectSpread2({}, result), {}, { + transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { + message: versionedMessageFromResponse(result.version, result.transaction.message) + }) + }); + }); + return _context72.abrupt("return", res); case 7: - return _context49.abrupt("return", res.result); - - case 8: case "end": - return _context49.stop(); + return _context72.stop(); } - }, _callee49, this); + }, _callee72, this); })); - function getInflationGovernor(_x77) { - return _getInflationGovernor.apply(this, arguments); + function getTransactions(_x105, _x106) { + return _getTransactions.apply(this, arguments); } - return getInflationGovernor; + return getTransactions; }() /** - * Fetch the inflation reward for a list of addresses for an epoch + * Fetch a list of Transactions and transaction statuses from the cluster + * for a confirmed block. + * + * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead. */ }, { - key: "getInflationReward", + key: "getConfirmedBlock", value: function () { - var _getInflationReward = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee50(addresses, epoch, commitmentOrConfig) { - var _extractCommitmentFro14, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee50$(_context50) { - while (1) switch (_context50.prev = _context50.next) { + var _getConfirmedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee73(slot, commitment) { + var args, unsafeRes, res, result, block; + return _regeneratorRuntime().wrap(function _callee73$(_context73) { + while (1) switch (_context73.prev = _context73.next) { case 0: - _extractCommitmentFro14 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro14.commitment, config = _extractCommitmentFro14.config; - args = this._buildArgs([addresses.map(function (pubkey) { - return pubkey.toBase58(); - })], commitment, undefined - /* encoding */ - , _objectSpread2(_objectSpread2({}, config), {}, { - epoch: epoch != null ? epoch : config === null || config === void 0 ? void 0 : config.epoch - })); - _context50.next = 4; - return this._rpcRequest('getInflationReward', args); + args = this._buildArgsAtLeastConfirmed([slot], commitment); + _context73.next = 3; + return this._rpcRequest('getConfirmedBlock', args); - case 4: - unsafeRes = _context50.sent; - res = _create(unsafeRes, GetInflationRewardResult); + case 3: + unsafeRes = _context73.sent; + res = _create(unsafeRes, GetConfirmedBlockRpcResult); if (!('error' in res)) { - _context50.next = 8; + _context73.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get inflation reward'); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); - case 8: - return _context50.abrupt("return", res.result); + case 7: + result = res.result; - case 9: + if (result) { + _context73.next = 10; + break; + } + + throw new Error('Confirmed block ' + slot + ' not found'); + + case 10: + block = _objectSpread2(_objectSpread2({}, result), {}, { + transactions: result.transactions.map(function (_ref37) { + var transaction = _ref37.transaction, + meta = _ref37.meta; + var message = new Message(transaction.message); + return { + meta: meta, + transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { + message: message + }) + }; + }) + }); + return _context73.abrupt("return", _objectSpread2(_objectSpread2({}, block), {}, { + transactions: block.transactions.map(function (_ref38) { + var transaction = _ref38.transaction, + meta = _ref38.meta; + return { + meta: meta, + transaction: Transaction.populate(transaction.message, transaction.signatures) + }; + }) + })); + + case 12: case "end": - return _context50.stop(); + return _context73.stop(); } - }, _callee50, this); + }, _callee73, this); })); - function getInflationReward(_x78, _x79, _x80) { - return _getInflationReward.apply(this, arguments); + function getConfirmedBlock(_x107, _x108) { + return _getConfirmedBlock.apply(this, arguments); } - return getInflationReward; + return getConfirmedBlock; }() /** - * Fetch the specific inflation values for the current epoch + * Fetch confirmed blocks between two slots */ }, { - key: "getInflationRate", + key: "getBlocks", value: function () { - var _getInflationRate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee51() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee51$(_context51) { - while (1) switch (_context51.prev = _context51.next) { + var _getBlocks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee74(startSlot, endSlot, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee74$(_context74) { + while (1) switch (_context74.prev = _context74.next) { case 0: - _context51.next = 2; - return this._rpcRequest('getInflationRate', []); + args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment); + _context74.next = 3; + return this._rpcRequest('getBlocks', args); - case 2: - unsafeRes = _context51.sent; - res = _create(unsafeRes, GetInflationRateRpcResult); + case 3: + unsafeRes = _context74.sent; + res = _create(unsafeRes, jsonRpcResult(array(number()))); if (!('error' in res)) { - _context51.next = 6; + _context74.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get inflation rate'); - - case 6: - return _context51.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get blocks'); case 7: + return _context74.abrupt("return", res.result); + + case 8: case "end": - return _context51.stop(); + return _context74.stop(); } - }, _callee51, this); + }, _callee74, this); })); - function getInflationRate() { - return _getInflationRate.apply(this, arguments); + function getBlocks(_x109, _x110, _x111) { + return _getBlocks.apply(this, arguments); } - return getInflationRate; + return getBlocks; }() /** - * Fetch the Epoch Info parameters + * Fetch a list of Signatures from the cluster for a block, excluding rewards */ }, { - key: "getEpochInfo", + key: "getBlockSignatures", value: function () { - var _getEpochInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee52(commitmentOrConfig) { - var _extractCommitmentFro15, commitment, config, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee52$(_context52) { - while (1) switch (_context52.prev = _context52.next) { + var _getBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee75(slot, commitment) { + var args, unsafeRes, res, result; + return _regeneratorRuntime().wrap(function _callee75$(_context75) { + while (1) switch (_context75.prev = _context75.next) { case 0: - _extractCommitmentFro15 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro15.commitment, config = _extractCommitmentFro15.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context52.next = 4; - return this._rpcRequest('getEpochInfo', args); + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { + transactionDetails: 'signatures', + rewards: false + }); + _context75.next = 3; + return this._rpcRequest('getBlock', args); - case 4: - unsafeRes = _context52.sent; - res = _create(unsafeRes, GetEpochInfoRpcResult); + case 3: + unsafeRes = _context75.sent; + res = _create(unsafeRes, GetBlockSignaturesRpcResult); if (!('error' in res)) { - _context52.next = 8; + _context75.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get epoch info'); + throw new SolanaJSONRPCError(res.error, 'failed to get block'); - case 8: - return _context52.abrupt("return", res.result); + case 7: + result = res.result; - case 9: + if (result) { + _context75.next = 10; + break; + } + + throw new Error('Block ' + slot + ' not found'); + + case 10: + return _context75.abrupt("return", result); + + case 11: case "end": - return _context52.stop(); + return _context75.stop(); } - }, _callee52, this); + }, _callee75, this); })); - function getEpochInfo(_x81) { - return _getEpochInfo.apply(this, arguments); + function getBlockSignatures(_x112, _x113) { + return _getBlockSignatures.apply(this, arguments); } - return getEpochInfo; + return getBlockSignatures; }() /** - * Fetch the Epoch Schedule parameters + * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead. */ }, { - key: "getEpochSchedule", + key: "getConfirmedBlockSignatures", value: function () { - var _getEpochSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee53() { - var unsafeRes, res, epochSchedule; - return _regeneratorRuntime().wrap(function _callee53$(_context53) { - while (1) switch (_context53.prev = _context53.next) { + var _getConfirmedBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee76(slot, commitment) { + var args, unsafeRes, res, result; + return _regeneratorRuntime().wrap(function _callee76$(_context76) { + while (1) switch (_context76.prev = _context76.next) { case 0: - _context53.next = 2; - return this._rpcRequest('getEpochSchedule', []); + args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { + transactionDetails: 'signatures', + rewards: false + }); + _context76.next = 3; + return this._rpcRequest('getConfirmedBlock', args); - case 2: - unsafeRes = _context53.sent; - res = _create(unsafeRes, GetEpochScheduleRpcResult); + case 3: + unsafeRes = _context76.sent; + res = _create(unsafeRes, GetBlockSignaturesRpcResult); if (!('error' in res)) { - _context53.next = 6; + _context76.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get epoch schedule'); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); - case 6: - epochSchedule = res.result; - return _context53.abrupt("return", new EpochSchedule(epochSchedule.slotsPerEpoch, epochSchedule.leaderScheduleSlotOffset, epochSchedule.warmup, epochSchedule.firstNormalEpoch, epochSchedule.firstNormalSlot)); + case 7: + result = res.result; - case 8: + if (result) { + _context76.next = 10; + break; + } + + throw new Error('Confirmed block ' + slot + ' not found'); + + case 10: + return _context76.abrupt("return", result); + + case 11: case "end": - return _context53.stop(); + return _context76.stop(); } - }, _callee53, this); + }, _callee76, this); })); - function getEpochSchedule() { - return _getEpochSchedule.apply(this, arguments); + function getConfirmedBlockSignatures(_x114, _x115) { + return _getConfirmedBlockSignatures.apply(this, arguments); } - return getEpochSchedule; + return getConfirmedBlockSignatures; }() /** - * Fetch the leader schedule for the current epoch - * @return {Promise>} + * Fetch a transaction details for a confirmed transaction + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead. */ }, { - key: "getLeaderSchedule", + key: "getConfirmedTransaction", value: function () { - var _getLeaderSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee54() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee54$(_context54) { - while (1) switch (_context54.prev = _context54.next) { + var _getConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee77(signature, commitment) { + var args, unsafeRes, res, result, message, signatures; + return _regeneratorRuntime().wrap(function _callee77$(_context77) { + while (1) switch (_context77.prev = _context77.next) { case 0: - _context54.next = 2; - return this._rpcRequest('getLeaderSchedule', []); + args = this._buildArgsAtLeastConfirmed([signature], commitment); + _context77.next = 3; + return this._rpcRequest('getConfirmedTransaction', args); - case 2: - unsafeRes = _context54.sent; - res = _create(unsafeRes, GetLeaderScheduleRpcResult); + case 3: + unsafeRes = _context77.sent; + res = _create(unsafeRes, GetTransactionRpcResult); if (!('error' in res)) { - _context54.next = 6; + _context77.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get leader schedule'); - - case 6: - return _context54.abrupt("return", res.result); + throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); case 7: + result = res.result; + + if (result) { + _context77.next = 10; + break; + } + + return _context77.abrupt("return", result); + + case 10: + message = new Message(result.transaction.message); + signatures = result.transaction.signatures; + return _context77.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { + transaction: Transaction.populate(message, signatures) + })); + + case 13: case "end": - return _context54.stop(); + return _context77.stop(); } - }, _callee54, this); + }, _callee77, this); })); - function getLeaderSchedule() { - return _getLeaderSchedule.apply(this, arguments); + function getConfirmedTransaction(_x116, _x117) { + return _getConfirmedTransaction.apply(this, arguments); } - return getLeaderSchedule; + return getConfirmedTransaction; }() /** - * Fetch the minimum balance needed to exempt an account of `dataLength` - * size from rent + * Fetch parsed transaction details for a confirmed transaction + * + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead. */ }, { - key: "getMinimumBalanceForRentExemption", + key: "getParsedConfirmedTransaction", value: function () { - var _getMinimumBalanceForRentExemption = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee55(dataLength, commitment) { + var _getParsedConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee78(signature, commitment) { var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee55$(_context55) { - while (1) switch (_context55.prev = _context55.next) { + return _regeneratorRuntime().wrap(function _callee78$(_context78) { + while (1) switch (_context78.prev = _context78.next) { case 0: - args = this._buildArgs([dataLength], commitment); - _context55.next = 3; - return this._rpcRequest('getMinimumBalanceForRentExemption', args); + args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); + _context78.next = 3; + return this._rpcRequest('getConfirmedTransaction', args); case 3: - unsafeRes = _context55.sent; - res = _create(unsafeRes, GetMinimumBalanceForRentExemptionRpcResult); + unsafeRes = _context78.sent; + res = _create(unsafeRes, GetParsedTransactionRpcResult); if (!('error' in res)) { - _context55.next = 8; + _context78.next = 7; break; } - console.warn('Unable to fetch minimum balance for rent exemption'); - return _context55.abrupt("return", 0); + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction'); - case 8: - return _context55.abrupt("return", res.result); + case 7: + return _context78.abrupt("return", res.result); - case 9: + case 8: case "end": - return _context55.stop(); + return _context78.stop(); } - }, _callee55, this); + }, _callee78, this); })); - function getMinimumBalanceForRentExemption(_x82, _x83) { - return _getMinimumBalanceForRentExemption.apply(this, arguments); + function getParsedConfirmedTransaction(_x118, _x119) { + return _getParsedConfirmedTransaction.apply(this, arguments); } - return getMinimumBalanceForRentExemption; + return getParsedConfirmedTransaction; }() /** - * Fetch a recent blockhash from the cluster, return with context - * @return {Promise>} + * Fetch parsed transaction details for a batch of confirmed transactions * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead. */ }, { - key: "getRecentBlockhashAndContext", + key: "getParsedConfirmedTransactions", value: function () { - var _getRecentBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee56(commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee56$(_context56) { - while (1) switch (_context56.prev = _context56.next) { + var _getParsedConfirmedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee79(signatures, commitment) { + var _this22 = this; + + var batch, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee79$(_context79) { + while (1) switch (_context79.prev = _context79.next) { case 0: - args = this._buildArgs([], commitment); - _context56.next = 3; - return this._rpcRequest('getRecentBlockhash', args); + batch = signatures.map(function (signature) { + var args = _this22._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); - case 3: - unsafeRes = _context56.sent; - res = _create(unsafeRes, GetRecentBlockhashAndContextRpcResult); + return { + methodName: 'getConfirmedTransaction', + args: args + }; + }); + _context79.next = 3; + return this._rpcBatchRequest(batch); - if (!('error' in res)) { - _context56.next = 7; - break; - } + case 3: + unsafeRes = _context79.sent; + res = unsafeRes.map(function (unsafeRes) { + var res = _create(unsafeRes, GetParsedTransactionRpcResult); - throw new SolanaJSONRPCError(res.error, 'failed to get recent blockhash'); + if ('error' in res) { + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions'); + } - case 7: - return _context56.abrupt("return", res.result); + return res.result; + }); + return _context79.abrupt("return", res); - case 8: + case 6: case "end": - return _context56.stop(); + return _context79.stop(); } - }, _callee56, this); + }, _callee79, this); })); - function getRecentBlockhashAndContext(_x84) { - return _getRecentBlockhashAndContext.apply(this, arguments); + function getParsedConfirmedTransactions(_x120, _x121) { + return _getParsedConfirmedTransactions.apply(this, arguments); } - return getRecentBlockhashAndContext; + return getParsedConfirmedTransactions; }() /** - * Fetch recent performance samples - * @return {Promise>} + * Fetch a list of all the confirmed signatures for transactions involving an address + * within a specified slot range. Max range allowed is 10,000 slots. + * + * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead. + * + * @param address queried address + * @param startSlot start slot, inclusive + * @param endSlot end slot, inclusive */ }, { - key: "getRecentPerformanceSamples", + key: "getConfirmedSignaturesForAddress", value: function () { - var _getRecentPerformanceSamples = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee57(limit) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee57$(_context57) { - while (1) switch (_context57.prev = _context57.next) { + var _getConfirmedSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee80(address, startSlot, endSlot) { + var options, firstAvailableBlock, block, highestConfirmedRoot, _block, confirmedSignatureInfo; + + return _regeneratorRuntime().wrap(function _callee80$(_context80) { + while (1) switch (_context80.prev = _context80.next) { case 0: - _context57.next = 2; - return this._rpcRequest('getRecentPerformanceSamples', limit ? [limit] : []); + options = {}; + _context80.next = 3; + return this.getFirstAvailableBlock(); - case 2: - unsafeRes = _context57.sent; - res = _create(unsafeRes, GetRecentPerformanceSamplesRpcResult); + case 3: + firstAvailableBlock = _context80.sent; - if (!('error' in res)) { - _context57.next = 6; + case 4: + if ('until' in options) { + _context80.next = 24; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get recent performance samples'); + startSlot--; - case 6: - return _context57.abrupt("return", res.result); + if (!(startSlot <= 0 || startSlot < firstAvailableBlock)) { + _context80.next = 8; + break; + } - case 7: - case "end": - return _context57.stop(); - } - }, _callee57, this); - })); + return _context80.abrupt("break", 24); - function getRecentPerformanceSamples(_x85) { - return _getRecentPerformanceSamples.apply(this, arguments); - } + case 8: + _context80.prev = 8; + _context80.next = 11; + return this.getConfirmedBlockSignatures(startSlot, 'finalized'); - return getRecentPerformanceSamples; - }() - /** - * Fetch the fee calculator for a recent blockhash from the cluster, return with context - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getFeeForMessage} instead. - */ + case 11: + block = _context80.sent; - }, { - key: "getFeeCalculatorForBlockhash", - value: function () { - var _getFeeCalculatorForBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee58(blockhash, commitment) { - var args, unsafeRes, res, _res$result, context, value; + if (block.signatures.length > 0) { + options.until = block.signatures[block.signatures.length - 1].toString(); + } - return _regeneratorRuntime().wrap(function _callee58$(_context58) { - while (1) switch (_context58.prev = _context58.next) { - case 0: - args = this._buildArgs([blockhash], commitment); - _context58.next = 3; - return this._rpcRequest('getFeeCalculatorForBlockhash', args); + _context80.next = 22; + break; - case 3: - unsafeRes = _context58.sent; - res = _create(unsafeRes, GetFeeCalculatorRpcResult); + case 15: + _context80.prev = 15; + _context80.t0 = _context80["catch"](8); - if (!('error' in res)) { - _context58.next = 7; + if (!(_context80.t0 instanceof Error && _context80.t0.message.includes('skipped'))) { + _context80.next = 21; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get fee calculator'); - - case 7: - _res$result = res.result, context = _res$result.context, value = _res$result.value; - return _context58.abrupt("return", { - context: context, - value: value !== null ? value.feeCalculator : null - }); - - case 9: - case "end": - return _context58.stop(); - } - }, _callee58, this); - })); + return _context80.abrupt("continue", 4); - function getFeeCalculatorForBlockhash(_x86, _x87) { - return _getFeeCalculatorForBlockhash.apply(this, arguments); - } + case 21: + throw _context80.t0; - return getFeeCalculatorForBlockhash; - }() - /** - * Fetch the fee for a message from the cluster, return with context - */ + case 22: + _context80.next = 4; + break; - }, { - key: "getFeeForMessage", - value: function () { - var _getFeeForMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee59(message, commitment) { - var wireMessage, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee59$(_context59) { - while (1) switch (_context59.prev = _context59.next) { - case 0: - wireMessage = toBuffer(message.serialize()).toString('base64'); - args = this._buildArgs([wireMessage], commitment); - _context59.next = 4; - return this._rpcRequest('getFeeForMessage', args); + case 24: + _context80.next = 26; + return this.getSlot('finalized'); - case 4: - unsafeRes = _context59.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(nullable(number()))); + case 26: + highestConfirmedRoot = _context80.sent; - if (!('error' in res)) { - _context59.next = 8; + case 27: + if ('before' in options) { + _context80.next = 47; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get fee for message'); + endSlot++; - case 8: - if (!(res.result === null)) { - _context59.next = 10; + if (!(endSlot > highestConfirmedRoot)) { + _context80.next = 31; break; } - throw new Error('invalid blockhash'); - - case 10: - return _context59.abrupt("return", res.result); - - case 11: - case "end": - return _context59.stop(); - } - }, _callee59, this); - })); + return _context80.abrupt("break", 47); - function getFeeForMessage(_x88, _x89) { - return _getFeeForMessage.apply(this, arguments); - } + case 31: + _context80.prev = 31; + _context80.next = 34; + return this.getConfirmedBlockSignatures(endSlot); - return getFeeForMessage; - }() - /** - * Fetch a list of prioritization fees from recent blocks. - */ + case 34: + _block = _context80.sent; - }, { - key: "getRecentPrioritizationFees", - value: function () { - var _getRecentPrioritizationFees = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee60(config) { - var _config$lockedWritabl; + if (_block.signatures.length > 0) { + options.before = _block.signatures[_block.signatures.length - 1].toString(); + } - var accounts, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee60$(_context60) { - while (1) switch (_context60.prev = _context60.next) { - case 0: - accounts = config === null || config === void 0 ? void 0 : (_config$lockedWritabl = config.lockedWritableAccounts) === null || _config$lockedWritabl === void 0 ? void 0 : _config$lockedWritabl.map(function (key) { - return key.toBase58(); - }); - args = this._buildArgs(accounts !== null && accounts !== void 0 && accounts.length ? [accounts] : []); - _context60.next = 4; - return this._rpcRequest('getRecentPrioritizationFees', args); + _context80.next = 45; + break; - case 4: - unsafeRes = _context60.sent; - res = _create(unsafeRes, GetRecentPrioritizationFeesRpcResult); + case 38: + _context80.prev = 38; + _context80.t1 = _context80["catch"](31); - if (!('error' in res)) { - _context60.next = 8; + if (!(_context80.t1 instanceof Error && _context80.t1.message.includes('skipped'))) { + _context80.next = 44; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get recent prioritization fees'); + return _context80.abrupt("continue", 27); - case 8: - return _context60.abrupt("return", res.result); + case 44: + throw _context80.t1; - case 9: + case 45: + _context80.next = 27; + break; + + case 47: + _context80.next = 49; + return this.getConfirmedSignaturesForAddress2(address, options); + + case 49: + confirmedSignatureInfo = _context80.sent; + return _context80.abrupt("return", confirmedSignatureInfo.map(function (info) { + return info.signature; + })); + + case 51: case "end": - return _context60.stop(); + return _context80.stop(); } - }, _callee60, this); + }, _callee80, this, [[8, 15], [31, 38]]); })); - function getRecentPrioritizationFees(_x90) { - return _getRecentPrioritizationFees.apply(this, arguments); + function getConfirmedSignaturesForAddress(_x122, _x123, _x124) { + return _getConfirmedSignaturesForAddress.apply(this, arguments); } - return getRecentPrioritizationFees; + return getConfirmedSignaturesForAddress; }() /** - * Fetch a recent blockhash from the cluster - * @return {Promise<{blockhash: Blockhash, feeCalculator: FeeCalculator}>} + * Returns confirmed signatures for transactions involving an + * address backwards in time from the provided signature or most recent confirmed block * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getLatestBlockhash} instead. + * + * @param address queried address + * @param options */ }, { - key: "getRecentBlockhash", + key: "getConfirmedSignaturesForAddress2", value: function () { - var _getRecentBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee61(commitment) { - var res; - return _regeneratorRuntime().wrap(function _callee61$(_context61) { - while (1) switch (_context61.prev = _context61.next) { + var _getConfirmedSignaturesForAddress2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee81(address, options, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee81$(_context81) { + while (1) switch (_context81.prev = _context81.next) { case 0: - _context61.prev = 0; - _context61.next = 3; - return this.getRecentBlockhashAndContext(commitment); + args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); + _context81.next = 3; + return this._rpcRequest('getConfirmedSignaturesForAddress2', args); case 3: - res = _context61.sent; - return _context61.abrupt("return", res.value); + unsafeRes = _context81.sent; + res = _create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult); + + if (!('error' in res)) { + _context81.next = 7; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address'); case 7: - _context61.prev = 7; - _context61.t0 = _context61["catch"](0); - throw new Error('failed to get recent blockhash: ' + _context61.t0); + return _context81.abrupt("return", res.result); - case 10: + case 8: case "end": - return _context61.stop(); + return _context81.stop(); } - }, _callee61, this, [[0, 7]]); + }, _callee81, this); })); - function getRecentBlockhash(_x91) { - return _getRecentBlockhash.apply(this, arguments); + function getConfirmedSignaturesForAddress2(_x125, _x126, _x127) { + return _getConfirmedSignaturesForAddress2.apply(this, arguments); } - return getRecentBlockhash; + return getConfirmedSignaturesForAddress2; }() /** - * Fetch the latest blockhash from the cluster - * @return {Promise} + * Returns confirmed signatures for transactions involving an + * address backwards in time from the provided signature or most recent confirmed block + * + * + * @param address queried address + * @param options */ }, { - key: "getLatestBlockhash", + key: "getSignaturesForAddress", value: function () { - var _getLatestBlockhash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee62(commitmentOrConfig) { - var res; - return _regeneratorRuntime().wrap(function _callee62$(_context62) { - while (1) switch (_context62.prev = _context62.next) { + var _getSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee82(address, options, commitment) { + var args, unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee82$(_context82) { + while (1) switch (_context82.prev = _context82.next) { case 0: - _context62.prev = 0; - _context62.next = 3; - return this.getLatestBlockhashAndContext(commitmentOrConfig); + args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); + _context82.next = 3; + return this._rpcRequest('getSignaturesForAddress', args); case 3: - res = _context62.sent; - return _context62.abrupt("return", res.value); + unsafeRes = _context82.sent; + res = _create(unsafeRes, GetSignaturesForAddressRpcResult); + + if (!('error' in res)) { + _context82.next = 7; + break; + } + + throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address'); case 7: - _context62.prev = 7; - _context62.t0 = _context62["catch"](0); - throw new Error('failed to get recent blockhash: ' + _context62.t0); + return _context82.abrupt("return", res.result); - case 10: + case 8: case "end": - return _context62.stop(); + return _context82.stop(); } - }, _callee62, this, [[0, 7]]); + }, _callee82, this); })); - function getLatestBlockhash(_x92) { - return _getLatestBlockhash.apply(this, arguments); + function getSignaturesForAddress(_x128, _x129, _x130) { + return _getSignaturesForAddress.apply(this, arguments); } - return getLatestBlockhash; + return getSignaturesForAddress; }() - /** - * Fetch the latest blockhash from the cluster - * @return {Promise} - */ - }, { - key: "getLatestBlockhashAndContext", + key: "getAddressLookupTable", value: function () { - var _getLatestBlockhashAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee63(commitmentOrConfig) { - var _extractCommitmentFro16, commitment, config, args, unsafeRes, res; + var _getAddressLookupTable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee83(accountKey, config) { + var _yield$this$getAccoun, context, accountInfo, value; - return _regeneratorRuntime().wrap(function _callee63$(_context63) { - while (1) switch (_context63.prev = _context63.next) { + return _regeneratorRuntime().wrap(function _callee83$(_context83) { + while (1) switch (_context83.prev = _context83.next) { case 0: - _extractCommitmentFro16 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro16.commitment, config = _extractCommitmentFro16.config; - args = this._buildArgs([], commitment, undefined - /* encoding */ - , config); - _context63.next = 4; - return this._rpcRequest('getLatestBlockhash', args); + _context83.next = 2; + return this.getAccountInfoAndContext(accountKey, config); - case 4: - unsafeRes = _context63.sent; - res = _create(unsafeRes, GetLatestBlockhashRpcResult); + case 2: + _yield$this$getAccoun = _context83.sent; + context = _yield$this$getAccoun.context; + accountInfo = _yield$this$getAccoun.value; + value = null; - if (!('error' in res)) { - _context63.next = 8; - break; + if (accountInfo !== null) { + value = new AddressLookupTableAccount({ + key: accountKey, + state: AddressLookupTableAccount.deserialize(accountInfo.data) + }); } - throw new SolanaJSONRPCError(res.error, 'failed to get latest blockhash'); + return _context83.abrupt("return", { + context: context, + value: value + }); case 8: - return _context63.abrupt("return", res.result); - - case 9: case "end": - return _context63.stop(); + return _context83.stop(); } - }, _callee63, this); + }, _callee83, this); })); - function getLatestBlockhashAndContext(_x93) { - return _getLatestBlockhashAndContext.apply(this, arguments); + function getAddressLookupTable(_x131, _x132) { + return _getAddressLookupTable.apply(this, arguments); } - return getLatestBlockhashAndContext; + return getAddressLookupTable; }() /** - * Fetch the node version + * Fetch the contents of a Nonce account from the cluster, return with context */ }, { - key: "getVersion", + key: "getNonceAndContext", value: function () { - var _getVersion = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee64() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee64$(_context64) { - while (1) switch (_context64.prev = _context64.next) { + var _getNonceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee84(nonceAccount, commitmentOrConfig) { + var _yield$this$getAccoun2, context, accountInfo, value; + + return _regeneratorRuntime().wrap(function _callee84$(_context84) { + while (1) switch (_context84.prev = _context84.next) { case 0: - _context64.next = 2; - return this._rpcRequest('getVersion', []); + _context84.next = 2; + return this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig); case 2: - unsafeRes = _context64.sent; - res = _create(unsafeRes, jsonRpcResult(VersionResult)); + _yield$this$getAccoun2 = _context84.sent; + context = _yield$this$getAccoun2.context; + accountInfo = _yield$this$getAccoun2.value; + value = null; - if (!('error' in res)) { - _context64.next = 6; - break; + if (accountInfo !== null) { + value = NonceAccount.fromAccountData(accountInfo.data); } - throw new SolanaJSONRPCError(res.error, 'failed to get version'); - - case 6: - return _context64.abrupt("return", res.result); + return _context84.abrupt("return", { + context: context, + value: value + }); - case 7: + case 8: case "end": - return _context64.stop(); + return _context84.stop(); } - }, _callee64, this); + }, _callee84, this); })); - function getVersion() { - return _getVersion.apply(this, arguments); + function getNonceAndContext(_x133, _x134) { + return _getNonceAndContext.apply(this, arguments); } - return getVersion; + return getNonceAndContext; }() /** - * Fetch the genesis hash + * Fetch the contents of a Nonce account from the cluster */ }, { - key: "getGenesisHash", + key: "getNonce", value: function () { - var _getGenesisHash = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee65() { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee65$(_context65) { - while (1) switch (_context65.prev = _context65.next) { + var _getNonce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee85(nonceAccount, commitmentOrConfig) { + return _regeneratorRuntime().wrap(function _callee85$(_context85) { + while (1) switch (_context85.prev = _context85.next) { case 0: - _context65.next = 2; - return this._rpcRequest('getGenesisHash', []); + _context85.next = 2; + return this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(function (x) { + return x.value; + })["catch"](function (e) { + throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e); + }); case 2: - unsafeRes = _context65.sent; - res = _create(unsafeRes, jsonRpcResult(string())); - - if (!('error' in res)) { - _context65.next = 6; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get genesis hash'); - - case 6: - return _context65.abrupt("return", res.result); + return _context85.abrupt("return", _context85.sent); - case 7: + case 3: case "end": - return _context65.stop(); + return _context85.stop(); } - }, _callee65, this); + }, _callee85, this); })); - function getGenesisHash() { - return _getGenesisHash.apply(this, arguments); + function getNonce(_x135, _x136) { + return _getNonce.apply(this, arguments); } - return getGenesisHash; + return getNonce; }() /** - * Fetch a processed block from the cluster. + * Request an allocation of lamports to the specified address * - * @deprecated Instead, call `getBlock` using a `GetVersionedBlockConfig` by - * setting the `maxSupportedTransactionVersion` property. - */ - - /** - * Fetch a processed block from the cluster. + * ```typescript + * import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js"; + * + * (async () => { + * const connection = new Connection("https://api.testnet.solana.com", "confirmed"); + * const myAddress = new PublicKey("2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM"); + * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL); + * await connection.confirmTransaction(signature); + * })(); + * ``` */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "getBlock", + key: "requestAirdrop", value: function () { - var _getBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee66(slot, rawConfig) { - var _extractCommitmentFro17, commitment, config, args, unsafeRes, res, _res, _res2, result; - - return _regeneratorRuntime().wrap(function _callee66$(_context66) { - while (1) switch (_context66.prev = _context66.next) { + var _requestAirdrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee86(to, lamports) { + var unsafeRes, res; + return _regeneratorRuntime().wrap(function _callee86$(_context86) { + while (1) switch (_context86.prev = _context86.next) { case 0: - _extractCommitmentFro17 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro17.commitment, config = _extractCommitmentFro17.config; - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined - /* encoding */ - , config); - _context66.next = 4; - return this._rpcRequest('getBlock', args); - - case 4: - unsafeRes = _context66.sent; - _context66.prev = 5; - _context66.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; - _context66.next = _context66.t0 === 'accounts' ? 9 : _context66.t0 === 'none' ? 13 : 17; - break; + _context86.next = 2; + return this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]); - case 9: - res = _create(unsafeRes, GetAccountsModeBlockRpcResult); + case 2: + unsafeRes = _context86.sent; + res = _create(unsafeRes, RequestAirdropRpcResult); if (!('error' in res)) { - _context66.next = 12; - break; - } - - throw res.error; - - case 12: - return _context66.abrupt("return", res.result); - - case 13: - _res = _create(unsafeRes, GetNoneModeBlockRpcResult); - - if (!('error' in _res)) { - _context66.next = 16; - break; - } - - throw _res.error; - - case 16: - return _context66.abrupt("return", _res.result); - - case 17: - _res2 = _create(unsafeRes, GetBlockRpcResult); - - if (!('error' in _res2)) { - _context66.next = 20; + _context86.next = 6; break; } - throw _res2.error; - - case 20: - result = _res2.result; - return _context66.abrupt("return", result ? _objectSpread2(_objectSpread2({}, result), {}, { - transactions: result.transactions.map(function (_ref36) { - var transaction = _ref36.transaction, - meta = _ref36.meta, - version = _ref36.version; - return { - meta: meta, - transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { - message: versionedMessageFromResponse(version, transaction.message) - }), - version: version - }; - }) - }) : null); - - case 22: - _context66.next = 27; - break; - - case 24: - _context66.prev = 24; - _context66.t1 = _context66["catch"](5); - throw new SolanaJSONRPCError(_context66.t1, 'failed to get confirmed block'); + throw new SolanaJSONRPCError(res.error, "airdrop to ".concat(to.toBase58(), " failed")); - case 27: + case 6: + return _context86.abrupt("return", res.result); + + case 7: case "end": - return _context66.stop(); + return _context86.stop(); } - }, _callee66, this, [[5, 24]]); + }, _callee86, this); })); - function getBlock(_x94, _x95) { - return _getBlock.apply(this, arguments); + function requestAirdrop(_x137, _x138) { + return _requestAirdrop.apply(this, arguments); } - return getBlock; + return requestAirdrop; }() /** - * Fetch parsed transaction details for a confirmed or finalized block + * @internal */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "getParsedBlock", + key: "_blockhashWithExpiryBlockHeight", value: function () { - var _getParsedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee67(slot, rawConfig) { - var _extractCommitmentFro18, commitment, config, args, unsafeRes, res, _res3, _res4; - - return _regeneratorRuntime().wrap(function _callee67$(_context67) { - while (1) switch (_context67.prev = _context67.next) { + var _blockhashWithExpiryBlockHeight2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee87(disableCache) { + var timeSinceFetch, expired; + return _regeneratorRuntime().wrap(function _callee87$(_context87) { + while (1) switch (_context87.prev = _context87.next) { case 0: - _extractCommitmentFro18 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro18.commitment, config = _extractCommitmentFro18.config; - args = this._buildArgsAtLeastConfirmed([slot], commitment, 'jsonParsed', config); - _context67.next = 4; - return this._rpcRequest('getBlock', args); + if (disableCache) { + _context87.next = 10; + break; + } + + case 1: + if (!this._pollingBlockhash) { + _context87.next = 6; + break; + } + + _context87.next = 4; + return sleep(100); case 4: - unsafeRes = _context67.sent; - _context67.prev = 5; - _context67.t0 = config === null || config === void 0 ? void 0 : config.transactionDetails; - _context67.next = _context67.t0 === 'accounts' ? 9 : _context67.t0 === 'none' ? 13 : 17; + _context87.next = 1; break; - case 9: - res = _create(unsafeRes, GetParsedAccountsModeBlockRpcResult); + case 6: + timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch; + expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS; - if (!('error' in res)) { - _context67.next = 12; + if (!(this._blockhashInfo.latestBlockhash !== null && !expired)) { + _context87.next = 10; break; } - throw res.error; + return _context87.abrupt("return", this._blockhashInfo.latestBlockhash); + + case 10: + _context87.next = 12; + return this._pollNewBlockhash(); case 12: - return _context67.abrupt("return", res.result); + return _context87.abrupt("return", _context87.sent); case 13: - _res3 = _create(unsafeRes, GetParsedNoneModeBlockRpcResult); + case "end": + return _context87.stop(); + } + }, _callee87, this); + })); - if (!('error' in _res3)) { - _context67.next = 16; + function _blockhashWithExpiryBlockHeight(_x139) { + return _blockhashWithExpiryBlockHeight2.apply(this, arguments); + } + + return _blockhashWithExpiryBlockHeight; + }() + /** + * @internal + */ + + }, { + key: "_pollNewBlockhash", + value: function () { + var _pollNewBlockhash2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee88() { + var startTime, cachedLatestBlockhash, cachedBlockhash, i, latestBlockhash; + return _regeneratorRuntime().wrap(function _callee88$(_context88) { + while (1) switch (_context88.prev = _context88.next) { + case 0: + this._pollingBlockhash = true; + _context88.prev = 1; + startTime = Date.now(); + cachedLatestBlockhash = this._blockhashInfo.latestBlockhash; + cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null; + i = 0; + + case 6: + if (!(i < 50)) { + _context88.next = 18; break; } - throw _res3.error; - - case 16: - return _context67.abrupt("return", _res3.result); + _context88.next = 9; + return this.getLatestBlockhash('finalized'); - case 17: - _res4 = _create(unsafeRes, GetParsedBlockRpcResult); + case 9: + latestBlockhash = _context88.sent; - if (!('error' in _res4)) { - _context67.next = 20; + if (!(cachedBlockhash !== latestBlockhash.blockhash)) { + _context88.next = 13; break; } - throw _res4.error; + this._blockhashInfo = { + latestBlockhash: latestBlockhash, + lastFetch: Date.now(), + transactionSignatures: [], + simulatedSignatures: [] + }; + return _context88.abrupt("return", latestBlockhash); - case 20: - return _context67.abrupt("return", _res4.result); + case 13: + _context88.next = 15; + return sleep(MS_PER_SLOT / 2); - case 21: - _context67.next = 26; + case 15: + i++; + _context88.next = 6; break; - case 23: - _context67.prev = 23; - _context67.t1 = _context67["catch"](5); - throw new SolanaJSONRPCError(_context67.t1, 'failed to get block'); + case 18: + throw new Error("Unable to obtain a new blockhash after ".concat(Date.now() - startTime, "ms")); - case 26: + case 19: + _context88.prev = 19; + this._pollingBlockhash = false; + return _context88.finish(19); + + case 22: case "end": - return _context67.stop(); + return _context88.stop(); } - }, _callee67, this, [[5, 23]]); + }, _callee88, this, [[1,, 19, 22]]); })); - function getParsedBlock(_x96, _x97) { - return _getParsedBlock.apply(this, arguments); + function _pollNewBlockhash() { + return _pollNewBlockhash2.apply(this, arguments); } - return getParsedBlock; + return _pollNewBlockhash; }() - /* - * Returns the current block height of the node - */ - - /* - * Returns recent block production information from the current or previous epoch + /** + * get the stake minimum delegation */ }, { - key: "getBlockProduction", + key: "getStakeMinimumDelegation", value: function () { - var _getBlockProduction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee68(configOrCommitment) { - var extra, commitment, c, rest, args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee68$(_context68) { - while (1) switch (_context68.prev = _context68.next) { - case 0: - if (typeof configOrCommitment === 'string') { - commitment = configOrCommitment; - } else if (configOrCommitment) { - c = configOrCommitment.commitment, rest = _objectWithoutProperties(configOrCommitment, _excluded3); - commitment = c; - extra = rest; - } + var _getStakeMinimumDelegation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee89(config) { + var _extractCommitmentFro23, commitment, configArg, args, unsafeRes, res; - args = this._buildArgs([], commitment, 'base64', extra); - _context68.next = 4; - return this._rpcRequest('getBlockProduction', args); + return _regeneratorRuntime().wrap(function _callee89$(_context89) { + while (1) switch (_context89.prev = _context89.next) { + case 0: + _extractCommitmentFro23 = extractCommitmentFromConfig(config), commitment = _extractCommitmentFro23.commitment, configArg = _extractCommitmentFro23.config; + args = this._buildArgs([], commitment, 'base64', configArg); + _context89.next = 4; + return this._rpcRequest('getStakeMinimumDelegation', args); case 4: - unsafeRes = _context68.sent; - res = _create(unsafeRes, BlockProductionResponseStruct); + unsafeRes = _context89.sent; + res = _create(unsafeRes, jsonRpcResultAndContext(number())); if (!('error' in res)) { - _context68.next = 8; + _context89.next = 8; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get block production information'); + throw new SolanaJSONRPCError(res.error, "failed to get stake minimum delegation"); case 8: - return _context68.abrupt("return", res.result); + return _context89.abrupt("return", res.result); case 9: case "end": - return _context68.stop(); + return _context89.stop(); } - }, _callee68, this); + }, _callee89, this); })); - function getBlockProduction(_x98) { - return _getBlockProduction.apply(this, arguments); + function getStakeMinimumDelegation(_x140) { + return _getStakeMinimumDelegation.apply(this, arguments); } - return getBlockProduction; + return getStakeMinimumDelegation; }() /** - * Fetch a confirmed or finalized transaction from the cluster. + * Simulate a transaction * - * @deprecated Instead, call `getTransaction` using a - * `GetVersionedTransactionConfig` by setting the - * `maxSupportedTransactionVersion` property. + * @deprecated Instead, call {@link simulateTransaction} with {@link + * VersionedTransaction} and {@link SimulateTransactionConfig} parameters */ /** - * Fetch a confirmed or finalized transaction from the cluster. + * Simulate a transaction */ // eslint-disable-next-line no-dupe-class-members }, { - key: "getTransaction", + key: "simulateTransaction", value: function () { - var _getTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee69(signature, rawConfig) { - var _extractCommitmentFro19, commitment, config, args, unsafeRes, res, result; + var _simulateTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee90(transactionOrMessage, configOrSigners, includeAccounts) { + var versionedTx, _wireTransaction, _encodedTransaction, _config, _args91, _unsafeRes, _res5, transaction, originalTx, signers, _transaction3, disableCache, _transaction4, latestBlockhash, _signature3, message, signData, wireTransaction, encodedTransaction, config, addresses, args, unsafeRes, res, logs, traceIndent, logTrace; - return _regeneratorRuntime().wrap(function _callee69$(_context69) { - while (1) switch (_context69.prev = _context69.next) { + return _regeneratorRuntime().wrap(function _callee90$(_context90) { + while (1) switch (_context90.prev = _context90.next) { case 0: - _extractCommitmentFro19 = extractCommitmentFromConfig(rawConfig), commitment = _extractCommitmentFro19.commitment, config = _extractCommitmentFro19.config; - args = this._buildArgsAtLeastConfirmed([signature], commitment, undefined - /* encoding */ - , config); - _context69.next = 4; - return this._rpcRequest('getTransaction', args); + if (!('message' in transactionOrMessage)) { + _context90.next = 17; + break; + } - case 4: - unsafeRes = _context69.sent; - res = _create(unsafeRes, GetTransactionRpcResult); + versionedTx = transactionOrMessage; + _wireTransaction = versionedTx.serialize(); + _encodedTransaction = Buffer$1.from(_wireTransaction).toString('base64'); - if (!('error' in res)) { - _context69.next = 8; + if (!(Array.isArray(configOrSigners) || includeAccounts !== undefined)) { + _context90.next = 6; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + throw new Error('Invalid arguments'); - case 8: - result = res.result; + case 6: + _config = configOrSigners || {}; + _config.encoding = 'base64'; - if (result) { - _context69.next = 11; - break; + if (!('commitment' in _config)) { + _config.commitment = this.commitment; } - return _context69.abrupt("return", result); - - case 11: - return _context69.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { - transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { - message: versionedMessageFromResponse(result.version, result.transaction.message) - }) - })); + _args91 = [_encodedTransaction, _config]; + _context90.next = 12; + return this._rpcRequest('simulateTransaction', _args91); case 12: - case "end": - return _context69.stop(); - } - }, _callee69, this); - })); + _unsafeRes = _context90.sent; + _res5 = _create(_unsafeRes, SimulatedTransactionResponseStruct); - function getTransaction(_x99, _x100) { - return _getTransaction.apply(this, arguments); - } + if (!('error' in _res5)) { + _context90.next = 16; + break; + } - return getTransaction; - }() - /** - * Fetch parsed transaction details for a confirmed or finalized transaction - */ + throw new Error('failed to simulate transaction: ' + _res5.error.message); - }, { - key: "getParsedTransaction", - value: function () { - var _getParsedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee70(signature, commitmentOrConfig) { - var _extractCommitmentFro20, commitment, config, args, unsafeRes, res; + case 16: + return _context90.abrupt("return", _res5.result); - return _regeneratorRuntime().wrap(function _callee70$(_context70) { - while (1) switch (_context70.prev = _context70.next) { - case 0: - _extractCommitmentFro20 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro20.commitment, config = _extractCommitmentFro20.config; - args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); - _context70.next = 4; - return this._rpcRequest('getTransaction', args); + case 17: + if (transactionOrMessage instanceof Transaction) { + originalTx = transactionOrMessage; + transaction = new Transaction(); + transaction.feePayer = originalTx.feePayer; + transaction.instructions = transactionOrMessage.instructions; + transaction.nonceInfo = originalTx.nonceInfo; + transaction.signatures = originalTx.signatures; + } else { + transaction = Transaction.populate(transactionOrMessage); // HACK: this function relies on mutating the populated transaction - case 4: - unsafeRes = _context70.sent; - res = _create(unsafeRes, GetParsedTransactionRpcResult); + transaction._message = transaction._json = undefined; + } - if (!('error' in res)) { - _context70.next = 8; + if (!(configOrSigners !== undefined && !Array.isArray(configOrSigners))) { + _context90.next = 20; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + throw new Error('Invalid arguments'); - case 8: - return _context70.abrupt("return", res.result); + case 20: + signers = configOrSigners; - case 9: - case "end": - return _context70.stop(); - } - }, _callee70, this); - })); + if (!(transaction.nonceInfo && signers)) { + _context90.next = 25; + break; + } - function getParsedTransaction(_x101, _x102) { - return _getParsedTransaction.apply(this, arguments); - } + (_transaction3 = transaction).sign.apply(_transaction3, _toConsumableArray(signers)); - return getParsedTransaction; - }() - /** - * Fetch parsed transaction details for a batch of confirmed transactions - */ + _context90.next = 45; + break; - }, { - key: "getParsedTransactions", - value: function () { - var _getParsedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee71(signatures, commitmentOrConfig) { - var _this20 = this; + case 25: + disableCache = this._disableBlockhashCaching; - var _extractCommitmentFro21, commitment, config, batch, unsafeRes, res; + case 26: + _context90.next = 28; + return this._blockhashWithExpiryBlockHeight(disableCache); - return _regeneratorRuntime().wrap(function _callee71$(_context71) { - while (1) switch (_context71.prev = _context71.next) { - case 0: - _extractCommitmentFro21 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro21.commitment, config = _extractCommitmentFro21.config; - batch = signatures.map(function (signature) { - var args = _this20._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed', config); + case 28: + latestBlockhash = _context90.sent; + transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; + transaction.recentBlockhash = latestBlockhash.blockhash; - return { - methodName: 'getTransaction', - args: args - }; - }); - _context71.next = 4; - return this._rpcBatchRequest(batch); + if (signers) { + _context90.next = 33; + break; + } - case 4: - unsafeRes = _context71.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetParsedTransactionRpcResult); + return _context90.abrupt("break", 45); - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); - } + case 33: + (_transaction4 = transaction).sign.apply(_transaction4, _toConsumableArray(signers)); - return res.result; - }); - return _context71.abrupt("return", res); + if (transaction.signature) { + _context90.next = 36; + break; + } - case 7: - case "end": - return _context71.stop(); - } - }, _callee71, this); - })); + throw new Error('!signature'); - function getParsedTransactions(_x103, _x104) { - return _getParsedTransactions.apply(this, arguments); - } + case 36: + _signature3 = transaction.signature.toString('base64'); - return getParsedTransactions; - }() - /** - * Fetch transaction details for a batch of confirmed transactions. - * Similar to {@link getParsedTransactions} but returns a {@link TransactionResponse}. - * - * @deprecated Instead, call `getTransactions` using a - * `GetVersionedTransactionConfig` by setting the - * `maxSupportedTransactionVersion` property. - */ + if (!(!this._blockhashInfo.simulatedSignatures.includes(_signature3) && !this._blockhashInfo.transactionSignatures.includes(_signature3))) { + _context90.next = 42; + break; + } - /** - * Fetch transaction details for a batch of confirmed transactions. - * Similar to {@link getParsedTransactions} but returns a {@link - * VersionedTransactionResponse}. - */ - // eslint-disable-next-line no-dupe-class-members + // The signature of this transaction has not been seen before with the + // current recentBlockhash, all done. Let's break + this._blockhashInfo.simulatedSignatures.push(_signature3); - }, { - key: "getTransactions", - value: function () { - var _getTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee72(signatures, commitmentOrConfig) { - var _this21 = this; + return _context90.abrupt("break", 45); - var _extractCommitmentFro22, commitment, config, batch, unsafeRes, res; + case 42: + // This transaction would be treated as duplicate (its derived signature + // matched to one of already recorded signatures). + // So, we must fetch a new blockhash for a different signature by disabling + // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). + disableCache = true; - return _regeneratorRuntime().wrap(function _callee72$(_context72) { - while (1) switch (_context72.prev = _context72.next) { - case 0: - _extractCommitmentFro22 = extractCommitmentFromConfig(commitmentOrConfig), commitment = _extractCommitmentFro22.commitment, config = _extractCommitmentFro22.config; - batch = signatures.map(function (signature) { - var args = _this21._buildArgsAtLeastConfirmed([signature], commitment, undefined - /* encoding */ - , config); + case 43: + _context90.next = 26; + break; - return { - methodName: 'getTransaction', - args: args + case 45: + message = transaction._compile(); + signData = message.serialize(); + wireTransaction = transaction._serialize(signData); + encodedTransaction = wireTransaction.toString('base64'); + config = { + encoding: 'base64', + commitment: this.commitment + }; + + if (includeAccounts) { + addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(function (key) { + return key.toBase58(); + }); + config['accounts'] = { + encoding: 'base64', + addresses: addresses }; - }); - _context72.next = 4; - return this._rpcBatchRequest(batch); + } - case 4: - unsafeRes = _context72.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetTransactionRpcResult); + if (signers) { + config.sigVerify = true; + } + + args = [encodedTransaction, config]; + _context90.next = 55; + return this._rpcRequest('simulateTransaction', args); + + case 55: + unsafeRes = _context90.sent; + res = _create(unsafeRes, SimulatedTransactionResponseStruct); + + if (!('error' in res)) { + _context90.next = 60; + break; + } - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get transactions'); + if ('data' in res.error) { + logs = res.error.data.logs; + + if (logs && Array.isArray(logs)) { + traceIndent = '\n '; + logTrace = traceIndent + logs.join(traceIndent); + console.error(res.error.message, logTrace); } + } - var result = res.result; - if (!result) return result; - return _objectSpread2(_objectSpread2({}, result), {}, { - transaction: _objectSpread2(_objectSpread2({}, result.transaction), {}, { - message: versionedMessageFromResponse(result.version, result.transaction.message) - }) - }); - }); - return _context72.abrupt("return", res); + throw new SendTransactionError('failed to simulate transaction: ' + res.error.message, logs); - case 7: + case 60: + return _context90.abrupt("return", res.result); + + case 61: case "end": - return _context72.stop(); + return _context90.stop(); } - }, _callee72, this); + }, _callee90, this); })); - function getTransactions(_x105, _x106) { - return _getTransactions.apply(this, arguments); + function simulateTransaction(_x141, _x142, _x143) { + return _simulateTransaction.apply(this, arguments); } - return getTransactions; + return simulateTransaction; }() /** - * Fetch a list of Transactions and transaction statuses from the cluster - * for a confirmed block. + * Sign and send a transaction * - * @deprecated Deprecated since v1.13.0. Please use {@link getBlock} instead. + * @deprecated Instead, call {@link sendTransaction} with a {@link + * VersionedTransaction} + */ + + /** + * Sign and send a transaction */ + // eslint-disable-next-line no-dupe-class-members }, { - key: "getConfirmedBlock", + key: "sendTransaction", value: function () { - var _getConfirmedBlock = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee73(slot, commitment) { - var args, unsafeRes, res, result, block; - return _regeneratorRuntime().wrap(function _callee73$(_context73) { - while (1) switch (_context73.prev = _context73.next) { + var _sendTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee91(transaction, signersOrOptions, options) { + var _wireTransaction2, signers, disableCache, latestBlockhash, _signature4, wireTransaction; + + return _regeneratorRuntime().wrap(function _callee91$(_context91) { + while (1) switch (_context91.prev = _context91.next) { case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment); - _context73.next = 3; - return this._rpcRequest('getConfirmedBlock', args); + if (!('version' in transaction)) { + _context91.next = 7; + break; + } + + if (!(signersOrOptions && Array.isArray(signersOrOptions))) { + _context91.next = 3; + break; + } + + throw new Error('Invalid arguments'); case 3: - unsafeRes = _context73.sent; - res = _create(unsafeRes, GetConfirmedBlockRpcResult); + _wireTransaction2 = transaction.serialize(); + _context91.next = 6; + return this.sendRawTransaction(_wireTransaction2, signersOrOptions); - if (!('error' in res)) { - _context73.next = 7; + case 6: + return _context91.abrupt("return", _context91.sent); + + case 7: + if (!(signersOrOptions === undefined || !Array.isArray(signersOrOptions))) { + _context91.next = 9; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); + throw new Error('Invalid arguments'); - case 7: - result = res.result; + case 9: + signers = signersOrOptions; - if (result) { - _context73.next = 10; + if (!transaction.nonceInfo) { + _context91.next = 14; break; } - throw new Error('Confirmed block ' + slot + ' not found'); + transaction.sign.apply(transaction, _toConsumableArray(signers)); + _context91.next = 32; + break; - case 10: - block = _objectSpread2(_objectSpread2({}, result), {}, { - transactions: result.transactions.map(function (_ref37) { - var transaction = _ref37.transaction, - meta = _ref37.meta; - var message = new Message(transaction.message); - return { - meta: meta, - transaction: _objectSpread2(_objectSpread2({}, transaction), {}, { - message: message - }) - }; - }) - }); - return _context73.abrupt("return", _objectSpread2(_objectSpread2({}, block), {}, { - transactions: block.transactions.map(function (_ref38) { - var transaction = _ref38.transaction, - meta = _ref38.meta; - return { - meta: meta, - transaction: Transaction.populate(transaction.message, transaction.signatures) - }; - }) - })); + case 14: + disableCache = this._disableBlockhashCaching; - case 12: + case 15: + _context91.next = 17; + return this._blockhashWithExpiryBlockHeight(disableCache); + + case 17: + latestBlockhash = _context91.sent; + transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; + transaction.recentBlockhash = latestBlockhash.blockhash; + transaction.sign.apply(transaction, _toConsumableArray(signers)); + + if (transaction.signature) { + _context91.next = 23; + break; + } + + throw new Error('!signature'); + + case 23: + _signature4 = transaction.signature.toString('base64'); + + if (this._blockhashInfo.transactionSignatures.includes(_signature4)) { + _context91.next = 29; + break; + } + + // The signature of this transaction has not been seen before with the + // current recentBlockhash, all done. Let's break + this._blockhashInfo.transactionSignatures.push(_signature4); + + return _context91.abrupt("break", 32); + + case 29: + // This transaction would be treated as duplicate (its derived signature + // matched to one of already recorded signatures). + // So, we must fetch a new blockhash for a different signature by disabling + // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). + disableCache = true; + + case 30: + _context91.next = 15; + break; + + case 32: + wireTransaction = transaction.serialize(); + _context91.next = 35; + return this.sendRawTransaction(wireTransaction, options); + + case 35: + return _context91.abrupt("return", _context91.sent); + + case 36: case "end": - return _context73.stop(); + return _context91.stop(); } - }, _callee73, this); + }, _callee91, this); })); - function getConfirmedBlock(_x107, _x108) { - return _getConfirmedBlock.apply(this, arguments); + function sendTransaction(_x144, _x145, _x146) { + return _sendTransaction.apply(this, arguments); } - return getConfirmedBlock; + return sendTransaction; }() /** - * Fetch confirmed blocks between two slots + * Send a transaction that has already been signed and serialized into the + * wire format */ }, { - key: "getBlocks", + key: "sendRawTransaction", value: function () { - var _getBlocks = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee74(startSlot, endSlot, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee74$(_context74) { - while (1) switch (_context74.prev = _context74.next) { + var _sendRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee92(rawTransaction, options) { + var encodedTransaction, result; + return _regeneratorRuntime().wrap(function _callee92$(_context92) { + while (1) switch (_context92.prev = _context92.next) { case 0: - args = this._buildArgsAtLeastConfirmed(endSlot !== undefined ? [startSlot, endSlot] : [startSlot], commitment); - _context74.next = 3; - return this._rpcRequest('getBlocks', args); + encodedTransaction = toBuffer(rawTransaction).toString('base64'); + _context92.next = 3; + return this.sendEncodedTransaction(encodedTransaction, options); case 3: - unsafeRes = _context74.sent; - res = _create(unsafeRes, jsonRpcResult(array(number()))); - - if (!('error' in res)) { - _context74.next = 7; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get blocks'); - - case 7: - return _context74.abrupt("return", res.result); + result = _context92.sent; + return _context92.abrupt("return", result); - case 8: + case 5: case "end": - return _context74.stop(); + return _context92.stop(); } - }, _callee74, this); + }, _callee92, this); })); - function getBlocks(_x109, _x110, _x111) { - return _getBlocks.apply(this, arguments); + function sendRawTransaction(_x147, _x148) { + return _sendRawTransaction.apply(this, arguments); } - return getBlocks; + return sendRawTransaction; }() /** - * Fetch a list of Signatures from the cluster for a block, excluding rewards + * Send a transaction that has already been signed, serialized into the + * wire format, and encoded as a base64 string */ }, { - key: "getBlockSignatures", + key: "sendEncodedTransaction", value: function () { - var _getBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee75(slot, commitment) { - var args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee75$(_context75) { - while (1) switch (_context75.prev = _context75.next) { + var _sendEncodedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee93(encodedTransaction, options) { + var config, skipPreflight, preflightCommitment, args, unsafeRes, res, logs; + return _regeneratorRuntime().wrap(function _callee93$(_context93) { + while (1) switch (_context93.prev = _context93.next) { case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { - transactionDetails: 'signatures', - rewards: false - }); - _context75.next = 3; - return this._rpcRequest('getBlock', args); + config = { + encoding: 'base64' + }; + skipPreflight = options && options.skipPreflight; + preflightCommitment = options && options.preflightCommitment || this.commitment; - case 3: - unsafeRes = _context75.sent; - res = _create(unsafeRes, GetBlockSignaturesRpcResult); + if (options && options.maxRetries != null) { + config.maxRetries = options.maxRetries; + } - if (!('error' in res)) { - _context75.next = 7; - break; + if (options && options.minContextSlot != null) { + config.minContextSlot = options.minContextSlot; } - throw new SolanaJSONRPCError(res.error, 'failed to get block'); + if (skipPreflight) { + config.skipPreflight = skipPreflight; + } - case 7: - result = res.result; + if (preflightCommitment) { + config.preflightCommitment = preflightCommitment; + } - if (result) { - _context75.next = 10; + args = [encodedTransaction, config]; + _context93.next = 10; + return this._rpcRequest('sendTransaction', args); + + case 10: + unsafeRes = _context93.sent; + res = _create(unsafeRes, SendTransactionRpcResult); + + if (!('error' in res)) { + _context93.next = 15; break; } - throw new Error('Block ' + slot + ' not found'); + if ('data' in res.error) { + logs = res.error.data.logs; + } - case 10: - return _context75.abrupt("return", result); + throw new SendTransactionError('failed to send transaction: ' + res.error.message, logs); - case 11: + case 15: + return _context93.abrupt("return", res.result); + + case 16: case "end": - return _context75.stop(); + return _context93.stop(); } - }, _callee75, this); + }, _callee93, this); })); - function getBlockSignatures(_x112, _x113) { - return _getBlockSignatures.apply(this, arguments); + function sendEncodedTransaction(_x149, _x150) { + return _sendEncodedTransaction.apply(this, arguments); } - return getBlockSignatures; + return sendEncodedTransaction; }() /** - * Fetch a list of Signatures from the cluster for a confirmed block, excluding rewards - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getBlockSignatures} instead. + * @internal */ }, { - key: "getConfirmedBlockSignatures", - value: function () { - var _getConfirmedBlockSignatures = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee76(slot, commitment) { - var args, unsafeRes, res, result; - return _regeneratorRuntime().wrap(function _callee76$(_context76) { - while (1) switch (_context76.prev = _context76.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([slot], commitment, undefined, { - transactionDetails: 'signatures', - rewards: false - }); - _context76.next = 3; - return this._rpcRequest('getConfirmedBlock', args); + key: "_wsOnOpen", + value: function _wsOnOpen() { + var _this23 = this; - case 3: - unsafeRes = _context76.sent; - res = _create(unsafeRes, GetBlockSignaturesRpcResult); + this._rpcWebSocketConnected = true; + this._rpcWebSocketHeartbeat = setInterval(function () { + // Ping server every 5s to prevent idle timeouts + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee94() { + return _regeneratorRuntime().wrap(function _callee94$(_context94) { + while (1) switch (_context94.prev = _context94.next) { + case 0: + _context94.prev = 0; + _context94.next = 3; + return _this23._rpcWebSocket.notify('ping'); - if (!('error' in res)) { - _context76.next = 7; + case 3: + _context94.next = 7; break; - } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed block'); + case 5: + _context94.prev = 5; + _context94.t0 = _context94["catch"](0); - case 7: - result = res.result; + case 7: + case "end": + return _context94.stop(); + } + }, _callee94, null, [[0, 5]]); + }))(); + }, 5000); - if (result) { - _context76.next = 10; - break; - } + this._updateSubscriptions(); + } + /** + * @internal + */ - throw new Error('Confirmed block ' + slot + ' not found'); + }, { + key: "_wsOnError", + value: function _wsOnError(err) { + this._rpcWebSocketConnected = false; + console.error('ws error:', err.message); + } + /** + * @internal + */ - case 10: - return _context76.abrupt("return", result); + }, { + key: "_wsOnClose", + value: function _wsOnClose(code) { + var _this24 = this; - case 11: - case "end": - return _context76.stop(); - } - }, _callee76, this); - })); + this._rpcWebSocketConnected = false; + this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER; - function getConfirmedBlockSignatures(_x114, _x115) { - return _getConfirmedBlockSignatures.apply(this, arguments); + if (this._rpcWebSocketIdleTimeout) { + clearTimeout(this._rpcWebSocketIdleTimeout); + this._rpcWebSocketIdleTimeout = null; } - return getConfirmedBlockSignatures; - }() + if (this._rpcWebSocketHeartbeat) { + clearInterval(this._rpcWebSocketHeartbeat); + this._rpcWebSocketHeartbeat = null; + } + + if (code === 1000) { + // explicit close, check if any subscriptions have been made since close + this._updateSubscriptions(); + + return; + } // implicit close, prepare subscriptions for auto-reconnect + + + this._subscriptionCallbacksByServerSubscriptionId = {}; + Object.entries(this._subscriptionsByHash).forEach(function (_ref40) { + var _ref41 = _slicedToArray(_ref40, 2), + hash = _ref41[0], + subscription = _ref41[1]; + + _this24._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'pending' + })); + }); + } /** - * Fetch a transaction details for a confirmed transaction - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getTransaction} instead. + * @internal */ }, { - key: "getConfirmedTransaction", - value: function () { - var _getConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee77(signature, commitment) { - var args, unsafeRes, res, result, message, signatures; - return _regeneratorRuntime().wrap(function _callee77$(_context77) { - while (1) switch (_context77.prev = _context77.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([signature], commitment); - _context77.next = 3; - return this._rpcRequest('getConfirmedTransaction', args); - - case 3: - unsafeRes = _context77.sent; - res = _create(unsafeRes, GetTransactionRpcResult); - - if (!('error' in res)) { - _context77.next = 7; - break; - } + key: "_setSubscription", + value: function _setSubscription(hash, nextSubscription) { + var _this$_subscriptionsB; - throw new SolanaJSONRPCError(res.error, 'failed to get transaction'); + var prevState = (_this$_subscriptionsB = this._subscriptionsByHash[hash]) === null || _this$_subscriptionsB === void 0 ? void 0 : _this$_subscriptionsB.state; + this._subscriptionsByHash[hash] = nextSubscription; - case 7: - result = res.result; + if (prevState !== nextSubscription.state) { + var stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash]; - if (result) { - _context77.next = 10; - break; - } + if (stateChangeCallbacks) { + stateChangeCallbacks.forEach(function (cb) { + try { + cb(nextSubscription.state); // eslint-disable-next-line no-empty + } catch (_unused3) {} + }); + } + } + } + /** + * @internal + */ - return _context77.abrupt("return", result); + }, { + key: "_onSubscriptionStateChange", + value: function _onSubscriptionStateChange(clientSubscriptionId, callback) { + var _this25 = this; - case 10: - message = new Message(result.transaction.message); - signatures = result.transaction.signatures; - return _context77.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, { - transaction: Transaction.populate(message, signatures) - })); + var _this$_subscriptionSt; - case 13: - case "end": - return _context77.stop(); - } - }, _callee77, this); - })); + var hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - function getConfirmedTransaction(_x116, _x117) { - return _getConfirmedTransaction.apply(this, arguments); + if (hash == null) { + return function () {}; } - return getConfirmedTransaction; - }() + var stateChangeCallbacks = (_this$_subscriptionSt = this._subscriptionStateChangeCallbacksByHash)[hash] || (_this$_subscriptionSt[hash] = new Set()); + stateChangeCallbacks.add(callback); + return function () { + stateChangeCallbacks["delete"](callback); + + if (stateChangeCallbacks.size === 0) { + delete _this25._subscriptionStateChangeCallbacksByHash[hash]; + } + }; + } /** - * Fetch parsed transaction details for a confirmed transaction - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransaction} instead. + * @internal */ }, { - key: "getParsedConfirmedTransaction", + key: "_updateSubscriptions", value: function () { - var _getParsedConfirmedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee78(signature, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee78$(_context78) { - while (1) switch (_context78.prev = _context78.next) { + var _updateSubscriptions2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee98() { + var _this26 = this; + + var activeWebSocketGeneration, isCurrentConnectionStillActive; + return _regeneratorRuntime().wrap(function _callee98$(_context98) { + while (1) switch (_context98.prev = _context98.next) { case 0: - args = this._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); - _context78.next = 3; - return this._rpcRequest('getConfirmedTransaction', args); + if (!(Object.keys(this._subscriptionsByHash).length === 0)) { + _context98.next = 3; + break; + } + + if (this._rpcWebSocketConnected) { + this._rpcWebSocketConnected = false; + this._rpcWebSocketIdleTimeout = setTimeout(function () { + _this26._rpcWebSocketIdleTimeout = null; + + try { + _this26._rpcWebSocket.close(); + } catch (err) { + // swallow error if socket has already been closed. + if (err instanceof Error) { + console.log("Error when closing socket connection: ".concat(err.message)); + } + } + }, 500); + } + + return _context98.abrupt("return"); case 3: - unsafeRes = _context78.sent; - res = _create(unsafeRes, GetParsedTransactionRpcResult); + if (this._rpcWebSocketIdleTimeout !== null) { + clearTimeout(this._rpcWebSocketIdleTimeout); + this._rpcWebSocketIdleTimeout = null; + this._rpcWebSocketConnected = true; + } - if (!('error' in res)) { - _context78.next = 7; + if (this._rpcWebSocketConnected) { + _context98.next = 7; break; } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transaction'); + this._rpcWebSocket.connect(); + + return _context98.abrupt("return"); case 7: - return _context78.abrupt("return", res.result); + activeWebSocketGeneration = this._rpcWebSocketGeneration; - case 8: - case "end": - return _context78.stop(); - } - }, _callee78, this); - })); + isCurrentConnectionStillActive = function isCurrentConnectionStillActive() { + return activeWebSocketGeneration === _this26._rpcWebSocketGeneration; + }; - function getParsedConfirmedTransaction(_x118, _x119) { - return _getParsedConfirmedTransaction.apply(this, arguments); - } + _context98.next = 11; + return Promise.all( // Don't be tempted to change this to `Object.entries`. We call + // `_updateSubscriptions` recursively when processing the state, + // so it's important that we look up the *current* version of + // each subscription, every time we process a hash. + Object.keys(this._subscriptionsByHash).map( /*#__PURE__*/function () { + var _ref42 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee97(hash) { + var subscription; + return _regeneratorRuntime().wrap(function _callee97$(_context97) { + while (1) switch (_context97.prev = _context97.next) { + case 0: + subscription = _this26._subscriptionsByHash[hash]; - return getParsedConfirmedTransaction; - }() - /** - * Fetch parsed transaction details for a batch of confirmed transactions - * - * @deprecated Deprecated since Solana v1.8.0. Please use {@link getParsedTransactions} instead. - */ + if (!(subscription === undefined)) { + _context97.next = 3; + break; + } - }, { - key: "getParsedConfirmedTransactions", - value: function () { - var _getParsedConfirmedTransactions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee79(signatures, commitment) { - var _this22 = this; + return _context97.abrupt("return"); - var batch, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee79$(_context79) { - while (1) switch (_context79.prev = _context79.next) { - case 0: - batch = signatures.map(function (signature) { - var args = _this22._buildArgsAtLeastConfirmed([signature], commitment, 'jsonParsed'); + case 3: + _context97.t0 = subscription.state; + _context97.next = _context97.t0 === 'pending' ? 6 : _context97.t0 === 'unsubscribed' ? 6 : _context97.t0 === 'subscribed' ? 15 : 19; + break; - return { - methodName: 'getConfirmedTransaction', - args: args - }; - }); - _context79.next = 3; - return this._rpcBatchRequest(batch); + case 6: + if (!(subscription.callbacks.size === 0)) { + _context97.next = 12; + break; + } - case 3: - unsafeRes = _context79.sent; - res = unsafeRes.map(function (unsafeRes) { - var res = _create(unsafeRes, GetParsedTransactionRpcResult); + /** + * You can end up here when: + * + * - a subscription has recently unsubscribed + * without having new callbacks added to it + * while the unsubscribe was in flight, or + * - when a pending subscription has its + * listeners removed before a request was + * sent to the server. + * + * Being that nobody is interested in this + * subscription any longer, delete it. + */ + delete _this26._subscriptionsByHash[hash]; - if ('error' in res) { - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed transactions'); - } + if (subscription.state === 'unsubscribed') { + delete _this26._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]; + } - return res.result; - }); - return _context79.abrupt("return", res); + _context97.next = 11; + return _this26._updateSubscriptions(); - case 6: - case "end": - return _context79.stop(); - } - }, _callee79, this); - })); + case 11: + return _context97.abrupt("return"); - function getParsedConfirmedTransactions(_x120, _x121) { - return _getParsedConfirmedTransactions.apply(this, arguments); - } + case 12: + _context97.next = 14; + return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee95() { + var args, method, serverSubscriptionId; + return _regeneratorRuntime().wrap(function _callee95$(_context95) { + while (1) switch (_context95.prev = _context95.next) { + case 0: + args = subscription.args, method = subscription.method; + _context95.prev = 1; - return getParsedConfirmedTransactions; - }() - /** - * Fetch a list of all the confirmed signatures for transactions involving an address - * within a specified slot range. Max range allowed is 10,000 slots. - * - * @deprecated Deprecated since v1.3. Please use {@link getConfirmedSignaturesForAddress2} instead. - * - * @param address queried address - * @param startSlot start slot, inclusive - * @param endSlot end slot, inclusive - */ + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'subscribing' + })); - }, { - key: "getConfirmedSignaturesForAddress", - value: function () { - var _getConfirmedSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee80(address, startSlot, endSlot) { - var options, firstAvailableBlock, block, highestConfirmedRoot, _block, confirmedSignatureInfo; + _context95.next = 5; + return _this26._rpcWebSocket.call(method, args); - return _regeneratorRuntime().wrap(function _callee80$(_context80) { - while (1) switch (_context80.prev = _context80.next) { - case 0: - options = {}; - _context80.next = 3; - return this.getFirstAvailableBlock(); + case 5: + serverSubscriptionId = _context95.sent; - case 3: - firstAvailableBlock = _context80.sent; + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + serverSubscriptionId: serverSubscriptionId, + state: 'subscribed' + })); - case 4: - if ('until' in options) { - _context80.next = 24; - break; - } + _this26._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks; + _context95.next = 10; + return _this26._updateSubscriptions(); - startSlot--; + case 10: + _context95.next = 20; + break; - if (!(startSlot <= 0 || startSlot < firstAvailableBlock)) { - _context80.next = 8; - break; - } + case 12: + _context95.prev = 12; + _context95.t0 = _context95["catch"](1); - return _context80.abrupt("break", 24); + if (_context95.t0 instanceof Error) { + console.error("".concat(method, " error for argument"), args, _context95.t0.message); + } - case 8: - _context80.prev = 8; - _context80.next = 11; - return this.getConfirmedBlockSignatures(startSlot, 'finalized'); + if (isCurrentConnectionStillActive()) { + _context95.next = 17; + break; + } - case 11: - block = _context80.sent; + return _context95.abrupt("return"); - if (block.signatures.length > 0) { - options.until = block.signatures[block.signatures.length - 1].toString(); - } + case 17: + // TODO: Maybe add an 'errored' state or a retry limit? + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'pending' + })); - _context80.next = 22; - break; + _context95.next = 20; + return _this26._updateSubscriptions(); - case 15: - _context80.prev = 15; - _context80.t0 = _context80["catch"](8); + case 20: + case "end": + return _context95.stop(); + } + }, _callee95, null, [[1, 12]]); + }))(); - if (!(_context80.t0 instanceof Error && _context80.t0.message.includes('skipped'))) { - _context80.next = 21; - break; - } + case 14: + return _context97.abrupt("break", 19); - return _context80.abrupt("continue", 4); + case 15: + if (!(subscription.callbacks.size === 0)) { + _context97.next = 18; + break; + } - case 21: - throw _context80.t0; + _context97.next = 18; + return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee96() { + var serverSubscriptionId, unsubscribeMethod; + return _regeneratorRuntime().wrap(function _callee96$(_context96) { + while (1) switch (_context96.prev = _context96.next) { + case 0: + serverSubscriptionId = subscription.serverSubscriptionId, unsubscribeMethod = subscription.unsubscribeMethod; - case 22: - _context80.next = 4; - break; + if (!_this26._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) { + _context96.next = 5; + break; + } - case 24: - _context80.next = 26; - return this.getSlot('finalized'); + /** + * Special case. + * If we're dealing with a subscription that has been auto- + * disposed by the RPC, then we can skip the RPC call to + * tear down the subscription here. + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ + _this26._subscriptionsAutoDisposedByRpc["delete"](serverSubscriptionId); - case 26: - highestConfirmedRoot = _context80.sent; + _context96.next = 21; + break; - case 27: - if ('before' in options) { - _context80.next = 47; - break; - } + case 5: + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribing' + })); - endSlot++; + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribing' + })); - if (!(endSlot > highestConfirmedRoot)) { - _context80.next = 31; - break; - } + _context96.prev = 7; + _context96.next = 10; + return _this26._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]); - return _context80.abrupt("break", 47); + case 10: + _context96.next = 21; + break; - case 31: - _context80.prev = 31; - _context80.next = 34; - return this.getConfirmedBlockSignatures(endSlot); + case 12: + _context96.prev = 12; + _context96.t0 = _context96["catch"](7); - case 34: - _block = _context80.sent; + if (_context96.t0 instanceof Error) { + console.error("".concat(unsubscribeMethod, " error:"), _context96.t0.message); + } - if (_block.signatures.length > 0) { - options.before = _block.signatures[_block.signatures.length - 1].toString(); - } + if (isCurrentConnectionStillActive()) { + _context96.next = 17; + break; + } - _context80.next = 45; - break; + return _context96.abrupt("return"); - case 38: - _context80.prev = 38; - _context80.t1 = _context80["catch"](31); + case 17: + // TODO: Maybe add an 'errored' state or a retry limit? + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'subscribed' + })); - if (!(_context80.t1 instanceof Error && _context80.t1.message.includes('skipped'))) { - _context80.next = 44; - break; - } + _context96.next = 20; + return _this26._updateSubscriptions(); - return _context80.abrupt("continue", 27); + case 20: + return _context96.abrupt("return"); - case 44: - throw _context80.t1; + case 21: + _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { + state: 'unsubscribed' + })); - case 45: - _context80.next = 27; - break; + _context96.next = 24; + return _this26._updateSubscriptions(); - case 47: - _context80.next = 49; - return this.getConfirmedSignaturesForAddress2(address, options); + case 24: + case "end": + return _context96.stop(); + } + }, _callee96, null, [[7, 12]]); + }))(); - case 49: - confirmedSignatureInfo = _context80.sent; - return _context80.abrupt("return", confirmedSignatureInfo.map(function (info) { - return info.signature; - })); + case 18: + return _context97.abrupt("break", 19); - case 51: + case 19: + case "end": + return _context97.stop(); + } + }, _callee97); + })); + + return function (_x151) { + return _ref42.apply(this, arguments); + }; + }())); + + case 11: case "end": - return _context80.stop(); + return _context98.stop(); } - }, _callee80, this, [[8, 15], [31, 38]]); + }, _callee98, this); })); - function getConfirmedSignaturesForAddress(_x122, _x123, _x124) { - return _getConfirmedSignaturesForAddress.apply(this, arguments); + function _updateSubscriptions() { + return _updateSubscriptions2.apply(this, arguments); } - return getConfirmedSignaturesForAddress; + return _updateSubscriptions; }() /** - * Returns confirmed signatures for transactions involving an - * address backwards in time from the provided signature or most recent confirmed block - * - * - * @param address queried address - * @param options + * @internal */ }, { - key: "getConfirmedSignaturesForAddress2", - value: function () { - var _getConfirmedSignaturesForAddress2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee81(address, options, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee81$(_context81) { - while (1) switch (_context81.prev = _context81.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); - _context81.next = 3; - return this._rpcRequest('getConfirmedSignaturesForAddress2', args); + key: "_handleServerNotification", + value: function _handleServerNotification(serverSubscriptionId, callbackArgs) { + var callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]; - case 3: - unsafeRes = _context81.sent; - res = _create(unsafeRes, GetConfirmedSignaturesForAddress2RpcResult); + if (callbacks === undefined) { + return; + } - if (!('error' in res)) { - _context81.next = 7; - break; - } + callbacks.forEach(function (cb) { + try { + cb.apply(void 0, _toConsumableArray(callbackArgs)); + } catch (e) { + console.error(e); + } + }); + } + /** + * @internal + */ + + }, { + key: "_wsOnAccountNotification", + value: function _wsOnAccountNotification(notification) { + var _create$1 = _create(notification, AccountNotificationResult), + result = _create$1.result, + subscription = _create$1.subscription; + + this._handleServerNotification(subscription, [result.value, result.context]); + } + /** + * @internal + */ + + }, { + key: "_makeSubscription", + value: function _makeSubscription(subscriptionConfig, + /** + * When preparing `args` for a call to `_makeSubscription`, be sure + * to carefully apply a default `commitment` property, if necessary. + * + * - If the user supplied a `commitment` use that. + * - Otherwise, if the `Connection::commitment` is set, use that. + * - Otherwise, set it to the RPC server default: `finalized`. + * + * This is extremely important to ensure that these two fundamentally + * identical subscriptions produce the same identifying hash: + * + * - A subscription made without specifying a commitment. + * - A subscription made where the commitment specified is the same + * as the default applied to the subscription above. + * + * Example; these two subscriptions must produce the same hash: + * + * - An `accountSubscribe` subscription for `'PUBKEY'` + * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment + * `'finalized'`. + * + * See the 'making a subscription with defaulted params omitted' test + * in `connection-subscriptions.ts` for more. + */ + args) { + var _this27 = this; + + var clientSubscriptionId = this._nextClientSubscriptionId++; + var hash = fastStableStringify$1([subscriptionConfig.method, args]); + var existingSubscription = this._subscriptionsByHash[hash]; + + if (existingSubscription === undefined) { + this._subscriptionsByHash[hash] = _objectSpread2(_objectSpread2({}, subscriptionConfig), {}, { + args: args, + callbacks: new Set([subscriptionConfig.callback]), + state: 'pending' + }); + } else { + existingSubscription.callbacks.add(subscriptionConfig.callback); + } - throw new SolanaJSONRPCError(res.error, 'failed to get confirmed signatures for address'); + this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash; + this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee99() { + var subscription; + return _regeneratorRuntime().wrap(function _callee99$(_context99) { + while (1) switch (_context99.prev = _context99.next) { + case 0: + delete _this27._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; + delete _this27._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; + subscription = _this27._subscriptionsByHash[hash]; + assert(subscription !== undefined, "Could not find a `Subscription` when tearing down client subscription #".concat(clientSubscriptionId)); + subscription.callbacks["delete"](subscriptionConfig.callback); + _context99.next = 7; + return _this27._updateSubscriptions(); case 7: - return _context81.abrupt("return", res.result); - - case 8: case "end": - return _context81.stop(); + return _context99.stop(); } - }, _callee81, this); + }, _callee99); })); - function getConfirmedSignaturesForAddress2(_x125, _x126, _x127) { - return _getConfirmedSignaturesForAddress2.apply(this, arguments); - } + this._updateSubscriptions(); - return getConfirmedSignaturesForAddress2; - }() + return clientSubscriptionId; + } /** - * Returns confirmed signatures for transactions involving an - * address backwards in time from the provided signature or most recent confirmed block - * + * Register a callback to be invoked whenever the specified account changes * - * @param address queried address - * @param options + * @param publicKey Public key of the account to monitor + * @param callback Function to invoke whenever the account is changed + * @param commitment Specify the commitment level account changes must reach before notification + * @return subscription id */ }, { - key: "getSignaturesForAddress", - value: function () { - var _getSignaturesForAddress = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee82(address, options, commitment) { - var args, unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee82$(_context82) { - while (1) switch (_context82.prev = _context82.next) { - case 0: - args = this._buildArgsAtLeastConfirmed([address.toBase58()], commitment, undefined, options); - _context82.next = 3; - return this._rpcRequest('getSignaturesForAddress', args); - - case 3: - unsafeRes = _context82.sent; - res = _create(unsafeRes, GetSignaturesForAddressRpcResult); - - if (!('error' in res)) { - _context82.next = 7; - break; - } - - throw new SolanaJSONRPCError(res.error, 'failed to get signatures for address'); - - case 7: - return _context82.abrupt("return", res.result); - - case 8: - case "end": - return _context82.stop(); - } - }, _callee82, this); - })); + key: "onAccountChange", + value: function onAccountChange(publicKey, callback, commitment) { + var args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. + 'base64'); - function getSignaturesForAddress(_x128, _x129, _x130) { - return _getSignaturesForAddress.apply(this, arguments); - } + return this._makeSubscription({ + callback: callback, + method: 'accountSubscribe', + unsubscribeMethod: 'accountUnsubscribe' + }, args); + } + /** + * Deregister an account notification callback + * + * @param id client subscription id to deregister + */ - return getSignaturesForAddress; - }() }, { - key: "getAddressLookupTable", + key: "removeAccountChangeListener", value: function () { - var _getAddressLookupTable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee83(accountKey, config) { - var _yield$this$getAccoun, context, accountInfo, value; - - return _regeneratorRuntime().wrap(function _callee83$(_context83) { - while (1) switch (_context83.prev = _context83.next) { + var _removeAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee100(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee100$(_context100) { + while (1) switch (_context100.prev = _context100.next) { case 0: - _context83.next = 2; - return this.getAccountInfoAndContext(accountKey, config); + _context100.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'account change'); case 2: - _yield$this$getAccoun = _context83.sent; - context = _yield$this$getAccoun.context; - accountInfo = _yield$this$getAccoun.value; - value = null; - - if (accountInfo !== null) { - value = new AddressLookupTableAccount({ - key: accountKey, - state: AddressLookupTableAccount.deserialize(accountInfo.data) - }); - } - - return _context83.abrupt("return", { - context: context, - value: value - }); - - case 8: case "end": - return _context83.stop(); + return _context100.stop(); } - }, _callee83, this); + }, _callee100, this); })); - function getAddressLookupTable(_x131, _x132) { - return _getAddressLookupTable.apply(this, arguments); + function removeAccountChangeListener(_x152) { + return _removeAccountChangeListener.apply(this, arguments); } - return getAddressLookupTable; + return removeAccountChangeListener; }() /** - * Fetch the contents of a Nonce account from the cluster, return with context + * @internal */ }, { - key: "getNonceAndContext", - value: function () { - var _getNonceAndContext = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee84(nonceAccount, commitmentOrConfig) { - var _yield$this$getAccoun2, context, accountInfo, value; - - return _regeneratorRuntime().wrap(function _callee84$(_context84) { - while (1) switch (_context84.prev = _context84.next) { - case 0: - _context84.next = 2; - return this.getAccountInfoAndContext(nonceAccount, commitmentOrConfig); - - case 2: - _yield$this$getAccoun2 = _context84.sent; - context = _yield$this$getAccoun2.context; - accountInfo = _yield$this$getAccoun2.value; - value = null; - - if (accountInfo !== null) { - value = NonceAccount.fromAccountData(accountInfo.data); - } - - return _context84.abrupt("return", { - context: context, - value: value - }); + key: "_wsOnProgramAccountNotification", + value: function _wsOnProgramAccountNotification(notification) { + var _create2 = _create(notification, ProgramAccountNotificationResult), + result = _create2.result, + subscription = _create2.subscription; - case 8: - case "end": - return _context84.stop(); - } - }, _callee84, this); - })); + this._handleServerNotification(subscription, [{ + accountId: result.value.pubkey, + accountInfo: result.value.account + }, result.context]); + } + /** + * Register a callback to be invoked whenever accounts owned by the + * specified program change + * + * @param programId Public key of the program to monitor + * @param callback Function to invoke whenever the account is changed + * @param commitment Specify the commitment level account changes must reach before notification + * @param filters The program account filters to pass into the RPC method + * @return subscription id + */ - function getNonceAndContext(_x133, _x134) { - return _getNonceAndContext.apply(this, arguments); - } + }, { + key: "onProgramAccountChange", + value: function onProgramAccountChange(programId, callback, commitment, filters) { + var args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. + 'base64' + /* encoding */ + , filters ? { + filters: filters + } : undefined + /* extra */ + ); - return getNonceAndContext; - }() + return this._makeSubscription({ + callback: callback, + method: 'programSubscribe', + unsubscribeMethod: 'programUnsubscribe' + }, args); + } /** - * Fetch the contents of a Nonce account from the cluster + * Deregister an account notification callback + * + * @param id client subscription id to deregister */ }, { - key: "getNonce", + key: "removeProgramAccountChangeListener", value: function () { - var _getNonce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee85(nonceAccount, commitmentOrConfig) { - return _regeneratorRuntime().wrap(function _callee85$(_context85) { - while (1) switch (_context85.prev = _context85.next) { + var _removeProgramAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee101(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee101$(_context101) { + while (1) switch (_context101.prev = _context101.next) { case 0: - _context85.next = 2; - return this.getNonceAndContext(nonceAccount, commitmentOrConfig).then(function (x) { - return x.value; - })["catch"](function (e) { - throw new Error('failed to get nonce for account ' + nonceAccount.toBase58() + ': ' + e); - }); + _context101.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change'); case 2: - return _context85.abrupt("return", _context85.sent); - - case 3: case "end": - return _context85.stop(); + return _context101.stop(); } - }, _callee85, this); + }, _callee101, this); })); - function getNonce(_x135, _x136) { - return _getNonce.apply(this, arguments); + function removeProgramAccountChangeListener(_x153) { + return _removeProgramAccountChangeListener.apply(this, arguments); } - return getNonce; + return removeProgramAccountChangeListener; }() /** - * Request an allocation of lamports to the specified address - * - * ```typescript - * import { Connection, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js"; + * Registers a callback to be invoked whenever logs are emitted. + */ + + }, { + key: "onLogs", + value: function onLogs(filter, callback, commitment) { + var args = this._buildArgs([_typeof$1(filter) === 'object' ? { + mentions: [filter.toString()] + } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default. + ); + + return this._makeSubscription({ + callback: callback, + method: 'logsSubscribe', + unsubscribeMethod: 'logsUnsubscribe' + }, args); + } + /** + * Deregister a logs callback. * - * (async () => { - * const connection = new Connection("https://api.testnet.solana.com", "confirmed"); - * const myAddress = new PublicKey("2nr1bHFT86W9tGnyvmYW4vcHKsQB3sVQfnddasz4kExM"); - * const signature = await connection.requestAirdrop(myAddress, LAMPORTS_PER_SOL); - * await connection.confirmTransaction(signature); - * })(); - * ``` + * @param id client subscription id to deregister. */ }, { - key: "requestAirdrop", + key: "removeOnLogsListener", value: function () { - var _requestAirdrop = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee86(to, lamports) { - var unsafeRes, res; - return _regeneratorRuntime().wrap(function _callee86$(_context86) { - while (1) switch (_context86.prev = _context86.next) { + var _removeOnLogsListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee102(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee102$(_context102) { + while (1) switch (_context102.prev = _context102.next) { case 0: - _context86.next = 2; - return this._rpcRequest('requestAirdrop', [to.toBase58(), lamports]); + _context102.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'logs'); case 2: - unsafeRes = _context86.sent; - res = _create(unsafeRes, RequestAirdropRpcResult); - - if (!('error' in res)) { - _context86.next = 6; - break; - } - - throw new SolanaJSONRPCError(res.error, "airdrop to ".concat(to.toBase58(), " failed")); - - case 6: - return _context86.abrupt("return", res.result); - - case 7: case "end": - return _context86.stop(); + return _context102.stop(); } - }, _callee86, this); + }, _callee102, this); })); - function requestAirdrop(_x137, _x138) { - return _requestAirdrop.apply(this, arguments); + function removeOnLogsListener(_x154) { + return _removeOnLogsListener.apply(this, arguments); } - return requestAirdrop; + return removeOnLogsListener; }() /** * @internal */ }, { - key: "_blockhashWithExpiryBlockHeight", - value: function () { - var _blockhashWithExpiryBlockHeight2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee87(disableCache) { - var timeSinceFetch, expired; - return _regeneratorRuntime().wrap(function _callee87$(_context87) { - while (1) switch (_context87.prev = _context87.next) { - case 0: - if (disableCache) { - _context87.next = 10; - break; - } - - case 1: - if (!this._pollingBlockhash) { - _context87.next = 6; - break; - } - - _context87.next = 4; - return sleep(100); - - case 4: - _context87.next = 1; - break; - - case 6: - timeSinceFetch = Date.now() - this._blockhashInfo.lastFetch; - expired = timeSinceFetch >= BLOCKHASH_CACHE_TIMEOUT_MS; - - if (!(this._blockhashInfo.latestBlockhash !== null && !expired)) { - _context87.next = 10; - break; - } - - return _context87.abrupt("return", this._blockhashInfo.latestBlockhash); - - case 10: - _context87.next = 12; - return this._pollNewBlockhash(); + key: "_wsOnLogsNotification", + value: function _wsOnLogsNotification(notification) { + var _create3 = _create(notification, LogsNotificationResult), + result = _create3.result, + subscription = _create3.subscription; - case 12: - return _context87.abrupt("return", _context87.sent); + this._handleServerNotification(subscription, [result.value, result.context]); + } + /** + * @internal + */ - case 13: - case "end": - return _context87.stop(); - } - }, _callee87, this); - })); + }, { + key: "_wsOnSlotNotification", + value: function _wsOnSlotNotification(notification) { + var _create4 = _create(notification, SlotNotificationResult), + result = _create4.result, + subscription = _create4.subscription; - function _blockhashWithExpiryBlockHeight(_x139) { - return _blockhashWithExpiryBlockHeight2.apply(this, arguments); - } + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon slot changes + * + * @param callback Function to invoke whenever the slot changes + * @return subscription id + */ - return _blockhashWithExpiryBlockHeight; - }() + }, { + key: "onSlotChange", + value: function onSlotChange(callback) { + return this._makeSubscription({ + callback: callback, + method: 'slotSubscribe', + unsubscribeMethod: 'slotUnsubscribe' + }, [] + /* args */ + ); + } /** - * @internal + * Deregister a slot notification callback + * + * @param id client subscription id to deregister */ }, { - key: "_pollNewBlockhash", + key: "removeSlotChangeListener", value: function () { - var _pollNewBlockhash2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee88() { - var startTime, cachedLatestBlockhash, cachedBlockhash, i, latestBlockhash; - return _regeneratorRuntime().wrap(function _callee88$(_context88) { - while (1) switch (_context88.prev = _context88.next) { + var _removeSlotChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee103(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee103$(_context103) { + while (1) switch (_context103.prev = _context103.next) { case 0: - this._pollingBlockhash = true; - _context88.prev = 1; - startTime = Date.now(); - cachedLatestBlockhash = this._blockhashInfo.latestBlockhash; - cachedBlockhash = cachedLatestBlockhash ? cachedLatestBlockhash.blockhash : null; - i = 0; - - case 6: - if (!(i < 50)) { - _context88.next = 18; - break; - } - - _context88.next = 9; - return this.getLatestBlockhash('finalized'); - - case 9: - latestBlockhash = _context88.sent; - - if (!(cachedBlockhash !== latestBlockhash.blockhash)) { - _context88.next = 13; - break; - } - - this._blockhashInfo = { - latestBlockhash: latestBlockhash, - lastFetch: Date.now(), - transactionSignatures: [], - simulatedSignatures: [] - }; - return _context88.abrupt("return", latestBlockhash); - - case 13: - _context88.next = 15; - return sleep(MS_PER_SLOT / 2); - - case 15: - i++; - _context88.next = 6; - break; - - case 18: - throw new Error("Unable to obtain a new blockhash after ".concat(Date.now() - startTime, "ms")); - - case 19: - _context88.prev = 19; - this._pollingBlockhash = false; - return _context88.finish(19); + _context103.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change'); - case 22: + case 2: case "end": - return _context88.stop(); + return _context103.stop(); } - }, _callee88, this, [[1,, 19, 22]]); + }, _callee103, this); })); - function _pollNewBlockhash() { - return _pollNewBlockhash2.apply(this, arguments); + function removeSlotChangeListener(_x155) { + return _removeSlotChangeListener.apply(this, arguments); } - return _pollNewBlockhash; + return removeSlotChangeListener; }() /** - * get the stake minimum delegation + * @internal */ }, { - key: "getStakeMinimumDelegation", - value: function () { - var _getStakeMinimumDelegation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee89(config) { - var _extractCommitmentFro23, commitment, configArg, args, unsafeRes, res; - - return _regeneratorRuntime().wrap(function _callee89$(_context89) { - while (1) switch (_context89.prev = _context89.next) { - case 0: - _extractCommitmentFro23 = extractCommitmentFromConfig(config), commitment = _extractCommitmentFro23.commitment, configArg = _extractCommitmentFro23.config; - args = this._buildArgs([], commitment, 'base64', configArg); - _context89.next = 4; - return this._rpcRequest('getStakeMinimumDelegation', args); - - case 4: - unsafeRes = _context89.sent; - res = _create(unsafeRes, jsonRpcResultAndContext(number())); + key: "_wsOnSlotUpdatesNotification", + value: function _wsOnSlotUpdatesNotification(notification) { + var _create5 = _create(notification, SlotUpdateNotificationResult), + result = _create5.result, + subscription = _create5.subscription; - if (!('error' in res)) { - _context89.next = 8; - break; - } + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s + * may be useful to track live progress of a cluster. + * + * @param callback Function to invoke whenever the slot updates + * @return subscription id + */ - throw new SolanaJSONRPCError(res.error, "failed to get stake minimum delegation"); + }, { + key: "onSlotUpdate", + value: function onSlotUpdate(callback) { + return this._makeSubscription({ + callback: callback, + method: 'slotsUpdatesSubscribe', + unsubscribeMethod: 'slotsUpdatesUnsubscribe' + }, [] + /* args */ + ); + } + /** + * Deregister a slot update notification callback + * + * @param id client subscription id to deregister + */ - case 8: - return _context89.abrupt("return", res.result); + }, { + key: "removeSlotUpdateListener", + value: function () { + var _removeSlotUpdateListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee104(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee104$(_context104) { + while (1) switch (_context104.prev = _context104.next) { + case 0: + _context104.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update'); - case 9: + case 2: case "end": - return _context89.stop(); + return _context104.stop(); } - }, _callee89, this); + }, _callee104, this); })); - function getStakeMinimumDelegation(_x140) { - return _getStakeMinimumDelegation.apply(this, arguments); + function removeSlotUpdateListener(_x156) { + return _removeSlotUpdateListener.apply(this, arguments); } - return getStakeMinimumDelegation; + return removeSlotUpdateListener; }() /** - * Simulate a transaction - * - * @deprecated Instead, call {@link simulateTransaction} with {@link - * VersionedTransaction} and {@link SimulateTransactionConfig} parameters - */ - - /** - * Simulate a transaction + * @internal */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "simulateTransaction", + key: "_unsubscribeClientSubscription", value: function () { - var _simulateTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee90(transactionOrMessage, configOrSigners, includeAccounts) { - var versionedTx, _wireTransaction, _encodedTransaction, _config, _args91, _unsafeRes, _res5, transaction, originalTx, signers, _transaction3, disableCache, _transaction4, latestBlockhash, _signature3, message, signData, wireTransaction, encodedTransaction, config, addresses, args, unsafeRes, res, logs, traceIndent, logTrace; - - return _regeneratorRuntime().wrap(function _callee90$(_context90) { - while (1) switch (_context90.prev = _context90.next) { + var _unsubscribeClientSubscription2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee105(clientSubscriptionId, subscriptionName) { + var dispose; + return _regeneratorRuntime().wrap(function _callee105$(_context105) { + while (1) switch (_context105.prev = _context105.next) { case 0: - if (!('message' in transactionOrMessage)) { - _context90.next = 17; - break; - } - - versionedTx = transactionOrMessage; - _wireTransaction = versionedTx.serialize(); - _encodedTransaction = Buffer$1.from(_wireTransaction).toString('base64'); + dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - if (!(Array.isArray(configOrSigners) || includeAccounts !== undefined)) { - _context90.next = 6; + if (!dispose) { + _context105.next = 6; break; } - throw new Error('Invalid arguments'); - - case 6: - _config = configOrSigners || {}; - _config.encoding = 'base64'; - - if (!('commitment' in _config)) { - _config.commitment = this.commitment; - } - - _args91 = [_encodedTransaction, _config]; - _context90.next = 12; - return this._rpcRequest('simulateTransaction', _args91); - - case 12: - _unsafeRes = _context90.sent; - _res5 = _create(_unsafeRes, SimulatedTransactionResponseStruct); - - if (!('error' in _res5)) { - _context90.next = 16; - break; - } + _context105.next = 4; + return dispose(); - throw new Error('failed to simulate transaction: ' + _res5.error.message); + case 4: + _context105.next = 7; + break; - case 16: - return _context90.abrupt("return", _res5.result); + case 6: + console.warn('Ignored unsubscribe request because an active subscription with id ' + "`".concat(clientSubscriptionId, "` for '").concat(subscriptionName, "' events ") + 'could not be found.'); - case 17: - if (transactionOrMessage instanceof Transaction) { - originalTx = transactionOrMessage; - transaction = new Transaction(); - transaction.feePayer = originalTx.feePayer; - transaction.instructions = transactionOrMessage.instructions; - transaction.nonceInfo = originalTx.nonceInfo; - transaction.signatures = originalTx.signatures; - } else { - transaction = Transaction.populate(transactionOrMessage); // HACK: this function relies on mutating the populated transaction + case 7: + case "end": + return _context105.stop(); + } + }, _callee105, this); + })); - transaction._message = transaction._json = undefined; - } + function _unsubscribeClientSubscription(_x157, _x158) { + return _unsubscribeClientSubscription2.apply(this, arguments); + } - if (!(configOrSigners !== undefined && !Array.isArray(configOrSigners))) { - _context90.next = 20; - break; - } + return _unsubscribeClientSubscription; + }() + }, { + key: "_buildArgs", + value: function _buildArgs(args, override, encoding, extra) { + var commitment = override || this._commitment; - throw new Error('Invalid arguments'); + if (commitment || encoding || extra) { + var options = {}; - case 20: - signers = configOrSigners; + if (encoding) { + options.encoding = encoding; + } - if (!(transaction.nonceInfo && signers)) { - _context90.next = 25; - break; - } + if (commitment) { + options.commitment = commitment; + } - (_transaction3 = transaction).sign.apply(_transaction3, _toConsumableArray(signers)); + if (extra) { + options = Object.assign(options, extra); + } - _context90.next = 45; - break; + args.push(options); + } - case 25: - disableCache = this._disableBlockhashCaching; + return args; + } + /** + * @internal + */ - case 26: - _context90.next = 28; - return this._blockhashWithExpiryBlockHeight(disableCache); + }, { + key: "_buildArgsAtLeastConfirmed", + value: function _buildArgsAtLeastConfirmed(args, override, encoding, extra) { + var commitment = override || this._commitment; - case 28: - latestBlockhash = _context90.sent; - transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; - transaction.recentBlockhash = latestBlockhash.blockhash; + if (commitment && !['confirmed', 'finalized'].includes(commitment)) { + throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`'); + } - if (signers) { - _context90.next = 33; - break; - } + return this._buildArgs(args, override, encoding, extra); + } + /** + * @internal + */ - return _context90.abrupt("break", 45); + }, { + key: "_wsOnSignatureNotification", + value: function _wsOnSignatureNotification(notification) { + var _create6 = _create(notification, SignatureNotificationResult), + result = _create6.result, + subscription = _create6.subscription; - case 33: - (_transaction4 = transaction).sign.apply(_transaction4, _toConsumableArray(signers)); + if (result.value !== 'receivedSignature') { + /** + * Special case. + * After a signature is processed, RPCs automatically dispose of the + * subscription on the server side. We need to track which of these + * subscriptions have been disposed in such a way, so that we know + * whether the client is dealing with a not-yet-processed signature + * (in which case we must tear down the server subscription) or an + * already-processed signature (in which case the client can simply + * clear out the subscription locally without telling the server). + * + * NOTE: There is a proposal to eliminate this special case, here: + * https://github.com/solana-labs/solana/issues/18892 + */ + this._subscriptionsAutoDisposedByRpc.add(subscription); + } - if (transaction.signature) { - _context90.next = 36; - break; - } + this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{ + type: 'received' + }, result.context] : [{ + type: 'status', + result: result.value + }, result.context]); + } + /** + * Register a callback to be invoked upon signature updates + * + * @param signature Transaction signature string in base 58 + * @param callback Function to invoke on signature notifications + * @param commitment Specify the commitment level signature must reach before notification + * @return subscription id + */ - throw new Error('!signature'); + }, { + key: "onSignature", + value: function onSignature(signature, _callback, commitment) { + var _this28 = this; - case 36: - _signature3 = transaction.signature.toString('base64'); + var args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default. + ); - if (!(!this._blockhashInfo.simulatedSignatures.includes(_signature3) && !this._blockhashInfo.transactionSignatures.includes(_signature3))) { - _context90.next = 42; - break; - } + var clientSubscriptionId = this._makeSubscription({ + callback: function callback(notification, context) { + if (notification.type === 'status') { + _callback(notification.result, context); // Signatures subscriptions are auto-removed by the RPC service + // so no need to explicitly send an unsubscribe message. - // The signature of this transaction has not been seen before with the - // current recentBlockhash, all done. Let's break - this._blockhashInfo.simulatedSignatures.push(_signature3); - return _context90.abrupt("break", 45); + try { + _this28.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - case 42: - // This transaction would be treated as duplicate (its derived signature - // matched to one of already recorded signatures). - // So, we must fetch a new blockhash for a different signature by disabling - // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). - disableCache = true; + } catch (_err) {// Already removed. + } + } + }, + method: 'signatureSubscribe', + unsubscribeMethod: 'signatureUnsubscribe' + }, args); - case 43: - _context90.next = 26; - break; + return clientSubscriptionId; + } + /** + * Register a callback to be invoked when a transaction is + * received and/or processed. + * + * @param signature Transaction signature string in base 58 + * @param callback Function to invoke on signature notifications + * @param options Enable received notifications and set the commitment + * level that signature must reach before notification + * @return subscription id + */ - case 45: - message = transaction._compile(); - signData = message.serialize(); - wireTransaction = transaction._serialize(signData); - encodedTransaction = wireTransaction.toString('base64'); - config = { - encoding: 'base64', - commitment: this.commitment - }; + }, { + key: "onSignatureWithOptions", + value: function onSignatureWithOptions(signature, _callback2, options) { + var _this29 = this; - if (includeAccounts) { - addresses = (Array.isArray(includeAccounts) ? includeAccounts : message.nonProgramIds()).map(function (key) { - return key.toBase58(); - }); - config['accounts'] = { - encoding: 'base64', - addresses: addresses - }; - } + var _options$commitment = _objectSpread2(_objectSpread2({}, options), {}, { + commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default. - if (signers) { - config.sigVerify = true; - } + }), + commitment = _options$commitment.commitment, + extra = _objectWithoutProperties(_options$commitment, _excluded4); - args = [encodedTransaction, config]; - _context90.next = 55; - return this._rpcRequest('simulateTransaction', args); + var args = this._buildArgs([signature], commitment, undefined + /* encoding */ + , extra); - case 55: - unsafeRes = _context90.sent; - res = _create(unsafeRes, SimulatedTransactionResponseStruct); + var clientSubscriptionId = this._makeSubscription({ + callback: function callback(notification, context) { + _callback2(notification, context); // Signatures subscriptions are auto-removed by the RPC service + // so no need to explicitly send an unsubscribe message. - if (!('error' in res)) { - _context90.next = 60; - break; - } - if ('data' in res.error) { - logs = res.error.data.logs; + try { + _this29.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - if (logs && Array.isArray(logs)) { - traceIndent = '\n '; - logTrace = traceIndent + logs.join(traceIndent); - console.error(res.error.message, logTrace); - } - } + } catch (_err) {// Already removed. + } + }, + method: 'signatureSubscribe', + unsubscribeMethod: 'signatureUnsubscribe' + }, args); - throw new SendTransactionError('failed to simulate transaction: ' + res.error.message, logs); + return clientSubscriptionId; + } + /** + * Deregister a signature notification callback + * + * @param id client subscription id to deregister + */ - case 60: - return _context90.abrupt("return", res.result); + }, { + key: "removeSignatureListener", + value: function () { + var _removeSignatureListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee106(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee106$(_context106) { + while (1) switch (_context106.prev = _context106.next) { + case 0: + _context106.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result'); - case 61: + case 2: case "end": - return _context90.stop(); + return _context106.stop(); } - }, _callee90, this); + }, _callee106, this); })); - function simulateTransaction(_x141, _x142, _x143) { - return _simulateTransaction.apply(this, arguments); + function removeSignatureListener(_x159) { + return _removeSignatureListener.apply(this, arguments); } - return simulateTransaction; + return removeSignatureListener; }() /** - * Sign and send a transaction + * @internal + */ + + }, { + key: "_wsOnRootNotification", + value: function _wsOnRootNotification(notification) { + var _create7 = _create(notification, RootNotificationResult), + result = _create7.result, + subscription = _create7.subscription; + + this._handleServerNotification(subscription, [result]); + } + /** + * Register a callback to be invoked upon root changes * - * @deprecated Instead, call {@link sendTransaction} with a {@link - * VersionedTransaction} + * @param callback Function to invoke whenever the root changes + * @return subscription id */ + }, { + key: "onRootChange", + value: function onRootChange(callback) { + return this._makeSubscription({ + callback: callback, + method: 'rootSubscribe', + unsubscribeMethod: 'rootUnsubscribe' + }, [] + /* args */ + ); + } /** - * Sign and send a transaction + * Deregister a root notification callback + * + * @param id client subscription id to deregister */ - // eslint-disable-next-line no-dupe-class-members }, { - key: "sendTransaction", + key: "removeRootChangeListener", value: function () { - var _sendTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee91(transaction, signersOrOptions, options) { - var _wireTransaction2, signers, disableCache, latestBlockhash, _signature4, wireTransaction; - - return _regeneratorRuntime().wrap(function _callee91$(_context91) { - while (1) switch (_context91.prev = _context91.next) { + var _removeRootChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee107(clientSubscriptionId) { + return _regeneratorRuntime().wrap(function _callee107$(_context107) { + while (1) switch (_context107.prev = _context107.next) { case 0: - if (!('version' in transaction)) { - _context91.next = 7; - break; - } + _context107.next = 2; + return this._unsubscribeClientSubscription(clientSubscriptionId, 'root change'); - if (!(signersOrOptions && Array.isArray(signersOrOptions))) { - _context91.next = 3; - break; - } + case 2: + case "end": + return _context107.stop(); + } + }, _callee107, this); + })); - throw new Error('Invalid arguments'); + function removeRootChangeListener(_x160) { + return _removeRootChangeListener.apply(this, arguments); + } - case 3: - _wireTransaction2 = transaction.serialize(); - _context91.next = 6; - return this.sendRawTransaction(_wireTransaction2, signersOrOptions); + return removeRootChangeListener; + }() + }]); - case 6: - return _context91.abrupt("return", _context91.sent); + return Connection; + }(); + /** + * Keypair signer interface + */ - case 7: - if (!(signersOrOptions === undefined || !Array.isArray(signersOrOptions))) { - _context91.next = 9; - break; - } + /** + * An account keypair used for signing transactions. + */ - throw new Error('Invalid arguments'); - case 9: - signers = signersOrOptions; + var Keypair = /*#__PURE__*/function () { + /** + * Create a new keypair instance. + * Generate random keypair if no {@link Ed25519Keypair} is provided. + * + * @param keypair ed25519 keypair + */ + function Keypair(keypair) { + _classCallCheck(this, Keypair); + + this._keypair = void 0; + this._keypair = keypair !== null && keypair !== void 0 ? keypair : generateKeypair(); + } + /** + * Generate a new random keypair + */ + + + _createClass(Keypair, [{ + key: "publicKey", + get: + /** + * The public key for this keypair + */ + function get() { + return new PublicKey(this._keypair.publicKey); + } + /** + * The raw secret key for this keypair + */ + + }, { + key: "secretKey", + get: function get() { + return new Uint8Array(this._keypair.secretKey); + } + }], [{ + key: "generate", + value: function generate() { + return new Keypair(generateKeypair()); + } + /** + * Create a keypair from a raw secret key byte array. + * + * This method should only be used to recreate a keypair from a previously + * generated secret key. Generating keypairs from a random seed should be done + * with the {@link Keypair.fromSeed} method. + * + * @throws error if the provided secret key is invalid and validation is not skipped. + * + * @param secretKey secret key byte array + * @param options: skip secret key validation + */ + + }, { + key: "fromSecretKey", + value: function fromSecretKey(secretKey, options) { + if (secretKey.byteLength !== 64) { + throw new Error('bad secret key size'); + } - if (!transaction.nonceInfo) { - _context91.next = 14; - break; - } + var publicKey = secretKey.slice(32, 64); - transaction.sign.apply(transaction, _toConsumableArray(signers)); - _context91.next = 32; - break; + if (!options || !options.skipValidation) { + var privateScalar = secretKey.slice(0, 32); + var computedPublicKey = getPublicKey(privateScalar); - case 14: - disableCache = this._disableBlockhashCaching; + for (var ii = 0; ii < 32; ii++) { + if (publicKey[ii] !== computedPublicKey[ii]) { + throw new Error('provided secretKey is invalid'); + } + } + } - case 15: - _context91.next = 17; - return this._blockhashWithExpiryBlockHeight(disableCache); + return new Keypair({ + publicKey: publicKey, + secretKey: secretKey + }); + } + /** + * Generate a keypair from a 32 byte seed. + * + * @param seed seed byte array + */ - case 17: - latestBlockhash = _context91.sent; - transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight; - transaction.recentBlockhash = latestBlockhash.blockhash; - transaction.sign.apply(transaction, _toConsumableArray(signers)); + }, { + key: "fromSeed", + value: function fromSeed(seed) { + var publicKey = getPublicKey(seed); + var secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, 32); + return new Keypair({ + publicKey: publicKey, + secretKey: secretKey + }); + } + }]); - if (transaction.signature) { - _context91.next = 23; - break; - } + return Keypair; + }(); + /** + * An enumeration of valid address lookup table InstructionType's + * @internal + */ - throw new Error('!signature'); - case 23: - _signature4 = transaction.signature.toString('base64'); + var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({ + CreateLookupTable: { + index: 0, + layout: struct([u32('instruction'), u64('recentSlot'), u8('bumpSeed')]) + }, + FreezeLookupTable: { + index: 1, + layout: struct([u32('instruction')]) + }, + ExtendLookupTable: { + index: 2, + layout: struct([u32('instruction'), u64(), seq$1(publicKey(), offset$1(u32(), -8), 'addresses')]) + }, + DeactivateLookupTable: { + index: 3, + layout: struct([u32('instruction')]) + }, + CloseLookupTable: { + index: 4, + layout: struct([u32('instruction')]) + } + }); - if (this._blockhashInfo.transactionSignatures.includes(_signature4)) { - _context91.next = 29; - break; - } + var AddressLookupTableInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function AddressLookupTableInstruction() { + _classCallCheck(this, AddressLookupTableInstruction); + } - // The signature of this transaction has not been seen before with the - // current recentBlockhash, all done. Let's break - this._blockhashInfo.transactionSignatures.push(_signature4); + _createClass(AddressLookupTableInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var index = instructionTypeLayout.decode(instruction.data); + var type; - return _context91.abrupt("break", 32); + for (var _i10 = 0, _Object$entries2 = Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS); _i10 < _Object$entries2.length; _i10++) { + var _Object$entries2$_i2 = _slicedToArray(_Object$entries2[_i10], 2), + layoutType = _Object$entries2$_i2[0], + layout = _Object$entries2$_i2[1]; - case 29: - // This transaction would be treated as duplicate (its derived signature - // matched to one of already recorded signatures). - // So, we must fetch a new blockhash for a different signature by disabling - // our cache not to wait for the cache expiration (BLOCKHASH_CACHE_TIMEOUT_MS). - disableCache = true; + if (layout.index == index) { + type = layoutType; + break; + } + } - case 30: - _context91.next = 15; - break; + if (!type) { + throw new Error('Invalid Instruction. Should be a LookupTable Instruction'); + } - case 32: - wireTransaction = transaction.serialize(); - _context91.next = 35; - return this.sendRawTransaction(wireTransaction, options); + return type; + } + }, { + key: "decodeCreateLookupTable", + value: function decodeCreateLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 4); - case 35: - return _context91.abrupt("return", _context91.sent); + var _decodeData$12 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data), + recentSlot = _decodeData$12.recentSlot; - case 36: - case "end": - return _context91.stop(); - } - }, _callee91, this); - })); + return { + authority: instruction.keys[1].pubkey, + payer: instruction.keys[2].pubkey, + recentSlot: Number(recentSlot) + }; + } + }, { + key: "decodeExtendLookupTable", + value: function decodeExtendLookupTable(instruction) { + this.checkProgramId(instruction.programId); - function sendTransaction(_x144, _x145, _x146) { - return _sendTransaction.apply(this, arguments); + if (instruction.keys.length < 2) { + throw new Error("invalid instruction; found ".concat(instruction.keys.length, " keys, expected at least 2")); } - return sendTransaction; - }() + var _decodeData$13 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data), + addresses = _decodeData$13.addresses; + + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey, + payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined, + addresses: addresses.map(function (buffer) { + return new PublicKey(buffer); + }) + }; + } + }, { + key: "decodeCloseLookupTable", + value: function decodeCloseLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 3); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey, + recipient: instruction.keys[2].pubkey + }; + } + }, { + key: "decodeFreezeLookupTable", + value: function decodeFreezeLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 2); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey + }; + } + }, { + key: "decodeDeactivateLookupTable", + value: function decodeDeactivateLookupTable(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeysLength(instruction.keys, 2); + return { + lookupTable: instruction.keys[0].pubkey, + authority: instruction.keys[1].pubkey + }; + } /** - * Send a transaction that has already been signed and serialized into the - * wire format + * @internal */ }, { - key: "sendRawTransaction", - value: function () { - var _sendRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee92(rawTransaction, options) { - var encodedTransaction, result; - return _regeneratorRuntime().wrap(function _callee92$(_context92) { - while (1) switch (_context92.prev = _context92.next) { - case 0: - encodedTransaction = toBuffer(rawTransaction).toString('base64'); - _context92.next = 3; - return this.sendEncodedTransaction(encodedTransaction, options); - - case 3: - result = _context92.sent; - return _context92.abrupt("return", result); - - case 5: - case "end": - return _context92.stop(); - } - }, _callee92, this); - })); - - function sendRawTransaction(_x147, _x148) { - return _sendRawTransaction.apply(this, arguments); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(AddressLookupTableProgram.programId)) { + throw new Error('invalid instruction; programId is not AddressLookupTable Program'); } - - return sendRawTransaction; - }() + } /** - * Send a transaction that has already been signed, serialized into the - * wire format, and encoded as a base64 string + * @internal */ }, { - key: "sendEncodedTransaction", - value: function () { - var _sendEncodedTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee93(encodedTransaction, options) { - var config, skipPreflight, preflightCommitment, args, unsafeRes, res, logs; - return _regeneratorRuntime().wrap(function _callee93$(_context93) { - while (1) switch (_context93.prev = _context93.next) { - case 0: - config = { - encoding: 'base64' - }; - skipPreflight = options && options.skipPreflight; - preflightCommitment = options && options.preflightCommitment || this.commitment; - - if (options && options.maxRetries != null) { - config.maxRetries = options.maxRetries; - } - - if (options && options.minContextSlot != null) { - config.minContextSlot = options.minContextSlot; - } - - if (skipPreflight) { - config.skipPreflight = skipPreflight; - } - - if (preflightCommitment) { - config.preflightCommitment = preflightCommitment; - } + key: "checkKeysLength", + value: function checkKeysLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); + } + } + }]); - args = [encodedTransaction, config]; - _context93.next = 10; - return this._rpcRequest('sendTransaction', args); + return AddressLookupTableInstruction; + }(); - case 10: - unsafeRes = _context93.sent; - res = _create(unsafeRes, SendTransactionRpcResult); + var AddressLookupTableProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function AddressLookupTableProgram() { + _classCallCheck(this, AddressLookupTableProgram); + } - if (!('error' in res)) { - _context93.next = 15; - break; - } + _createClass(AddressLookupTableProgram, null, [{ + key: "createLookupTable", + value: function createLookupTable(params) { + var _PublicKey$findProgra = PublicKey.findProgramAddressSync([params.authority.toBuffer(), toBufferLE_1(BigInt(params.recentSlot), 8)], this.programId), + _PublicKey$findProgra2 = _slicedToArray(_PublicKey$findProgra, 2), + lookupTableAddress = _PublicKey$findProgra2[0], + bumpSeed = _PublicKey$findProgra2[1]; - if ('data' in res.error) { - logs = res.error.data.logs; - } + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable; + var data = encodeData(type, { + recentSlot: BigInt(params.recentSlot), + bumpSeed: bumpSeed + }); + var keys = [{ + pubkey: lookupTableAddress, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }, { + pubkey: params.payer, + isSigner: true, + isWritable: true + }, { + pubkey: SystemProgram.programId, + isSigner: false, + isWritable: false + }]; + return [new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }), lookupTableAddress]; + } + }, { + key: "freezeLookupTable", + value: function freezeLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "extendLookupTable", + value: function extendLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable; + var data = encodeData(type, { + addresses: params.addresses.map(function (addr) { + return addr.toBytes(); + }) + }); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; - throw new SendTransactionError('failed to send transaction: ' + res.error.message, logs); + if (params.payer) { + keys.push({ + pubkey: params.payer, + isSigner: true, + isWritable: true + }, { + pubkey: SystemProgram.programId, + isSigner: false, + isWritable: false + }); + } - case 15: - return _context93.abrupt("return", res.result); + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "deactivateLookupTable", + value: function deactivateLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }, { + key: "closeLookupTable", + value: function closeLookupTable(params) { + var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable; + var data = encodeData(type); + var keys = [{ + pubkey: params.lookupTable, + isSigner: false, + isWritable: true + }, { + pubkey: params.authority, + isSigner: true, + isWritable: false + }, { + pubkey: params.recipient, + isSigner: false, + isWritable: true + }]; + return new TransactionInstruction({ + programId: this.programId, + keys: keys, + data: data + }); + } + }]); - case 16: - case "end": - return _context93.stop(); - } - }, _callee93, this); - })); + return AddressLookupTableProgram; + }(); - function sendEncodedTransaction(_x149, _x150) { - return _sendEncodedTransaction.apply(this, arguments); - } + AddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111'); + /** + * Compute Budget Instruction class + */ - return sendEncodedTransaction; - }() - /** - * @internal - */ + var ComputeBudgetInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function ComputeBudgetInstruction() { + _classCallCheck(this, ComputeBudgetInstruction); + } + /** + * Decode a compute budget instruction and retrieve the instruction type. + */ - }, { - key: "_wsOnOpen", - value: function _wsOnOpen() { - var _this23 = this; - this._rpcWebSocketConnected = true; - this._rpcWebSocketHeartbeat = setInterval(function () { - // Ping server every 5s to prevent idle timeouts - _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee94() { - return _regeneratorRuntime().wrap(function _callee94$(_context94) { - while (1) switch (_context94.prev = _context94.next) { - case 0: - _context94.prev = 0; - _context94.next = 3; - return _this23._rpcWebSocket.notify('ping'); + _createClass(ComputeBudgetInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u8('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; - case 3: - _context94.next = 7; - break; + for (var _i11 = 0, _Object$entries3 = Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS); _i11 < _Object$entries3.length; _i11++) { + var _Object$entries3$_i2 = _slicedToArray(_Object$entries3[_i11], 2), + ixType = _Object$entries3$_i2[0], + layout = _Object$entries3$_i2[1]; - case 5: - _context94.prev = 5; - _context94.t0 = _context94["catch"](0); + if (layout.index == typeIndex) { + type = ixType; + break; + } + } - case 7: - case "end": - return _context94.stop(); - } - }, _callee94, null, [[0, 5]]); - }))(); - }, 5000); + if (!type) { + throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction'); + } - this._updateSubscriptions(); + return type; } /** - * @internal + * Decode request units compute budget instruction and retrieve the instruction params. */ }, { - key: "_wsOnError", - value: function _wsOnError(err) { - this._rpcWebSocketConnected = false; - console.error('ws error:', err.message); + key: "decodeRequestUnits", + value: function decodeRequestUnits(instruction) { + this.checkProgramId(instruction.programId); + + var _decodeData$14 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data), + units = _decodeData$14.units, + additionalFee = _decodeData$14.additionalFee; + + return { + units: units, + additionalFee: additionalFee + }; } /** - * @internal + * Decode request heap frame compute budget instruction and retrieve the instruction params. */ }, { - key: "_wsOnClose", - value: function _wsOnClose(code) { - var _this24 = this; - - this._rpcWebSocketConnected = false; - this._rpcWebSocketGeneration = (this._rpcWebSocketGeneration + 1) % Number.MAX_SAFE_INTEGER; - - if (this._rpcWebSocketIdleTimeout) { - clearTimeout(this._rpcWebSocketIdleTimeout); - this._rpcWebSocketIdleTimeout = null; - } - - if (this._rpcWebSocketHeartbeat) { - clearInterval(this._rpcWebSocketHeartbeat); - this._rpcWebSocketHeartbeat = null; - } - - if (code === 1000) { - // explicit close, check if any subscriptions have been made since close - this._updateSubscriptions(); - - return; - } // implicit close, prepare subscriptions for auto-reconnect - + key: "decodeRequestHeapFrame", + value: function decodeRequestHeapFrame(instruction) { + this.checkProgramId(instruction.programId); - this._subscriptionCallbacksByServerSubscriptionId = {}; - Object.entries(this._subscriptionsByHash).forEach(function (_ref40) { - var _ref41 = _slicedToArray(_ref40, 2), - hash = _ref41[0], - subscription = _ref41[1]; + var _decodeData$15 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data), + bytes = _decodeData$15.bytes; - _this24._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'pending' - })); - }); + return { + bytes: bytes + }; } /** - * @internal + * Decode set compute unit limit compute budget instruction and retrieve the instruction params. */ }, { - key: "_setSubscription", - value: function _setSubscription(hash, nextSubscription) { - var _this$_subscriptionsB; - - var prevState = (_this$_subscriptionsB = this._subscriptionsByHash[hash]) === null || _this$_subscriptionsB === void 0 ? void 0 : _this$_subscriptionsB.state; - this._subscriptionsByHash[hash] = nextSubscription; + key: "decodeSetComputeUnitLimit", + value: function decodeSetComputeUnitLimit(instruction) { + this.checkProgramId(instruction.programId); - if (prevState !== nextSubscription.state) { - var stateChangeCallbacks = this._subscriptionStateChangeCallbacksByHash[hash]; + var _decodeData$16 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data), + units = _decodeData$16.units; - if (stateChangeCallbacks) { - stateChangeCallbacks.forEach(function (cb) { - try { - cb(nextSubscription.state); // eslint-disable-next-line no-empty - } catch (_unused3) {} - }); - } - } + return { + units: units + }; } /** - * @internal + * Decode set compute unit price compute budget instruction and retrieve the instruction params. */ }, { - key: "_onSubscriptionStateChange", - value: function _onSubscriptionStateChange(clientSubscriptionId, callback) { - var _this25 = this; - - var _this$_subscriptionSt; - - var hash = this._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - - if (hash == null) { - return function () {}; - } + key: "decodeSetComputeUnitPrice", + value: function decodeSetComputeUnitPrice(instruction) { + this.checkProgramId(instruction.programId); - var stateChangeCallbacks = (_this$_subscriptionSt = this._subscriptionStateChangeCallbacksByHash)[hash] || (_this$_subscriptionSt[hash] = new Set()); - stateChangeCallbacks.add(callback); - return function () { - stateChangeCallbacks["delete"](callback); + var _decodeData$17 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data), + microLamports = _decodeData$17.microLamports; - if (stateChangeCallbacks.size === 0) { - delete _this25._subscriptionStateChangeCallbacksByHash[hash]; - } + return { + microLamports: microLamports }; } /** @@ -29773,1245 +31306,1359 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// */ }, { - key: "_updateSubscriptions", - value: function () { - var _updateSubscriptions2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee98() { - var _this26 = this; - - var activeWebSocketGeneration, isCurrentConnectionStillActive; - return _regeneratorRuntime().wrap(function _callee98$(_context98) { - while (1) switch (_context98.prev = _context98.next) { - case 0: - if (!(Object.keys(this._subscriptionsByHash).length === 0)) { - _context98.next = 3; - break; - } - - if (this._rpcWebSocketConnected) { - this._rpcWebSocketConnected = false; - this._rpcWebSocketIdleTimeout = setTimeout(function () { - _this26._rpcWebSocketIdleTimeout = null; - - try { - _this26._rpcWebSocket.close(); - } catch (err) { - // swallow error if socket has already been closed. - if (err instanceof Error) { - console.log("Error when closing socket connection: ".concat(err.message)); - } - } - }, 500); - } - - return _context98.abrupt("return"); - - case 3: - if (this._rpcWebSocketIdleTimeout !== null) { - clearTimeout(this._rpcWebSocketIdleTimeout); - this._rpcWebSocketIdleTimeout = null; - this._rpcWebSocketConnected = true; - } - - if (this._rpcWebSocketConnected) { - _context98.next = 7; - break; - } - - this._rpcWebSocket.connect(); - - return _context98.abrupt("return"); - - case 7: - activeWebSocketGeneration = this._rpcWebSocketGeneration; - - isCurrentConnectionStillActive = function isCurrentConnectionStillActive() { - return activeWebSocketGeneration === _this26._rpcWebSocketGeneration; - }; - - _context98.next = 11; - return Promise.all( // Don't be tempted to change this to `Object.entries`. We call - // `_updateSubscriptions` recursively when processing the state, - // so it's important that we look up the *current* version of - // each subscription, every time we process a hash. - Object.keys(this._subscriptionsByHash).map( /*#__PURE__*/function () { - var _ref42 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee97(hash) { - var subscription; - return _regeneratorRuntime().wrap(function _callee97$(_context97) { - while (1) switch (_context97.prev = _context97.next) { - case 0: - subscription = _this26._subscriptionsByHash[hash]; - - if (!(subscription === undefined)) { - _context97.next = 3; - break; - } - - return _context97.abrupt("return"); - - case 3: - _context97.t0 = subscription.state; - _context97.next = _context97.t0 === 'pending' ? 6 : _context97.t0 === 'unsubscribed' ? 6 : _context97.t0 === 'subscribed' ? 15 : 19; - break; - - case 6: - if (!(subscription.callbacks.size === 0)) { - _context97.next = 12; - break; - } - - /** - * You can end up here when: - * - * - a subscription has recently unsubscribed - * without having new callbacks added to it - * while the unsubscribe was in flight, or - * - when a pending subscription has its - * listeners removed before a request was - * sent to the server. - * - * Being that nobody is interested in this - * subscription any longer, delete it. - */ - delete _this26._subscriptionsByHash[hash]; - - if (subscription.state === 'unsubscribed') { - delete _this26._subscriptionCallbacksByServerSubscriptionId[subscription.serverSubscriptionId]; - } - - _context97.next = 11; - return _this26._updateSubscriptions(); - - case 11: - return _context97.abrupt("return"); - - case 12: - _context97.next = 14; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee95() { - var args, method, serverSubscriptionId; - return _regeneratorRuntime().wrap(function _callee95$(_context95) { - while (1) switch (_context95.prev = _context95.next) { - case 0: - args = subscription.args, method = subscription.method; - _context95.prev = 1; - - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'subscribing' - })); - - _context95.next = 5; - return _this26._rpcWebSocket.call(method, args); - - case 5: - serverSubscriptionId = _context95.sent; - - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - serverSubscriptionId: serverSubscriptionId, - state: 'subscribed' - })); - - _this26._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId] = subscription.callbacks; - _context95.next = 10; - return _this26._updateSubscriptions(); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(ComputeBudgetProgram.programId)) { + throw new Error('invalid instruction; programId is not ComputeBudgetProgram'); + } + } + }]); - case 10: - _context95.next = 20; - break; + return ComputeBudgetInstruction; + }(); + /** + * An enumeration of valid ComputeBudgetInstructionType's + */ - case 12: - _context95.prev = 12; - _context95.t0 = _context95["catch"](1); + /** + * An enumeration of valid ComputeBudget InstructionType's + * @internal + */ - if (_context95.t0 instanceof Error) { - console.error("".concat(method, " error for argument"), args, _context95.t0.message); - } - if (isCurrentConnectionStillActive()) { - _context95.next = 17; - break; - } + var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({ + RequestUnits: { + index: 0, + layout: struct([u8('instruction'), u32('units'), u32('additionalFee')]) + }, + RequestHeapFrame: { + index: 1, + layout: struct([u8('instruction'), u32('bytes')]) + }, + SetComputeUnitLimit: { + index: 2, + layout: struct([u8('instruction'), u32('units')]) + }, + SetComputeUnitPrice: { + index: 3, + layout: struct([u8('instruction'), u64('microLamports')]) + } + }); + /** + * Factory class for transaction instructions to interact with the Compute Budget program + */ - return _context95.abrupt("return"); + var ComputeBudgetProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function ComputeBudgetProgram() { + _classCallCheck(this, ComputeBudgetProgram); + } + /** + * Public key that identifies the Compute Budget program + */ - case 17: - // TODO: Maybe add an 'errored' state or a retry limit? - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'pending' - })); + /** + * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice} + */ - _context95.next = 20; - return _this26._updateSubscriptions(); - case 20: - case "end": - return _context95.stop(); - } - }, _callee95, null, [[1, 12]]); - }))(); + _createClass(ComputeBudgetProgram, null, [{ + key: "requestUnits", + value: function requestUnits(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "requestHeapFrame", + value: function requestHeapFrame(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "setComputeUnitLimit", + value: function setComputeUnitLimit(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit; + var data = encodeData(type, params); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }, { + key: "setComputeUnitPrice", + value: function setComputeUnitPrice(params) { + var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice; + var data = encodeData(type, { + microLamports: BigInt(params.microLamports) + }); + return new TransactionInstruction({ + keys: [], + programId: this.programId, + data: data + }); + } + }]); - case 14: - return _context97.abrupt("break", 19); + return ComputeBudgetProgram; + }(); - case 15: - if (!(subscription.callbacks.size === 0)) { - _context97.next = 18; - break; - } + ComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111'); + var PRIVATE_KEY_BYTES$1 = 64; + var PUBLIC_KEY_BYTES$1 = 32; + var SIGNATURE_BYTES = 64; + /** + * Params for creating an ed25519 instruction using a public key + */ - _context97.next = 18; - return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee96() { - var serverSubscriptionId, unsubscribeMethod; - return _regeneratorRuntime().wrap(function _callee96$(_context96) { - while (1) switch (_context96.prev = _context96.next) { - case 0: - serverSubscriptionId = subscription.serverSubscriptionId, unsubscribeMethod = subscription.unsubscribeMethod; + var ED25519_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u8('padding'), u16('signatureOffset'), u16('signatureInstructionIndex'), u16('publicKeyOffset'), u16('publicKeyInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u16('messageInstructionIndex')]); - if (!_this26._subscriptionsAutoDisposedByRpc.has(serverSubscriptionId)) { - _context96.next = 5; - break; - } + var Ed25519Program = /*#__PURE__*/function () { + /** + * @internal + */ + function Ed25519Program() { + _classCallCheck(this, Ed25519Program); + } + /** + * Public key that identifies the ed25519 program + */ - /** - * Special case. - * If we're dealing with a subscription that has been auto- - * disposed by the RPC, then we can skip the RPC call to - * tear down the subscription here. - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ - _this26._subscriptionsAutoDisposedByRpc["delete"](serverSubscriptionId); + /** + * Create an ed25519 instruction with a public key and signature. The + * public key must be a buffer that is 32 bytes long, and the signature + * must be a buffer of 64 bytes. + */ - _context96.next = 21; - break; - case 5: - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribing' - })); + _createClass(Ed25519Program, null, [{ + key: "createInstructionWithPublicKey", + value: function createInstructionWithPublicKey(params) { + var publicKey = params.publicKey, + message = params.message, + signature = params.signature, + instructionIndex = params.instructionIndex; + assert(publicKey.length === PUBLIC_KEY_BYTES$1, "Public Key must be ".concat(PUBLIC_KEY_BYTES$1, " bytes but received ").concat(publicKey.length, " bytes")); + assert(signature.length === SIGNATURE_BYTES, "Signature must be ".concat(SIGNATURE_BYTES, " bytes but received ").concat(signature.length, " bytes")); + var publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span; + var signatureOffset = publicKeyOffset + publicKey.length; + var messageDataOffset = signatureOffset + signature.length; + var numSignatures = 1; + var instructionData = Buffer$1.alloc(messageDataOffset + message.length); + var index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction. + : instructionIndex; + ED25519_INSTRUCTION_LAYOUT.encode({ + numSignatures: numSignatures, + padding: 0, + signatureOffset: signatureOffset, + signatureInstructionIndex: index, + publicKeyOffset: publicKeyOffset, + publicKeyInstructionIndex: index, + messageDataOffset: messageDataOffset, + messageDataSize: message.length, + messageInstructionIndex: index + }, instructionData); + instructionData.fill(publicKey, publicKeyOffset); + instructionData.fill(signature, signatureOffset); + instructionData.fill(message, messageDataOffset); + return new TransactionInstruction({ + keys: [], + programId: Ed25519Program.programId, + data: instructionData + }); + } + /** + * Create an ed25519 instruction with a private key. The private key + * must be a buffer that is 64 bytes long. + */ - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribing' - })); + }, { + key: "createInstructionWithPrivateKey", + value: function createInstructionWithPrivateKey(params) { + var privateKey = params.privateKey, + message = params.message, + instructionIndex = params.instructionIndex; + assert(privateKey.length === PRIVATE_KEY_BYTES$1, "Private key must be ".concat(PRIVATE_KEY_BYTES$1, " bytes but received ").concat(privateKey.length, " bytes")); - _context96.prev = 7; - _context96.next = 10; - return _this26._rpcWebSocket.call(unsubscribeMethod, [serverSubscriptionId]); + try { + var keypair = Keypair.fromSecretKey(privateKey); - case 10: - _context96.next = 21; - break; + var _publicKey2 = keypair.publicKey.toBytes(); - case 12: - _context96.prev = 12; - _context96.t0 = _context96["catch"](7); + var _signature5 = _sign(message, keypair.secretKey); - if (_context96.t0 instanceof Error) { - console.error("".concat(unsubscribeMethod, " error:"), _context96.t0.message); - } + return this.createInstructionWithPublicKey({ + publicKey: _publicKey2, + message: message, + signature: _signature5, + instructionIndex: instructionIndex + }); + } catch (error) { + throw new Error("Error creating instruction; ".concat(error)); + } + } + }]); - if (isCurrentConnectionStillActive()) { - _context96.next = 17; - break; - } + return Ed25519Program; + }(); - return _context96.abrupt("return"); + Ed25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111'); // Supply a synchronous hashing algorithm to make this + // library interoperable with the synchronous APIs in web3.js. - case 17: - // TODO: Maybe add an 'errored' state or a retry limit? - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'subscribed' - })); + utils.hmacSha256Sync = function (key) { + var h = hmac.create(sha256, key); - _context96.next = 20; - return _this26._updateSubscriptions(); + for (var _len8 = arguments.length, msgs = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) { + msgs[_key8 - 1] = arguments[_key8]; + } - case 20: - return _context96.abrupt("return"); + msgs.forEach(function (msg) { + return h.update(msg); + }); + return h.digest(); + }; - case 21: - _this26._setSubscription(hash, _objectSpread2(_objectSpread2({}, subscription), {}, { - state: 'unsubscribed' - })); + var ecdsaSign = function ecdsaSign(msgHash, privKey) { + return signSync(msgHash, privKey, { + der: false, + recovered: true + }); + }; - _context96.next = 24; - return _this26._updateSubscriptions(); + utils.isValidPrivateKey; + var publicKeyCreate = getPublicKey$1; + var PRIVATE_KEY_BYTES = 32; + var ETHEREUM_ADDRESS_BYTES = 20; + var PUBLIC_KEY_BYTES = 64; + var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11; + /** + * Params for creating an secp256k1 instruction using a public key + */ - case 24: - case "end": - return _context96.stop(); - } - }, _callee96, null, [[7, 12]]); - }))(); + var SECP256K1_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u16('signatureOffset'), u8('signatureInstructionIndex'), u16('ethAddressOffset'), u8('ethAddressInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u8('messageInstructionIndex'), blob$1(20, 'ethAddress'), blob$1(64, 'signature'), u8('recoveryId')]); - case 18: - return _context97.abrupt("break", 19); + var Secp256k1Program = /*#__PURE__*/function () { + /** + * @internal + */ + function Secp256k1Program() { + _classCallCheck(this, Secp256k1Program); + } + /** + * Public key that identifies the secp256k1 program + */ - case 19: - case "end": - return _context97.stop(); - } - }, _callee97); - })); + /** + * Construct an Ethereum address from a secp256k1 public key buffer. + * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer + */ - return function (_x151) { - return _ref42.apply(this, arguments); - }; - }())); - case 11: - case "end": - return _context98.stop(); - } - }, _callee98, this); - })); + _createClass(Secp256k1Program, null, [{ + key: "publicKeyToEthAddress", + value: function publicKeyToEthAddress(publicKey) { + assert(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes")); - function _updateSubscriptions() { - return _updateSubscriptions2.apply(this, arguments); + try { + return Buffer$1.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES); + } catch (error) { + throw new Error("Error constructing Ethereum address: ".concat(error)); } - - return _updateSubscriptions; - }() + } /** - * @internal + * Create an secp256k1 instruction with a public key. The public key + * must be a buffer that is 64 bytes long. */ }, { - key: "_handleServerNotification", - value: function _handleServerNotification(serverSubscriptionId, callbackArgs) { - var callbacks = this._subscriptionCallbacksByServerSubscriptionId[serverSubscriptionId]; - - if (callbacks === undefined) { - return; - } - - callbacks.forEach(function (cb) { - try { - cb.apply(void 0, _toConsumableArray(callbackArgs)); - } catch (e) { - console.error(e); - } + key: "createInstructionWithPublicKey", + value: function createInstructionWithPublicKey(params) { + var publicKey = params.publicKey, + message = params.message, + signature = params.signature, + recoveryId = params.recoveryId, + instructionIndex = params.instructionIndex; + return Secp256k1Program.createInstructionWithEthAddress({ + ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey), + message: message, + signature: signature, + recoveryId: recoveryId, + instructionIndex: instructionIndex }); } /** - * @internal + * Create an secp256k1 instruction with an Ethereum address. The address + * must be a hex string or a buffer that is 20 bytes long. */ }, { - key: "_wsOnAccountNotification", - value: function _wsOnAccountNotification(notification) { - var _create$1 = _create(notification, AccountNotificationResult), - result = _create$1.result, - subscription = _create$1.subscription; + key: "createInstructionWithEthAddress", + value: function createInstructionWithEthAddress(params) { + var rawAddress = params.ethAddress, + message = params.message, + signature = params.signature, + recoveryId = params.recoveryId, + _params$instructionIn = params.instructionIndex, + instructionIndex = _params$instructionIn === void 0 ? 0 : _params$instructionIn; + var ethAddress; - this._handleServerNotification(subscription, [result.value, result.context]); + if (typeof rawAddress === 'string') { + if (rawAddress.startsWith('0x')) { + ethAddress = Buffer$1.from(rawAddress.substr(2), 'hex'); + } else { + ethAddress = Buffer$1.from(rawAddress, 'hex'); + } + } else { + ethAddress = rawAddress; + } + + assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes")); + var dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE; + var ethAddressOffset = dataStart; + var signatureOffset = dataStart + ethAddress.length; + var messageDataOffset = signatureOffset + signature.length + 1; + var numSignatures = 1; + var instructionData = Buffer$1.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length); + SECP256K1_INSTRUCTION_LAYOUT.encode({ + numSignatures: numSignatures, + signatureOffset: signatureOffset, + signatureInstructionIndex: instructionIndex, + ethAddressOffset: ethAddressOffset, + ethAddressInstructionIndex: instructionIndex, + messageDataOffset: messageDataOffset, + messageDataSize: message.length, + messageInstructionIndex: instructionIndex, + signature: toBuffer(signature), + ethAddress: toBuffer(ethAddress), + recoveryId: recoveryId + }, instructionData); + instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span); + return new TransactionInstruction({ + keys: [], + programId: Secp256k1Program.programId, + data: instructionData + }); } /** - * @internal + * Create an secp256k1 instruction with a private key. The private key + * must be a buffer that is 32 bytes long. */ }, { - key: "_makeSubscription", - value: function _makeSubscription(subscriptionConfig, - /** - * When preparing `args` for a call to `_makeSubscription`, be sure - * to carefully apply a default `commitment` property, if necessary. - * - * - If the user supplied a `commitment` use that. - * - Otherwise, if the `Connection::commitment` is set, use that. - * - Otherwise, set it to the RPC server default: `finalized`. - * - * This is extremely important to ensure that these two fundamentally - * identical subscriptions produce the same identifying hash: - * - * - A subscription made without specifying a commitment. - * - A subscription made where the commitment specified is the same - * as the default applied to the subscription above. - * - * Example; these two subscriptions must produce the same hash: - * - * - An `accountSubscribe` subscription for `'PUBKEY'` - * - An `accountSubscribe` subscription for `'PUBKEY'` with commitment - * `'finalized'`. - * - * See the 'making a subscription with defaulted params omitted' test - * in `connection-subscriptions.ts` for more. - */ - args) { - var _this27 = this; + key: "createInstructionWithPrivateKey", + value: function createInstructionWithPrivateKey(params) { + var pkey = params.privateKey, + message = params.message, + instructionIndex = params.instructionIndex; + assert(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes")); - var clientSubscriptionId = this._nextClientSubscriptionId++; - var hash = fastStableStringify$1([subscriptionConfig.method, args]); - var existingSubscription = this._subscriptionsByHash[hash]; + try { + var privateKey = toBuffer(pkey); - if (existingSubscription === undefined) { - this._subscriptionsByHash[hash] = _objectSpread2(_objectSpread2({}, subscriptionConfig), {}, { - args: args, - callbacks: new Set([subscriptionConfig.callback]), - state: 'pending' + var _publicKey3 = publicKeyCreate(privateKey, false + /* isCompressed */ + ).slice(1); // throw away leading byte + + + var messageHash = Buffer$1.from(keccak_256(toBuffer(message))); + + var _ecdsaSign3 = ecdsaSign(messageHash, privateKey), + _ecdsaSign4 = _slicedToArray(_ecdsaSign3, 2), + _signature6 = _ecdsaSign4[0], + recoveryId = _ecdsaSign4[1]; + + return this.createInstructionWithPublicKey({ + publicKey: _publicKey3, + message: message, + signature: _signature6, + recoveryId: recoveryId, + instructionIndex: instructionIndex }); - } else { - existingSubscription.callbacks.add(subscriptionConfig.callback); + } catch (error) { + throw new Error("Error creating instruction; ".concat(error)); } + } + }]); - this._subscriptionHashByClientSubscriptionId[clientSubscriptionId] = hash; - this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId] = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee99() { - var subscription; - return _regeneratorRuntime().wrap(function _callee99$(_context99) { - while (1) switch (_context99.prev = _context99.next) { - case 0: - delete _this27._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - delete _this27._subscriptionHashByClientSubscriptionId[clientSubscriptionId]; - subscription = _this27._subscriptionsByHash[hash]; - assert(subscription !== undefined, "Could not find a `Subscription` when tearing down client subscription #".concat(clientSubscriptionId)); - subscription.callbacks["delete"](subscriptionConfig.callback); - _context99.next = 7; - return _this27._updateSubscriptions(); + return Secp256k1Program; + }(); - case 7: - case "end": - return _context99.stop(); - } - }, _callee99); - })); + Secp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111'); + /** + * Address of the stake config account which configures the rate + * of stake warmup and cooldown as well as the slashing penalty. + */ - this._updateSubscriptions(); + var STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111'); + /** + * Stake account authority info + */ - return clientSubscriptionId; - } - /** - * Register a callback to be invoked whenever the specified account changes - * - * @param publicKey Public key of the account to monitor - * @param callback Function to invoke whenever the account is changed - * @param commitment Specify the commitment level account changes must reach before notification - * @return subscription id - */ + var Authorized = /*#__PURE__*/_createClass( + /** stake authority */ - }, { - key: "onAccountChange", - value: function onAccountChange(publicKey, callback, commitment) { - var args = this._buildArgs([publicKey.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. - 'base64'); + /** withdraw authority */ - return this._makeSubscription({ - callback: callback, - method: 'accountSubscribe', - unsubscribeMethod: 'accountUnsubscribe' - }, args); - } - /** - * Deregister an account notification callback - * - * @param id client subscription id to deregister - */ + /** + * Create a new Authorized object + * @param staker the stake authority + * @param withdrawer the withdraw authority + */ + function Authorized(staker, withdrawer) { + _classCallCheck(this, Authorized); - }, { - key: "removeAccountChangeListener", - value: function () { - var _removeAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee100(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee100$(_context100) { - while (1) switch (_context100.prev = _context100.next) { - case 0: - _context100.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'account change'); + this.staker = void 0; + this.withdrawer = void 0; + this.staker = staker; + this.withdrawer = withdrawer; + }); + /** + * Stake account lockup info + */ - case 2: - case "end": - return _context100.stop(); - } - }, _callee100, this); - })); - function removeAccountChangeListener(_x152) { - return _removeAccountChangeListener.apply(this, arguments); - } + var Lockup = /*#__PURE__*/_createClass( + /** Unix timestamp of lockup expiration */ - return removeAccountChangeListener; - }() - /** - * @internal - */ + /** Epoch of lockup expiration */ - }, { - key: "_wsOnProgramAccountNotification", - value: function _wsOnProgramAccountNotification(notification) { - var _create2 = _create(notification, ProgramAccountNotificationResult), - result = _create2.result, - subscription = _create2.subscription; + /** Lockup custodian authority */ - this._handleServerNotification(subscription, [{ - accountId: result.value.pubkey, - accountInfo: result.value.account - }, result.context]); - } - /** - * Register a callback to be invoked whenever accounts owned by the - * specified program change - * - * @param programId Public key of the program to monitor - * @param callback Function to invoke whenever the account is changed - * @param commitment Specify the commitment level account changes must reach before notification - * @param filters The program account filters to pass into the RPC method - * @return subscription id - */ + /** + * Create a new Lockup object + */ + function Lockup(unixTimestamp, epoch, custodian) { + _classCallCheck(this, Lockup); - }, { - key: "onProgramAccountChange", - value: function onProgramAccountChange(programId, callback, commitment, filters) { - var args = this._buildArgs([programId.toBase58()], commitment || this._commitment || 'finalized', // Apply connection/server default. - 'base64' - /* encoding */ - , filters ? { - filters: filters - } : undefined - /* extra */ - ); + this.unixTimestamp = void 0; + this.epoch = void 0; + this.custodian = void 0; + this.unixTimestamp = unixTimestamp; + this.epoch = epoch; + this.custodian = custodian; + } + /** + * Default, inactive Lockup value + */ + ); - return this._makeSubscription({ - callback: callback, - method: 'programSubscribe', - unsubscribeMethod: 'programUnsubscribe' - }, args); + Lockup["default"] = new Lockup(0, 0, PublicKey["default"]); + /** + * Stake Instruction class + */ + + var StakeInstruction = /*#__PURE__*/function () { + /** + * @internal + */ + function StakeInstruction() { + _classCallCheck(this, StakeInstruction); + } + /** + * Decode a stake instruction and retrieve the instruction type. + */ + + + _createClass(StakeInstruction, null, [{ + key: "decodeInstructionType", + value: function decodeInstructionType(instruction) { + this.checkProgramId(instruction.programId); + var instructionTypeLayout = u32('instruction'); + var typeIndex = instructionTypeLayout.decode(instruction.data); + var type; + + for (var _i12 = 0, _Object$entries4 = Object.entries(STAKE_INSTRUCTION_LAYOUTS); _i12 < _Object$entries4.length; _i12++) { + var _Object$entries4$_i2 = _slicedToArray(_Object$entries4[_i12], 2), + ixType = _Object$entries4$_i2[0], + layout = _Object$entries4$_i2[1]; + + if (layout.index == typeIndex) { + type = ixType; + break; + } + } + + if (!type) { + throw new Error('Instruction type incorrect; not a StakeInstruction'); + } + + return type; } /** - * Deregister an account notification callback - * - * @param id client subscription id to deregister + * Decode a initialize stake instruction and retrieve the instruction params. */ }, { - key: "removeProgramAccountChangeListener", - value: function () { - var _removeProgramAccountChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee101(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee101$(_context101) { - while (1) switch (_context101.prev = _context101.next) { - case 0: - _context101.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'program account change'); - - case 2: - case "end": - return _context101.stop(); - } - }, _callee101, this); - })); + key: "decodeInitialize", + value: function decodeInitialize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - function removeProgramAccountChangeListener(_x153) { - return _removeProgramAccountChangeListener.apply(this, arguments); - } + var _decodeData$18 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data), + authorized = _decodeData$18.authorized, + lockup = _decodeData$18.lockup; - return removeProgramAccountChangeListener; - }() + return { + stakePubkey: instruction.keys[0].pubkey, + authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)), + lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian)) + }; + } /** - * Registers a callback to be invoked whenever logs are emitted. + * Decode a delegate stake instruction and retrieve the instruction params. */ }, { - key: "onLogs", - value: function onLogs(filter, callback, commitment) { - var args = this._buildArgs([_typeof$1(filter) === 'object' ? { - mentions: [filter.toString()] - } : filter], commitment || this._commitment || 'finalized' // Apply connection/server default. - ); - - return this._makeSubscription({ - callback: callback, - method: 'logsSubscribe', - unsubscribeMethod: 'logsUnsubscribe' - }, args); + key: "decodeDelegate", + value: function decodeDelegate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 6); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + votePubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[5].pubkey + }; } /** - * Deregister a logs callback. - * - * @param id client subscription id to deregister. + * Decode an authorize stake instruction and retrieve the instruction params. */ }, { - key: "removeOnLogsListener", - value: function () { - var _removeOnLogsListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee102(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee102$(_context102) { - while (1) switch (_context102.prev = _context102.next) { - case 0: - _context102.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'logs'); + key: "decodeAuthorize", + value: function decodeAuthorize(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - case 2: - case "end": - return _context102.stop(); - } - }, _callee102, this); - })); + var _decodeData$19 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), + newAuthorized = _decodeData$19.newAuthorized, + stakeAuthorizationType = _decodeData$19.stakeAuthorizationType; - function removeOnLogsListener(_x154) { - return _removeOnLogsListener.apply(this, arguments); + var o = { + stakePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + newAuthorizedPubkey: new PublicKey(newAuthorized), + stakeAuthorizationType: { + index: stakeAuthorizationType + } + }; + + if (instruction.keys.length > 3) { + o.custodianPubkey = instruction.keys[3].pubkey; } - return removeOnLogsListener; - }() + return o; + } /** - * @internal + * Decode an authorize-with-seed stake instruction and retrieve the instruction params. */ }, { - key: "_wsOnLogsNotification", - value: function _wsOnLogsNotification(notification) { - var _create3 = _create(notification, LogsNotificationResult), - result = _create3.result, - subscription = _create3.subscription; + key: "decodeAuthorizeWithSeed", + value: function decodeAuthorizeWithSeed(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 2); - this._handleServerNotification(subscription, [result.value, result.context]); + var _decodeData$20 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), + newAuthorized = _decodeData$20.newAuthorized, + stakeAuthorizationType = _decodeData$20.stakeAuthorizationType, + authoritySeed = _decodeData$20.authoritySeed, + authorityOwner = _decodeData$20.authorityOwner; + + var o = { + stakePubkey: instruction.keys[0].pubkey, + authorityBase: instruction.keys[1].pubkey, + authoritySeed: authoritySeed, + authorityOwner: new PublicKey(authorityOwner), + newAuthorizedPubkey: new PublicKey(newAuthorized), + stakeAuthorizationType: { + index: stakeAuthorizationType + } + }; + + if (instruction.keys.length > 3) { + o.custodianPubkey = instruction.keys[3].pubkey; + } + + return o; } /** - * @internal + * Decode a split stake instruction and retrieve the instruction params. */ }, { - key: "_wsOnSlotNotification", - value: function _wsOnSlotNotification(notification) { - var _create4 = _create(notification, SlotNotificationResult), - result = _create4.result, - subscription = _create4.subscription; + key: "decodeSplit", + value: function decodeSplit(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - this._handleServerNotification(subscription, [result]); + var _decodeData$21 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data), + lamports = _decodeData$21.lamports; + + return { + stakePubkey: instruction.keys[0].pubkey, + splitStakePubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + lamports: lamports + }; } /** - * Register a callback to be invoked upon slot changes - * - * @param callback Function to invoke whenever the slot changes - * @return subscription id + * Decode a merge stake instruction and retrieve the instruction params. */ }, { - key: "onSlotChange", - value: function onSlotChange(callback) { - return this._makeSubscription({ - callback: callback, - method: 'slotSubscribe', - unsubscribeMethod: 'slotUnsubscribe' - }, [] - /* args */ - ); + key: "decodeMerge", + value: function decodeMerge(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + sourceStakePubKey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey + }; } /** - * Deregister a slot notification callback - * - * @param id client subscription id to deregister + * Decode a withdraw stake instruction and retrieve the instruction params. */ }, { - key: "removeSlotChangeListener", - value: function () { - var _removeSlotChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee103(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee103$(_context103) { - while (1) switch (_context103.prev = _context103.next) { - case 0: - _context103.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot change'); - - case 2: - case "end": - return _context103.stop(); - } - }, _callee103, this); - })); + key: "decodeWithdraw", + value: function decodeWithdraw(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 5); - function removeSlotChangeListener(_x155) { - return _removeSlotChangeListener.apply(this, arguments); - } + var _decodeData$22 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), + lamports = _decodeData$22.lamports; - return removeSlotChangeListener; - }() - /** - * @internal - */ + var o = { + stakePubkey: instruction.keys[0].pubkey, + toPubkey: instruction.keys[1].pubkey, + authorizedPubkey: instruction.keys[4].pubkey, + lamports: lamports + }; - }, { - key: "_wsOnSlotUpdatesNotification", - value: function _wsOnSlotUpdatesNotification(notification) { - var _create5 = _create(notification, SlotUpdateNotificationResult), - result = _create5.result, - subscription = _create5.subscription; + if (instruction.keys.length > 5) { + o.custodianPubkey = instruction.keys[5].pubkey; + } - this._handleServerNotification(subscription, [result]); + return o; } /** - * Register a callback to be invoked upon slot updates. {@link SlotUpdate}'s - * may be useful to track live progress of a cluster. - * - * @param callback Function to invoke whenever the slot updates - * @return subscription id + * Decode a deactivate stake instruction and retrieve the instruction params. */ }, { - key: "onSlotUpdate", - value: function onSlotUpdate(callback) { - return this._makeSubscription({ - callback: callback, - method: 'slotsUpdatesSubscribe', - unsubscribeMethod: 'slotsUpdatesUnsubscribe' - }, [] - /* args */ - ); + key: "decodeDeactivate", + value: function decodeDeactivate(instruction) { + this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); + decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data); + return { + stakePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey + }; } /** - * Deregister a slot update notification callback - * - * @param id client subscription id to deregister + * @internal */ }, { - key: "removeSlotUpdateListener", - value: function () { - var _removeSlotUpdateListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee104(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee104$(_context104) { - while (1) switch (_context104.prev = _context104.next) { - case 0: - _context104.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'slot update'); - - case 2: - case "end": - return _context104.stop(); - } - }, _callee104, this); - })); - - function removeSlotUpdateListener(_x156) { - return _removeSlotUpdateListener.apply(this, arguments); + key: "checkProgramId", + value: function checkProgramId(programId) { + if (!programId.equals(StakeProgram.programId)) { + throw new Error('invalid instruction; programId is not StakeProgram'); } - - return removeSlotUpdateListener; - }() + } /** * @internal */ }, { - key: "_unsubscribeClientSubscription", - value: function () { - var _unsubscribeClientSubscription2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee105(clientSubscriptionId, subscriptionName) { - var dispose; - return _regeneratorRuntime().wrap(function _callee105$(_context105) { - while (1) switch (_context105.prev = _context105.next) { - case 0: - dispose = this._subscriptionDisposeFunctionsByClientSubscriptionId[clientSubscriptionId]; - - if (!dispose) { - _context105.next = 6; - break; - } - - _context105.next = 4; - return dispose(); - - case 4: - _context105.next = 7; - break; - - case 6: - console.warn('Ignored unsubscribe request because an active subscription with id ' + "`".concat(clientSubscriptionId, "` for '").concat(subscriptionName, "' events ") + 'could not be found.'); - - case 7: - case "end": - return _context105.stop(); - } - }, _callee105, this); - })); - - function _unsubscribeClientSubscription(_x157, _x158) { - return _unsubscribeClientSubscription2.apply(this, arguments); + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { + if (keys.length < expectedLength) { + throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); } + } + }]); - return _unsubscribeClientSubscription; - }() - }, { - key: "_buildArgs", - value: function _buildArgs(args, override, encoding, extra) { - var commitment = override || this._commitment; + return StakeInstruction; + }(); + /** + * An enumeration of valid StakeInstructionType's + */ - if (commitment || encoding || extra) { - var options = {}; + /** + * An enumeration of valid stake InstructionType's + * @internal + */ - if (encoding) { - options.encoding = encoding; - } - if (commitment) { - options.commitment = commitment; - } + var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({ + Initialize: { + index: 0, + layout: struct([u32('instruction'), authorized(), lockup()]) + }, + Authorize: { + index: 1, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType')]) + }, + Delegate: { + index: 2, + layout: struct([u32('instruction')]) + }, + Split: { + index: 3, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + Withdraw: { + index: 4, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + Deactivate: { + index: 5, + layout: struct([u32('instruction')]) + }, + Merge: { + index: 7, + layout: struct([u32('instruction')]) + }, + AuthorizeWithSeed: { + index: 8, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')]) + } + }); + /** + * Stake authorization type + */ - if (extra) { - options = Object.assign(options, extra); - } + /** + * An enumeration of valid StakeAuthorizationLayout's + */ - args.push(options); - } + var StakeAuthorizationLayout = Object.freeze({ + Staker: { + index: 0 + }, + Withdrawer: { + index: 1 + } + }); + /** + * Factory class for transactions to interact with the Stake program + */ - return args; - } - /** - * @internal - */ + var StakeProgram = /*#__PURE__*/function () { + /** + * @internal + */ + function StakeProgram() { + _classCallCheck(this, StakeProgram); + } + /** + * Public key that identifies the Stake program + */ - }, { - key: "_buildArgsAtLeastConfirmed", - value: function _buildArgsAtLeastConfirmed(args, override, encoding, extra) { - var commitment = override || this._commitment; + /** + * Generate an Initialize instruction to add to a Stake Create transaction + */ - if (commitment && !['confirmed', 'finalized'].includes(commitment)) { - throw new Error('Using Connection with default commitment: `' + this._commitment + '`, but method requires at least `confirmed`'); - } - return this._buildArgs(args, override, encoding, extra); + _createClass(StakeProgram, null, [{ + key: "initialize", + value: function initialize(params) { + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + maybeLockup = params.lockup; + var lockup = maybeLockup || Lockup["default"]; + var type = STAKE_INSTRUCTION_LAYOUTS.Initialize; + var data = encodeData(type, { + authorized: { + staker: toBuffer(authorized.staker.toBuffer()), + withdrawer: toBuffer(authorized.withdrawer.toBuffer()) + }, + lockup: { + unixTimestamp: lockup.unixTimestamp, + epoch: lockup.epoch, + custodian: toBuffer(lockup.custodian.toBuffer()) + } + }); + var instructionData = { + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); } /** - * @internal + * Generate a Transaction that creates a new Stake account at + * an address generated with `from`, a seed, and the Stake programId */ }, { - key: "_wsOnSignatureNotification", - value: function _wsOnSignatureNotification(notification) { - var _create6 = _create(notification, SignatureNotificationResult), - result = _create6.result, - subscription = _create6.subscription; - - if (result.value !== 'receivedSignature') { - /** - * Special case. - * After a signature is processed, RPCs automatically dispose of the - * subscription on the server side. We need to track which of these - * subscriptions have been disposed in such a way, so that we know - * whether the client is dealing with a not-yet-processed signature - * (in which case we must tear down the server subscription) or an - * already-processed signature (in which case the client can simply - * clear out the subscription locally without telling the server). - * - * NOTE: There is a proposal to eliminate this special case, here: - * https://github.com/solana-labs/solana/issues/18892 - */ - this._subscriptionsAutoDisposedByRpc.add(subscription); - } - - this._handleServerNotification(subscription, result.value === 'receivedSignature' ? [{ - type: 'received' - }, result.context] : [{ - type: 'status', - result: result.value - }, result.context]); + key: "createAccountWithSeed", + value: function createAccountWithSeed(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccountWithSeed({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.stakePubkey, + basePubkey: params.basePubkey, + seed: params.seed, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + lockup = params.lockup; + return transaction.add(this.initialize({ + stakePubkey: stakePubkey, + authorized: authorized, + lockup: lockup + })); } /** - * Register a callback to be invoked upon signature updates - * - * @param signature Transaction signature string in base 58 - * @param callback Function to invoke on signature notifications - * @param commitment Specify the commitment level signature must reach before notification - * @return subscription id + * Generate a Transaction that creates a new Stake account */ }, { - key: "onSignature", - value: function onSignature(signature, _callback, commitment) { - var _this28 = this; - - var args = this._buildArgs([signature], commitment || this._commitment || 'finalized' // Apply connection/server default. - ); - - var clientSubscriptionId = this._makeSubscription({ - callback: function callback(notification, context) { - if (notification.type === 'status') { - _callback(notification.result, context); // Signatures subscriptions are auto-removed by the RPC service - // so no need to explicitly send an unsubscribe message. - - - try { - _this28.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty - - } catch (_err) {// Already removed. - } - } - }, - method: 'signatureSubscribe', - unsubscribeMethod: 'signatureUnsubscribe' - }, args); - - return clientSubscriptionId; + key: "createAccount", + value: function createAccount(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.stakePubkey, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + var stakePubkey = params.stakePubkey, + authorized = params.authorized, + lockup = params.lockup; + return transaction.add(this.initialize({ + stakePubkey: stakePubkey, + authorized: authorized, + lockup: lockup + })); } /** - * Register a callback to be invoked when a transaction is - * received and/or processed. - * - * @param signature Transaction signature string in base 58 - * @param callback Function to invoke on signature notifications - * @param options Enable received notifications and set the commitment - * level that signature must reach before notification - * @return subscription id + * Generate a Transaction that delegates Stake tokens to a validator + * Vote PublicKey. This transaction can also be used to redelegate Stake + * to a new validator Vote PublicKey. */ }, { - key: "onSignatureWithOptions", - value: function onSignatureWithOptions(signature, _callback2, options) { - var _this29 = this; - - var _options$commitment = _objectSpread2(_objectSpread2({}, options), {}, { - commitment: options && options.commitment || this._commitment || 'finalized' // Apply connection/server default. - - }), - commitment = _options$commitment.commitment, - extra = _objectWithoutProperties(_options$commitment, _excluded4); - - var args = this._buildArgs([signature], commitment, undefined - /* encoding */ - , extra); - - var clientSubscriptionId = this._makeSubscription({ - callback: function callback(notification, context) { - _callback2(notification, context); // Signatures subscriptions are auto-removed by the RPC service - // so no need to explicitly send an unsubscribe message. - + key: "delegate", + value: function delegate(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + votePubkey = params.votePubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Delegate; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: votePubkey, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: STAKE_CONFIG_ID, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); + } + /** + * Generate a Transaction that authorizes a new PublicKey as Staker + * or Withdrawer on the Stake account. + */ - try { - _this29.removeSignatureListener(clientSubscriptionId); // eslint-disable-next-line no-empty + }, { + key: "authorize", + value: function authorize(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + newAuthorizedPubkey = params.newAuthorizedPubkey, + stakeAuthorizationType = params.stakeAuthorizationType, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Authorize; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + stakeAuthorizationType: stakeAuthorizationType.index + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }]; - } catch (_err) {// Already removed. - } - }, - method: 'signatureSubscribe', - unsubscribeMethod: 'signatureUnsubscribe' - }, args); + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); + } - return clientSubscriptionId; + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); } /** - * Deregister a signature notification callback - * - * @param id client subscription id to deregister + * Generate a Transaction that authorizes a new PublicKey as Staker + * or Withdrawer on the Stake account. */ }, { - key: "removeSignatureListener", - value: function () { - var _removeSignatureListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee106(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee106$(_context106) { - while (1) switch (_context106.prev = _context106.next) { - case 0: - _context106.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'signature result'); - - case 2: - case "end": - return _context106.stop(); - } - }, _callee106, this); - })); + key: "authorizeWithSeed", + value: function authorizeWithSeed(params) { + var stakePubkey = params.stakePubkey, + authorityBase = params.authorityBase, + authoritySeed = params.authoritySeed, + authorityOwner = params.authorityOwner, + newAuthorizedPubkey = params.newAuthorizedPubkey, + stakeAuthorizationType = params.stakeAuthorizationType, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + stakeAuthorizationType: stakeAuthorizationType.index, + authoritySeed: authoritySeed, + authorityOwner: toBuffer(authorityOwner.toBuffer()) + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorityBase, + isSigner: true, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }]; - function removeSignatureListener(_x159) { - return _removeSignatureListener.apply(this, arguments); + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); } - return removeSignatureListener; - }() + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); + } /** * @internal */ }, { - key: "_wsOnRootNotification", - value: function _wsOnRootNotification(notification) { - var _create7 = _create(notification, RootNotificationResult), - result = _create7.result, - subscription = _create7.subscription; - - this._handleServerNotification(subscription, [result]); + key: "splitInstruction", + value: function splitInstruction(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + splitStakePubkey = params.splitStakePubkey, + lamports = params.lamports; + var type = STAKE_INSTRUCTION_LAYOUTS.Split; + var data = encodeData(type, { + lamports: lamports + }); + return new TransactionInstruction({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: splitStakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); } /** - * Register a callback to be invoked upon root changes - * - * @param callback Function to invoke whenever the root changes - * @return subscription id + * Generate a Transaction that splits Stake tokens into another stake account */ }, { - key: "onRootChange", - value: function onRootChange(callback) { - return this._makeSubscription({ - callback: callback, - method: 'rootSubscribe', - unsubscribeMethod: 'rootUnsubscribe' - }, [] - /* args */ - ); + key: "split", + value: function split(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.authorizedPubkey, + newAccountPubkey: params.splitStakePubkey, + lamports: 0, + space: this.space, + programId: this.programId + })); + return transaction.add(this.splitInstruction(params)); } /** - * Deregister a root notification callback - * - * @param id client subscription id to deregister + * Generate a Transaction that splits Stake tokens into another account + * derived from a base public key and seed */ }, { - key: "removeRootChangeListener", - value: function () { - var _removeRootChangeListener = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee107(clientSubscriptionId) { - return _regeneratorRuntime().wrap(function _callee107$(_context107) { - while (1) switch (_context107.prev = _context107.next) { - case 0: - _context107.next = 2; - return this._unsubscribeClientSubscription(clientSubscriptionId, 'root change'); - - case 2: - case "end": - return _context107.stop(); - } - }, _callee107, this); + key: "splitWithSeed", + value: function splitWithSeed(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + splitStakePubkey = params.splitStakePubkey, + basePubkey = params.basePubkey, + seed = params.seed, + lamports = params.lamports; + var transaction = new Transaction(); + transaction.add(SystemProgram.allocate({ + accountPubkey: splitStakePubkey, + basePubkey: basePubkey, + seed: seed, + space: this.space, + programId: this.programId + })); + return transaction.add(this.splitInstruction({ + stakePubkey: stakePubkey, + authorizedPubkey: authorizedPubkey, + splitStakePubkey: splitStakePubkey, + lamports: lamports })); - - function removeRootChangeListener(_x160) { - return _removeRootChangeListener.apply(this, arguments); - } - - return removeRootChangeListener; - }() - }]); - - return Connection; - }(); - /** - * Keypair signer interface - */ - - /** - * An account keypair used for signing transactions. - */ - - - var Keypair = /*#__PURE__*/function () { - /** - * Create a new keypair instance. - * Generate random keypair if no {@link Ed25519Keypair} is provided. - * - * @param keypair ed25519 keypair - */ - function Keypair(keypair) { - _classCallCheck(this, Keypair); - - this._keypair = void 0; - this._keypair = keypair !== null && keypair !== void 0 ? keypair : generateKeypair(); - } - /** - * Generate a new random keypair - */ - - - _createClass(Keypair, [{ - key: "publicKey", - get: - /** - * The public key for this keypair - */ - function get() { - return new PublicKey(this._keypair.publicKey); } /** - * The raw secret key for this keypair + * Generate a Transaction that merges Stake accounts. */ }, { - key: "secretKey", - get: function get() { - return new Uint8Array(this._keypair.secretKey); - } - }], [{ - key: "generate", - value: function generate() { - return new Keypair(generateKeypair()); + key: "merge", + value: function merge(params) { + var stakePubkey = params.stakePubkey, + sourceStakePubKey = params.sourceStakePubKey, + authorizedPubkey = params.authorizedPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Merge; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: sourceStakePubKey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }); } /** - * Create a keypair from a raw secret key byte array. - * - * This method should only be used to recreate a keypair from a previously - * generated secret key. Generating keypairs from a random seed should be done - * with the {@link Keypair.fromSeed} method. - * - * @throws error if the provided secret key is invalid and validation is not skipped. - * - * @param secretKey secret key byte array - * @param options: skip secret key validation + * Generate a Transaction that withdraws deactivated Stake tokens. */ }, { - key: "fromSecretKey", - value: function fromSecretKey(secretKey, options) { - if (secretKey.byteLength !== 64) { - throw new Error('bad secret key size'); - } - - var publicKey = secretKey.slice(32, 64); - - if (!options || !options.skipValidation) { - var privateScalar = secretKey.slice(0, 32); - var computedPublicKey = getPublicKey(privateScalar); + key: "withdraw", + value: function withdraw(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey, + toPubkey = params.toPubkey, + lamports = params.lamports, + custodianPubkey = params.custodianPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Withdraw; + var data = encodeData(type, { + lamports: lamports + }); + var keys = [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }]; - for (var ii = 0; ii < 32; ii++) { - if (publicKey[ii] !== computedPublicKey[ii]) { - throw new Error('provided secretKey is invalid'); - } - } + if (custodianPubkey) { + keys.push({ + pubkey: custodianPubkey, + isSigner: false, + isWritable: false + }); } - return new Keypair({ - publicKey: publicKey, - secretKey: secretKey + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data }); } /** - * Generate a keypair from a 32 byte seed. - * - * @param seed seed byte array + * Generate a Transaction that deactivates Stake tokens. */ }, { - key: "fromSeed", - value: function fromSeed(seed) { - var publicKey = getPublicKey(seed); - var secretKey = new Uint8Array(64); - secretKey.set(seed); - secretKey.set(publicKey, 32); - return new Keypair({ - publicKey: publicKey, - secretKey: secretKey + key: "deactivate", + value: function deactivate(params) { + var stakePubkey = params.stakePubkey, + authorizedPubkey = params.authorizedPubkey; + var type = STAKE_INSTRUCTION_LAYOUTS.Deactivate; + var data = encodeData(type); + return new Transaction().add({ + keys: [{ + pubkey: stakePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: authorizedPubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data }); } }]); - return Keypair; + return StakeProgram; }(); + + StakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111'); + StakeProgram.space = 200; + /** + * Vote account info + */ + + var VoteInit = /*#__PURE__*/_createClass( + /** [0, 100] */ + function VoteInit(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) { + _classCallCheck(this, VoteInit); + + this.nodePubkey = void 0; + this.authorizedVoter = void 0; + this.authorizedWithdrawer = void 0; + this.commission = void 0; + this.nodePubkey = nodePubkey; + this.authorizedVoter = authorizedVoter; + this.authorizedWithdrawer = authorizedWithdrawer; + this.commission = commission; + }); /** - * An enumeration of valid address lookup table InstructionType's - * @internal + * Create vote account transaction params */ + /** + * Vote Instruction class + */ - var LOOKUP_TABLE_INSTRUCTION_LAYOUTS = Object.freeze({ - CreateLookupTable: { - index: 0, - layout: struct([u32('instruction'), u64('recentSlot'), u8('bumpSeed')]) - }, - FreezeLookupTable: { - index: 1, - layout: struct([u32('instruction')]) - }, - ExtendLookupTable: { - index: 2, - layout: struct([u32('instruction'), u64(), seq$1(publicKey(), offset$1(u32(), -8), 'addresses')]) - }, - DeactivateLookupTable: { - index: 3, - layout: struct([u32('instruction')]) - }, - CloseLookupTable: { - index: 4, - layout: struct([u32('instruction')]) - } - }); - var AddressLookupTableInstruction = /*#__PURE__*/function () { + var VoteInstruction = /*#__PURE__*/function () { /** * @internal */ - function AddressLookupTableInstruction() { - _classCallCheck(this, AddressLookupTableInstruction); + function VoteInstruction() { + _classCallCheck(this, VoteInstruction); } + /** + * Decode a vote instruction and retrieve the instruction type. + */ - _createClass(AddressLookupTableInstruction, null, [{ + + _createClass(VoteInstruction, null, [{ key: "decodeInstructionType", value: function decodeInstructionType(instruction) { this.checkProgramId(instruction.programId); var instructionTypeLayout = u32('instruction'); - var index = instructionTypeLayout.decode(instruction.data); + var typeIndex = instructionTypeLayout.decode(instruction.data); var type; - for (var _i10 = 0, _Object$entries2 = Object.entries(LOOKUP_TABLE_INSTRUCTION_LAYOUTS); _i10 < _Object$entries2.length; _i10++) { - var _Object$entries2$_i2 = _slicedToArray(_Object$entries2[_i10], 2), - layoutType = _Object$entries2$_i2[0], - layout = _Object$entries2$_i2[1]; + for (var _i13 = 0, _Object$entries5 = Object.entries(VOTE_INSTRUCTION_LAYOUTS); _i13 < _Object$entries5.length; _i13++) { + var _Object$entries5$_i2 = _slicedToArray(_Object$entries5[_i13], 2), + ixType = _Object$entries5$_i2[0], + layout = _Object$entries5$_i2[1]; - if (layout.index == index) { - type = layoutType; + if (layout.index == typeIndex) { + type = ixType; break; } } if (!type) { - throw new Error('Invalid Instruction. Should be a LookupTable Instruction'); + throw new Error('Instruction type incorrect; not a VoteInstruction'); } return type; } + /** + * Decode an initialize vote instruction and retrieve the instruction params. + */ + }, { - key: "decodeCreateLookupTable", - value: function decodeCreateLookupTable(instruction) { + key: "decodeInitializeAccount", + value: function decodeInitializeAccount(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 4); + this.checkKeyLength(instruction.keys, 4); - var _decodeData$12 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable, instruction.data), - recentSlot = _decodeData$12.recentSlot; + var _decodeData$23 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data), + voteInit = _decodeData$23.voteInit; return { - authority: instruction.keys[1].pubkey, - payer: instruction.keys[2].pubkey, - recentSlot: Number(recentSlot) + votePubkey: instruction.keys[0].pubkey, + nodePubkey: instruction.keys[3].pubkey, + voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission) }; } + /** + * Decode an authorize instruction and retrieve the instruction params. + */ + }, { - key: "decodeExtendLookupTable", - value: function decodeExtendLookupTable(instruction) { + key: "decodeAuthorize", + value: function decodeAuthorize(instruction) { this.checkProgramId(instruction.programId); + this.checkKeyLength(instruction.keys, 3); - if (instruction.keys.length < 2) { - throw new Error("invalid instruction; found ".concat(instruction.keys.length, " keys, expected at least 2")); - } - - var _decodeData$13 = decodeData$1(LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable, instruction.data), - addresses = _decodeData$13.addresses; + var _decodeData$24 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), + newAuthorized = _decodeData$24.newAuthorized, + voteAuthorizationType = _decodeData$24.voteAuthorizationType; return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey, - payer: instruction.keys.length > 2 ? instruction.keys[2].pubkey : undefined, - addresses: addresses.map(function (buffer) { - return new PublicKey(buffer); - }) - }; - } - }, { - key: "decodeCloseLookupTable", - value: function decodeCloseLookupTable(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 3); - return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey, - recipient: instruction.keys[2].pubkey + votePubkey: instruction.keys[0].pubkey, + authorizedPubkey: instruction.keys[2].pubkey, + newAuthorizedPubkey: new PublicKey(newAuthorized), + voteAuthorizationType: { + index: voteAuthorizationType + } }; } + /** + * Decode an authorize instruction and retrieve the instruction params. + */ + }, { - key: "decodeFreezeLookupTable", - value: function decodeFreezeLookupTable(instruction) { + key: "decodeAuthorizeWithSeed", + value: function decodeAuthorizeWithSeed(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 2); + this.checkKeyLength(instruction.keys, 3); + + var _decodeData$25 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), + _decodeData$25$voteAu = _decodeData$25.voteAuthorizeWithSeedArgs, + currentAuthorityDerivedKeyOwnerPubkey = _decodeData$25$voteAu.currentAuthorityDerivedKeyOwnerPubkey, + currentAuthorityDerivedKeySeed = _decodeData$25$voteAu.currentAuthorityDerivedKeySeed, + newAuthorized = _decodeData$25$voteAu.newAuthorized, + voteAuthorizationType = _decodeData$25$voteAu.voteAuthorizationType; + return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey + currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey, + currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey), + currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, + newAuthorizedPubkey: new PublicKey(newAuthorized), + voteAuthorizationType: { + index: voteAuthorizationType + }, + votePubkey: instruction.keys[0].pubkey }; } + /** + * Decode a withdraw instruction and retrieve the instruction params. + */ + }, { - key: "decodeDeactivateLookupTable", - value: function decodeDeactivateLookupTable(instruction) { + key: "decodeWithdraw", + value: function decodeWithdraw(instruction) { this.checkProgramId(instruction.programId); - this.checkKeysLength(instruction.keys, 2); + this.checkKeyLength(instruction.keys, 3); + + var _decodeData$26 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), + lamports = _decodeData$26.lamports; + return { - lookupTable: instruction.keys[0].pubkey, - authority: instruction.keys[1].pubkey + votePubkey: instruction.keys[0].pubkey, + authorizedWithdrawerPubkey: instruction.keys[2].pubkey, + lamports: lamports, + toPubkey: instruction.keys[1].pubkey }; } /** @@ -31021,8 +32668,8 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// }, { key: "checkProgramId", value: function checkProgramId(programId) { - if (!programId.equals(AddressLookupTableProgram.programId)) { - throw new Error('invalid instruction; programId is not AddressLookupTable Program'); + if (!programId.equals(VoteProgram.programId)) { + throw new Error('invalid instruction; programId is not VoteProgram'); } } /** @@ -31030,2301 +32677,2096 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// */ }, { - key: "checkKeysLength", - value: function checkKeysLength(keys, expectedLength) { + key: "checkKeyLength", + value: function checkKeyLength(keys, expectedLength) { if (keys.length < expectedLength) { throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); } } }]); - return AddressLookupTableInstruction; + return VoteInstruction; }(); + /** + * An enumeration of valid VoteInstructionType's + */ - var AddressLookupTableProgram = /*#__PURE__*/function () { + + var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({ + InitializeAccount: { + index: 0, + layout: struct([u32('instruction'), voteInit()]) + }, + Authorize: { + index: 1, + layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('voteAuthorizationType')]) + }, + Withdraw: { + index: 3, + layout: struct([u32('instruction'), ns64('lamports')]) + }, + AuthorizeWithSeed: { + index: 10, + layout: struct([u32('instruction'), voteAuthorizeWithSeedArgs()]) + } + }); + /** + * VoteAuthorize type + */ + + /** + * An enumeration of valid VoteAuthorization layouts. + */ + + var VoteAuthorizationLayout = Object.freeze({ + Voter: { + index: 0 + }, + Withdrawer: { + index: 1 + } + }); + /** + * Factory class for transactions to interact with the Vote program + */ + + var VoteProgram = /*#__PURE__*/function () { /** * @internal */ - function AddressLookupTableProgram() { - _classCallCheck(this, AddressLookupTableProgram); + function VoteProgram() { + _classCallCheck(this, VoteProgram); } + /** + * Public key that identifies the Vote program + */ - _createClass(AddressLookupTableProgram, null, [{ - key: "createLookupTable", - value: function createLookupTable(params) { - var _PublicKey$findProgra = PublicKey.findProgramAddressSync([params.authority.toBuffer(), toBufferLE_1(BigInt(params.recentSlot), 8)], this.programId), - _PublicKey$findProgra2 = _slicedToArray(_PublicKey$findProgra, 2), - lookupTableAddress = _PublicKey$findProgra2[0], - bumpSeed = _PublicKey$findProgra2[1]; + /** + * Generate an Initialize instruction. + */ - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CreateLookupTable; + + _createClass(VoteProgram, null, [{ + key: "initializeAccount", + value: function initializeAccount(params) { + var votePubkey = params.votePubkey, + nodePubkey = params.nodePubkey, + voteInit = params.voteInit; + var type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount; var data = encodeData(type, { - recentSlot: BigInt(params.recentSlot), - bumpSeed: bumpSeed + voteInit: { + nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()), + authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()), + authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()), + commission: voteInit.commission + } + }); + var instructionData = { + keys: [{ + pubkey: votePubkey, + isSigner: false, + isWritable: true + }, { + pubkey: SYSVAR_RENT_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: nodePubkey, + isSigner: true, + isWritable: false + }], + programId: this.programId, + data: data + }; + return new TransactionInstruction(instructionData); + } + /** + * Generate a transaction that creates a new Vote account. + */ + + }, { + key: "createAccount", + value: function createAccount(params) { + var transaction = new Transaction(); + transaction.add(SystemProgram.createAccount({ + fromPubkey: params.fromPubkey, + newAccountPubkey: params.votePubkey, + lamports: params.lamports, + space: this.space, + programId: this.programId + })); + return transaction.add(this.initializeAccount({ + votePubkey: params.votePubkey, + nodePubkey: params.voteInit.nodePubkey, + voteInit: params.voteInit + })); + } + /** + * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account. + */ + + }, { + key: "authorize", + value: function authorize(params) { + var votePubkey = params.votePubkey, + authorizedPubkey = params.authorizedPubkey, + newAuthorizedPubkey = params.newAuthorizedPubkey, + voteAuthorizationType = params.voteAuthorizationType; + var type = VOTE_INSTRUCTION_LAYOUTS.Authorize; + var data = encodeData(type, { + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + voteAuthorizationType: voteAuthorizationType.index }); var keys = [{ - pubkey: lookupTableAddress, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, - isSigner: true, + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, isWritable: false }, { - pubkey: params.payer, + pubkey: authorizedPubkey, isSigner: true, - isWritable: true - }, { - pubkey: SystemProgram.programId, - isSigner: false, isWritable: false }]; - return [new TransactionInstruction({ - programId: this.programId, + return new Transaction().add({ keys: keys, + programId: this.programId, data: data - }), lookupTableAddress]; + }); } + /** + * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account + * where the current Voter or Withdrawer authority is a derived key. + */ + }, { - key: "freezeLookupTable", - value: function freezeLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.FreezeLookupTable; - var data = encodeData(type); + key: "authorizeWithSeed", + value: function authorizeWithSeed(params) { + var currentAuthorityDerivedKeyBasePubkey = params.currentAuthorityDerivedKeyBasePubkey, + currentAuthorityDerivedKeyOwnerPubkey = params.currentAuthorityDerivedKeyOwnerPubkey, + currentAuthorityDerivedKeySeed = params.currentAuthorityDerivedKeySeed, + newAuthorizedPubkey = params.newAuthorizedPubkey, + voteAuthorizationType = params.voteAuthorizationType, + votePubkey = params.votePubkey; + var type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; + var data = encodeData(type, { + voteAuthorizeWithSeedArgs: { + currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()), + currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, + newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), + voteAuthorizationType: voteAuthorizationType.index + } + }); var keys = [{ - pubkey: params.lookupTable, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, + pubkey: SYSVAR_CLOCK_PUBKEY, + isSigner: false, + isWritable: false + }, { + pubkey: currentAuthorityDerivedKeyBasePubkey, isSigner: true, isWritable: false }]; - return new TransactionInstruction({ - programId: this.programId, + return new Transaction().add({ keys: keys, + programId: this.programId, data: data }); } + /** + * Generate a transaction to withdraw from a Vote account. + */ + }, { - key: "extendLookupTable", - value: function extendLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.ExtendLookupTable; + key: "withdraw", + value: function withdraw(params) { + var votePubkey = params.votePubkey, + authorizedWithdrawerPubkey = params.authorizedWithdrawerPubkey, + lamports = params.lamports, + toPubkey = params.toPubkey; + var type = VOTE_INSTRUCTION_LAYOUTS.Withdraw; var data = encodeData(type, { - addresses: params.addresses.map(function (addr) { - return addr.toBytes(); - }) + lamports: lamports }); var keys = [{ - pubkey: params.lookupTable, + pubkey: votePubkey, isSigner: false, isWritable: true }, { - pubkey: params.authority, + pubkey: toPubkey, + isSigner: false, + isWritable: true + }, { + pubkey: authorizedWithdrawerPubkey, isSigner: true, isWritable: false }]; + return new Transaction().add({ + keys: keys, + programId: this.programId, + data: data + }); + } + /** + * Generate a transaction to withdraw safely from a Vote account. + * + * This function was created as a safeguard for vote accounts running validators, `safeWithdraw` + * checks that the withdraw amount will not exceed the specified balance while leaving enough left + * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the + * `withdraw` method directly. + */ - if (params.payer) { - keys.push({ - pubkey: params.payer, - isSigner: true, - isWritable: true - }, { - pubkey: SystemProgram.programId, - isSigner: false, - isWritable: false + }, { + key: "safeWithdraw", + value: function safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) { + if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) { + throw new Error('Withdraw will leave vote account with insuffcient funds.'); + } + + return VoteProgram.withdraw(params); + } + }]); + + return VoteProgram; + }(); + + VoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111'); + VoteProgram.space = 3731; + var VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111'); + /** + * @internal + */ + + var InfoString = type({ + name: string(), + website: optional(string()), + details: optional(string()), + keybaseUsername: optional(string()) + }); + /** + * ValidatorInfo class + */ + + var ValidatorInfo = /*#__PURE__*/function () { + /** + * validator public key + */ + + /** + * validator information + */ + + /** + * Construct a valid ValidatorInfo + * + * @param key validator public key + * @param info validator information + */ + function ValidatorInfo(key, info) { + _classCallCheck(this, ValidatorInfo); + + this.key = void 0; + this.info = void 0; + this.key = key; + this.info = info; + } + /** + * Deserialize ValidatorInfo from the config account data. Exactly two config + * keys are required in the data. + * + * @param buffer config account data + * @return null if info was not found + */ + + + _createClass(ValidatorInfo, null, [{ + key: "fromConfigData", + value: function fromConfigData(buffer) { + var byteArray = _toConsumableArray(buffer); + + var configKeyCount = decodeLength(byteArray); + if (configKeyCount !== 2) return null; + var configKeys = []; + + for (var i = 0; i < 2; i++) { + var _publicKey4 = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH)); + + byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); + var isSigner = byteArray.slice(0, 1)[0] === 1; + byteArray = byteArray.slice(1); + configKeys.push({ + publicKey: _publicKey4, + isSigner: isSigner }); } - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); - } - }, { - key: "deactivateLookupTable", - value: function deactivateLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.DeactivateLookupTable; - var data = encodeData(type); - var keys = [{ - pubkey: params.lookupTable, - isSigner: false, - isWritable: true - }, { - pubkey: params.authority, - isSigner: true, - isWritable: false - }]; - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); - } - }, { - key: "closeLookupTable", - value: function closeLookupTable(params) { - var type = LOOKUP_TABLE_INSTRUCTION_LAYOUTS.CloseLookupTable; - var data = encodeData(type); - var keys = [{ - pubkey: params.lookupTable, - isSigner: false, - isWritable: true - }, { - pubkey: params.authority, - isSigner: true, - isWritable: false - }, { - pubkey: params.recipient, - isSigner: false, - isWritable: true - }]; - return new TransactionInstruction({ - programId: this.programId, - keys: keys, - data: data - }); + if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) { + if (configKeys[1].isSigner) { + var rawInfo = rustString().decode(Buffer$1.from(byteArray)); + var info = JSON.parse(rawInfo); + _assert(info, InfoString); + return new ValidatorInfo(configKeys[1].publicKey, info); + } + } + + return null; } }]); - return AddressLookupTableProgram; + return ValidatorInfo; }(); - AddressLookupTableProgram.programId = new PublicKey('AddressLookupTab1e1111111111111111111111111'); + var VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111'); /** - * Compute Budget Instruction class + * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88 + * + * @internal */ - var ComputeBudgetInstruction = /*#__PURE__*/function () { + var VoteAccountLayout = struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), u8('commission'), nu64$1(), // votes.length + seq$1(struct([nu64$1('slot'), u32('confirmationCount')]), offset$1(u32(), -8), 'votes'), u8('rootSlotValid'), nu64$1('rootSlot'), nu64$1(), // authorizedVoters.length + seq$1(struct([nu64$1('epoch'), publicKey('authorizedVoter')]), offset$1(u32(), -8), 'authorizedVoters'), struct([seq$1(struct([publicKey('authorizedPubkey'), nu64$1('epochOfLastAuthorizedSwitch'), nu64$1('targetEpoch')]), 32, 'buf'), nu64$1('idx'), u8('isEmpty')], 'priorVoters'), nu64$1(), // epochCredits.length + seq$1(struct([nu64$1('epoch'), nu64$1('credits'), nu64$1('prevCredits')]), offset$1(u32(), -8), 'epochCredits'), struct([nu64$1('slot'), nu64$1('timestamp')], 'lastTimestamp')]); + /** + * VoteAccount class + */ + + var VoteAccount = /*#__PURE__*/function () { /** * @internal */ - function ComputeBudgetInstruction() { - _classCallCheck(this, ComputeBudgetInstruction); + function VoteAccount(args) { + _classCallCheck(this, VoteAccount); + + this.nodePubkey = void 0; + this.authorizedWithdrawer = void 0; + this.commission = void 0; + this.rootSlot = void 0; + this.votes = void 0; + this.authorizedVoters = void 0; + this.priorVoters = void 0; + this.epochCredits = void 0; + this.lastTimestamp = void 0; + this.nodePubkey = args.nodePubkey; + this.authorizedWithdrawer = args.authorizedWithdrawer; + this.commission = args.commission; + this.rootSlot = args.rootSlot; + this.votes = args.votes; + this.authorizedVoters = args.authorizedVoters; + this.priorVoters = args.priorVoters; + this.epochCredits = args.epochCredits; + this.lastTimestamp = args.lastTimestamp; } /** - * Decode a compute budget instruction and retrieve the instruction type. + * Deserialize VoteAccount from the account data. + * + * @param buffer account data + * @return VoteAccount */ - _createClass(ComputeBudgetInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u8('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; - - for (var _i11 = 0, _Object$entries3 = Object.entries(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS); _i11 < _Object$entries3.length; _i11++) { - var _Object$entries3$_i2 = _slicedToArray(_Object$entries3[_i11], 2), - ixType = _Object$entries3$_i2[0], - layout = _Object$entries3$_i2[1]; - - if (layout.index == typeIndex) { - type = ixType; - break; - } - } + _createClass(VoteAccount, null, [{ + key: "fromAccountData", + value: function fromAccountData(buffer) { + var versionOffset = 4; + var va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset); + var rootSlot = va.rootSlot; - if (!type) { - throw new Error('Instruction type incorrect; not a ComputeBudgetInstruction'); + if (!va.rootSlotValid) { + rootSlot = null; } - return type; + return new VoteAccount({ + nodePubkey: new PublicKey(va.nodePubkey), + authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer), + commission: va.commission, + votes: va.votes, + rootSlot: rootSlot, + authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter), + priorVoters: getPriorVoters(va.priorVoters), + epochCredits: va.epochCredits, + lastTimestamp: va.lastTimestamp + }); } - /** - * Decode request units compute budget instruction and retrieve the instruction params. - */ - - }, { - key: "decodeRequestUnits", - value: function decodeRequestUnits(instruction) { - this.checkProgramId(instruction.programId); - - var _decodeData$14 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits, instruction.data), - units = _decodeData$14.units, - additionalFee = _decodeData$14.additionalFee; + }]); - return { - units: units, - additionalFee: additionalFee - }; - } - /** - * Decode request heap frame compute budget instruction and retrieve the instruction params. - */ + return VoteAccount; + }(); - }, { - key: "decodeRequestHeapFrame", - value: function decodeRequestHeapFrame(instruction) { - this.checkProgramId(instruction.programId); + function parseAuthorizedVoter(_ref46) { + var authorizedVoter = _ref46.authorizedVoter, + epoch = _ref46.epoch; + return { + epoch: epoch, + authorizedVoter: new PublicKey(authorizedVoter) + }; + } - var _decodeData$15 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame, instruction.data), - bytes = _decodeData$15.bytes; + function parsePriorVoters(_ref47) { + var authorizedPubkey = _ref47.authorizedPubkey, + epochOfLastAuthorizedSwitch = _ref47.epochOfLastAuthorizedSwitch, + targetEpoch = _ref47.targetEpoch; + return { + authorizedPubkey: new PublicKey(authorizedPubkey), + epochOfLastAuthorizedSwitch: epochOfLastAuthorizedSwitch, + targetEpoch: targetEpoch + }; + } - return { - bytes: bytes - }; - } - /** - * Decode set compute unit limit compute budget instruction and retrieve the instruction params. - */ + function getPriorVoters(_ref48) { + var buf = _ref48.buf, + idx = _ref48.idx, + isEmpty = _ref48.isEmpty; - }, { - key: "decodeSetComputeUnitLimit", - value: function decodeSetComputeUnitLimit(instruction) { - this.checkProgramId(instruction.programId); + if (isEmpty) { + return []; + } - var _decodeData$16 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit, instruction.data), - units = _decodeData$16.units; + return [].concat(_toConsumableArray(buf.slice(idx + 1).map(parsePriorVoters)), _toConsumableArray(buf.slice(0, idx).map(parsePriorVoters))); + } - return { - units: units - }; - } - /** - * Decode set compute unit price compute budget instruction and retrieve the instruction params. - */ + var endpoint = { + http: { + devnet: 'http://api.devnet.solana.com', + testnet: 'http://api.testnet.solana.com', + 'mainnet-beta': 'http://api.mainnet-beta.solana.com/' + }, + https: { + devnet: 'https://api.devnet.solana.com', + testnet: 'https://api.testnet.solana.com', + 'mainnet-beta': 'https://api.mainnet-beta.solana.com/' + } + }; + /** + * Retrieves the RPC API URL for the specified cluster + */ - }, { - key: "decodeSetComputeUnitPrice", - value: function decodeSetComputeUnitPrice(instruction) { - this.checkProgramId(instruction.programId); + function clusterApiUrl(cluster, tls) { + var key = tls === false ? 'http' : 'https'; - var _decodeData$17 = decodeData$1(COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice, instruction.data), - microLamports = _decodeData$17.microLamports; + if (!cluster) { + return endpoint[key]['devnet']; + } - return { - microLamports: microLamports - }; - } - /** - * @internal - */ + var url = endpoint[key][cluster]; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(ComputeBudgetProgram.programId)) { - throw new Error('invalid instruction; programId is not ComputeBudgetProgram'); - } - } - }]); + if (!url) { + throw new Error("Unknown ".concat(key, " cluster: ").concat(cluster)); + } - return ComputeBudgetInstruction; - }(); + return url; + } /** - * An enumeration of valid ComputeBudgetInstructionType's + * Send and confirm a raw transaction + * + * If `commitment` option is not specified, defaults to 'max' commitment. + * + * @param {Connection} connection + * @param {Buffer} rawTransaction + * @param {TransactionConfirmationStrategy} confirmationStrategy + * @param {ConfirmOptions} [options] + * @returns {Promise} */ /** - * An enumeration of valid ComputeBudget InstructionType's - * @internal + * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy` + * is no longer supported and will be removed in a future version. */ + // eslint-disable-next-line no-redeclare + // eslint-disable-next-line no-redeclare - var COMPUTE_BUDGET_INSTRUCTION_LAYOUTS = Object.freeze({ - RequestUnits: { - index: 0, - layout: struct([u8('instruction'), u32('units'), u32('additionalFee')]) - }, - RequestHeapFrame: { - index: 1, - layout: struct([u8('instruction'), u32('bytes')]) - }, - SetComputeUnitLimit: { - index: 2, - layout: struct([u8('instruction'), u32('units')]) - }, - SetComputeUnitPrice: { - index: 3, - layout: struct([u8('instruction'), u64('microLamports')]) - } - }); + function sendAndConfirmRawTransaction(_x161, _x162, _x163, _x164) { + return _sendAndConfirmRawTransaction.apply(this, arguments); + } /** - * Factory class for transaction instructions to interact with the Compute Budget program + * There are 1-billion lamports in one SOL */ - var ComputeBudgetProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function ComputeBudgetProgram() { - _classCallCheck(this, ComputeBudgetProgram); - } - /** - * Public key that identifies the Compute Budget program - */ - /** - * @deprecated Instead, call {@link setComputeUnitLimit} and/or {@link setComputeUnitPrice} - */ + function _sendAndConfirmRawTransaction() { + _sendAndConfirmRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee109(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) { + var confirmationStrategy, options, sendOptions, signature, commitment, confirmationPromise, status; + return _regeneratorRuntime().wrap(function _callee109$(_context109) { + while (1) switch (_context109.prev = _context109.next) { + case 0: + if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) { + confirmationStrategy = confirmationStrategyOrConfirmOptions; + options = maybeConfirmOptions; + } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) { + confirmationStrategy = confirmationStrategyOrConfirmOptions; + options = maybeConfirmOptions; + } else { + options = confirmationStrategyOrConfirmOptions; + } + sendOptions = options && { + skipPreflight: options.skipPreflight, + preflightCommitment: options.preflightCommitment || options.commitment, + minContextSlot: options.minContextSlot + }; + _context109.next = 4; + return connection.sendRawTransaction(rawTransaction, sendOptions); - _createClass(ComputeBudgetProgram, null, [{ - key: "requestUnits", - value: function requestUnits(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestUnits; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "requestHeapFrame", - value: function requestHeapFrame(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.RequestHeapFrame; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "setComputeUnitLimit", - value: function setComputeUnitLimit(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitLimit; - var data = encodeData(type, params); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }, { - key: "setComputeUnitPrice", - value: function setComputeUnitPrice(params) { - var type = COMPUTE_BUDGET_INSTRUCTION_LAYOUTS.SetComputeUnitPrice; - var data = encodeData(type, { - microLamports: BigInt(params.microLamports) - }); - return new TransactionInstruction({ - keys: [], - programId: this.programId, - data: data - }); - } - }]); + case 4: + signature = _context109.sent; + commitment = options && options.commitment; + confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment); + _context109.next = 9; + return confirmationPromise; - return ComputeBudgetProgram; - }(); + case 9: + status = _context109.sent.value; - ComputeBudgetProgram.programId = new PublicKey('ComputeBudget111111111111111111111111111111'); - var PRIVATE_KEY_BYTES$1 = 64; - var PUBLIC_KEY_BYTES$1 = 32; - var SIGNATURE_BYTES = 64; - /** - * Params for creating an ed25519 instruction using a public key - */ + if (!status.err) { + _context109.next = 12; + break; + } - var ED25519_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u8('padding'), u16('signatureOffset'), u16('signatureInstructionIndex'), u16('publicKeyOffset'), u16('publicKeyInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u16('messageInstructionIndex')]); + throw new Error("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); - var Ed25519Program = /*#__PURE__*/function () { - /** - * @internal - */ - function Ed25519Program() { - _classCallCheck(this, Ed25519Program); - } - /** - * Public key that identifies the ed25519 program - */ + case 12: + return _context109.abrupt("return", signature); - /** - * Create an ed25519 instruction with a public key and signature. The - * public key must be a buffer that is 32 bytes long, and the signature - * must be a buffer of 64 bytes. - */ + case 13: + case "end": + return _context109.stop(); + } + }, _callee109); + })); + return _sendAndConfirmRawTransaction.apply(this, arguments); + } + + var LAMPORTS_PER_SOL = 1000000000; + + var index_browser_esm = /*#__PURE__*/Object.freeze({ + __proto__: null, + Account: Account, + AddressLookupTableAccount: AddressLookupTableAccount, + AddressLookupTableInstruction: AddressLookupTableInstruction, + AddressLookupTableProgram: AddressLookupTableProgram, + Authorized: Authorized, + BLOCKHASH_CACHE_TIMEOUT_MS: BLOCKHASH_CACHE_TIMEOUT_MS, + BPF_LOADER_DEPRECATED_PROGRAM_ID: BPF_LOADER_DEPRECATED_PROGRAM_ID, + BPF_LOADER_PROGRAM_ID: BPF_LOADER_PROGRAM_ID, + BpfLoader: BpfLoader, + COMPUTE_BUDGET_INSTRUCTION_LAYOUTS: COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, + ComputeBudgetInstruction: ComputeBudgetInstruction, + ComputeBudgetProgram: ComputeBudgetProgram, + Connection: Connection, + Ed25519Program: Ed25519Program, + Enum: Enum, + EpochSchedule: EpochSchedule, + FeeCalculatorLayout: FeeCalculatorLayout, + Keypair: Keypair, + LAMPORTS_PER_SOL: LAMPORTS_PER_SOL, + LOOKUP_TABLE_INSTRUCTION_LAYOUTS: LOOKUP_TABLE_INSTRUCTION_LAYOUTS, + Loader: Loader, + Lockup: Lockup, + MAX_SEED_LENGTH: MAX_SEED_LENGTH, + Message: Message, + MessageAccountKeys: MessageAccountKeys, + MessageV0: MessageV0, + NONCE_ACCOUNT_LENGTH: NONCE_ACCOUNT_LENGTH, + NonceAccount: NonceAccount, + PACKET_DATA_SIZE: PACKET_DATA_SIZE, + PUBLIC_KEY_LENGTH: PUBLIC_KEY_LENGTH, + PublicKey: PublicKey, + SIGNATURE_LENGTH_IN_BYTES: SIGNATURE_LENGTH_IN_BYTES, + SOLANA_SCHEMA: SOLANA_SCHEMA, + STAKE_CONFIG_ID: STAKE_CONFIG_ID, + STAKE_INSTRUCTION_LAYOUTS: STAKE_INSTRUCTION_LAYOUTS, + SYSTEM_INSTRUCTION_LAYOUTS: SYSTEM_INSTRUCTION_LAYOUTS, + SYSVAR_CLOCK_PUBKEY: SYSVAR_CLOCK_PUBKEY, + SYSVAR_EPOCH_SCHEDULE_PUBKEY: SYSVAR_EPOCH_SCHEDULE_PUBKEY, + SYSVAR_INSTRUCTIONS_PUBKEY: SYSVAR_INSTRUCTIONS_PUBKEY, + SYSVAR_RECENT_BLOCKHASHES_PUBKEY: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + SYSVAR_RENT_PUBKEY: SYSVAR_RENT_PUBKEY, + SYSVAR_REWARDS_PUBKEY: SYSVAR_REWARDS_PUBKEY, + SYSVAR_SLOT_HASHES_PUBKEY: SYSVAR_SLOT_HASHES_PUBKEY, + SYSVAR_SLOT_HISTORY_PUBKEY: SYSVAR_SLOT_HISTORY_PUBKEY, + SYSVAR_STAKE_HISTORY_PUBKEY: SYSVAR_STAKE_HISTORY_PUBKEY, + Secp256k1Program: Secp256k1Program, + SendTransactionError: SendTransactionError, + SolanaJSONRPCError: SolanaJSONRPCError, + SolanaJSONRPCErrorCode: SolanaJSONRPCErrorCode, + StakeAuthorizationLayout: StakeAuthorizationLayout, + StakeInstruction: StakeInstruction, + StakeProgram: StakeProgram, + Struct: Struct, + SystemInstruction: SystemInstruction, + SystemProgram: SystemProgram, + Transaction: Transaction, + TransactionExpiredBlockheightExceededError: TransactionExpiredBlockheightExceededError, + TransactionExpiredNonceInvalidError: TransactionExpiredNonceInvalidError, + TransactionExpiredTimeoutError: TransactionExpiredTimeoutError, + TransactionInstruction: TransactionInstruction, + TransactionMessage: TransactionMessage, + get TransactionStatus () { return TransactionStatus; }, + VALIDATOR_INFO_KEY: VALIDATOR_INFO_KEY, + VERSION_PREFIX_MASK: VERSION_PREFIX_MASK, + VOTE_PROGRAM_ID: VOTE_PROGRAM_ID, + ValidatorInfo: ValidatorInfo, + VersionedMessage: VersionedMessage, + VersionedTransaction: VersionedTransaction, + VoteAccount: VoteAccount, + VoteAuthorizationLayout: VoteAuthorizationLayout, + VoteInit: VoteInit, + VoteInstruction: VoteInstruction, + VoteProgram: VoteProgram, + clusterApiUrl: clusterApiUrl, + sendAndConfirmRawTransaction: sendAndConfirmRawTransaction, + sendAndConfirmTransaction: sendAndConfirmTransaction + }); + var require$$1 = /*@__PURE__*/getAugmentedNamespace(index_browser_esm); - _createClass(Ed25519Program, null, [{ - key: "createInstructionWithPublicKey", - value: function createInstructionWithPublicKey(params) { - var publicKey = params.publicKey, - message = params.message, - signature = params.signature, - instructionIndex = params.instructionIndex; - assert(publicKey.length === PUBLIC_KEY_BYTES$1, "Public Key must be ".concat(PUBLIC_KEY_BYTES$1, " bytes but received ").concat(publicKey.length, " bytes")); - assert(signature.length === SIGNATURE_BYTES, "Signature must be ".concat(SIGNATURE_BYTES, " bytes but received ").concat(signature.length, " bytes")); - var publicKeyOffset = ED25519_INSTRUCTION_LAYOUT.span; - var signatureOffset = publicKeyOffset + publicKey.length; - var messageDataOffset = signatureOffset + signature.length; - var numSignatures = 1; - var instructionData = Buffer$1.alloc(messageDataOffset + message.length); - var index = instructionIndex == null ? 0xffff // An index of `u16::MAX` makes it default to the current instruction. - : instructionIndex; - ED25519_INSTRUCTION_LAYOUT.encode({ - numSignatures: numSignatures, - padding: 0, - signatureOffset: signatureOffset, - signatureInstructionIndex: index, - publicKeyOffset: publicKeyOffset, - publicKeyInstructionIndex: index, - messageDataOffset: messageDataOffset, - messageDataSize: message.length, - messageInstructionIndex: index - }, instructionData); - instructionData.fill(publicKey, publicKeyOffset); - instructionData.fill(signature, signatureOffset); - instructionData.fill(message, messageDataOffset); - return new TransactionInstruction({ - keys: [], - programId: Ed25519Program.programId, - data: instructionData - }); - } - /** - * Create an ed25519 instruction with a private key. The private key - * must be a buffer that is 64 bytes long. - */ + var cjs = {}; - }, { - key: "createInstructionWithPrivateKey", - value: function createInstructionWithPrivateKey(params) { - var privateKey = params.privateKey, - message = params.message, - instructionIndex = params.instructionIndex; - assert(privateKey.length === PRIVATE_KEY_BYTES$1, "Private key must be ".concat(PRIVATE_KEY_BYTES$1, " bytes but received ").concat(privateKey.length, " bytes")); + Object.defineProperty(cjs, '__esModule', { + value: true + }); // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ + + var SolanaMobileWalletAdapterErrorCode = { + ERROR_ASSOCIATION_PORT_OUT_OF_RANGE: 'ERROR_ASSOCIATION_PORT_OUT_OF_RANGE', + ERROR_FORBIDDEN_WALLET_BASE_URL: 'ERROR_FORBIDDEN_WALLET_BASE_URL', + ERROR_SECURE_CONTEXT_REQUIRED: 'ERROR_SECURE_CONTEXT_REQUIRED', + ERROR_SESSION_CLOSED: 'ERROR_SESSION_CLOSED', + ERROR_SESSION_TIMEOUT: 'ERROR_SESSION_TIMEOUT', + ERROR_WALLET_NOT_FOUND: 'ERROR_WALLET_NOT_FOUND' + }; - try { - var keypair = Keypair.fromSecretKey(privateKey); + var SolanaMobileWalletAdapterError = /*#__PURE__*/function (_Error) { + _inherits(SolanaMobileWalletAdapterError, _Error); - var _publicKey2 = keypair.publicKey.toBytes(); + var _super = _createSuper(SolanaMobileWalletAdapterError); - var _signature5 = _sign(message, keypair.secretKey); + function SolanaMobileWalletAdapterError() { + var _this; - return this.createInstructionWithPublicKey({ - publicKey: _publicKey2, - message: message, - signature: _signature5, - instructionIndex: instructionIndex - }); - } catch (error) { - throw new Error("Error creating instruction; ".concat(error)); - } - } - }]); + _classCallCheck(this, SolanaMobileWalletAdapterError); - return Ed25519Program; - }(); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - Ed25519Program.programId = new PublicKey('Ed25519SigVerify111111111111111111111111111'); // Supply a synchronous hashing algorithm to make this - // library interoperable with the synchronous APIs in web3.js. + var code = args[0], + message = args[1], + data = args[2]; + _this = _super.call(this, message); + _this.code = code; + _this.data = data; + _this.name = 'SolanaMobileWalletAdapterError'; + return _this; + } - utils.hmacSha256Sync = function (key) { - var h = hmac.create(sha256, key); + return _createClass(SolanaMobileWalletAdapterError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - for (var _len8 = arguments.length, msgs = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) { - msgs[_key8 - 1] = arguments[_key8]; - } - msgs.forEach(function (msg) { - return h.update(msg); - }); - return h.digest(); + var SolanaMobileWalletAdapterProtocolErrorCode = { + // Keep these in sync with `mobilewalletadapter/common/ProtocolContract.java`. + ERROR_AUTHORIZATION_FAILED: -1, + ERROR_INVALID_PAYLOADS: -2, + ERROR_NOT_SIGNED: -3, + ERROR_NOT_SUBMITTED: -4, + ERROR_TOO_MANY_PAYLOADS: -5, + ERROR_ATTEST_ORIGIN_ANDROID: -100 }; - var ecdsaSign = function ecdsaSign(msgHash, privKey) { - return signSync(msgHash, privKey, { - der: false, - recovered: true - }); - }; + var SolanaMobileWalletAdapterProtocolError = /*#__PURE__*/function (_Error2) { + _inherits(SolanaMobileWalletAdapterProtocolError, _Error2); - utils.isValidPrivateKey; - var publicKeyCreate = getPublicKey$1; - var PRIVATE_KEY_BYTES = 32; - var ETHEREUM_ADDRESS_BYTES = 20; - var PUBLIC_KEY_BYTES = 64; - var SIGNATURE_OFFSETS_SERIALIZED_SIZE = 11; - /** - * Params for creating an secp256k1 instruction using a public key - */ + var _super2 = _createSuper(SolanaMobileWalletAdapterProtocolError); - var SECP256K1_INSTRUCTION_LAYOUT = struct([u8('numSignatures'), u16('signatureOffset'), u8('signatureInstructionIndex'), u16('ethAddressOffset'), u8('ethAddressInstructionIndex'), u16('messageDataOffset'), u16('messageDataSize'), u8('messageInstructionIndex'), blob$1(20, 'ethAddress'), blob$1(64, 'signature'), u8('recoveryId')]); + function SolanaMobileWalletAdapterProtocolError() { + var _this2; - var Secp256k1Program = /*#__PURE__*/function () { - /** - * @internal - */ - function Secp256k1Program() { - _classCallCheck(this, Secp256k1Program); - } - /** - * Public key that identifies the secp256k1 program - */ + _classCallCheck(this, SolanaMobileWalletAdapterProtocolError); - /** - * Construct an Ethereum address from a secp256k1 public key buffer. - * @param {Buffer} publicKey a 64 byte secp256k1 public key buffer - */ + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var jsonRpcMessageId = args[0], + code = args[1], + message = args[2], + data = args[3]; + _this2 = _super2.call(this, message); + _this2.code = code; + _this2.data = data; + _this2.jsonRpcMessageId = jsonRpcMessageId; + _this2.name = 'SolanaMobileWalletAdapterProtocolError'; + return _this2; + } - _createClass(Secp256k1Program, null, [{ - key: "publicKeyToEthAddress", - value: function publicKeyToEthAddress(publicKey) { - assert(publicKey.length === PUBLIC_KEY_BYTES, "Public key must be ".concat(PUBLIC_KEY_BYTES, " bytes but received ").concat(publicKey.length, " bytes")); + return _createClass(SolanaMobileWalletAdapterProtocolError); + }( /*#__PURE__*/_wrapNativeSuper(Error)); + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + + + function __awaiter$1(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { - return Buffer$1.from(keccak_256(toBuffer(publicKey))).slice(-ETHEREUM_ADDRESS_BYTES); - } catch (error) { - throw new Error("Error constructing Ethereum address: ".concat(error)); + step(generator.next(value)); + } catch (e) { + reject(e); } } - /** - * Create an secp256k1 instruction with a public key. The public key - * must be a buffer that is 64 bytes long. - */ - - }, { - key: "createInstructionWithPublicKey", - value: function createInstructionWithPublicKey(params) { - var publicKey = params.publicKey, - message = params.message, - signature = params.signature, - recoveryId = params.recoveryId, - instructionIndex = params.instructionIndex; - return Secp256k1Program.createInstructionWithEthAddress({ - ethAddress: Secp256k1Program.publicKeyToEthAddress(publicKey), - message: message, - signature: signature, - recoveryId: recoveryId, - instructionIndex: instructionIndex - }); - } - /** - * Create an secp256k1 instruction with an Ethereum address. The address - * must be a hex string or a buffer that is 20 bytes long. - */ - - }, { - key: "createInstructionWithEthAddress", - value: function createInstructionWithEthAddress(params) { - var rawAddress = params.ethAddress, - message = params.message, - signature = params.signature, - recoveryId = params.recoveryId, - _params$instructionIn = params.instructionIndex, - instructionIndex = _params$instructionIn === void 0 ? 0 : _params$instructionIn; - var ethAddress; - if (typeof rawAddress === 'string') { - if (rawAddress.startsWith('0x')) { - ethAddress = Buffer$1.from(rawAddress.substr(2), 'hex'); - } else { - ethAddress = Buffer$1.from(rawAddress, 'hex'); - } - } else { - ethAddress = rawAddress; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - - assert(ethAddress.length === ETHEREUM_ADDRESS_BYTES, "Address must be ".concat(ETHEREUM_ADDRESS_BYTES, " bytes but received ").concat(ethAddress.length, " bytes")); - var dataStart = 1 + SIGNATURE_OFFSETS_SERIALIZED_SIZE; - var ethAddressOffset = dataStart; - var signatureOffset = dataStart + ethAddress.length; - var messageDataOffset = signatureOffset + signature.length + 1; - var numSignatures = 1; - var instructionData = Buffer$1.alloc(SECP256K1_INSTRUCTION_LAYOUT.span + message.length); - SECP256K1_INSTRUCTION_LAYOUT.encode({ - numSignatures: numSignatures, - signatureOffset: signatureOffset, - signatureInstructionIndex: instructionIndex, - ethAddressOffset: ethAddressOffset, - ethAddressInstructionIndex: instructionIndex, - messageDataOffset: messageDataOffset, - messageDataSize: message.length, - messageInstructionIndex: instructionIndex, - signature: toBuffer(signature), - ethAddress: toBuffer(ethAddress), - recoveryId: recoveryId - }, instructionData); - instructionData.fill(toBuffer(message), SECP256K1_INSTRUCTION_LAYOUT.span); - return new TransactionInstruction({ - keys: [], - programId: Secp256k1Program.programId, - data: instructionData - }); } - /** - * Create an secp256k1 instruction with a private key. The private key - * must be a buffer that is 32 bytes long. - */ - - }, { - key: "createInstructionWithPrivateKey", - value: function createInstructionWithPrivateKey(params) { - var pkey = params.privateKey, - message = params.message, - instructionIndex = params.instructionIndex; - assert(pkey.length === PRIVATE_KEY_BYTES, "Private key must be ".concat(PRIVATE_KEY_BYTES, " bytes but received ").concat(pkey.length, " bytes")); - try { - var privateKey = toBuffer(pkey); + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } - var _publicKey3 = publicKeyCreate(privateKey, false - /* isCompressed */ - ).slice(1); // throw away leading byte + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function createHelloReq(ecdhPublicKey, associationKeypairPrivateKey) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var publicKeyBuffer, signatureBuffer, response; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return crypto.subtle.exportKey('raw', ecdhPublicKey); - var messageHash = Buffer$1.from(keccak_256(toBuffer(message))); + case 2: + publicKeyBuffer = _context.sent; + _context.next = 5; + return crypto.subtle.sign({ + hash: 'SHA-256', + name: 'ECDSA' + }, associationKeypairPrivateKey, publicKeyBuffer); - var _ecdsaSign3 = ecdsaSign(messageHash, privateKey), - _ecdsaSign4 = _slicedToArray(_ecdsaSign3, 2), - _signature6 = _ecdsaSign4[0], - recoveryId = _ecdsaSign4[1]; + case 5: + signatureBuffer = _context.sent; + response = new Uint8Array(publicKeyBuffer.byteLength + signatureBuffer.byteLength); + response.set(new Uint8Array(publicKeyBuffer), 0); + response.set(new Uint8Array(signatureBuffer), publicKeyBuffer.byteLength); + return _context.abrupt("return", response); - return this.createInstructionWithPublicKey({ - publicKey: _publicKey3, - message: message, - signature: _signature6, - recoveryId: recoveryId, - instructionIndex: instructionIndex - }); - } catch (error) { - throw new Error("Error creating instruction; ".concat(error)); + case 10: + case "end": + return _context.stop(); } - } - }]); - - return Secp256k1Program; - }(); + }, _callee); + })); + } - Secp256k1Program.programId = new PublicKey('KeccakSecp256k11111111111111111111111111111'); - /** - * Address of the stake config account which configures the rate - * of stake warmup and cooldown as well as the slashing penalty. - */ + var SEQUENCE_NUMBER_BYTES = 4; - var STAKE_CONFIG_ID = new PublicKey('StakeConfig11111111111111111111111111111111'); - /** - * Stake account authority info - */ + function createSequenceNumberVector(sequenceNumber) { + if (sequenceNumber >= 4294967296) { + throw new Error('Outbound sequence number overflow. The maximum sequence number is 32-bytes.'); + } - var Authorized = /*#__PURE__*/_createClass( - /** stake authority */ + var byteArray = new ArrayBuffer(SEQUENCE_NUMBER_BYTES); + var view = new DataView(byteArray); + view.setUint32(0, sequenceNumber, + /* littleEndian */ + false); + return new Uint8Array(byteArray); + } - /** withdraw authority */ + function generateAssociationKeypair() { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return crypto.subtle.generateKey({ + name: 'ECDSA', + namedCurve: 'P-256' + }, false + /* extractable */ + , ['sign'] + /* keyUsages */ + ); - /** - * Create a new Authorized object - * @param staker the stake authority - * @param withdrawer the withdraw authority - */ - function Authorized(staker, withdrawer) { - _classCallCheck(this, Authorized); + case 2: + return _context2.abrupt("return", _context2.sent); - this.staker = void 0; - this.withdrawer = void 0; - this.staker = staker; - this.withdrawer = withdrawer; - }); - /** - * Stake account lockup info - */ + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } + function generateECDHKeypair() { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return crypto.subtle.generateKey({ + name: 'ECDH', + namedCurve: 'P-256' + }, false + /* extractable */ + , ['deriveKey', 'deriveBits'] + /* keyUsages */ + ); - var Lockup = /*#__PURE__*/_createClass( - /** Unix timestamp of lockup expiration */ + case 2: + return _context3.abrupt("return", _context3.sent); - /** Epoch of lockup expiration */ + case 3: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + } - /** Lockup custodian authority */ + var INITIALIZATION_VECTOR_BYTES = 12; - /** - * Create a new Lockup object - */ - function Lockup(unixTimestamp, epoch, custodian) { - _classCallCheck(this, Lockup); + function encryptJsonRpcMessage(jsonRpcMessage, sharedSecret) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var plaintext, sequenceNumberVector, initializationVector, ciphertext, response; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + plaintext = JSON.stringify(jsonRpcMessage); + sequenceNumberVector = createSequenceNumberVector(jsonRpcMessage.id); + initializationVector = new Uint8Array(INITIALIZATION_VECTOR_BYTES); + crypto.getRandomValues(initializationVector); + _context4.next = 6; + return crypto.subtle.encrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, new TextEncoder().encode(plaintext)); + + case 6: + ciphertext = _context4.sent; + response = new Uint8Array(sequenceNumberVector.byteLength + initializationVector.byteLength + ciphertext.byteLength); + response.set(new Uint8Array(sequenceNumberVector), 0); + response.set(new Uint8Array(initializationVector), sequenceNumberVector.byteLength); + response.set(new Uint8Array(ciphertext), sequenceNumberVector.byteLength + initializationVector.byteLength); + return _context4.abrupt("return", response); - this.unixTimestamp = void 0; - this.epoch = void 0; - this.custodian = void 0; - this.unixTimestamp = unixTimestamp; - this.epoch = epoch; - this.custodian = custodian; + case 12: + case "end": + return _context4.stop(); + } + }, _callee4); + })); } - /** - * Default, inactive Lockup value - */ - ); - Lockup["default"] = new Lockup(0, 0, PublicKey["default"]); - /** - * Stake Instruction class - */ + function decryptJsonRpcMessage(message, sharedSecret) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { + var sequenceNumberVector, initializationVector, ciphertext, plaintextBuffer, plaintext, jsonRpcMessage; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + sequenceNumberVector = message.slice(0, SEQUENCE_NUMBER_BYTES); + initializationVector = message.slice(SEQUENCE_NUMBER_BYTES, SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES); + ciphertext = message.slice(SEQUENCE_NUMBER_BYTES + INITIALIZATION_VECTOR_BYTES); + _context5.next = 5; + return crypto.subtle.decrypt(getAlgorithmParams(sequenceNumberVector, initializationVector), sharedSecret, ciphertext); - var StakeInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function StakeInstruction() { - _classCallCheck(this, StakeInstruction); - } - /** - * Decode a stake instruction and retrieve the instruction type. - */ + case 5: + plaintextBuffer = _context5.sent; + plaintext = getUtf8Decoder().decode(plaintextBuffer); + jsonRpcMessage = JSON.parse(plaintext); + if (!Object.hasOwnProperty.call(jsonRpcMessage, 'error')) { + _context5.next = 10; + break; + } - _createClass(StakeInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; + throw new SolanaMobileWalletAdapterProtocolError(jsonRpcMessage.id, jsonRpcMessage.error.code, jsonRpcMessage.error.message); - for (var _i12 = 0, _Object$entries4 = Object.entries(STAKE_INSTRUCTION_LAYOUTS); _i12 < _Object$entries4.length; _i12++) { - var _Object$entries4$_i2 = _slicedToArray(_Object$entries4[_i12], 2), - ixType = _Object$entries4$_i2[0], - layout = _Object$entries4$_i2[1]; + case 10: + return _context5.abrupt("return", jsonRpcMessage); - if (layout.index == typeIndex) { - type = ixType; - break; - } + case 11: + case "end": + return _context5.stop(); } + }, _callee5); + })); + } - if (!type) { - throw new Error('Instruction type incorrect; not a StakeInstruction'); - } + function getAlgorithmParams(sequenceNumber, initializationVector) { + return { + additionalData: sequenceNumber, + iv: initializationVector, + name: 'AES-GCM', + tagLength: 128 // 16 byte tag => 128 bits - return type; - } - /** - * Decode a initialize stake instruction and retrieve the instruction params. - */ + }; + } - }, { - key: "decodeInitialize", - value: function decodeInitialize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + var _utf8Decoder; - var _decodeData$18 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Initialize, instruction.data), - authorized = _decodeData$18.authorized, - lockup = _decodeData$18.lockup; + function getUtf8Decoder() { + if (_utf8Decoder === undefined) { + _utf8Decoder = new TextDecoder('utf-8'); + } - return { - stakePubkey: instruction.keys[0].pubkey, - authorized: new Authorized(new PublicKey(authorized.staker), new PublicKey(authorized.withdrawer)), - lockup: new Lockup(lockup.unixTimestamp, lockup.epoch, new PublicKey(lockup.custodian)) - }; - } - /** - * Decode a delegate stake instruction and retrieve the instruction params. - */ + return _utf8Decoder; + } - }, { - key: "decodeDelegate", - value: function decodeDelegate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 6); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Delegate, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - votePubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[5].pubkey - }; - } - /** - * Decode an authorize stake instruction and retrieve the instruction params. - */ + function parseHelloRsp(payloadBuffer, // The X9.62-encoded wallet endpoint ephemeral ECDH public keypoint. + associationPublicKey, ecdhPrivateKey) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() { + var _yield$Promise$all, _yield$Promise$all2, associationPublicKeyBuffer, walletPublicKey, sharedSecret, ecdhSecretKey, aesKeyMaterialVal; - }, { - key: "decodeAuthorize", - value: function decodeAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return Promise.all([crypto.subtle.exportKey('raw', associationPublicKey), crypto.subtle.importKey('raw', payloadBuffer, { + name: 'ECDH', + namedCurve: 'P-256' + }, false + /* extractable */ + , [] + /* keyUsages */ + )]); - var _decodeData$19 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), - newAuthorized = _decodeData$19.newAuthorized, - stakeAuthorizationType = _decodeData$19.stakeAuthorizationType; + case 2: + _yield$Promise$all = _context6.sent; + _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2); + associationPublicKeyBuffer = _yield$Promise$all2[0]; + walletPublicKey = _yield$Promise$all2[1]; + _context6.next = 8; + return crypto.subtle.deriveBits({ + name: 'ECDH', + "public": walletPublicKey + }, ecdhPrivateKey, 256); + + case 8: + sharedSecret = _context6.sent; + _context6.next = 11; + return crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false + /* extractable */ + , ['deriveKey'] + /* keyUsages */ + ); + + case 11: + ecdhSecretKey = _context6.sent; + _context6.next = 14; + return crypto.subtle.deriveKey({ + name: 'HKDF', + hash: 'SHA-256', + salt: new Uint8Array(associationPublicKeyBuffer), + info: new Uint8Array() + }, ecdhSecretKey, { + name: 'AES-GCM', + length: 128 + }, false + /* extractable */ + , ['encrypt', 'decrypt']); - var o = { - stakePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - newAuthorizedPubkey: new PublicKey(newAuthorized), - stakeAuthorizationType: { - index: stakeAuthorizationType - } - }; + case 14: + aesKeyMaterialVal = _context6.sent; + return _context6.abrupt("return", aesKeyMaterialVal); - if (instruction.keys.length > 3) { - o.custodianPubkey = instruction.keys[3].pubkey; + case 16: + case "end": + return _context6.stop(); } + }, _callee6); + })); + } - return o; - } - /** - * Decode an authorize-with-seed stake instruction and retrieve the instruction params. - */ + function getRandomAssociationPort() { + return assertAssociationPort(49152 + Math.floor(Math.random() * (65535 - 49152 + 1))); + } - }, { - key: "decodeAuthorizeWithSeed", - value: function decodeAuthorizeWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 2); + function assertAssociationPort(port) { + if (port < 49152 || port > 65535) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_PORT_OUT_OF_RANGE, "Association port number must be between 49152 and 65535. ".concat(port, " given."), { + port: port + }); + } - var _decodeData$20 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), - newAuthorized = _decodeData$20.newAuthorized, - stakeAuthorizationType = _decodeData$20.stakeAuthorizationType, - authoritySeed = _decodeData$20.authoritySeed, - authorityOwner = _decodeData$20.authorityOwner; + return port; + } // https://stackoverflow.com/a/9458996/802047 - var o = { - stakePubkey: instruction.keys[0].pubkey, - authorityBase: instruction.keys[1].pubkey, - authoritySeed: authoritySeed, - authorityOwner: new PublicKey(authorityOwner), - newAuthorizedPubkey: new PublicKey(newAuthorized), - stakeAuthorizationType: { - index: stakeAuthorizationType - } - }; - if (instruction.keys.length > 3) { - o.custodianPubkey = instruction.keys[3].pubkey; - } + function arrayBufferToBase64String(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var len = bytes.byteLength; - return o; - } - /** - * Decode a split stake instruction and retrieve the instruction params. - */ + for (var ii = 0; ii < len; ii++) { + binary += String.fromCharCode(bytes[ii]); + } - }, { - key: "decodeSplit", - value: function decodeSplit(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + return window.btoa(binary); + } - var _decodeData$21 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Split, instruction.data), - lamports = _decodeData$21.lamports; + function getStringWithURLUnsafeCharactersReplaced(unsafeBase64EncodedString) { + return unsafeBase64EncodedString.replace(/[/+=]/g, function (m) { + return { + '/': '_', + '+': '-', + '=': '.' + }[m]; + }); + } - return { - stakePubkey: instruction.keys[0].pubkey, - splitStakePubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - lamports: lamports - }; - } - /** - * Decode a merge stake instruction and retrieve the instruction params. - */ + var INTENT_NAME = 'solana-wallet'; - }, { - key: "decodeMerge", - value: function decodeMerge(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Merge, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - sourceStakePubKey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey - }; - } - /** - * Decode a withdraw stake instruction and retrieve the instruction params. - */ + function getPathParts(pathString) { + return pathString // Strip leading and trailing slashes + .replace(/(^\/+|\/+$)/g, '') // Return an array of directories + .split('/'); + } - }, { - key: "decodeWithdraw", - value: function decodeWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 5); + function getIntentURL(methodPathname, intentUrlBase) { + var baseUrl = null; + + if (intentUrlBase) { + try { + baseUrl = new URL(intentUrlBase); + } catch (_a) {} // eslint-disable-line no-empty + + + if ((baseUrl === null || baseUrl === void 0 ? void 0 : baseUrl.protocol) !== 'https:') { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs'); + } + } - var _decodeData$22 = decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), - lamports = _decodeData$22.lamports; + baseUrl || (baseUrl = new URL("".concat(INTENT_NAME, ":/"))); + var pathname = methodPathname.startsWith('/') ? // Method is an absolute path. Replace it wholesale. + methodPathname : // Method is a relative path. Merge it with the existing one. + [].concat(_toConsumableArray(getPathParts(baseUrl.pathname)), _toConsumableArray(getPathParts(methodPathname))).join('/'); + return new URL(pathname, baseUrl); + } - var o = { - stakePubkey: instruction.keys[0].pubkey, - toPubkey: instruction.keys[1].pubkey, - authorizedPubkey: instruction.keys[4].pubkey, - lamports: lamports - }; + function getAssociateAndroidIntentURL(associationPublicKey, putativePort, associationURLBase) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() { + var associationPort, exportedKey, encodedKey, url; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + associationPort = assertAssociationPort(putativePort); + _context7.next = 3; + return crypto.subtle.exportKey('raw', associationPublicKey); - if (instruction.keys.length > 5) { - o.custodianPubkey = instruction.keys[5].pubkey; + case 3: + exportedKey = _context7.sent; + encodedKey = arrayBufferToBase64String(exportedKey); + url = getIntentURL('v1/associate/local', associationURLBase); + url.searchParams.set('association', getStringWithURLUnsafeCharactersReplaced(encodedKey)); + url.searchParams.set('port', "".concat(associationPort)); + return _context7.abrupt("return", url); + + case 9: + case "end": + return _context7.stop(); } + }, _callee7); + })); + } // Typescript `enums` thwart tree-shaking. See https://bargsten.org/jsts/enums/ - return o; - } - /** - * Decode a deactivate stake instruction and retrieve the instruction params. - */ - }, { - key: "decodeDeactivate", - value: function decodeDeactivate(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); - decodeData$1(STAKE_INSTRUCTION_LAYOUTS.Deactivate, instruction.data); - return { - stakePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey - }; - } - /** - * @internal - */ + var Browser = { + Firefox: 0, + Other: 1 + }; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(StakeProgram.programId)) { - throw new Error('invalid instruction; programId is not StakeProgram'); - } + function getBrowser() { + return navigator.userAgent.indexOf('Firefox/') !== -1 ? Browser.Firefox : Browser.Other; + } + + function getDetectionPromise() { + // Chrome and others silently fail if a custom protocol is not supported. + // For these, we wait to see if the browser is navigated away from in + // a reasonable amount of time (ie. the native wallet opened). + return new Promise(function (resolve, reject) { + function cleanup() { + clearTimeout(timeoutId); + window.removeEventListener('blur', handleBlur); } - /** - * @internal - */ - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } + function handleBlur() { + cleanup(); + resolve(); } - }]); - return StakeInstruction; - }(); - /** - * An enumeration of valid StakeInstructionType's - */ + window.addEventListener('blur', handleBlur); + var timeoutId = setTimeout(function () { + cleanup(); + reject(); + }, 2000); + }); + } - /** - * An enumeration of valid stake InstructionType's - * @internal - */ + var _frame = null; + function launchUrlThroughHiddenFrame(url) { + if (_frame == null) { + _frame = document.createElement('iframe'); + _frame.style.display = 'none'; + document.body.appendChild(_frame); + } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - var STAKE_INSTRUCTION_LAYOUTS = Object.freeze({ - Initialize: { - index: 0, - layout: struct([u32('instruction'), authorized(), lockup()]) - }, - Authorize: { - index: 1, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType')]) - }, - Delegate: { - index: 2, - layout: struct([u32('instruction')]) - }, - Split: { - index: 3, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - Withdraw: { - index: 4, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - Deactivate: { - index: 5, - layout: struct([u32('instruction')]) - }, - Merge: { - index: 7, - layout: struct([u32('instruction')]) - }, - AuthorizeWithSeed: { - index: 8, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('stakeAuthorizationType'), rustString('authoritySeed'), publicKey('authorityOwner')]) - } - }); - /** - * Stake authorization type - */ - /** - * An enumeration of valid StakeAuthorizationLayout's - */ + _frame.contentWindow.location.href = url.toString(); + } - var StakeAuthorizationLayout = Object.freeze({ - Staker: { - index: 0 - }, - Withdrawer: { - index: 1 - } - }); - /** - * Factory class for transactions to interact with the Stake program - */ + function startSession(associationPublicKey, associationURLBase) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { + var randomAssociationPort, associationUrl, browser, detectionPromise; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + randomAssociationPort = getRandomAssociationPort(); + _context8.next = 3; + return getAssociateAndroidIntentURL(associationPublicKey, randomAssociationPort, associationURLBase); - var StakeProgram = /*#__PURE__*/function () { + case 3: + associationUrl = _context8.sent; + + if (!(associationUrl.protocol === 'https:')) { + _context8.next = 8; + break; + } + + // The association URL is an Android 'App Link' or iOS 'Universal Link'. + // These are regular web URLs that are designed to launch an app if it + // is installed or load the actual target webpage if not. + window.location.assign(associationUrl); + _context8.next = 26; + break; + + case 8: + _context8.prev = 8; + browser = getBrowser(); + _context8.t0 = browser; + _context8.next = _context8.t0 === Browser.Firefox ? 13 : _context8.t0 === Browser.Other ? 15 : 20; + break; + + case 13: + // If a custom protocol is not supported in Firefox, it throws. + launchUrlThroughHiddenFrame(associationUrl); // If we reached this line, it's supported. + + return _context8.abrupt("break", 21); + + case 15: + detectionPromise = getDetectionPromise(); + window.location.assign(associationUrl); + _context8.next = 19; + return detectionPromise; + + case 19: + return _context8.abrupt("break", 21); + + case 20: + + case 21: + _context8.next = 26; + break; + + case 23: + _context8.prev = 23; + _context8.t1 = _context8["catch"](8); + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_WALLET_NOT_FOUND, 'Found no installed wallet that supports the mobile wallet protocol.'); + + case 26: + return _context8.abrupt("return", randomAssociationPort); + + case 27: + case "end": + return _context8.stop(); + } + }, _callee8, null, [[8, 23]]); + })); + } + + var WEBSOCKET_CONNECTION_CONFIG = { /** - * @internal + * 300 milliseconds is a generally accepted threshold for what someone + * would consider an acceptable response time for a user interface + * after having performed a low-attention tapping task. We set the initial + * interval at which we wait for the wallet to set up the websocket at + * half this, as per the Nyquist frequency, with a progressive backoff + * sequence from there. The total wait time is 30s, which allows for the + * user to be presented with a disambiguation dialog, select a wallet, and + * for the wallet app to subsequently start. */ - function StakeProgram() { - _classCallCheck(this, StakeProgram); + retryDelayScheduleMs: [150, 150, 200, 500, 500, 750, 750, 1000], + timeoutMs: 30000 + }; + var WEBSOCKET_PROTOCOL = 'com.solana.mobilewalletadapter.v1'; + + function assertSecureContext() { + if (typeof window === 'undefined' || window.isSecureContext !== true) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SECURE_CONTEXT_REQUIRED, 'The mobile wallet adapter protocol must be used in a secure context (`https`).'); } - /** - * Public key that identifies the Stake program - */ + } - /** - * Generate an Initialize instruction to add to a Stake Create transaction - */ + function assertSecureEndpointSpecificURI(walletUriBase) { + var url; + try { + url = new URL(walletUriBase); + } catch (_a) { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Invalid base URL supplied by wallet'); + } - _createClass(StakeProgram, null, [{ - key: "initialize", - value: function initialize(params) { - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - maybeLockup = params.lockup; - var lockup = maybeLockup || Lockup["default"]; - var type = STAKE_INSTRUCTION_LAYOUTS.Initialize; - var data = encodeData(type, { - authorized: { - staker: toBuffer(authorized.staker.toBuffer()), - withdrawer: toBuffer(authorized.withdrawer.toBuffer()) - }, - lockup: { - unixTimestamp: lockup.unixTimestamp, - epoch: lockup.epoch, - custodian: toBuffer(lockup.custodian.toBuffer()) - } - }); - var instructionData = { - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a Transaction that creates a new Stake account at - * an address generated with `from`, a seed, and the Stake programId - */ + if (url.protocol !== 'https:') { + throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_FORBIDDEN_WALLET_BASE_URL, 'Base URLs supplied by wallets must be valid `https` URLs'); + } + } - }, { - key: "createAccountWithSeed", - value: function createAccountWithSeed(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccountWithSeed({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.stakePubkey, - basePubkey: params.basePubkey, - seed: params.seed, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - lockup = params.lockup; - return transaction.add(this.initialize({ - stakePubkey: stakePubkey, - authorized: authorized, - lockup: lockup - })); - } - /** - * Generate a Transaction that creates a new Stake account - */ + function getSequenceNumberFromByteArray(byteArray) { + var view = new DataView(byteArray); + return view.getUint32(0, + /* littleEndian */ + false); + } - }, { - key: "createAccount", - value: function createAccount(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.stakePubkey, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - var stakePubkey = params.stakePubkey, - authorized = params.authorized, - lockup = params.lockup; - return transaction.add(this.initialize({ - stakePubkey: stakePubkey, - authorized: authorized, - lockup: lockup - })); - } - /** - * Generate a Transaction that delegates Stake tokens to a validator - * Vote PublicKey. This transaction can also be used to redelegate Stake - * to a new validator Vote PublicKey. - */ + function transact$2(callback, config) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() { + var _this3 = this; - }, { - key: "delegate", - value: function delegate(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - votePubkey = params.votePubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Delegate; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: votePubkey, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: STAKE_CONFIG_ID, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that authorizes a new PublicKey as Staker - * or Withdrawer on the Stake account. - */ + var associationKeypair, sessionPort, websocketURL, connectionStartTime, getNextRetryDelayMs, nextJsonRpcMessageId, lastKnownInboundSequenceNumber, state; + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + assertSecureContext(); + _context13.next = 3; + return generateAssociationKeypair(); - }, { - key: "authorize", - value: function authorize(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - newAuthorizedPubkey = params.newAuthorizedPubkey, - stakeAuthorizationType = params.stakeAuthorizationType, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Authorize; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - stakeAuthorizationType: stakeAuthorizationType.index - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; + case 3: + associationKeypair = _context13.sent; + _context13.next = 6; + return startSession(associationKeypair.publicKey, config === null || config === void 0 ? void 0 : config.baseUri); - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + case 6: + sessionPort = _context13.sent; + websocketURL = "ws://localhost:".concat(sessionPort, "/solana-wallet"); - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that authorizes a new PublicKey as Staker - * or Withdrawer on the Stake account. - */ + getNextRetryDelayMs = function () { + var schedule = _toConsumableArray(WEBSOCKET_CONNECTION_CONFIG.retryDelayScheduleMs); - }, { - key: "authorizeWithSeed", - value: function authorizeWithSeed(params) { - var stakePubkey = params.stakePubkey, - authorityBase = params.authorityBase, - authoritySeed = params.authoritySeed, - authorityOwner = params.authorityOwner, - newAuthorizedPubkey = params.newAuthorizedPubkey, - stakeAuthorizationType = params.stakeAuthorizationType, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - stakeAuthorizationType: stakeAuthorizationType.index, - authoritySeed: authoritySeed, - authorityOwner: toBuffer(authorityOwner.toBuffer()) - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorityBase, - isSigner: true, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }]; + return function () { + return schedule.length > 1 ? schedule.shift() : schedule[0]; + }; + }(); - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + nextJsonRpcMessageId = 1; + lastKnownInboundSequenceNumber = 0; + state = { + __type: 'disconnected' + }; + return _context13.abrupt("return", new Promise(function (resolve, reject) { + var socket; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * @internal - */ + var jsonRpcResponsePromises = {}; - }, { - key: "splitInstruction", - value: function splitInstruction(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - splitStakePubkey = params.splitStakePubkey, - lamports = params.lamports; - var type = STAKE_INSTRUCTION_LAYOUTS.Split; - var data = encodeData(type, { - lamports: lamports - }); - return new TransactionInstruction({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: splitStakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that splits Stake tokens into another stake account - */ + var handleOpen = function handleOpen() { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() { + var _state, associationKeypair, ecdhKeypair; - }, { - key: "split", - value: function split(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.authorizedPubkey, - newAccountPubkey: params.splitStakePubkey, - lamports: 0, - space: this.space, - programId: this.programId - })); - return transaction.add(this.splitInstruction(params)); - } - /** - * Generate a Transaction that splits Stake tokens into another account - * derived from a base public key and seed - */ + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (!(state.__type !== 'connecting')) { + _context9.next = 3; + break; + } - }, { - key: "splitWithSeed", - value: function splitWithSeed(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - splitStakePubkey = params.splitStakePubkey, - basePubkey = params.basePubkey, - seed = params.seed, - lamports = params.lamports; - var transaction = new Transaction(); - transaction.add(SystemProgram.allocate({ - accountPubkey: splitStakePubkey, - basePubkey: basePubkey, - seed: seed, - space: this.space, - programId: this.programId - })); - return transaction.add(this.splitInstruction({ - stakePubkey: stakePubkey, - authorizedPubkey: authorizedPubkey, - splitStakePubkey: splitStakePubkey, - lamports: lamports - })); - } - /** - * Generate a Transaction that merges Stake accounts. - */ + console.warn('Expected adapter state to be `connecting` at the moment the websocket opens. ' + "Got `".concat(state.__type, "`.")); + return _context9.abrupt("return"); - }, { - key: "merge", - value: function merge(params) { - var stakePubkey = params.stakePubkey, - sourceStakePubKey = params.sourceStakePubKey, - authorizedPubkey = params.authorizedPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Merge; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: sourceStakePubKey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that withdraws deactivated Stake tokens. - */ + case 3: + _state = state, associationKeypair = _state.associationKeypair; + socket.removeEventListener('open', handleOpen); + _context9.next = 7; + return generateECDHKeypair(); + + case 7: + ecdhKeypair = _context9.sent; + _context9.t0 = socket; + _context9.next = 11; + return createHelloReq(ecdhKeypair.publicKey, associationKeypair.privateKey); + + case 11: + _context9.t1 = _context9.sent; + + _context9.t0.send.call(_context9.t0, _context9.t1); + + state = { + __type: 'hello_req_sent', + associationPublicKey: associationKeypair.publicKey, + ecdhPrivateKey: ecdhKeypair.privateKey + }; + + case 14: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + }; - }, { - key: "withdraw", - value: function withdraw(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey, - toPubkey = params.toPubkey, - lamports = params.lamports, - custodianPubkey = params.custodianPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Withdraw; - var data = encodeData(type, { - lamports: lamports - }); - var keys = [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_STAKE_HISTORY_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; + var handleClose = function handleClose(evt) { + if (evt.wasClean) { + state = { + __type: 'disconnected' + }; + } else { + reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_CLOSED, "The wallet session dropped unexpectedly (".concat(evt.code, ": ").concat(evt.reason, ")."), { + closeEvent: evt + })); + } - if (custodianPubkey) { - keys.push({ - pubkey: custodianPubkey, - isSigner: false, - isWritable: false - }); - } + disposeSocket(); + }; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a Transaction that deactivates Stake tokens. - */ + var handleError = function handleError(_evt) { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + disposeSocket(); - }, { - key: "deactivate", - value: function deactivate(params) { - var stakePubkey = params.stakePubkey, - authorizedPubkey = params.authorizedPubkey; - var type = STAKE_INSTRUCTION_LAYOUTS.Deactivate; - var data = encodeData(type); - return new Transaction().add({ - keys: [{ - pubkey: stakePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }); - } - }]); + if (!(Date.now() - connectionStartTime >= WEBSOCKET_CONNECTION_CONFIG.timeoutMs)) { + _context10.next = 5; + break; + } - return StakeProgram; - }(); + reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_SESSION_TIMEOUT, "Failed to connect to the wallet websocket on port ".concat(sessionPort, "."))); + _context10.next = 8; + break; - StakeProgram.programId = new PublicKey('Stake11111111111111111111111111111111111111'); - StakeProgram.space = 200; - /** - * Vote account info - */ + case 5: + _context10.next = 7; + return new Promise(function (resolve) { + var retryDelayMs = getNextRetryDelayMs(); + retryWaitTimeoutId = window.setTimeout(resolve, retryDelayMs); + }); - var VoteInit = /*#__PURE__*/_createClass( - /** [0, 100] */ - function VoteInit(nodePubkey, authorizedVoter, authorizedWithdrawer, commission) { - _classCallCheck(this, VoteInit); + case 7: + attemptSocketConnection(); - this.nodePubkey = void 0; - this.authorizedVoter = void 0; - this.authorizedWithdrawer = void 0; - this.commission = void 0; - this.nodePubkey = nodePubkey; - this.authorizedVoter = authorizedVoter; - this.authorizedWithdrawer = authorizedWithdrawer; - this.commission = commission; - }); - /** - * Create vote account transaction params - */ + case 8: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + }; - /** - * Vote Instruction class - */ + var handleMessage = function handleMessage(evt) { + return __awaiter$1(_this3, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() { + var responseBuffer, sequenceNumberVector, sequenceNumber, jsonRpcMessage, responsePromise, _responsePromise, sharedSecret, wallet; + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return evt.data.arrayBuffer(); - var VoteInstruction = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteInstruction() { - _classCallCheck(this, VoteInstruction); - } - /** - * Decode a vote instruction and retrieve the instruction type. - */ + case 2: + responseBuffer = _context12.sent; + _context12.t0 = state.__type; + _context12.next = _context12.t0 === 'connected' ? 6 : _context12.t0 === 'hello_req_sent' ? 30 : 51; + break; + case 6: + _context12.prev = 6; + sequenceNumberVector = responseBuffer.slice(0, SEQUENCE_NUMBER_BYTES); + sequenceNumber = getSequenceNumberFromByteArray(sequenceNumberVector); - _createClass(VoteInstruction, null, [{ - key: "decodeInstructionType", - value: function decodeInstructionType(instruction) { - this.checkProgramId(instruction.programId); - var instructionTypeLayout = u32('instruction'); - var typeIndex = instructionTypeLayout.decode(instruction.data); - var type; + if (!(sequenceNumber !== lastKnownInboundSequenceNumber + 1)) { + _context12.next = 11; + break; + } - for (var _i13 = 0, _Object$entries5 = Object.entries(VOTE_INSTRUCTION_LAYOUTS); _i13 < _Object$entries5.length; _i13++) { - var _Object$entries5$_i2 = _slicedToArray(_Object$entries5[_i13], 2), - ixType = _Object$entries5$_i2[0], - layout = _Object$entries5$_i2[1]; + throw new Error('Encrypted message has invalid sequence number'); - if (layout.index == typeIndex) { - type = ixType; - break; - } - } + case 11: + lastKnownInboundSequenceNumber = sequenceNumber; + _context12.next = 14; + return decryptJsonRpcMessage(responseBuffer, state.sharedSecret); - if (!type) { - throw new Error('Instruction type incorrect; not a VoteInstruction'); - } + case 14: + jsonRpcMessage = _context12.sent; + responsePromise = jsonRpcResponsePromises[jsonRpcMessage.id]; + delete jsonRpcResponsePromises[jsonRpcMessage.id]; + responsePromise.resolve(jsonRpcMessage.result); + _context12.next = 29; + break; - return type; - } - /** - * Decode an initialize vote instruction and retrieve the instruction params. - */ + case 20: + _context12.prev = 20; + _context12.t1 = _context12["catch"](6); - }, { - key: "decodeInitializeAccount", - value: function decodeInitializeAccount(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 4); + if (!(_context12.t1 instanceof SolanaMobileWalletAdapterProtocolError)) { + _context12.next = 28; + break; + } - var _decodeData$23 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.InitializeAccount, instruction.data), - voteInit = _decodeData$23.voteInit; + _responsePromise = jsonRpcResponsePromises[_context12.t1.jsonRpcMessageId]; + delete jsonRpcResponsePromises[_context12.t1.jsonRpcMessageId]; - return { - votePubkey: instruction.keys[0].pubkey, - nodePubkey: instruction.keys[3].pubkey, - voteInit: new VoteInit(new PublicKey(voteInit.nodePubkey), new PublicKey(voteInit.authorizedVoter), new PublicKey(voteInit.authorizedWithdrawer), voteInit.commission) - }; - } - /** - * Decode an authorize instruction and retrieve the instruction params. - */ + _responsePromise.reject(_context12.t1); - }, { - key: "decodeAuthorize", - value: function decodeAuthorize(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + _context12.next = 29; + break; - var _decodeData$24 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Authorize, instruction.data), - newAuthorized = _decodeData$24.newAuthorized, - voteAuthorizationType = _decodeData$24.voteAuthorizationType; + case 28: + throw _context12.t1; + + case 29: + return _context12.abrupt("break", 51); + + case 30: + _context12.next = 32; + return parseHelloRsp(responseBuffer, state.associationPublicKey, state.ecdhPrivateKey); + + case 32: + sharedSecret = _context12.sent; + state = { + __type: 'connected', + sharedSecret: sharedSecret + }; + wallet = new Proxy({}, { + get: function get(target, p) { + if (target[p] == null) { + var method = p.toString().replace(/[A-Z]/g, function (letter) { + return "_".concat(letter.toLowerCase()); + }).toLowerCase(); + + target[p] = function (params) { + return __awaiter$1(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() { + var id; + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + id = nextJsonRpcMessageId++; + _context11.t0 = socket; + _context11.next = 4; + return encryptJsonRpcMessage({ + id: id, + jsonrpc: '2.0', + method: method, + params: params !== null && params !== void 0 ? params : {} + }, sharedSecret); + + case 4: + _context11.t1 = _context11.sent; + + _context11.t0.send.call(_context11.t0, _context11.t1); + + return _context11.abrupt("return", new Promise(function (_resolve, reject) { + jsonRpcResponsePromises[id] = { + resolve: function resolve(result) { + switch (p) { + case 'authorize': + case 'reauthorize': + { + var wallet_uri_base = result.wallet_uri_base; + + if (wallet_uri_base != null) { + try { + assertSecureEndpointSpecificURI(wallet_uri_base); + } catch (e) { + reject(e); + return; + } + } + + break; + } + } + + _resolve(result); + }, + reject: reject + }; + })); + + case 7: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + }; + } + + return target[p]; + }, + defineProperty: function defineProperty() { + return false; + }, + deleteProperty: function deleteProperty() { + return false; + } + }); + _context12.prev = 35; + _context12.t2 = resolve; + _context12.next = 39; + return callback(wallet); + + case 39: + _context12.t3 = _context12.sent; + (0, _context12.t2)(_context12.t3); + _context12.next = 46; + break; - return { - votePubkey: instruction.keys[0].pubkey, - authorizedPubkey: instruction.keys[2].pubkey, - newAuthorizedPubkey: new PublicKey(newAuthorized), - voteAuthorizationType: { - index: voteAuthorizationType - } - }; - } - /** - * Decode an authorize instruction and retrieve the instruction params. - */ + case 43: + _context12.prev = 43; + _context12.t4 = _context12["catch"](35); + reject(_context12.t4); - }, { - key: "decodeAuthorizeWithSeed", - value: function decodeAuthorizeWithSeed(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + case 46: + _context12.prev = 46; + disposeSocket(); + socket.close(); + return _context12.finish(46); - var _decodeData$25 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed, instruction.data), - _decodeData$25$voteAu = _decodeData$25.voteAuthorizeWithSeedArgs, - currentAuthorityDerivedKeyOwnerPubkey = _decodeData$25$voteAu.currentAuthorityDerivedKeyOwnerPubkey, - currentAuthorityDerivedKeySeed = _decodeData$25$voteAu.currentAuthorityDerivedKeySeed, - newAuthorized = _decodeData$25$voteAu.newAuthorized, - voteAuthorizationType = _decodeData$25$voteAu.voteAuthorizationType; + case 50: + return _context12.abrupt("break", 51); - return { - currentAuthorityDerivedKeyBasePubkey: instruction.keys[2].pubkey, - currentAuthorityDerivedKeyOwnerPubkey: new PublicKey(currentAuthorityDerivedKeyOwnerPubkey), - currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, - newAuthorizedPubkey: new PublicKey(newAuthorized), - voteAuthorizationType: { - index: voteAuthorizationType - }, - votePubkey: instruction.keys[0].pubkey - }; - } - /** - * Decode a withdraw instruction and retrieve the instruction params. - */ + case 51: + case "end": + return _context12.stop(); + } + }, _callee12, null, [[6, 20], [35, 43, 46, 50]]); + })); + }; - }, { - key: "decodeWithdraw", - value: function decodeWithdraw(instruction) { - this.checkProgramId(instruction.programId); - this.checkKeyLength(instruction.keys, 3); + var disposeSocket; + var retryWaitTimeoutId; - var _decodeData$26 = decodeData$1(VOTE_INSTRUCTION_LAYOUTS.Withdraw, instruction.data), - lamports = _decodeData$26.lamports; + var attemptSocketConnection = function attemptSocketConnection() { + if (disposeSocket) { + disposeSocket(); + } - return { - votePubkey: instruction.keys[0].pubkey, - authorizedWithdrawerPubkey: instruction.keys[2].pubkey, - lamports: lamports, - toPubkey: instruction.keys[1].pubkey - }; - } - /** - * @internal - */ + state = { + __type: 'connecting', + associationKeypair: associationKeypair + }; - }, { - key: "checkProgramId", - value: function checkProgramId(programId) { - if (!programId.equals(VoteProgram.programId)) { - throw new Error('invalid instruction; programId is not VoteProgram'); - } - } - /** - * @internal - */ + if (connectionStartTime === undefined) { + connectionStartTime = Date.now(); + } - }, { - key: "checkKeyLength", - value: function checkKeyLength(keys, expectedLength) { - if (keys.length < expectedLength) { - throw new Error("invalid instruction; found ".concat(keys.length, " keys, expected at least ").concat(expectedLength)); - } - } - }]); + socket = new WebSocket(websocketURL, [WEBSOCKET_PROTOCOL]); + socket.addEventListener('open', handleOpen); + socket.addEventListener('close', handleClose); + socket.addEventListener('error', handleError); + socket.addEventListener('message', handleMessage); + + disposeSocket = function disposeSocket() { + window.clearTimeout(retryWaitTimeoutId); + socket.removeEventListener('open', handleOpen); + socket.removeEventListener('close', handleClose); + socket.removeEventListener('error', handleError); + socket.removeEventListener('message', handleMessage); + }; + }; - return VoteInstruction; - }(); - /** - * An enumeration of valid VoteInstructionType's - */ + attemptSocketConnection(); + })); + case 13: + case "end": + return _context13.stop(); + } + }, _callee13); + })); + } - var VOTE_INSTRUCTION_LAYOUTS = Object.freeze({ - InitializeAccount: { - index: 0, - layout: struct([u32('instruction'), voteInit()]) - }, - Authorize: { - index: 1, - layout: struct([u32('instruction'), publicKey('newAuthorized'), u32('voteAuthorizationType')]) - }, - Withdraw: { - index: 3, - layout: struct([u32('instruction'), ns64('lamports')]) - }, - AuthorizeWithSeed: { - index: 10, - layout: struct([u32('instruction'), voteAuthorizeWithSeedArgs()]) - } - }); - /** - * VoteAuthorize type - */ + cjs.SolanaMobileWalletAdapterError = SolanaMobileWalletAdapterError; + cjs.SolanaMobileWalletAdapterErrorCode = SolanaMobileWalletAdapterErrorCode; + cjs.SolanaMobileWalletAdapterProtocolError = SolanaMobileWalletAdapterProtocolError; + cjs.SolanaMobileWalletAdapterProtocolErrorCode = SolanaMobileWalletAdapterProtocolErrorCode; + cjs.transact = transact$2; - /** - * An enumeration of valid VoteAuthorization layouts. - */ + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - var VoteAuthorizationLayout = Object.freeze({ - Voter: { - index: 0 - }, - Withdrawer: { - index: 1 - } - }); - /** - * Factory class for transactions to interact with the Vote program - */ - var VoteProgram = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteProgram() { - _classCallCheck(this, VoteProgram); + function base(ALPHABET) { + if (ALPHABET.length >= 255) { + throw new TypeError('Alphabet too long'); } - /** - * Public key that identifies the Vote program - */ - - /** - * Generate an Initialize instruction. - */ + var BASE_MAP = new Uint8Array(256); - _createClass(VoteProgram, null, [{ - key: "initializeAccount", - value: function initializeAccount(params) { - var votePubkey = params.votePubkey, - nodePubkey = params.nodePubkey, - voteInit = params.voteInit; - var type = VOTE_INSTRUCTION_LAYOUTS.InitializeAccount; - var data = encodeData(type, { - voteInit: { - nodePubkey: toBuffer(voteInit.nodePubkey.toBuffer()), - authorizedVoter: toBuffer(voteInit.authorizedVoter.toBuffer()), - authorizedWithdrawer: toBuffer(voteInit.authorizedWithdrawer.toBuffer()), - commission: voteInit.commission - } - }); - var instructionData = { - keys: [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_RENT_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: nodePubkey, - isSigner: true, - isWritable: false - }], - programId: this.programId, - data: data - }; - return new TransactionInstruction(instructionData); - } - /** - * Generate a transaction that creates a new Vote account. - */ + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } - }, { - key: "createAccount", - value: function createAccount(params) { - var transaction = new Transaction(); - transaction.add(SystemProgram.createAccount({ - fromPubkey: params.fromPubkey, - newAccountPubkey: params.votePubkey, - lamports: params.lamports, - space: this.space, - programId: this.programId - })); - return transaction.add(this.initializeAccount({ - votePubkey: params.votePubkey, - nodePubkey: params.voteInit.nodePubkey, - voteInit: params.voteInit - })); - } - /** - * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account. - */ + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); - }, { - key: "authorize", - value: function authorize(params) { - var votePubkey = params.votePubkey, - authorizedPubkey = params.authorizedPubkey, - newAuthorizedPubkey = params.newAuthorizedPubkey, - voteAuthorizationType = params.voteAuthorizationType; - var type = VOTE_INSTRUCTION_LAYOUTS.Authorize; - var data = encodeData(type, { - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - voteAuthorizationType: voteAuthorizationType.index - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: authorizedPubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x + ' is ambiguous'); } - /** - * Generate a transaction that authorizes a new Voter or Withdrawer on the Vote account - * where the current Voter or Withdrawer authority is a derived key. - */ - }, { - key: "authorizeWithSeed", - value: function authorizeWithSeed(params) { - var currentAuthorityDerivedKeyBasePubkey = params.currentAuthorityDerivedKeyBasePubkey, - currentAuthorityDerivedKeyOwnerPubkey = params.currentAuthorityDerivedKeyOwnerPubkey, - currentAuthorityDerivedKeySeed = params.currentAuthorityDerivedKeySeed, - newAuthorizedPubkey = params.newAuthorizedPubkey, - voteAuthorizationType = params.voteAuthorizationType, - votePubkey = params.votePubkey; - var type = VOTE_INSTRUCTION_LAYOUTS.AuthorizeWithSeed; - var data = encodeData(type, { - voteAuthorizeWithSeedArgs: { - currentAuthorityDerivedKeyOwnerPubkey: toBuffer(currentAuthorityDerivedKeyOwnerPubkey.toBuffer()), - currentAuthorityDerivedKeySeed: currentAuthorityDerivedKeySeed, - newAuthorized: toBuffer(newAuthorizedPubkey.toBuffer()), - voteAuthorizationType: voteAuthorizationType.index - } - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: SYSVAR_CLOCK_PUBKEY, - isSigner: false, - isWritable: false - }, { - pubkey: currentAuthorityDerivedKeyBasePubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction to withdraw from a Vote account. - */ + BASE_MAP[xc] = i; + } - }, { - key: "withdraw", - value: function withdraw(params) { - var votePubkey = params.votePubkey, - authorizedWithdrawerPubkey = params.authorizedWithdrawerPubkey, - lamports = params.lamports, - toPubkey = params.toPubkey; - var type = VOTE_INSTRUCTION_LAYOUTS.Withdraw; - var data = encodeData(type, { - lamports: lamports - }); - var keys = [{ - pubkey: votePubkey, - isSigner: false, - isWritable: true - }, { - pubkey: toPubkey, - isSigner: false, - isWritable: true - }, { - pubkey: authorizedWithdrawerPubkey, - isSigner: true, - isWritable: false - }]; - return new Transaction().add({ - keys: keys, - programId: this.programId, - data: data - }); - } - /** - * Generate a transaction to withdraw safely from a Vote account. - * - * This function was created as a safeguard for vote accounts running validators, `safeWithdraw` - * checks that the withdraw amount will not exceed the specified balance while leaving enough left - * to cover rent. If you wish to close the vote account by withdrawing the full amount, call the - * `withdraw` method directly. - */ + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - }, { - key: "safeWithdraw", - value: function safeWithdraw(params, currentVoteAccountBalance, rentExemptMinimum) { - if (params.lamports > currentVoteAccountBalance - rentExemptMinimum) { - throw new Error('Withdraw will leave vote account with insuffcient funds.'); - } + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - return VoteProgram.withdraw(params); + function encode(source) { + if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); } - }]); - return VoteProgram; - }(); + if (!(source instanceof Uint8Array)) { + throw new TypeError('Expected Uint8Array'); + } - VoteProgram.programId = new PublicKey('Vote111111111111111111111111111111111111111'); - VoteProgram.space = 3731; - var VALIDATOR_INFO_KEY = new PublicKey('Va1idator1nfo111111111111111111111111111111'); - /** - * @internal - */ + if (source.length === 0) { + return ''; + } // Skip & count leading zeroes. - var InfoString = type({ - name: string(), - website: optional(string()), - details: optional(string()), - keybaseUsername: optional(string()) - }); - /** - * ValidatorInfo class - */ - var ValidatorInfo = /*#__PURE__*/function () { - /** - * validator public key - */ + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; - /** - * validator information - */ + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } // Allocate enough space in big-endian base58 representation. - /** - * Construct a valid ValidatorInfo - * - * @param key validator public key - * @param info validator information - */ - function ValidatorInfo(key, info) { - _classCallCheck(this, ValidatorInfo); - this.key = void 0; - this.info = void 0; - this.key = key; - this.info = info; + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); // Process the bytes. + + while (pbegin !== pend) { + var carry = source[pbegin]; // Apply "b58 = b58 * 256 + ch". + + var i = 0; + + for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) { + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE >>> 0; + carry = carry / BASE >>> 0; + } + + if (carry !== 0) { + throw new Error('Non-zero carry'); + } + + length = i; + pbegin++; + } // Skip leading zeroes in base58 result. + + + var it2 = size - length; + + while (it2 !== size && b58[it2] === 0) { + it2++; + } // Translate the result into a string. + + + var str = LEADER.repeat(zeroes); + + for (; it2 < size; ++it2) { + str += ALPHABET.charAt(b58[it2]); + } + + return str; } - /** - * Deserialize ValidatorInfo from the config account data. Exactly two config - * keys are required in the data. - * - * @param buffer config account data - * @return null if info was not found - */ + function decodeUnsafe(source) { + if (typeof source !== 'string') { + throw new TypeError('Expected String'); + } - _createClass(ValidatorInfo, null, [{ - key: "fromConfigData", - value: function fromConfigData(buffer) { - var byteArray = _toConsumableArray(buffer); + if (source.length === 0) { + return new Uint8Array(); + } - var configKeyCount = decodeLength(byteArray); - if (configKeyCount !== 2) return null; - var configKeys = []; + var psz = 0; // Skip and count leading '1's. - for (var i = 0; i < 2; i++) { - var _publicKey4 = new PublicKey(byteArray.slice(0, PUBLIC_KEY_LENGTH)); + var zeroes = 0; + var length = 0; - byteArray = byteArray.slice(PUBLIC_KEY_LENGTH); - var isSigner = byteArray.slice(0, 1)[0] === 1; - byteArray = byteArray.slice(1); - configKeys.push({ - publicKey: _publicKey4, - isSigner: isSigner - }); + while (source[psz] === LEADER) { + zeroes++; + psz++; + } // Allocate enough space in big-endian base256 representation. + + + var size = (source.length - psz) * FACTOR + 1 >>> 0; // log(58) / log(256), rounded up. + + var b256 = new Uint8Array(size); // Process the characters. + + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; // Invalid character + + if (carry === 255) { + return; } - if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) { - if (configKeys[1].isSigner) { - var rawInfo = rustString().decode(Buffer$1.from(byteArray)); - var info = JSON.parse(rawInfo); - _assert(info, InfoString); - return new ValidatorInfo(configKeys[1].publicKey, info); - } + var i = 0; + + for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) { + carry += BASE * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; } - return null; - } - }]); + if (carry !== 0) { + throw new Error('Non-zero carry'); + } - return ValidatorInfo; - }(); + length = i; + psz++; + } // Skip leading zeroes in b256. - var VOTE_PROGRAM_ID = new PublicKey('Vote111111111111111111111111111111111111111'); - /** - * See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88 - * - * @internal - */ - var VoteAccountLayout = struct([publicKey('nodePubkey'), publicKey('authorizedWithdrawer'), u8('commission'), nu64$1(), // votes.length - seq$1(struct([nu64$1('slot'), u32('confirmationCount')]), offset$1(u32(), -8), 'votes'), u8('rootSlotValid'), nu64$1('rootSlot'), nu64$1(), // authorizedVoters.length - seq$1(struct([nu64$1('epoch'), publicKey('authorizedVoter')]), offset$1(u32(), -8), 'authorizedVoters'), struct([seq$1(struct([publicKey('authorizedPubkey'), nu64$1('epochOfLastAuthorizedSwitch'), nu64$1('targetEpoch')]), 32, 'buf'), nu64$1('idx'), u8('isEmpty')], 'priorVoters'), nu64$1(), // epochCredits.length - seq$1(struct([nu64$1('epoch'), nu64$1('credits'), nu64$1('prevCredits')]), offset$1(u32(), -8), 'epochCredits'), struct([nu64$1('slot'), nu64$1('timestamp')], 'lastTimestamp')]); - /** - * VoteAccount class - */ + var it4 = size - length; - var VoteAccount = /*#__PURE__*/function () { - /** - * @internal - */ - function VoteAccount(args) { - _classCallCheck(this, VoteAccount); + while (it4 !== size && b256[it4] === 0) { + it4++; + } - this.nodePubkey = void 0; - this.authorizedWithdrawer = void 0; - this.commission = void 0; - this.rootSlot = void 0; - this.votes = void 0; - this.authorizedVoters = void 0; - this.priorVoters = void 0; - this.epochCredits = void 0; - this.lastTimestamp = void 0; - this.nodePubkey = args.nodePubkey; - this.authorizedWithdrawer = args.authorizedWithdrawer; - this.commission = args.commission; - this.rootSlot = args.rootSlot; - this.votes = args.votes; - this.authorizedVoters = args.authorizedVoters; - this.priorVoters = args.priorVoters; - this.epochCredits = args.epochCredits; - this.lastTimestamp = args.lastTimestamp; - } - /** - * Deserialize VoteAccount from the account data. - * - * @param buffer account data - * @return VoteAccount - */ + var vch = new Uint8Array(zeroes + (size - it4)); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } - _createClass(VoteAccount, null, [{ - key: "fromAccountData", - value: function fromAccountData(buffer) { - var versionOffset = 4; - var va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset); - var rootSlot = va.rootSlot; + return vch; + } - if (!va.rootSlotValid) { - rootSlot = null; - } + function decode(string) { + var buffer = decodeUnsafe(string); - return new VoteAccount({ - nodePubkey: new PublicKey(va.nodePubkey), - authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer), - commission: va.commission, - votes: va.votes, - rootSlot: rootSlot, - authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter), - priorVoters: getPriorVoters(va.priorVoters), - epochCredits: va.epochCredits, - lastTimestamp: va.lastTimestamp - }); + if (buffer) { + return buffer; } - }]); - return VoteAccount; - }(); + throw new Error('Non-base' + BASE + ' character'); + } - function parseAuthorizedVoter(_ref46) { - var authorizedVoter = _ref46.authorizedVoter, - epoch = _ref46.epoch; return { - epoch: epoch, - authorizedVoter: new PublicKey(authorizedVoter) + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode }; } - function parsePriorVoters(_ref47) { - var authorizedPubkey = _ref47.authorizedPubkey, - epochOfLastAuthorizedSwitch = _ref47.epochOfLastAuthorizedSwitch, - targetEpoch = _ref47.targetEpoch; - return { - authorizedPubkey: new PublicKey(authorizedPubkey), - epochOfLastAuthorizedSwitch: epochOfLastAuthorizedSwitch, - targetEpoch: targetEpoch + var src = base; + + var basex = src; + var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + var bs58$1 = basex(ALPHABET); + + Object.defineProperty(cjs$1, '__esModule', { + value: true + }); + var web3_js = require$$1; + var mobileWalletAdapterProtocol = cjs; + var bs58 = bs58$1; + + function _interopDefaultLegacy$1(e) { + return e && _typeof$1(e) === 'object' && 'default' in e ? e : { + 'default': e }; } - function getPriorVoters(_ref48) { - var buf = _ref48.buf, - idx = _ref48.idx, - isEmpty = _ref48.isEmpty; + var bs58__default = /*#__PURE__*/_interopDefaultLegacy$1(bs58); + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ - if (isEmpty) { - return []; - } - return [].concat(_toConsumableArray(buf.slice(idx + 1).map(parsePriorVoters)), _toConsumableArray(buf.slice(0, idx).map(parsePriorVoters))); - } + function __rest(s, e) { + var t = {}; - var endpoint = { - http: { - devnet: 'http://api.devnet.solana.com', - testnet: 'http://api.testnet.solana.com', - 'mainnet-beta': 'http://api.mainnet-beta.solana.com/' - }, - https: { - devnet: 'https://api.devnet.solana.com', - testnet: 'https://api.testnet.solana.com', - 'mainnet-beta': 'https://api.mainnet-beta.solana.com/' - } - }; - /** - * Retrieves the RPC API URL for the specified cluster - */ + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - function clusterApiUrl(cluster, tls) { - var key = tls === false ? 'http' : 'https'; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + } - if (!cluster) { - return endpoint[key]['devnet']; + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); } - var url = endpoint[key][cluster]; + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } - if (!url) { - throw new Error("Unknown ".concat(key, " cluster: ").concat(cluster)); - } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } - return url; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); } - /** - * Send and confirm a raw transaction - * - * If `commitment` option is not specified, defaults to 'max' commitment. - * - * @param {Connection} connection - * @param {Buffer} rawTransaction - * @param {TransactionConfirmationStrategy} confirmationStrategy - * @param {ConfirmOptions} [options] - * @returns {Promise} - */ - /** - * @deprecated Calling `sendAndConfirmRawTransaction()` without a `confirmationStrategy` - * is no longer supported and will be removed in a future version. - */ - // eslint-disable-next-line no-redeclare - // eslint-disable-next-line no-redeclare + function fromUint8Array(byteArray) { + var _String$fromCharCode; + return window.btoa((_String$fromCharCode = String.fromCharCode).call.apply(_String$fromCharCode, [null].concat(_toConsumableArray(byteArray)))); + } - function sendAndConfirmRawTransaction(_x161, _x162, _x163, _x164) { - return _sendAndConfirmRawTransaction.apply(this, arguments); + function toUint8Array(base64EncodedByteArray) { + return new Uint8Array(window.atob(base64EncodedByteArray).split('').map(function (c) { + return c.charCodeAt(0); + })); } - /** - * There are 1-billion lamports in one SOL - */ + function getPayloadFromTransaction(transaction) { + var serializedTransaction = 'version' in transaction ? transaction.serialize() : transaction.serialize({ + requireAllSignatures: false, + verifySignatures: false + }); + var payload = fromUint8Array(serializedTransaction); + return payload; + } - function _sendAndConfirmRawTransaction() { - _sendAndConfirmRawTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee109(connection, rawTransaction, confirmationStrategyOrConfirmOptions, maybeConfirmOptions) { - var confirmationStrategy, options, sendOptions, signature, commitment, confirmationPromise, status; - return _regeneratorRuntime().wrap(function _callee109$(_context109) { - while (1) switch (_context109.prev = _context109.next) { + function getTransactionFromWireMessage(byteArray) { + var numSignatures = byteArray[0]; + var messageOffset = numSignatures * web3_js.SIGNATURE_LENGTH_IN_BYTES + 1; + var version = web3_js.VersionedMessage.deserializeMessageVersion(byteArray.slice(messageOffset, byteArray.length)); + + if (version === 'legacy') { + return web3_js.Transaction.from(byteArray); + } else { + return web3_js.VersionedTransaction.deserialize(byteArray); + } + } + + function transact$1(callback, config) { + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + var augmentedCallback; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { case 0: - if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'lastValidBlockHeight')) { - confirmationStrategy = confirmationStrategyOrConfirmOptions; - options = maybeConfirmOptions; - } else if (confirmationStrategyOrConfirmOptions && Object.prototype.hasOwnProperty.call(confirmationStrategyOrConfirmOptions, 'nonceValue')) { - confirmationStrategy = confirmationStrategyOrConfirmOptions; - options = maybeConfirmOptions; - } else { - options = confirmationStrategyOrConfirmOptions; - } + augmentedCallback = function augmentedCallback(wallet) { + var augmentedAPI = new Proxy({}, { + get: function get(target, p) { + if (target[p] == null) { + switch (p) { + case 'signAndSendTransactions': + target[p] = function (_a) { + var minContextSlot = _a.minContextSlot, + transactions = _a.transactions, + rest = __rest(_a, ["minContextSlot", "transactions"]); + + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var payloads, _yield$wallet$signAnd, base64EncodedSignatures, signatures; + + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + payloads = transactions.map(getPayloadFromTransaction); + _context.next = 3; + return wallet.signAndSendTransactions(Object.assign(Object.assign(Object.assign({}, rest), minContextSlot != null ? { + options: { + min_context_slot: minContextSlot + } + } : null), { + payloads: payloads + })); - sendOptions = options && { - skipPreflight: options.skipPreflight, - preflightCommitment: options.preflightCommitment || options.commitment, - minContextSlot: options.minContextSlot - }; - _context109.next = 4; - return connection.sendRawTransaction(rawTransaction, sendOptions); + case 3: + _yield$wallet$signAnd = _context.sent; + base64EncodedSignatures = _yield$wallet$signAnd.signatures; + signatures = base64EncodedSignatures.map(toUint8Array).map(bs58__default["default"].encode); + return _context.abrupt("return", signatures); - case 4: - signature = _context109.sent; - commitment = options && options.commitment; - confirmationPromise = confirmationStrategy ? connection.confirmTransaction(confirmationStrategy, commitment) : connection.confirmTransaction(signature, commitment); - _context109.next = 9; - return confirmationPromise; + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + }; - case 9: - status = _context109.sent.value; + break; - if (!status.err) { - _context109.next = 12; - break; - } + case 'signMessages': + target[p] = function (_a) { + var payloads = _a.payloads, + rest = __rest(_a, ["payloads"]); - throw new Error("Raw transaction ".concat(signature, " failed (").concat(JSON.stringify(status), ")")); + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var base64EncodedPayloads, _yield$wallet$signMes, base64EncodedSignedMessages, signedMessages; - case 12: - return _context109.abrupt("return", signature); + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + base64EncodedPayloads = payloads.map(fromUint8Array); + _context2.next = 3; + return wallet.signMessages(Object.assign(Object.assign({}, rest), { + payloads: base64EncodedPayloads + })); - case 13: + case 3: + _yield$wallet$signMes = _context2.sent; + base64EncodedSignedMessages = _yield$wallet$signMes.signed_payloads; + signedMessages = base64EncodedSignedMessages.map(toUint8Array); + return _context2.abrupt("return", signedMessages); + + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + }; + + break; + + case 'signTransactions': + target[p] = function (_a) { + var transactions = _a.transactions, + rest = __rest(_a, ["transactions"]); + + return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var payloads, _yield$wallet$signTra, base64EncodedCompiledTransactions, compiledTransactions, signedTransactions; + + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + payloads = transactions.map(getPayloadFromTransaction); + _context3.next = 3; + return wallet.signTransactions(Object.assign(Object.assign({}, rest), { + payloads: payloads + })); + + case 3: + _yield$wallet$signTra = _context3.sent; + base64EncodedCompiledTransactions = _yield$wallet$signTra.signed_payloads; + compiledTransactions = base64EncodedCompiledTransactions.map(toUint8Array); + signedTransactions = compiledTransactions.map(getTransactionFromWireMessage); + return _context3.abrupt("return", signedTransactions); + + case 8: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + }; + + break; + + default: + { + target[p] = wallet[p]; + break; + } + } + } + + return target[p]; + }, + defineProperty: function defineProperty() { + return false; + }, + deleteProperty: function deleteProperty() { + return false; + } + }); + return callback(augmentedAPI); + }; + + _context4.next = 3; + return mobileWalletAdapterProtocol.transact(augmentedCallback, config); + + case 3: + return _context4.abrupt("return", _context4.sent); + + case 4: case "end": - return _context109.stop(); + return _context4.stop(); } - }, _callee109); + }, _callee4); })); - return _sendAndConfirmRawTransaction.apply(this, arguments); } - var LAMPORTS_PER_SOL = 1000000000; - - var index_browser_esm = /*#__PURE__*/Object.freeze({ - __proto__: null, - Account: Account, - AddressLookupTableAccount: AddressLookupTableAccount, - AddressLookupTableInstruction: AddressLookupTableInstruction, - AddressLookupTableProgram: AddressLookupTableProgram, - Authorized: Authorized, - BLOCKHASH_CACHE_TIMEOUT_MS: BLOCKHASH_CACHE_TIMEOUT_MS, - BPF_LOADER_DEPRECATED_PROGRAM_ID: BPF_LOADER_DEPRECATED_PROGRAM_ID, - BPF_LOADER_PROGRAM_ID: BPF_LOADER_PROGRAM_ID, - BpfLoader: BpfLoader, - COMPUTE_BUDGET_INSTRUCTION_LAYOUTS: COMPUTE_BUDGET_INSTRUCTION_LAYOUTS, - ComputeBudgetInstruction: ComputeBudgetInstruction, - ComputeBudgetProgram: ComputeBudgetProgram, - Connection: Connection, - Ed25519Program: Ed25519Program, - Enum: Enum, - EpochSchedule: EpochSchedule, - FeeCalculatorLayout: FeeCalculatorLayout, - Keypair: Keypair, - LAMPORTS_PER_SOL: LAMPORTS_PER_SOL, - LOOKUP_TABLE_INSTRUCTION_LAYOUTS: LOOKUP_TABLE_INSTRUCTION_LAYOUTS, - Loader: Loader, - Lockup: Lockup, - MAX_SEED_LENGTH: MAX_SEED_LENGTH, - Message: Message, - MessageAccountKeys: MessageAccountKeys, - MessageV0: MessageV0, - NONCE_ACCOUNT_LENGTH: NONCE_ACCOUNT_LENGTH, - NonceAccount: NonceAccount, - PACKET_DATA_SIZE: PACKET_DATA_SIZE, - PUBLIC_KEY_LENGTH: PUBLIC_KEY_LENGTH, - PublicKey: PublicKey, - SIGNATURE_LENGTH_IN_BYTES: SIGNATURE_LENGTH_IN_BYTES, - SOLANA_SCHEMA: SOLANA_SCHEMA, - STAKE_CONFIG_ID: STAKE_CONFIG_ID, - STAKE_INSTRUCTION_LAYOUTS: STAKE_INSTRUCTION_LAYOUTS, - SYSTEM_INSTRUCTION_LAYOUTS: SYSTEM_INSTRUCTION_LAYOUTS, - SYSVAR_CLOCK_PUBKEY: SYSVAR_CLOCK_PUBKEY, - SYSVAR_EPOCH_SCHEDULE_PUBKEY: SYSVAR_EPOCH_SCHEDULE_PUBKEY, - SYSVAR_INSTRUCTIONS_PUBKEY: SYSVAR_INSTRUCTIONS_PUBKEY, - SYSVAR_RECENT_BLOCKHASHES_PUBKEY: SYSVAR_RECENT_BLOCKHASHES_PUBKEY, - SYSVAR_RENT_PUBKEY: SYSVAR_RENT_PUBKEY, - SYSVAR_REWARDS_PUBKEY: SYSVAR_REWARDS_PUBKEY, - SYSVAR_SLOT_HASHES_PUBKEY: SYSVAR_SLOT_HASHES_PUBKEY, - SYSVAR_SLOT_HISTORY_PUBKEY: SYSVAR_SLOT_HISTORY_PUBKEY, - SYSVAR_STAKE_HISTORY_PUBKEY: SYSVAR_STAKE_HISTORY_PUBKEY, - Secp256k1Program: Secp256k1Program, - SendTransactionError: SendTransactionError, - SolanaJSONRPCError: SolanaJSONRPCError, - SolanaJSONRPCErrorCode: SolanaJSONRPCErrorCode, - StakeAuthorizationLayout: StakeAuthorizationLayout, - StakeInstruction: StakeInstruction, - StakeProgram: StakeProgram, - Struct: Struct, - SystemInstruction: SystemInstruction, - SystemProgram: SystemProgram, - Transaction: Transaction, - TransactionExpiredBlockheightExceededError: TransactionExpiredBlockheightExceededError, - TransactionExpiredNonceInvalidError: TransactionExpiredNonceInvalidError, - TransactionExpiredTimeoutError: TransactionExpiredTimeoutError, - TransactionInstruction: TransactionInstruction, - TransactionMessage: TransactionMessage, - get TransactionStatus () { return TransactionStatus; }, - VALIDATOR_INFO_KEY: VALIDATOR_INFO_KEY, - VERSION_PREFIX_MASK: VERSION_PREFIX_MASK, - VOTE_PROGRAM_ID: VOTE_PROGRAM_ID, - ValidatorInfo: ValidatorInfo, - VersionedMessage: VersionedMessage, - VersionedTransaction: VersionedTransaction, - VoteAccount: VoteAccount, - VoteAuthorizationLayout: VoteAuthorizationLayout, - VoteInit: VoteInit, - VoteInstruction: VoteInstruction, - VoteProgram: VoteProgram, - clusterApiUrl: clusterApiUrl, - sendAndConfirmRawTransaction: sendAndConfirmRawTransaction, - sendAndConfirmTransaction: sendAndConfirmTransaction - }); + cjs$1.transact = transact$1; var Layout$1 = {}; @@ -36845,8 +38287,6 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// var lib = {}; - var require$$1 = /*@__PURE__*/getAugmentedNamespace(index_browser_esm); - var bn = {exports: {}}; (function (module) { @@ -36904,7 +38344,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { - Buffer = require$$0$1.Buffer; + Buffer = require$$1$1.Buffer; } } catch (e) {} @@ -40669,7 +42109,9 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// exports.map = map; })(lib); - var Buffer = require$$0$1.Buffer; + var Web3MobileWallet = cjs$1.Web3MobileWallet; + var transact = cjs$1.transact; + var Buffer = require$$1$1.Buffer; var BN = bn$1.exports; var ACCOUNT_LAYOUT = lib.struct([lib.publicKey('mint'), lib.publicKey('owner'), lib.u64('amount'), lib.u32('delegateOption'), lib.publicKey('delegate'), lib.u8('state'), lib.u32('isNativeOption'), lib.u64('isNative'), lib.u64('delegatedAmount'), lib.u32('closeAuthorityOption'), lib.publicKey('closeAuthority')]); @@ -40686,6 +42128,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// exports.TransactionInstruction = TransactionInstruction; exports.TransactionMessage = TransactionMessage; exports.VersionedTransaction = VersionedTransaction; + exports.Web3MobileWallet = Web3MobileWallet; exports.array = lib.array; exports.blob = blob; exports.bool = lib.bool; @@ -40704,6 +42147,7 @@ if(_global$1.fetch == undefined) { throw('Please polyfill .fetch | See: https:// exports.str = lib.str; exports.struct = lib.struct; exports.tagged = lib.tagged; + exports.transact = transact; exports.u128 = lib.u128; exports.u16 = lib.u16; exports.u32 = lib.u32; diff --git a/package.json b/package.json index 149bc7f..f9e688c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@depay/solana-web3.js", "moduleName": "SolanaWeb3js", - "version": "1.23.1", + "version": "1.24.0", "description": "Solana Web3.js browser pre-built usable in rollup bundles.", "main": "dist/umd/index.js", "module": "dist/esm/index.js", @@ -34,6 +34,8 @@ "@rollup/plugin-node-resolve": "^13.3.0", "@rollup/plugin-replace": "^4.0.0", "@rollup/plugin-sucrase": "^4.0.4", + "@solana-mobile/mobile-wallet-adapter-protocol": "^2.0.0", + "@solana-mobile/mobile-wallet-adapter-protocol-web3js": "^2.0.0", "@solana/web3.js": "^1.75.0", "bigint-buffer": "^1.1.5", "bn.js": "^5.0.0", diff --git a/src/index.js b/src/index.js index 93466c4..01f7abf 100644 --- a/src/index.js +++ b/src/index.js @@ -18,6 +18,9 @@ import { offset, } from "buffer-layout" +const Web3MobileWallet = require("@solana-mobile/mobile-wallet-adapter-protocol-web3js").Web3MobileWallet +const transact = require("@solana-mobile/mobile-wallet-adapter-protocol-web3js").transact + const Buffer = require('buffer/').Buffer const BN = require('bn.js') @@ -98,4 +101,6 @@ export { Buffer, BN, Keypair, + transact, + Web3MobileWallet, } diff --git a/yarn.lock b/yarn.lock index e08d627..c38f2ae 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1204,6 +1204,20 @@ estree-walker "^2.0.1" picomatch "^2.2.2" +"@solana-mobile/mobile-wallet-adapter-protocol-web3js@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@solana-mobile/mobile-wallet-adapter-protocol-web3js/-/mobile-wallet-adapter-protocol-web3js-2.0.0.tgz#5433705c174f59a177280f85396df051711be09d" + integrity sha512-cMADp/UIAN42QJVCM1oyj1wFM/9DTZNIa5z5eHXUXBksw/bNv2fWkiO+4ZUoQj1P4UoMoZJUBx9+qMVl18sPOA== + dependencies: + "@solana-mobile/mobile-wallet-adapter-protocol" "^2.0.0" + bs58 "^5.0.0" + js-base64 "^3.7.2" + +"@solana-mobile/mobile-wallet-adapter-protocol@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@solana-mobile/mobile-wallet-adapter-protocol/-/mobile-wallet-adapter-protocol-2.0.0.tgz#75a3e8163544f659803260cb1dd7aede6da96b36" + integrity sha512-mLK9B/AQgOxzbdRoOMH3G5wB5akWgGSBoVqIZ/6iDWY37uu/CuyX4lTwRyoRlOb8Cxs/tDwiovIGobkti2qF/w== + "@solana/buffer-layout@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@solana/buffer-layout/-/buffer-layout-4.0.0.tgz#75b1b11adc487234821c81dfae3119b73a5fd734" @@ -1363,6 +1377,11 @@ base-x@^3.0.2: dependencies: safe-buffer "^5.0.1" +base-x@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/base-x/-/base-x-4.0.0.tgz#d0e3b7753450c73f8ad2389b5c018a4af7b2224a" + integrity sha512-FuwxlW4H5kh37X/oW59pwTzzTKRzfrrQwhmyspRM7swOEZcHtDZSCt45U6oKgtuFE+WYPblePMVIPR4RZrh/hw== + base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" @@ -1446,6 +1465,13 @@ bs58@^4.0.0, bs58@^4.0.1: dependencies: base-x "^3.0.2" +bs58@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/bs58/-/bs58-5.0.0.tgz#865575b4d13c09ea2a84622df6c8cbeb54ffc279" + integrity sha512-r+ihvQJvahgYT50JD05dyJNKlmmSlMoOGwn1lCcEzanPglg7TxYjioQUYehQ9mAR/+hOSd2jRc/Z2y5UxBymvQ== + dependencies: + base-x "^4.0.0" + buffer-layout@^1.2.0: version "1.2.2" resolved "https://registry.yarnpkg.com/buffer-layout/-/buffer-layout-1.2.2.tgz#b9814e7c7235783085f9ca4966a0cfff112259d5" @@ -1808,6 +1834,11 @@ jayson@^3.4.4: uuid "^8.3.2" ws "^7.4.5" +js-base64@^3.7.2: + version "3.7.5" + resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-3.7.5.tgz#21e24cf6b886f76d6f5f165bfcd69cc55b9e3fca" + integrity sha512-3MEt5DTINKqfScXKfJFrRbxkrnk2AxPWGBL/ycjz4dK8iqiSJ06UxD8jh8xuh6p10TX4t2+7FsBYVxxQbMg+qA== + js-sha3@^0.8.0: version "0.8.0" resolved "https://registry.yarnpkg.com/js-sha3/-/js-sha3-0.8.0.tgz#b9b7a5da73afad7dedd0f8c463954cbde6818840"