@lightprotocol/stateless.js 0.20.2 → 0.20.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/browser/index.cjs +1 -1
- package/dist/cjs/browser/index.cjs.map +1 -1
- package/dist/cjs/browser/index.d.ts +0 -1
- package/dist/cjs/browser/rpc-interface.d.ts +2 -2
- package/dist/cjs/browser/utils/conversion.d.ts +3 -1
- package/dist/cjs/browser/utils/validation.d.ts +4 -0
- package/dist/cjs/node/index.cjs +1 -1
- package/dist/cjs/node/index.cjs.map +1 -1
- package/dist/cjs/node/index.d.ts +0 -1
- package/dist/cjs/node/rpc-interface.d.ts +2 -2
- package/dist/cjs/node/utils/conversion.d.ts +3 -1
- package/dist/cjs/node/utils/validation.d.ts +4 -0
- package/dist/types/index.d.ts +8 -4
- package/package.json +2 -2
- package/dist/cjs/browser/logger.d.ts +0 -1
- package/dist/cjs/node/logger.d.ts +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../../../../node_modules/.pnpm/bn.js@5.2.1/node_modules/bn.js/lib/bn.js","../../../../../src/state/types.ts","../../../../../src/constants.ts","../../../../../node_modules/.pnpm/bs58@6.0.0/node_modules/bs58/src/esm/index.js","../../../../../node_modules/.pnpm/base-x@5.0.0/node_modules/base-x/src/esm/index.js","../../../../../src/state/BN254.ts","../../../../../src/state/compressed-account.ts","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/_assert.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/_u64.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/utils.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/sha3.js","../../../../../src/utils/conversion.ts","../../../../../src/instruction/pack-compressed-accounts.ts","../../../../../src/utils/validation.ts","../../../../../src/utils/address.ts","../../../../../src/utils/airdrop.ts","../../../../../src/utils/parse-validity-proof.ts","../../../../../src/utils/send-and-confirm.ts","../../../../../src/utils/get-light-state-tree-info.ts","../../../../../node_modules/.pnpm/buffer-layout@1.2.2/node_modules/buffer-layout/lib/Layout.js","../../../../../node_modules/.pnpm/@coral-xyz+borsh@0.29.0_@solana+web3.js@1.98.0_bufferutil@4.0.8_utf-8-validate@5.0.10_/node_modules/@coral-xyz/borsh/dist/index.js","../../../../../src/programs/layout.ts","../../../../../src/programs/system.ts","../../../../../node_modules/.pnpm/superstruct@2.0.2/node_modules/superstruct/dist/index.mjs","../../../../../src/rpc-interface.ts","../../../../../src/rpc.ts","../../../../../src/actions/common.ts","../../../../../src/errors.ts","../../../../../src/test-helpers/merkle-tree/indexed-array.ts","../../../../../src/test-helpers/merkle-tree/merkle-tree.ts","../../../../../src/test-helpers/test-rpc/get-parsed-events.ts","../../../../../src/test-helpers/test-rpc/get-compressed-accounts.ts","../../../../../src/test-helpers/test-rpc/get-compressed-token-accounts.ts","../../../../../src/test-helpers/test-rpc/test-rpc.ts","../../../../../src/test-helpers/test-utils.ts","../../../../../src/idl.ts","../../../../../src/logger.ts","../../../../../src/utils/calculate-compute-unit-price.ts","../../../../../src/actions/compress.ts","../../../../../src/actions/create-account.ts","../../../../../src/actions/decompress.ts","../../../../../src/utils/pipe.ts","../../../../../src/utils/sleep.ts","../../../../../src/actions/transfer.ts"],"sourcesContent":["(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\nimport { PublicKey } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { NewAddressParamsPacked } from '../utils';\n\nexport enum TreeType {\n /**\n * v1 state merkle tree\n */\n State = 0,\n /**\n * v1 address merkle tree\n */\n Address = 1,\n /**\n * v2 state merkle tree\n */\n BatchedState = 2,\n /**\n * v2 address merkle tree\n */\n BatchedAddress = 3,\n}\n\nexport type ActiveTreeBundle = {\n tree: PublicKey;\n queue: PublicKey | null;\n cpiContext: PublicKey | null;\n treeType: TreeType;\n};\n\nexport interface PackedCompressedAccountWithMerkleContext {\n compressedAccount: CompressedAccount;\n merkleContext: PackedMerkleContext;\n rootIndex: number; // u16\n readOnly: boolean;\n}\n\nexport interface PackedMerkleContext {\n merkleTreePubkeyIndex: number; // u8\n nullifierQueuePubkeyIndex: number; // u8\n leafIndex: number; // u32\n queueIndex: null | QueueIndex; // Option<QueueIndex>\n}\n\nexport interface QueueIndex {\n queueId: number; // u8\n index: number; // u16\n}\n\n/**\n * Describe the generic compressed account details applicable to every\n * compressed account.\n * */\nexport interface CompressedAccount {\n /** Public key of program or user that owns the account */\n owner: PublicKey;\n /** Lamports attached to the account */\n lamports: BN; // u64 // FIXME: optional\n /**\n * TODO: use PublicKey. Optional unique account ID that is persistent across\n * transactions.\n */\n address: number[] | null; // Option<PublicKey>\n /** Optional data attached to the account */\n data: CompressedAccountData | null; // Option<CompressedAccountData>\n}\n\n/**\n * Describe the generic compressed account details applicable to every\n * compressed account.\n * */\nexport interface OutputCompressedAccountWithPackedContext {\n compressedAccount: CompressedAccount;\n merkleTreeIndex: number;\n}\n\nexport interface CompressedAccountData {\n discriminator: number[]; // [u8; 8] // TODO: test with uint8Array instead\n data: Buffer; // bytes\n dataHash: number[]; // [u8; 32]\n}\nexport interface MerkleTreeSequenceNumber {\n pubkey: PublicKey;\n seq: BN;\n}\n\nexport interface PublicTransactionEvent {\n inputCompressedAccountHashes: number[][]; // Vec<[u8; 32]>\n outputCompressedAccountHashes: number[][]; // Vec<[u8; 32]>\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n outputLeafIndices: number[]; // Vec<u32>\n sequenceNumbers: MerkleTreeSequenceNumber[]; // Vec<MerkleTreeSequenceNumber>\n relayFee: BN | null; // Option<u64>\n isCompress: boolean; // bool\n compressOrDecompressLamports: BN | null; // Option<u64>\n pubkeyArray: PublicKey[]; // Vec<PublicKey>\n message: Uint8Array | null; // Option<bytes>\n}\n\nexport interface InstructionDataInvoke {\n proof: CompressedProof | null; // Option<CompressedProof>\n inputCompressedAccountsWithMerkleContext: PackedCompressedAccountWithMerkleContext[];\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n relayFee: BN | null; // Option<u64>\n newAddressParams: NewAddressParamsPacked[]; // Vec<NewAddressParamsPacked>\n compressOrDecompressLamports: BN | null; // Option<u64>\n isCompress: boolean; // bool\n}\n\nexport interface InstructionDataInvokeCpi {\n proof: CompressedProof | null; // Option<CompressedProof>\n inputCompressedAccountsWithMerkleContext: PackedCompressedAccountWithMerkleContext[];\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n relayFee: BN | null; // Option<u64>\n newAddressParams: NewAddressParamsPacked[]; // Vec<NewAddressParamsPacked>\n compressOrDecompressLamports: BN | null; // Option<u64>\n isCompress: boolean; // bool\n compressedCpiContext: CompressedCpiContext | null;\n}\n\nexport interface CompressedCpiContext {\n /// Is set by the program that is invoking the CPI to signal that is should\n /// set the cpi context.\n set_context: boolean;\n /// Is set to wipe the cpi context since someone could have set it before\n /// with unrelated data.\n first_set_context: boolean;\n /// Index of cpi context account in remaining accounts.\n cpi_context_account_index: number;\n}\n\nexport interface CompressedProof {\n a: number[]; // [u8; 32]\n b: number[]; // [u8; 64]\n c: number[]; // [u8; 32]\n}\n\nexport interface InputTokenDataWithContext {\n amount: BN;\n delegateIndex: number | null; // Option<u8>\n merkleContext: PackedMerkleContext;\n rootIndex: number; // u16\n lamports: BN | null;\n tlv: Buffer | null;\n}\nexport type TokenData = {\n /// The mint associated with this account\n mint: PublicKey;\n /// The owner of this account.\n owner: PublicKey;\n /// The amount of tokens this account holds.\n amount: BN;\n /// If `delegate` is `Some` then `delegated_amount` represents\n /// the amount authorized by the delegate\n delegate: PublicKey | null;\n /// The account's state\n state: number; // AccountState_IdlType;\n /// TokenExtension tlv\n tlv: Buffer | null;\n};\n","import BN from 'bn.js';\nimport { Buffer } from 'buffer';\nimport { ConfirmOptions, PublicKey } from '@solana/web3.js';\nimport { ActiveTreeBundle, TreeType } from './state/types';\n\nexport const FIELD_SIZE = new BN(\n '21888242871839275222246405745257275088548364400416034343698204186575808495617',\n);\nexport const HIGHEST_ADDRESS_PLUS_ONE = new BN(\n '452312848583266388373324160190187140051835877600158453279131187530910662655',\n);\n\nexport const COMPUTE_BUDGET_PATTERN = [2, 64, 66, 15, 0];\n\nexport const INVOKE_DISCRIMINATOR = Buffer.from([\n 26, 16, 169, 7, 21, 202, 242, 25,\n]);\n\nexport const INVOKE_CPI_DISCRIMINATOR = Buffer.from([\n 49, 212, 191, 129, 39, 194, 43, 196,\n]);\n\nexport const INSERT_INTO_QUEUES_DISCRIMINATOR = Buffer.from([\n 180, 143, 159, 153, 35, 46, 248, 163,\n]);\n\n// TODO: implement properly\nexport const noopProgram = 'noopb9bkMVfRPU8AsbpTUg8AQkHtKwMYZiFUjNRtMmV';\nexport const lightProgram = 'SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7';\nexport const accountCompressionProgram = // also: merkletree program\n 'compr6CUsB5m2jS4Y3831ztGSTnDpnKJTKS95d64XVq';\n\nexport const getRegisteredProgramPda = () =>\n new PublicKey('35hkDgaAKwMCaxRz2ocSZ6NaUrtKkyNqU6c4RV3tYJRh'); // TODO: better labelling. gov authority pda\n\nexport const getAccountCompressionAuthority = () =>\n PublicKey.findProgramAddressSync(\n [Buffer.from('cpi_authority')],\n new PublicKey(\n // TODO: can add check to ensure its consistent with the idl\n lightProgram,\n ),\n )[0];\n\nexport const defaultStaticAccounts = () => [\n new PublicKey(getRegisteredProgramPda()),\n new PublicKey(noopProgram),\n new PublicKey(accountCompressionProgram),\n new PublicKey(getAccountCompressionAuthority()),\n];\nexport const defaultStaticAccountsStruct = () => {\n return {\n registeredProgramPda: new PublicKey(getRegisteredProgramPda()),\n noopProgram: new PublicKey(noopProgram),\n accountCompressionProgram: new PublicKey(accountCompressionProgram),\n accountCompressionAuthority: new PublicKey(\n getAccountCompressionAuthority(),\n ),\n cpiSignatureAccount: null,\n };\n};\n\nexport type StateTreeLUTPair = {\n stateTreeLookupTable: PublicKey;\n nullifyTable: PublicKey;\n};\n\n/**\n * Returns the Default Public State Tree LUTs for Devnet and Mainnet-Beta.\n */\nexport const defaultStateTreeLookupTables = (): {\n mainnet: StateTreeLUTPair[];\n devnet: StateTreeLUTPair[];\n} => {\n return {\n mainnet: [\n {\n stateTreeLookupTable: new PublicKey(\n stateTreeLookupTableMainnet,\n ),\n nullifyTable: new PublicKey(\n nullifiedStateTreeLookupTableMainnet,\n ),\n },\n ],\n devnet: [\n {\n stateTreeLookupTable: new PublicKey(stateTreeLookupTableDevnet),\n nullifyTable: new PublicKey(\n nullifiedStateTreeLookupTableDevnet,\n ),\n },\n ],\n };\n};\n\n/**\n * @internal\n */\nexport const isLocalTest = (url: string) => {\n return url.includes('localhost') || url.includes('127.0.0.1');\n};\n\n/**\n * @internal\n */\nexport const localTestActiveStateTreeInfo = (): ActiveTreeBundle[] => {\n return [\n {\n tree: new PublicKey(merkletreePubkey),\n queue: new PublicKey(nullifierQueuePubkey),\n cpiContext: new PublicKey(cpiContextPubkey),\n treeType: TreeType.State,\n },\n {\n tree: new PublicKey(merkleTree2Pubkey),\n queue: new PublicKey(nullifierQueue2Pubkey),\n cpiContext: new PublicKey(cpiContext2Pubkey),\n treeType: TreeType.State,\n },\n ];\n};\n\n/**\n * Use only with Localnet testing.\n * For public networks, fetch via {@link defaultStateTreeLookupTables} and {@link getLightStateTreeInfo}.\n */\nexport const defaultTestStateTreeAccounts = () => {\n return {\n nullifierQueue: new PublicKey(nullifierQueuePubkey),\n merkleTree: new PublicKey(merkletreePubkey),\n merkleTreeHeight: DEFAULT_MERKLE_TREE_HEIGHT,\n addressTree: new PublicKey(addressTree),\n addressQueue: new PublicKey(addressQueue),\n };\n};\n\n/**\n * @internal testing only\n */\nexport const defaultTestStateTreeAccounts2 = () => {\n return {\n nullifierQueue2: new PublicKey(nullifierQueue2Pubkey),\n merkleTree2: new PublicKey(merkleTree2Pubkey),\n };\n};\n\nexport const stateTreeLookupTableMainnet =\n '7i86eQs3GSqHjN47WdWLTCGMW6gde1q96G2EVnUyK2st';\nexport const nullifiedStateTreeLookupTableMainnet =\n 'H9QD4u1fG7KmkAzn2tDXhheushxFe1EcrjGGyEFXeMqT';\n\nexport const stateTreeLookupTableDevnet =\n '8n8rH2bFRVA6cSGNDpgqcKHCndbFCT1bXxAQG89ejVsh';\nexport const nullifiedStateTreeLookupTableDevnet =\n '5dhaJLBjnVBQFErr8oiCJmcVsx3Zj6xDekGB2zULPsnP';\n\nexport const nullifierQueuePubkey =\n 'nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148';\nexport const cpiContextPubkey = 'cpi1uHzrEhBG733DoEJNgHCyRS3XmmyVNZx5fonubE4';\n\nexport const merkletreePubkey = 'smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT';\nexport const addressTree = 'amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2';\nexport const addressQueue = 'aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F';\n\nexport const merkleTree2Pubkey = 'smt2rJAFdyJJupwMKAqTNAJwvjhmiZ4JYGZmbVRw1Ho';\nexport const nullifierQueue2Pubkey =\n 'nfq2hgS7NYemXsFaFUCe3EMXSDSfnZnAe27jC6aPP1X';\nexport const cpiContext2Pubkey = 'cpi2cdhkH5roePvcudTgUL8ppEBfTay1desGh8G8QxK';\n\nexport const confirmConfig: ConfirmOptions = {\n commitment: 'confirmed',\n preflightCommitment: 'confirmed',\n};\n\nexport const DEFAULT_MERKLE_TREE_HEIGHT = 26;\nexport const DEFAULT_MERKLE_TREE_ROOTS = 2800;\n/** Threshold (per asset) at which new in-UTXOs get merged, in order to reduce UTXO pool size */\nexport const UTXO_MERGE_THRESHOLD = 20;\nexport const UTXO_MERGE_MAXIMUM = 10;\n\n/**\n * Treshold after which the currently used transaction Merkle tree is switched\n * to the next one\n */\nexport const TRANSACTION_MERKLE_TREE_ROLLOVER_THRESHOLD = new BN(\n Math.floor(2 ** DEFAULT_MERKLE_TREE_HEIGHT * 0.95),\n);\n\n/**\n * Fee to provide continous funding for the state Merkle tree.\n * Once the state Merkle tree is at 95% capacity the accumulated fees\n * will be used to fund the next state Merkle tree with the same parameters.\n *\n * Is charged per output compressed account.\n */\nexport const STATE_MERKLE_TREE_ROLLOVER_FEE = new BN(300);\n\n/**\n * Fee to provide continous funding for the address queue and address Merkle tree.\n * Once the address Merkle tree is at 95% capacity the accumulated fees\n * will be used to fund the next address queue and address tree with the same parameters.\n *\n * Is charged per newly created address.\n */\nexport const ADDRESS_QUEUE_ROLLOVER_FEE = new BN(392);\n\n/**\n * Is charged if the transaction nullifies at least one compressed account.\n */\nexport const STATE_MERKLE_TREE_NETWORK_FEE = new BN(5000);\n\n/**\n * Is charged if the transaction creates at least one address.\n */\nexport const ADDRESS_TREE_NETWORK_FEE = new BN(5000);\n","import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n let carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n","// TODO: consider implementing BN254 as wrapper class around _BN mirroring\n// PublicKey this would encapsulate our runtime checks and also enforce\n// typesafety at compile time\n\nimport { FIELD_SIZE } from '../constants';\nimport { PublicKey } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport bs58 from 'bs58';\nimport { Buffer } from 'buffer';\n\n/**\n * bignumber with <254-bit max size. Anchor serialization doesn't support native\n * bigint yet, so we wrap BN. This wrapper has simple base10 encoding which is\n * needed for zk circuit compat, in addition to the base58 encoding that users\n * are used to from working with the web3.js PublicKey type.\n */\nexport type BN254 = BN;\n\nexport const bn = (\n number: string | number | BN | Buffer | Uint8Array | number[],\n base?: number | 'hex' | undefined,\n endian?: BN.Endianness | undefined,\n): BN => new BN(number, base, endian);\n\n/** Create a bigint instance with <254-bit max size and base58 capabilities */\nexport const createBN254 = (\n number: string | number | BN | Buffer | Uint8Array | number[],\n base?: number | 'hex' | 'base58' | undefined,\n): BN254 => {\n if (base === 'base58') {\n if (typeof number !== 'string')\n throw new Error('Must be a base58 string');\n return createBN254(bs58.decode(number));\n }\n\n const bigintNumber = new BN(number, base);\n\n return enforceSize(bigintNumber);\n};\n\n/**\n * Enforces a maximum size of <254 bits for bigint instances. This is necessary\n * for compatibility with zk-SNARKs, where hashes must be less than the field\n * modulus (~2^254).\n */\nfunction enforceSize(bigintNumber: BN254): BN254 {\n if (bigintNumber.gte(FIELD_SIZE)) {\n throw new Error('Value is too large. Max <254 bits');\n }\n return bigintNumber;\n}\n\n/** Convert <254-bit bigint to Base58 string. */\nexport function encodeBN254toBase58(bigintNumber: BN): string {\n /// enforce size\n const bn254 = createBN254(bigintNumber);\n const bn254Buffer = bn254.toArrayLike(Buffer, undefined, 32);\n\n return bs58.encode(bn254Buffer);\n}\n","import BN from 'bn.js';\nimport { PublicKey } from '@solana/web3.js';\nimport { CompressedAccount, CompressedAccountData } from './types';\nimport { BN254, bn } from './BN254';\n\nexport type CompressedAccountWithMerkleContext = CompressedAccount &\n MerkleContext & {\n readOnly: boolean;\n };\n\n/**\n * Context for compressed account inserted into a state Merkle tree\n * */\nexport type MerkleContext = {\n /** State Merkle tree */\n merkleTree: PublicKey;\n /** The state nullfier queue belonging to merkleTree */\n nullifierQueue: PublicKey;\n /** Poseidon hash of the utxo preimage. Is a leaf in state merkle tree */\n hash: number[]; // TODO: BN254;\n /** 'hash' position within the Merkle tree */\n leafIndex: number;\n};\n\nexport type MerkleContextWithMerkleProof = MerkleContext & {\n /** Recent valid 'hash' proof path, expires after n slots */\n merkleProof: BN254[];\n /** Index of state root the merkleproof is valid for, expires after n slots */\n rootIndex: number;\n /** Current root */\n root: BN254;\n};\n\nexport const createCompressedAccount = (\n owner: PublicKey,\n lamports?: BN,\n data?: CompressedAccountData,\n address?: number[],\n): CompressedAccount => ({\n owner,\n lamports: lamports ?? bn(0),\n address: address ?? null,\n data: data ?? null,\n});\n\nexport const createCompressedAccountWithMerkleContext = (\n merkleContext: MerkleContext,\n owner: PublicKey,\n lamports?: BN,\n data?: CompressedAccountData,\n address?: number[],\n): CompressedAccountWithMerkleContext => ({\n ...createCompressedAccount(owner, lamports, data, address),\n ...merkleContext,\n readOnly: false,\n});\n\nexport const createMerkleContext = (\n merkleTree: PublicKey,\n nullifierQueue: PublicKey,\n hash: number[], // TODO: BN254,\n leafIndex: number,\n): MerkleContext => ({\n merkleTree,\n nullifierQueue,\n hash,\n leafIndex,\n});\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","import { Buffer } from 'buffer';\nimport { bn, createBN254 } from '../state/BN254';\nimport { FIELD_SIZE } from '../constants';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { Keypair } from '@solana/web3.js';\nimport BN from 'bn.js';\n\nexport function byteArrayToKeypair(byteArray: number[]): Keypair {\n return Keypair.fromSecretKey(Uint8Array.from(byteArray));\n}\n/**\n * @internal\n * convert BN to hex with '0x' prefix\n */\nexport function toHex(bn: BN): string {\n return '0x' + bn.toString('hex');\n}\n\nexport const toArray = <T>(value: T | T[]) =>\n Array.isArray(value) ? value : [value];\n\nexport const bufToDecStr = (buf: Buffer): string => {\n return createBN254(buf).toString();\n};\nfunction isSmallerThanBn254FieldSizeBe(bytes: Buffer): boolean {\n const bigint = bn(bytes, undefined, 'be');\n return bigint.lt(FIELD_SIZE);\n}\n\n/**\n * Hash the provided `bytes` with Keccak256 and ensure the result fits in the\n * BN254 prime field by repeatedly hashing the inputs with various \"bump seeds\"\n * and truncating the resulting hash to 31 bytes.\n *\n * @deprecated Use `hashvToBn254FieldSizeBe` instead.\n */\nexport function hashToBn254FieldSizeBe(bytes: Buffer): [Buffer, number] | null {\n // TODO(vadorovsky, affects-onchain): Get rid of the bump mechanism, it\n // makes no sense. Doing the same as in the `hashvToBn254FieldSizeBe` below\n // - overwriting the most significant byte with zero - is sufficient for\n // truncation, it's also faster, doesn't force us to return `Option` and\n // care about handling an error which is practically never returned.\n //\n // The reason we can't do it now is that it would affect on-chain programs.\n // Once we can update programs, we can get rid of the seed bump (or even of\n // this function all together in favor of the `hashv` variant).\n let bumpSeed = 255;\n while (bumpSeed >= 0) {\n const inputWithBumpSeed = Buffer.concat([\n bytes,\n Buffer.from([bumpSeed]),\n ]);\n const hash = keccak_256(inputWithBumpSeed);\n if (hash.length !== 32) {\n throw new Error('Invalid hash length');\n }\n hash[0] = 0;\n\n if (isSmallerThanBn254FieldSizeBe(Buffer.from(hash))) {\n return [Buffer.from(hash), bumpSeed];\n }\n\n bumpSeed -= 1;\n }\n return null;\n}\n\n/**\n * Hash the provided `bytes` with Keccak256 and ensure that the result fits in\n * the BN254 prime field by truncating the resulting hash to 31 bytes.\n *\n * @param bytes Input bytes\n *\n * @returns Hash digest\n */\nexport function hashvToBn254FieldSizeBe(bytes: Uint8Array[]): Uint8Array {\n const hasher = keccak_256.create();\n for (const input of bytes) {\n hasher.update(input);\n }\n const hash = hasher.digest();\n hash[0] = 0;\n return hash;\n}\n\n/** Mutates array in place */\nexport function pushUniqueItems<T>(items: T[], map: T[]): void {\n items.forEach(item => {\n if (!map.includes(item)) {\n map.push(item);\n }\n });\n}\n\nexport function toCamelCase(\n obj: Array<any> | unknown | any,\n): Array<any> | unknown | any {\n if (Array.isArray(obj)) {\n return obj.map(v => toCamelCase(v));\n } else if (obj !== null && typeof obj === 'object') {\n return Object.entries(obj).reduce((result, [key, value]) => {\n const camelCaseKey = key.replace(/([-_][a-z])/gi, $1 => {\n return $1.toUpperCase().replace('-', '').replace('_', '');\n });\n result[camelCaseKey] = toCamelCase(value);\n return result;\n }, {} as any);\n }\n return obj;\n}\n\n// FIXME: check bundling and how to resolve the type error\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n describe('toArray function', () => {\n it('should convert a single item to an array', () => {\n expect(toArray(1)).toEqual([1]);\n });\n\n it('should leave an array unchanged', () => {\n expect(toArray([1, 2, 3])).toEqual([1, 2, 3]);\n });\n });\n\n describe('isSmallerThanBn254FieldSizeBe function', () => {\n it('should return true for a small number', () => {\n const buf = Buffer.from(\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'hex',\n );\n expect(isSmallerThanBn254FieldSizeBe(buf)).toBe(true);\n });\n\n it('should return false for a large number', () => {\n const buf = Buffer.from(\n '0000000000000000000000000000000000000000000000000000000000000065',\n 'hex',\n ).reverse();\n expect(isSmallerThanBn254FieldSizeBe(buf)).toBe(false);\n });\n });\n\n describe('hashToBn254FieldSizeBe function', () => {\n const refBumpSeed = [252];\n const bytes = [\n 131, 219, 249, 246, 221, 196, 33, 3, 114, 23, 121, 235, 18, 229, 71,\n 152, 39, 87, 169, 208, 143, 101, 43, 128, 245, 59, 22, 134, 182,\n 231, 116, 33,\n ];\n const refResult = [\n 0, 146, 15, 187, 171, 163, 183, 93, 237, 121, 37, 231, 55, 162, 208,\n 188, 244, 77, 185, 157, 93, 9, 101, 193, 220, 247, 109, 94, 48, 212,\n 98, 149,\n ];\n\n it('should return a valid value for initial buffer', async () => {\n const result = await hashToBn254FieldSizeBe(Buffer.from(bytes));\n expect(Array.from(result![0])).toEqual(refResult);\n });\n\n it('should return a valid value for initial buffer', async () => {\n const buf = Buffer.from(\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'hex',\n );\n const result = await hashToBn254FieldSizeBe(buf);\n expect(result).not.toBeNull();\n if (result) {\n expect(result[0]).toBeInstanceOf(Buffer);\n expect(result[1]).toBe(255);\n }\n });\n\n it('should return a valid value for a buffer that can be hashed to a smaller value', async () => {\n const buf = Buffer.from(\n 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe',\n 'hex',\n );\n const result = await hashToBn254FieldSizeBe(buf);\n expect(result).not.toBeNull();\n if (result) {\n expect(result[1]).toBeLessThanOrEqual(255);\n expect(result[0]).toBeInstanceOf(Buffer);\n // Check if the hashed value is indeed smaller than the bn254 field size\n expect(isSmallerThanBn254FieldSizeBe(result[0])).toBe(true);\n }\n });\n\n it('should correctly hash the input buffer', async () => {\n const buf = Buffer.from('deadbeef', 'hex');\n const result = await hashToBn254FieldSizeBe(buf);\n expect(result).not.toBeNull();\n if (result) {\n // Since the actual hash value depends on the crypto implementation and input,\n // we cannot predict the exact output. However, we can check if the output is valid.\n expect(result[0].length).toBe(32); // SHA-256 hash length\n expect(result[1]).toBeLessThanOrEqual(255);\n expect(isSmallerThanBn254FieldSizeBe(result[0])).toBe(true);\n }\n });\n });\n\n describe('pushUniqueItems function', () => {\n it('should add unique items', () => {\n const map = [1, 2, 3];\n const itemsToAdd = [3, 4, 5];\n pushUniqueItems(itemsToAdd, map);\n expect(map).toEqual([1, 2, 3, 4, 5]);\n });\n\n it('should ignore duplicates', () => {\n const map = [1, 2, 3];\n const itemsToAdd = [1, 2, 3];\n pushUniqueItems(itemsToAdd, map);\n expect(map).toEqual([1, 2, 3]);\n });\n\n it('should handle empty arrays', () => {\n const map: number[] = [];\n const itemsToAdd: number[] = [];\n pushUniqueItems(itemsToAdd, map);\n expect(map).toEqual([]);\n });\n });\n\n describe('bufToDecStr', () => {\n it(\"should convert buffer [0] to '0'\", () => {\n expect(bufToDecStr(Buffer.from([0]))).toEqual('0');\n });\n\n it(\"should convert buffer [1] to '1'\", () => {\n expect(bufToDecStr(Buffer.from([1]))).toEqual('1');\n });\n\n it(\"should convert buffer [1, 0] to '256'\", () => {\n expect(bufToDecStr(Buffer.from([1, 0]))).toEqual('256');\n });\n\n it(\"should convert buffer [1, 1] to '257'\", () => {\n expect(bufToDecStr(Buffer.from([1, 1]))).toEqual('257');\n });\n\n it(\"should convert buffer [7, 91, 205, 21] to '123456789'\", () => {\n expect(bufToDecStr(Buffer.from([7, 91, 205, 21]))).toEqual(\n '123456789',\n );\n });\n });\n\n describe('toCamelCase', () => {\n it('should convert object keys to camelCase', () => {\n const input = { test_key: 1, 'another-testKey': 2 };\n const expected = { testKey: 1, anotherTestKey: 2 };\n expect(toCamelCase(input)).toEqual(expected);\n });\n\n it('should handle arrays of objects', () => {\n const input = [{ array_key: 3 }, { 'another_array-key': 4 }];\n const expected = [{ arrayKey: 3 }, { anotherArrayKey: 4 }];\n expect(toCamelCase(input)).toEqual(expected);\n });\n\n it('should return the input if it is neither an object nor an array', () => {\n const input = 'testString';\n expect(toCamelCase(input)).toBe(input);\n });\n });\n}\n","import { AccountMeta, PublicKey } from '@solana/web3.js';\nimport {\n CompressedAccount,\n OutputCompressedAccountWithPackedContext,\n PackedCompressedAccountWithMerkleContext,\n} from '../state';\nimport { CompressedAccountWithMerkleContext } from '../state/compressed-account';\nimport { toArray } from '../utils/conversion';\n\n/**\n * @internal Finds the index of a PublicKey in an array, or adds it if not\n * present\n * */\nexport function getIndexOrAdd(\n accountsArray: PublicKey[],\n key: PublicKey,\n): number {\n const index = accountsArray.findIndex(existingKey =>\n existingKey.equals(key),\n );\n if (index === -1) {\n accountsArray.push(key);\n return accountsArray.length - 1;\n }\n return index;\n}\n\n/**\n * @internal\n * Pads output state trees with the 0th state tree of the input state.\n *\n * @param outputStateMerkleTrees Optional output state trees to be\n * inserted into the output state.\n * Defaults to the 0th state tree of\n * the input state. Gets padded to the\n * length of outputCompressedAccounts.\n * @param numberOfOutputCompressedAccounts The number of output compressed\n * accounts.\n * @param inputCompressedAccountsWithMerkleContext The input compressed accounts\n * with merkle context.\n *\n * @returns Padded output state trees.\n */\nexport function padOutputStateMerkleTrees(\n outputStateMerkleTrees: PublicKey[] | PublicKey | undefined,\n numberOfOutputCompressedAccounts: number,\n inputCompressedAccountsWithMerkleContext: CompressedAccountWithMerkleContext[],\n): PublicKey[] {\n if (numberOfOutputCompressedAccounts <= 0) {\n return [];\n }\n\n /// Default: use the 0th state tree of input state for all output accounts\n if (outputStateMerkleTrees === undefined) {\n if (inputCompressedAccountsWithMerkleContext.length === 0) {\n throw new Error(\n 'No input compressed accounts nor output state trees provided. Please pass in at least one of the following: outputStateMerkleTree or inputCompressedAccount',\n );\n }\n return new Array(numberOfOutputCompressedAccounts).fill(\n inputCompressedAccountsWithMerkleContext[0].merkleTree,\n );\n /// Align the number of output state trees with the number of output\n /// accounts, and fill up with 0th output state tree\n } else {\n /// Into array\n const treesArray = toArray(outputStateMerkleTrees);\n if (treesArray.length >= numberOfOutputCompressedAccounts) {\n return treesArray.slice(0, numberOfOutputCompressedAccounts);\n } else {\n return treesArray.concat(\n new Array(\n numberOfOutputCompressedAccounts - treesArray.length,\n ).fill(treesArray[0]),\n );\n }\n }\n}\n\nexport function toAccountMetas(remainingAccounts: PublicKey[]): AccountMeta[] {\n return remainingAccounts.map(\n (account): AccountMeta => ({\n pubkey: account,\n isWritable: true,\n isSigner: false,\n }),\n );\n}\n\n/**\n * Packs Compressed Accounts.\n *\n * Replaces PublicKey with index pointer to remaining accounts.\n *\n *\n * @param inputCompressedAccounts Ix input state to be consumed\n * @param inputStateRootIndices The recent state root indices of the\n * input state. The expiry is tied to\n * the proof.\n * @param outputCompressedAccounts Ix output state to be created\n * @param outputStateMerkleTrees Optional output state trees to be\n * inserted into the output state.\n * Defaults to the 0th state tree of\n * the input state. Gets padded to the\n * length of outputCompressedAccounts.\n *\n * @param remainingAccounts Optional existing array of accounts\n * to append to.\n **/\nexport function packCompressedAccounts(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n inputStateRootIndices: number[],\n outputCompressedAccounts: CompressedAccount[],\n outputStateMerkleTrees?: PublicKey[] | PublicKey,\n remainingAccounts: PublicKey[] = [],\n): {\n packedInputCompressedAccounts: PackedCompressedAccountWithMerkleContext[];\n packedOutputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n remainingAccounts: PublicKey[];\n} {\n const _remainingAccounts = remainingAccounts.slice();\n\n const packedInputCompressedAccounts: PackedCompressedAccountWithMerkleContext[] =\n [];\n\n const packedOutputCompressedAccounts: OutputCompressedAccountWithPackedContext[] =\n [];\n\n /// input\n inputCompressedAccounts.forEach((account, index) => {\n const merkleTreePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.merkleTree,\n );\n\n const nullifierQueuePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.nullifierQueue,\n );\n\n packedInputCompressedAccounts.push({\n compressedAccount: {\n owner: account.owner,\n lamports: account.lamports,\n address: account.address,\n data: account.data,\n },\n merkleContext: {\n merkleTreePubkeyIndex,\n nullifierQueuePubkeyIndex,\n leafIndex: account.leafIndex,\n queueIndex: null,\n },\n rootIndex: inputStateRootIndices[index],\n readOnly: false,\n });\n });\n\n if (\n outputStateMerkleTrees === undefined &&\n inputCompressedAccounts.length === 0\n ) {\n throw new Error(\n 'No input compressed accounts nor output state trees provided. Please pass in at least one of the following: outputStateMerkleTree or inputCompressedAccount',\n );\n }\n /// output\n const paddedOutputStateMerkleTrees = padOutputStateMerkleTrees(\n outputStateMerkleTrees,\n outputCompressedAccounts.length,\n inputCompressedAccounts,\n );\n\n outputCompressedAccounts.forEach((account, index) => {\n const merkleTreePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n paddedOutputStateMerkleTrees[index],\n );\n packedOutputCompressedAccounts.push({\n compressedAccount: {\n owner: account.owner,\n lamports: account.lamports,\n address: account.address,\n data: account.data,\n },\n merkleTreeIndex: merkleTreePubkeyIndex,\n });\n });\n\n return {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts: _remainingAccounts,\n };\n}\n","import BN from 'bn.js';\nimport {\n CompressedAccount,\n CompressedAccountWithMerkleContext,\n bn,\n} from '../state';\n\nexport const validateSufficientBalance = (balance: BN) => {\n if (balance.lt(bn(0))) {\n throw new Error('Not enough balance for transfer');\n }\n};\n\nexport const validateSameOwner = (\n compressedAccounts:\n | CompressedAccount[]\n | CompressedAccountWithMerkleContext[],\n) => {\n if (compressedAccounts.length === 0) {\n throw new Error('No accounts provided for validation');\n }\n const zerothOwner = compressedAccounts[0].owner;\n if (\n !compressedAccounts.every(account => account.owner.equals(zerothOwner))\n ) {\n throw new Error('All input accounts must have the same owner');\n }\n};\n","import { AccountMeta, PublicKey } from '@solana/web3.js';\nimport { hashToBn254FieldSizeBe, hashvToBn254FieldSizeBe } from './conversion';\nimport { defaultTestStateTreeAccounts } from '../constants';\nimport { getIndexOrAdd } from '../instruction';\n\nexport function deriveAddressSeed(\n seeds: Uint8Array[],\n programId: PublicKey,\n): Uint8Array {\n const combinedSeeds: Uint8Array[] = [programId.toBytes(), ...seeds];\n const hash = hashvToBn254FieldSizeBe(combinedSeeds);\n return hash;\n}\n\n/**\n * Derive an address for a compressed account from a seed and an address Merkle\n * tree public key.\n *\n * @param seed Seed to derive the address from\n * @param addressMerkleTreePubkey Merkle tree public key. Defaults to\n * defaultTestStateTreeAccounts().addressTree\n * @returns Derived address\n */\nexport function deriveAddress(\n seed: Uint8Array,\n addressMerkleTreePubkey: PublicKey = defaultTestStateTreeAccounts()\n .addressTree,\n): PublicKey {\n if (seed.length != 32) {\n throw new Error('Seed length is not 32 bytes.');\n }\n const bytes = addressMerkleTreePubkey.toBytes();\n const combined = Buffer.from([...bytes, ...seed]);\n const hash = hashToBn254FieldSizeBe(combined);\n\n if (hash === null) {\n throw new Error('DeriveAddressError');\n }\n const buf = hash[0];\n return new PublicKey(buf);\n}\n\nexport interface NewAddressParams {\n /**\n * Seed for the compressed account. Must be seed used to derive\n * newAccountAddress\n */\n seed: Uint8Array;\n /**\n * Recent state root index of the address tree. The expiry is tied to the\n * validity proof.\n */\n addressMerkleTreeRootIndex: number;\n /**\n * Address tree pubkey. Must be base pubkey used to derive new address\n */\n addressMerkleTreePubkey: PublicKey;\n /**\n * Address space queue pubkey. Associated with the state tree.\n */\n addressQueuePubkey: PublicKey;\n}\n\nexport interface NewAddressParamsPacked {\n /**\n * Seed for the compressed account. Must be seed used to derive\n * newAccountAddress\n */\n seed: number[];\n /**\n * Recent state root index of the address tree. The expiry is tied to the\n * validity proof.\n */\n addressMerkleTreeRootIndex: number;\n /**\n * Index of the address merkle tree account in the remaining accounts array\n */\n addressMerkleTreeAccountIndex: number;\n /**\n * Index of the address queue account in the remaining accounts array\n */\n addressQueueAccountIndex: number;\n}\n\n/**\n * Packs new address params for instruction data in TypeScript clients\n *\n * @param newAddressParams New address params\n * @param remainingAccounts Remaining accounts\n * @returns Packed new address params\n */\nexport function packNewAddressParams(\n newAddressParams: NewAddressParams[],\n remainingAccounts: PublicKey[],\n): {\n newAddressParamsPacked: NewAddressParamsPacked[];\n remainingAccounts: PublicKey[];\n} {\n const _remainingAccounts = remainingAccounts.slice();\n\n const newAddressParamsPacked: NewAddressParamsPacked[] =\n newAddressParams.map(x => ({\n seed: Array.from(x.seed),\n addressMerkleTreeRootIndex: x.addressMerkleTreeRootIndex,\n addressMerkleTreeAccountIndex: 0, // will be assigned later\n addressQueueAccountIndex: 0, // will be assigned later\n }));\n\n newAddressParams.forEach((params, i) => {\n newAddressParamsPacked[i].addressMerkleTreeAccountIndex = getIndexOrAdd(\n _remainingAccounts,\n params.addressMerkleTreePubkey,\n );\n });\n\n newAddressParams.forEach((params, i) => {\n newAddressParamsPacked[i].addressQueueAccountIndex = getIndexOrAdd(\n _remainingAccounts,\n params.addressQueuePubkey,\n );\n });\n\n return { newAddressParamsPacked, remainingAccounts: _remainingAccounts };\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n const programId = new PublicKey(\n '7yucc7fL3JGbyMwg4neUaenNSdySS39hbAk89Ao3t1Hz',\n );\n\n describe('derive address seed', () => {\n it('should derive a valid address seed', () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('foo'),\n new TextEncoder().encode('bar'),\n ];\n expect(deriveAddressSeed(seeds, programId)).toStrictEqual(\n new Uint8Array([\n 0, 246, 150, 3, 192, 95, 53, 123, 56, 139, 206, 179, 253,\n 133, 115, 103, 120, 155, 251, 72, 250, 47, 117, 217, 118,\n 59, 174, 207, 49, 101, 201, 110,\n ]),\n );\n });\n\n it('should derive a valid address seed', () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('ayy'),\n new TextEncoder().encode('lmao'),\n ];\n expect(deriveAddressSeed(seeds, programId)).toStrictEqual(\n new Uint8Array([\n 0, 202, 44, 25, 221, 74, 144, 92, 69, 168, 38, 19, 206, 208,\n 29, 162, 53, 27, 120, 214, 152, 116, 15, 107, 212, 168, 33,\n 121, 187, 10, 76, 233,\n ]),\n );\n });\n });\n\n describe('deriveAddress function', () => {\n it('should derive a valid address from a seed and a merkle tree public key', async () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('foo'),\n new TextEncoder().encode('bar'),\n ];\n const seed = deriveAddressSeed(seeds, programId);\n const merkleTreePubkey = new PublicKey(\n '11111111111111111111111111111111',\n );\n const derivedAddress = deriveAddress(seed, merkleTreePubkey);\n expect(derivedAddress).toBeInstanceOf(PublicKey);\n expect(derivedAddress).toStrictEqual(\n new PublicKey('139uhyyBtEh4e1CBDJ68ooK5nCeWoncZf9HPyAfRrukA'),\n );\n });\n\n it('should derive a valid address from a seed and a merkle tree public key', async () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('ayy'),\n new TextEncoder().encode('lmao'),\n ];\n const seed = deriveAddressSeed(seeds, programId);\n const merkleTreePubkey = new PublicKey(\n '11111111111111111111111111111111',\n );\n const derivedAddress = deriveAddress(seed, merkleTreePubkey);\n expect(derivedAddress).toBeInstanceOf(PublicKey);\n expect(derivedAddress).toStrictEqual(\n new PublicKey('12bhHm6PQjbNmEn3Yu1Gq9k7XwVn2rZpzYokmLwbFazN'),\n );\n });\n });\n\n describe('packNewAddressParams function', () => {\n it('should pack new address params correctly', () => {\n const newAddressParams = [\n {\n seed: new Uint8Array([1, 2, 3, 4]),\n addressMerkleTreeRootIndex: 0,\n addressMerkleTreePubkey: new PublicKey(\n '11111111111111111111111111111111',\n ),\n addressQueuePubkey: new PublicKey(\n '11111111111111111111111111111112',\n ),\n },\n ];\n const remainingAccounts = [\n new PublicKey('11111111111111111111111111111112'),\n new PublicKey('11111111111111111111111111111111'),\n ];\n const packedParams = packNewAddressParams(\n newAddressParams,\n remainingAccounts,\n );\n expect(\n packedParams.newAddressParamsPacked[0]\n .addressMerkleTreeAccountIndex,\n ).toBe(1);\n expect(\n packedParams.newAddressParamsPacked[0].addressQueueAccountIndex,\n ).toBe(0);\n });\n });\n}\n","import {\n Commitment,\n Connection,\n PublicKey,\n TransactionConfirmationStrategy,\n} from '@solana/web3.js';\n\nexport async function airdropSol({\n connection,\n lamports,\n recipientPublicKey,\n}: {\n connection: Connection;\n lamports: number;\n recipientPublicKey: PublicKey;\n}) {\n const txHash = await connection.requestAirdrop(\n recipientPublicKey,\n lamports,\n );\n await confirmTransaction(connection, txHash);\n return txHash;\n}\n\nexport async function confirmTransaction(\n connection: Connection,\n signature: string,\n confirmation: Commitment = 'confirmed',\n) {\n const latestBlockHash = await connection.getLatestBlockhash(confirmation);\n const strategy: TransactionConfirmationStrategy = {\n signature: signature.toString(),\n lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,\n blockhash: latestBlockHash.blockhash,\n };\n return await connection.confirmTransaction(strategy, confirmation);\n}\n","import BN from 'bn.js';\nimport { FIELD_SIZE } from '../constants';\nimport { CompressedProof } from '../state';\n\ninterface GnarkProofJson {\n ar: string[];\n bs: string[][];\n krs: string[];\n}\n\ntype ProofABC = {\n a: Uint8Array;\n b: Uint8Array;\n c: Uint8Array;\n};\n\nexport const placeholderValidityProof = () => ({\n a: Array.from({ length: 32 }, (_, i) => i + 1),\n b: Array.from({ length: 64 }, (_, i) => i + 1),\n c: Array.from({ length: 32 }, (_, i) => i + 1),\n});\n\nexport const checkValidityProofShape = (proof: CompressedProof) => {\n if (\n proof.a.length !== 32 ||\n proof.b.length !== 64 ||\n proof.c.length !== 32\n ) {\n throw new Error('ValidityProof has invalid shape');\n }\n};\n\nexport function proofFromJsonStruct(json: GnarkProofJson): ProofABC {\n const proofAX = deserializeHexStringToBeBytes(json.ar[0]);\n const proofAY = deserializeHexStringToBeBytes(json.ar[1]);\n const proofA: Uint8Array = new Uint8Array([...proofAX, ...proofAY]);\n\n const proofBX0 = deserializeHexStringToBeBytes(json.bs[0][0]);\n const proofBX1 = deserializeHexStringToBeBytes(json.bs[0][1]);\n const proofBY0 = deserializeHexStringToBeBytes(json.bs[1][0]);\n const proofBY1 = deserializeHexStringToBeBytes(json.bs[1][1]);\n const proofB: Uint8Array = new Uint8Array([\n ...proofBX0,\n ...proofBX1,\n ...proofBY0,\n ...proofBY1,\n ]);\n\n const proofCX = deserializeHexStringToBeBytes(json.krs[0]);\n const proofCY = deserializeHexStringToBeBytes(json.krs[1]);\n const proofC: Uint8Array = new Uint8Array([...proofCX, ...proofCY]);\n\n const proofABC: ProofABC = { a: proofA, b: proofB, c: proofC };\n return proofABC;\n}\n\n// TODO: add unit test for negation\n// TODO: test if LE BE issue. unit test\nexport function negateAndCompressProof(proof: ProofABC): CompressedProof {\n const proofA = proof.a;\n const proofB = proof.b;\n const proofC = proof.c;\n\n const aXElement = proofA.slice(0, 32);\n const aYElement = new BN(proofA.slice(32, 64), 32, 'be');\n\n /// Negate\n const proofAIsPositive = yElementIsPositiveG1(aYElement) ? false : true;\n /// First byte of proofA is the bitmask\n aXElement[0] = addBitmaskToByte(aXElement[0], proofAIsPositive);\n\n const bXElement = proofB.slice(0, 64);\n const bYElement = proofB.slice(64, 128);\n\n const proofBIsPositive = yElementIsPositiveG2(\n new BN(bYElement.slice(0, 32), 32, 'be'),\n new BN(bYElement.slice(32, 64), 32, 'be'),\n );\n\n bXElement[0] = addBitmaskToByte(bXElement[0], proofBIsPositive);\n\n const cXElement = proofC.slice(0, 32);\n const cYElement = proofC.slice(32, 64);\n const proofCIsPositive = yElementIsPositiveG1(new BN(cYElement, 32, 'be'));\n cXElement[0] = addBitmaskToByte(cXElement[0], proofCIsPositive);\n\n const compressedProof: CompressedProof = {\n a: Array.from(aXElement),\n b: Array.from(bXElement),\n c: Array.from(cXElement),\n };\n\n return compressedProof;\n}\n\nfunction deserializeHexStringToBeBytes(hexStr: string): Uint8Array {\n // Using BN for simpler conversion from hex string to byte array\n const bn = new BN(\n hexStr.startsWith('0x') ? hexStr.substring(2) : hexStr,\n 'hex',\n );\n return new Uint8Array(bn.toArray('be', 32));\n}\n\nfunction yElementIsPositiveG1(yElement: BN): boolean {\n return yElement.lte(FIELD_SIZE.sub(yElement));\n}\n\nfunction yElementIsPositiveG2(yElement1: BN, yElement2: BN): boolean {\n const fieldMidpoint = FIELD_SIZE.div(new BN(2));\n\n // Compare the first component of the y coordinate\n if (yElement1.lt(fieldMidpoint)) {\n return true;\n } else if (yElement1.gt(fieldMidpoint)) {\n return false;\n }\n\n // If the first component is equal to the midpoint, compare the second component\n return yElement2.lt(fieldMidpoint);\n}\n// bitmask compatible with solana altbn128 compression syscall and arkworks' implementation\n// https://github.com/arkworks-rs/algebra/blob/master/ff/src/fields/models/fp/mod.rs#L580\n// https://github.com/arkworks-rs/algebra/blob/master/serialize/src/flags.rs#L18\n// fn u8_bitmask(value: u8, inf: bool, neg: bool) -> u8 {\n// let mut mask = 0;\n// match self {\n// inf => mask |= 1 << 6,\n// neg => mask |= 1 << 7,\n// _ => (),\n// }\n// mask\n// }\nfunction addBitmaskToByte(byte: number, yIsPositive: boolean): number {\n if (!yIsPositive) {\n return (byte |= 1 << 7);\n } else {\n return byte;\n }\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n // Unit test for addBitmaskToByte function\n describe('addBitmaskToByte', () => {\n it('should add a bitmask to the byte if yIsPositive is false', () => {\n const byte = 0b00000000;\n const yIsPositive = false;\n const result = addBitmaskToByte(byte, yIsPositive);\n expect(result).toBe(0b10000000); // 128 in binary, which is 1 << 7\n });\n\n it('should not modify the byte if yIsPositive is true', () => {\n const byte = 0b00000000;\n const yIsPositive = true;\n const result = addBitmaskToByte(byte, yIsPositive);\n expect(result).toBe(0b00000000);\n });\n });\n\n describe('test prover server', () => {\n const TEST_JSON = {\n ar: [\n '0x22bdaa3187d8fe294925a66fa0165a11bc9e07678fa2fc72402ebfd33d521c69',\n '0x2d18ff780b69898b4cdd8d7b6ac72d077799399f0f45e52665426456f3903584',\n ],\n bs: [\n [\n '0x138cc0962e49f76a701d2871d2799892c9782940095eb0429e979f336d2e162d',\n '0x2fe1bfbb15cbfb83d7e00ace23e45f890604003783eaf34affa35e0d6f4822bc',\n ],\n [\n '0x1a89264f82cc6e8ef1c696bea0b5803c28c0ba6ab61366bcb71e73a4135cae8d',\n '0xf778d857b3df01a4100265c9d014ce02d47425f0114685356165fa5ee3f3a26',\n ],\n ],\n krs: [\n '0x176b6ae9001f66832951e2d43a98a972667447bb1781f534b70cb010270dcdd3',\n '0xb748d5fac1686db28d94c02250af7eb4f28dfdabc8983305c45bcbc6e163eeb',\n ],\n };\n const COMPRESSED_PROOF_A = [\n 34, 189, 170, 49, 135, 216, 254, 41, 73, 37, 166, 111, 160, 22, 90,\n 17, 188, 158, 7, 103, 143, 162, 252, 114, 64, 46, 191, 211, 61, 82,\n 28, 105,\n ];\n const COMPRESSED_PROOF_B = [\n 147, 140, 192, 150, 46, 73, 247, 106, 112, 29, 40, 113, 210, 121,\n 152, 146, 201, 120, 41, 64, 9, 94, 176, 66, 158, 151, 159, 51, 109,\n 46, 22, 45, 47, 225, 191, 187, 21, 203, 251, 131, 215, 224, 10, 206,\n 35, 228, 95, 137, 6, 4, 0, 55, 131, 234, 243, 74, 255, 163, 94, 13,\n 111, 72, 34, 188,\n ];\n const COMPRESSED_PROOF_C = [\n 23, 107, 106, 233, 0, 31, 102, 131, 41, 81, 226, 212, 58, 152, 169,\n 114, 102, 116, 71, 187, 23, 129, 245, 52, 183, 12, 176, 16, 39, 13,\n 205, 211,\n ];\n\n it('should execute a compressed token mint', async () => {\n const proof = proofFromJsonStruct(TEST_JSON);\n const compressedProof = negateAndCompressProof(proof);\n expect(compressedProof.a).toEqual(COMPRESSED_PROOF_A);\n expect(compressedProof.b).toEqual(COMPRESSED_PROOF_B);\n expect(compressedProof.c).toEqual(COMPRESSED_PROOF_C);\n });\n });\n describe('Validity Proof Functions', () => {\n describe('placeholderValidityProof', () => {\n it('should create a validity proof with correct shape', () => {\n const validityProof = placeholderValidityProof();\n expect(validityProof.a.length).toBe(32);\n expect(validityProof.b.length).toBe(64);\n expect(validityProof.c.length).toBe(32);\n });\n });\n\n describe('checkValidityProofShape', () => {\n it('should not throw an error for valid proof shape', () => {\n const validProof = {\n a: Array.from(new Uint8Array(32)),\n b: Array.from(new Uint8Array(64)),\n c: Array.from(new Uint8Array(32)),\n };\n expect(() => checkValidityProofShape(validProof)).not.toThrow();\n });\n\n it('should throw an error for an invalid proof', () => {\n const invalidProof = {\n a: Array.from(new Uint8Array(31)), // incorrect length\n b: Array.from(new Uint8Array(64)),\n c: Array.from(new Uint8Array(32)),\n };\n expect(() => checkValidityProofShape(invalidProof)).toThrow(\n 'ValidityProof has invalid shape',\n );\n });\n });\n });\n}\n","import {\n VersionedTransaction,\n TransactionConfirmationStrategy,\n SignatureResult,\n RpcResponseAndContext,\n Signer,\n TransactionInstruction,\n TransactionMessage,\n ConfirmOptions,\n TransactionSignature,\n PublicKey,\n AddressLookupTableAccount,\n} from '@solana/web3.js';\nimport { Rpc } from '../rpc';\n\n/**\n * Builds a versioned Transaction from instructions.\n *\n * @param instructions instructions to include\n * @param payerPublicKey fee payer public key\n * @param blockhash blockhash to use\n * @param lookupTableAccounts lookup table accounts to include\n *\n * @return VersionedTransaction\n */\nexport function buildTx(\n instructions: TransactionInstruction[],\n payerPublicKey: PublicKey,\n blockhash: string,\n lookupTableAccounts?: AddressLookupTableAccount[],\n): VersionedTransaction {\n const messageV0 = new TransactionMessage({\n payerKey: payerPublicKey,\n recentBlockhash: blockhash,\n instructions,\n }).compileToV0Message(lookupTableAccounts);\n\n return new VersionedTransaction(messageV0);\n}\n\n/**\n * Sends a versioned transaction and confirms it.\n *\n * @param rpc connection to use\n * @param tx versioned transaction to send\n * @param confirmOptions confirmation options\n * @param blockHashCtx blockhash context for confirmation\n *\n * @return TransactionSignature\n */\nexport async function sendAndConfirmTx(\n rpc: Rpc,\n tx: VersionedTransaction,\n confirmOptions?: ConfirmOptions,\n blockHashCtx?: { blockhash: string; lastValidBlockHeight: number },\n): Promise<TransactionSignature> {\n const txId = await rpc.sendTransaction(tx, confirmOptions);\n\n if (!blockHashCtx) blockHashCtx = await rpc.getLatestBlockhash();\n\n const transactionConfirmationStrategy0: TransactionConfirmationStrategy = {\n signature: txId,\n blockhash: blockHashCtx.blockhash,\n lastValidBlockHeight: blockHashCtx.lastValidBlockHeight,\n };\n\n const ctxAndRes = await rpc.confirmTransaction(\n transactionConfirmationStrategy0,\n confirmOptions?.commitment || rpc.commitment || 'confirmed',\n );\n const slot = ctxAndRes.context.slot;\n await rpc.confirmTransactionIndexed(slot);\n return txId;\n}\n\n/**\n * Confirms a transaction with a given txId.\n *\n * @param rpc connection to use\n * @param txId transaction signature to confirm\n * @param confirmOptions confirmation options\n * @param blockHashCtx blockhash context for confirmation\n * @return SignatureResult\n */\nexport async function confirmTx(\n rpc: Rpc,\n txId: string,\n confirmOptions?: ConfirmOptions,\n blockHashCtx?: { blockhash: string; lastValidBlockHeight: number },\n): Promise<RpcResponseAndContext<SignatureResult>> {\n if (!blockHashCtx) blockHashCtx = await rpc.getLatestBlockhash();\n\n const transactionConfirmationStrategy: TransactionConfirmationStrategy = {\n signature: txId,\n blockhash: blockHashCtx.blockhash,\n lastValidBlockHeight: blockHashCtx.lastValidBlockHeight,\n };\n const res = await rpc.confirmTransaction(\n transactionConfirmationStrategy,\n confirmOptions?.commitment || rpc.commitment || 'confirmed',\n );\n const slot = res.context.slot;\n await rpc.confirmTransactionIndexed(slot);\n return res;\n}\n\n/**\n * Builds a versioned Transaction from instructions and signs it.\n *\n * @param instructions instructions to include in the transaction\n * @param payer payer of the transaction\n * @param blockhash recent blockhash to use in the transaction\n * @param additionalSigners non-feepayer signers to include in the\n * transaction\n * @param lookupTableAccounts lookup table accounts to include in the\n * transaction\n */\nexport function buildAndSignTx(\n instructions: TransactionInstruction[],\n payer: Signer,\n blockhash: string,\n additionalSigners: Signer[] = [],\n lookupTableAccounts?: AddressLookupTableAccount[],\n): VersionedTransaction {\n if (additionalSigners.includes(payer))\n throw new Error('payer must not be in additionalSigners');\n const allSigners = [payer, ...additionalSigners];\n\n const tx = buildTx(\n instructions,\n payer.publicKey,\n blockhash,\n lookupTableAccounts,\n );\n\n tx.sign(allSigners);\n\n return tx;\n}\n","import {\n AddressLookupTableProgram,\n Connection,\n Keypair,\n PublicKey,\n Signer,\n} from '@solana/web3.js';\nimport { buildAndSignTx, sendAndConfirmTx } from './send-and-confirm';\nimport { dedupeSigner } from '../actions';\nimport { ActiveTreeBundle, TreeType } from '../state/types';\n\n/**\n * Create two lookup tables storing all public state tree and queue addresses\n * returns lookup table addresses and txId\n *\n * @internal\n * @param connection - Connection to the Solana network\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n * @param recentSlot - Slot of the recent block\n */\nexport async function createStateTreeLookupTable({\n connection,\n payer,\n authority,\n recentSlot,\n}: {\n connection: Connection;\n payer: Keypair;\n authority: Keypair;\n recentSlot: number;\n}): Promise<{ address: PublicKey; txId: string }> {\n const [createInstruction1, lookupTableAddress1] =\n AddressLookupTableProgram.createLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n recentSlot,\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx(\n [createInstruction1],\n payer,\n blockhash.blockhash,\n dedupeSigner(payer as Signer, [authority]),\n );\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n address: lookupTableAddress1,\n txId,\n };\n}\n\n/**\n * Extend state tree lookup table with new state tree and queue addresses\n * @internal\n * @param connection - Connection to the Solana network\n * @param tableAddress - Address of the lookup table to extend\n * @param newStateTreeAddresses - Addresses of the new state trees to add\n * @param newQueueAddresses - Addresses of the new queues to add\n * @param newCpiContextAddresses - Addresses of the new cpi contexts to add\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n */\nexport async function extendStateTreeLookupTable({\n connection,\n tableAddress,\n newStateTreeAddresses,\n newQueueAddresses,\n newCpiContextAddresses,\n payer,\n authority,\n}: {\n connection: Connection;\n tableAddress: PublicKey;\n newStateTreeAddresses: PublicKey[];\n newQueueAddresses: PublicKey[];\n newCpiContextAddresses: PublicKey[];\n payer: Keypair;\n authority: Keypair;\n}): Promise<{ tableAddress: PublicKey; txId: string }> {\n const lutState = await connection.getAddressLookupTable(tableAddress);\n if (!lutState.value) {\n throw new Error('Lookup table not found');\n }\n if (lutState.value.state.addresses.length % 3 !== 0) {\n throw new Error('Lookup table must have a multiple of 3 addresses');\n }\n if (\n newStateTreeAddresses.length !== newQueueAddresses.length ||\n newStateTreeAddresses.length !== newCpiContextAddresses.length\n ) {\n throw new Error(\n 'Same number of newStateTreeAddresses, newQueueAddresses, and newCpiContextAddresses required',\n );\n }\n\n const instructions = AddressLookupTableProgram.extendLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n lookupTable: tableAddress,\n addresses: newStateTreeAddresses.flatMap((addr, index) => [\n addr,\n newQueueAddresses[index],\n newCpiContextAddresses[index],\n ]),\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx(\n [instructions],\n payer,\n blockhash.blockhash,\n dedupeSigner(payer as Signer, [authority]),\n );\n // we pass a Connection type so we don't have to depend on the Rpc module.\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n tableAddress,\n txId,\n };\n}\n\n/**\n * Adds state tree address to lookup table. Acts as nullifier lookup for rolled\n * over state trees.\n * @internal\n * @param connection - Connection to the Solana network\n * @param stateTreeAddress - Address of the state tree to nullify\n * @param nullifyTableAddress - Address of the nullifier lookup table to store\n * address in\n * @param stateTreeLookupTableAddress - lookup table storing all state tree\n * addresses\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n */\nexport async function nullifyLookupTable({\n connection,\n fullStateTreeAddress,\n nullifyTableAddress,\n stateTreeLookupTableAddress,\n payer,\n authority,\n}: {\n connection: Connection;\n fullStateTreeAddress: PublicKey;\n nullifyTableAddress: PublicKey;\n stateTreeLookupTableAddress: PublicKey;\n payer: Keypair;\n authority: Keypair;\n}): Promise<{ txId: string }> {\n // to be nullified address must be part of stateTreeLookupTable set\n const stateTreeLookupTable = await connection.getAddressLookupTable(\n stateTreeLookupTableAddress,\n );\n\n if (!stateTreeLookupTable.value) {\n throw new Error('State tree lookup table not found');\n }\n\n if (\n !stateTreeLookupTable.value.state.addresses.includes(\n fullStateTreeAddress,\n )\n ) {\n throw new Error(\n 'State tree address not found in lookup table. Pass correct address or stateTreeLookupTable',\n );\n }\n\n const nullifyTable =\n await connection.getAddressLookupTable(nullifyTableAddress);\n\n if (!nullifyTable.value) {\n throw new Error('Nullify table not found');\n }\n if (nullifyTable.value.state.addresses.includes(fullStateTreeAddress)) {\n throw new Error('Address already exists in nullify lookup table');\n }\n\n const instructions = AddressLookupTableProgram.extendLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n lookupTable: nullifyTableAddress,\n addresses: [fullStateTreeAddress],\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx([instructions], payer, blockhash.blockhash);\n // we pass a Connection type so we don't have to depend on the Rpc module.\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n txId,\n };\n}\n\n/**\n * Get most recent , active state tree data\n * we store in lookup table for each public state tree\n */\nexport async function getLightStateTreeInfo({\n connection,\n stateTreeLookupTableAddress,\n nullifyTableAddress,\n}: {\n connection: Connection;\n stateTreeLookupTableAddress: PublicKey;\n nullifyTableAddress: PublicKey;\n}): Promise<ActiveTreeBundle[]> {\n const stateTreeLookupTable = await connection.getAddressLookupTable(\n stateTreeLookupTableAddress,\n );\n\n if (!stateTreeLookupTable.value) {\n throw new Error('State tree lookup table not found');\n }\n\n if (stateTreeLookupTable.value.state.addresses.length % 3 !== 0) {\n throw new Error(\n 'State tree lookup table must have a multiple of 3 addresses',\n );\n }\n\n const nullifyTable =\n await connection.getAddressLookupTable(nullifyTableAddress);\n if (!nullifyTable.value) {\n throw new Error('Nullify table not found');\n }\n const stateTreePubkeys = stateTreeLookupTable.value.state.addresses;\n const nullifyTablePubkeys = nullifyTable.value.state.addresses;\n\n const bundles: ActiveTreeBundle[] = [];\n\n for (let i = 0; i < stateTreePubkeys.length; i += 3) {\n const tree = stateTreePubkeys[i];\n // Skip rolledover (full or almost full) Merkle trees\n if (!nullifyTablePubkeys.includes(tree)) {\n bundles.push({\n tree,\n queue: stateTreePubkeys[i + 1],\n cpiContext: stateTreePubkeys[i + 2],\n treeType: TreeType.State,\n });\n }\n }\n\n return bundles;\n}\n","/* The MIT License (MIT)\n *\n * Copyright 2015-2018 Peter A. Bigot\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n/**\n * Support for translating between Buffer instances and JavaScript\n * native types.\n *\n * {@link module:Layout~Layout|Layout} is the basis of a class\n * hierarchy that associates property names with sequences of encoded\n * bytes.\n *\n * Layouts are supported for these scalar (numeric) types:\n * * {@link module:Layout~UInt|Unsigned integers in little-endian\n * format} with {@link module:Layout.u8|8-bit}, {@link\n * module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},\n * {@link module:Layout.u32|32-bit}, {@link\n * module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}\n * representation ranges;\n * * {@link module:Layout~UIntBE|Unsigned integers in big-endian\n * format} with {@link module:Layout.u16be|16-bit}, {@link\n * module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},\n * {@link module:Layout.u40be|40-bit}, and {@link\n * module:Layout.u48be|48-bit} representation ranges;\n * * {@link module:Layout~Int|Signed integers in little-endian\n * format} with {@link module:Layout.s8|8-bit}, {@link\n * module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},\n * {@link module:Layout.s32|32-bit}, {@link\n * module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}\n * representation ranges;\n * * {@link module:Layout~IntBE|Signed integers in big-endian format}\n * with {@link module:Layout.s16be|16-bit}, {@link\n * module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},\n * {@link module:Layout.s40be|40-bit}, and {@link\n * module:Layout.s48be|48-bit} representation ranges;\n * * 64-bit integral values that decode to an exact (if magnitude is\n * less than 2^53) or nearby integral Number in {@link\n * module:Layout.nu64|unsigned little-endian}, {@link\n * module:Layout.nu64be|unsigned big-endian}, {@link\n * module:Layout.ns64|signed little-endian}, and {@link\n * module:Layout.ns64be|unsigned big-endian} encodings;\n * * 32-bit floating point values with {@link\n * module:Layout.f32|little-endian} and {@link\n * module:Layout.f32be|big-endian} representations;\n * * 64-bit floating point values with {@link\n * module:Layout.f64|little-endian} and {@link\n * module:Layout.f64be|big-endian} representations;\n * * {@link module:Layout.const|Constants} that take no space in the\n * encoded expression.\n *\n * and for these aggregate types:\n * * {@link module:Layout.seq|Sequence}s of instances of a {@link\n * module:Layout~Layout|Layout}, with JavaScript representation as\n * an Array and constant or data-dependent {@link\n * module:Layout~Sequence#count|length};\n * * {@link module:Layout.struct|Structure}s that aggregate a\n * heterogeneous sequence of {@link module:Layout~Layout|Layout}\n * instances, with JavaScript representation as an Object;\n * * {@link module:Layout.union|Union}s that support multiple {@link\n * module:Layout~VariantLayout|variant layouts} over a fixed\n * (padded) or variable (not padded) span of bytes, using an\n * unsigned integer at the start of the data or a separate {@link\n * module:Layout.unionLayoutDiscriminator|layout element} to\n * determine which layout to use when interpreting the buffer\n * contents;\n * * {@link module:Layout.bits|BitStructure}s that contain a sequence\n * of individual {@link\n * module:Layout~BitStructure#addField|BitField}s packed into an 8,\n * 16, 24, or 32-bit unsigned integer starting at the least- or\n * most-significant bit;\n * * {@link module:Layout.cstr|C strings} of varying length;\n * * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link\n * module:Layout~Blob#length|length} raw data.\n *\n * All {@link module:Layout~Layout|Layout} instances are immutable\n * after construction, to prevent internal state from becoming\n * inconsistent.\n *\n * @local Layout\n * @local ExternalLayout\n * @local GreedyCount\n * @local OffsetLayout\n * @local UInt\n * @local UIntBE\n * @local Int\n * @local IntBE\n * @local NearUInt64\n * @local NearUInt64BE\n * @local NearInt64\n * @local NearInt64BE\n * @local Float\n * @local FloatBE\n * @local Double\n * @local DoubleBE\n * @local Sequence\n * @local Structure\n * @local UnionDiscriminator\n * @local UnionLayoutDiscriminator\n * @local Union\n * @local VariantLayout\n * @local BitStructure\n * @local BitField\n * @local Boolean\n * @local Blob\n * @local CString\n * @local Constant\n * @local bindConstructorLayout\n * @module Layout\n * @license MIT\n * @author Peter A. Bigot\n * @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}\n */\n\n'use strict';\n\n/**\n * Base class for layout objects.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * Layout#encode|encode} or {@link Layout#decode|decode} functions.\n *\n * @param {Number} span - Initializer for {@link Layout#span|span}. The\n * parameter must be an integer; a negative value signifies that the\n * span is {@link Layout#getSpan|value-specific}.\n *\n * @param {string} [property] - Initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n */\nclass Layout {\n constructor(span, property) {\n if (!Number.isInteger(span)) {\n throw new TypeError('span must be an integer');\n }\n\n /** The span of the layout in bytes.\n *\n * Positive values are generally expected.\n *\n * Zero will only appear in {@link Constant}s and in {@link\n * Sequence}s where the {@link Sequence#count|count} is zero.\n *\n * A negative value indicates that the span is value-specific, and\n * must be obtained using {@link Layout#getSpan|getSpan}. */\n this.span = span;\n\n /** The property name used when this layout is represented in an\n * Object.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances. If left undefined the span of the unnamed layout will\n * be treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n\n /** Function to create an Object into which decoded properties will\n * be written.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances, which means:\n * * {@link Structure}\n * * {@link Union}\n * * {@link VariantLayout}\n * * {@link BitStructure}\n *\n * If left undefined the JavaScript representation of these layouts\n * will be Object instances.\n *\n * See {@link bindConstructorLayout}.\n */\n makeDestinationObject() {\n return {};\n }\n\n /**\n * Decode from a Buffer into an JavaScript value.\n *\n * @param {Buffer} b - the buffer from which encoded data is read.\n *\n * @param {Number} [offset] - the offset at which the encoded data\n * starts. If absent a zero offset is inferred.\n *\n * @returns {(Number|Array|Object)} - the value of the decoded data.\n *\n * @abstract\n */\n decode(b, offset) {\n throw new Error('Layout is abstract');\n }\n\n /**\n * Encode a JavaScript value into a Buffer.\n *\n * @param {(Number|Array|Object)} src - the value to be encoded into\n * the buffer. The type accepted depends on the (sub-)type of {@link\n * Layout}.\n *\n * @param {Buffer} b - the buffer into which encoded data will be\n * written.\n *\n * @param {Number} [offset] - the offset at which the encoded data\n * starts. If absent a zero offset is inferred.\n *\n * @returns {Number} - the number of bytes encoded, including the\n * space skipped for internal padding, but excluding data such as\n * {@link Sequence#count|lengths} when stored {@link\n * ExternalLayout|externally}. This is the adjustment to `offset`\n * producing the offset where data for the next layout would be\n * written.\n *\n * @abstract\n */\n encode(src, b, offset) {\n throw new Error('Layout is abstract');\n }\n\n /**\n * Calculate the span of a specific instance of a layout.\n *\n * @param {Buffer} b - the buffer that contains an encoded instance.\n *\n * @param {Number} [offset] - the offset at which the encoded instance\n * starts. If absent a zero offset is inferred.\n *\n * @return {Number} - the number of bytes covered by the layout\n * instance. If this method is not overridden in a subclass the\n * definition-time constant {@link Layout#span|span} will be\n * returned.\n *\n * @throws {RangeError} - if the length of the value cannot be\n * determined.\n */\n getSpan(b, offset) {\n if (0 > this.span) {\n throw new RangeError('indeterminate span');\n }\n return this.span;\n }\n\n /**\n * Replicate the layout using a new property.\n *\n * This function must be used to get a structurally-equivalent layout\n * with a different name since all {@link Layout} instances are\n * immutable.\n *\n * **NOTE** This is a shallow copy. All fields except {@link\n * Layout#property|property} are strictly equal to the origin layout.\n *\n * @param {String} property - the value for {@link\n * Layout#property|property} in the replica.\n *\n * @returns {Layout} - the copy with {@link Layout#property|property}\n * set to `property`.\n */\n replicate(property) {\n const rv = Object.create(this.constructor.prototype);\n Object.assign(rv, this);\n rv.property = property;\n return rv;\n }\n\n /**\n * Create an object from layout properties and an array of values.\n *\n * **NOTE** This function returns `undefined` if invoked on a layout\n * that does not return its value as an Object. Objects are\n * returned for things that are a {@link Structure}, which includes\n * {@link VariantLayout|variant layouts} if they are structures, and\n * excludes {@link Union}s. If you want this feature for a union\n * you must use {@link Union.getVariant|getVariant} to select the\n * desired layout.\n *\n * @param {Array} values - an array of values that correspond to the\n * default order for properties. As with {@link Layout#decode|decode}\n * layout elements that have no property name are skipped when\n * iterating over the array values. Only the top-level properties are\n * assigned; arguments are not assigned to properties of contained\n * layouts. Any unused values are ignored.\n *\n * @return {(Object|undefined)}\n */\n fromArray(values) {\n return undefined;\n }\n}\nexports.Layout = Layout;\n\n/* Provide text that carries a name (such as for a function that will\n * be throwing an error) annotated with the property of a given layout\n * (such as one for which the value was unacceptable).\n *\n * @ignore */\nfunction nameWithProperty(name, lo) {\n if (lo.property) {\n return name + '[' + lo.property + ']';\n }\n return name;\n}\nexports.nameWithProperty = nameWithProperty;\n\n/**\n * Augment a class so that instances can be encoded/decoded using a\n * given layout.\n *\n * Calling this function couples `Class` with `layout` in several ways:\n *\n * * `Class.layout_` becomes a static member property equal to `layout`;\n * * `layout.boundConstructor_` becomes a static member property equal\n * to `Class`;\n * * The {@link Layout#makeDestinationObject|makeDestinationObject()}\n * property of `layout` is set to a function that returns a `new\n * Class()`;\n * * `Class.decode(b, offset)` becomes a static member function that\n * delegates to {@link Layout#decode|layout.decode}. The\n * synthesized function may be captured and extended.\n * * `Class.prototype.encode(b, offset)` provides an instance member\n * function that delegates to {@link Layout#encode|layout.encode}\n * with `src` set to `this`. The synthesized function may be\n * captured and extended, but when the extension is invoked `this`\n * must be explicitly bound to the instance.\n *\n * @param {class} Class - a JavaScript class with a nullary\n * constructor.\n *\n * @param {Layout} layout - the {@link Layout} instance used to encode\n * instances of `Class`.\n */\nfunction bindConstructorLayout(Class, layout) {\n if ('function' !== typeof Class) {\n throw new TypeError('Class must be constructor');\n }\n if (Class.hasOwnProperty('layout_')) {\n throw new Error('Class is already bound to a layout');\n }\n if (!(layout && (layout instanceof Layout))) {\n throw new TypeError('layout must be a Layout');\n }\n if (layout.hasOwnProperty('boundConstructor_')) {\n throw new Error('layout is already bound to a constructor');\n }\n Class.layout_ = layout;\n layout.boundConstructor_ = Class;\n layout.makeDestinationObject = (() => new Class());\n Object.defineProperty(Class.prototype, 'encode', {\n value: function(b, offset) {\n return layout.encode(this, b, offset);\n },\n writable: true,\n });\n Object.defineProperty(Class, 'decode', {\n value: function(b, offset) {\n return layout.decode(b, offset);\n },\n writable: true,\n });\n}\nexports.bindConstructorLayout = bindConstructorLayout;\n\n/**\n * An object that behaves like a layout but does not consume space\n * within its containing layout.\n *\n * This is primarily used to obtain metadata about a member, such as a\n * {@link OffsetLayout} that can provide data about a {@link\n * Layout#getSpan|value-specific span}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support {@link\n * ExternalLayout#isCount|isCount} or other {@link Layout} functions.\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n * @augments {Layout}\n */\nclass ExternalLayout extends Layout {\n /**\n * Return `true` iff the external layout decodes to an unsigned\n * integer layout.\n *\n * In that case it can be used as the source of {@link\n * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},\n * or as {@link UnionLayoutDiscriminator#layout|external union\n * discriminators}.\n *\n * @abstract\n */\n isCount() {\n throw new Error('ExternalLayout is abstract');\n }\n}\n\n/**\n * An {@link ExternalLayout} that determines its {@link\n * Layout#decode|value} based on offset into and length of the buffer\n * on which it is invoked.\n *\n * *Factory*: {@link module:Layout.greedy|greedy}\n *\n * @param {Number} [elementSpan] - initializer for {@link\n * GreedyCount#elementSpan|elementSpan}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {ExternalLayout}\n */\nclass GreedyCount extends ExternalLayout {\n constructor(elementSpan, property) {\n if (undefined === elementSpan) {\n elementSpan = 1;\n }\n if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {\n throw new TypeError('elementSpan must be a (positive) integer');\n }\n super(-1, property);\n\n /** The layout for individual elements of the sequence. The value\n * must be a positive integer. If not provided, the value will be\n * 1. */\n this.elementSpan = elementSpan;\n }\n\n /** @override */\n isCount() {\n return true;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const rem = b.length - offset;\n return Math.floor(rem / this.elementSpan);\n }\n\n /** @override */\n encode(src, b, offset) {\n return 0;\n }\n}\n\n/**\n * An {@link ExternalLayout} that supports accessing a {@link Layout}\n * at a fixed offset from the start of another Layout. The offset may\n * be before, within, or after the base layout.\n *\n * *Factory*: {@link module:Layout.offset|offset}\n *\n * @param {Layout} layout - initializer for {@link\n * OffsetLayout#layout|layout}, modulo `property`.\n *\n * @param {Number} [offset] - Initializes {@link\n * OffsetLayout#offset|offset}. Defaults to zero.\n *\n * @param {string} [property] - Optional new property name for a\n * {@link Layout#replicate| replica} of `layout` to be used as {@link\n * OffsetLayout#layout|layout}. If not provided the `layout` is used\n * unchanged.\n *\n * @augments {Layout}\n */\nclass OffsetLayout extends ExternalLayout {\n constructor(layout, offset, property) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n\n if (undefined === offset) {\n offset = 0;\n } else if (!Number.isInteger(offset)) {\n throw new TypeError('offset must be integer or undefined');\n }\n\n super(layout.span, property || layout.property);\n\n /** The subordinated layout. */\n this.layout = layout;\n\n /** The location of {@link OffsetLayout#layout} relative to the\n * start of another layout.\n *\n * The value may be positive or negative, but an error will thrown\n * if at the point of use it goes outside the span of the Buffer\n * being accessed. */\n this.offset = offset;\n }\n\n /** @override */\n isCount() {\n return ((this.layout instanceof UInt)\n || (this.layout instanceof UIntBE));\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return this.layout.decode(b, offset + this.offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return this.layout.encode(src, b, offset + this.offset);\n }\n}\n\n/**\n * Represent an unsigned integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.u8|u8}, {@link\n * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link\n * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link\n * module:Layout.u48|u48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UInt extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readUIntLE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeUIntLE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent an unsigned integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.u8be|u8be}, {@link\n * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},\n * {@link module:Layout.u32be|u32be}, {@link\n * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UIntBE extends Layout {\n constructor(span, property) {\n super( span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readUIntBE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeUIntBE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent a signed integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.s8|s8}, {@link\n * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link\n * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link\n * module:Layout.s48|s48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Int extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readIntLE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeIntLE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent a signed integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.s8be|s8be}, {@link\n * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},\n * {@link module:Layout.s32be|s32be}, {@link\n * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass IntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readIntBE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeIntBE(src, offset, this.span);\n return this.span;\n }\n}\n\nconst V2E32 = Math.pow(2, 32);\n\n/* True modulus high and low 32-bit words, where low word is always\n * non-negative. */\nfunction divmodInt64(src) {\n const hi32 = Math.floor(src / V2E32);\n const lo32 = src - (hi32 * V2E32);\n return {hi32, lo32};\n}\n/* Reconstruct Number from quotient and non-negative remainder */\nfunction roundedInt64(hi32, lo32) {\n return hi32 * V2E32 + lo32;\n}\n\n/**\n * Represent an unsigned 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64|nu64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const lo32 = b.readUInt32LE(offset);\n const hi32 = b.readUInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32LE(split.lo32, offset);\n b.writeUInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent an unsigned 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64be|nu64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const hi32 = b.readUInt32BE(offset);\n const lo32 = b.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32BE(split.hi32, offset);\n b.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a signed 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64|ns64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const lo32 = b.readUInt32LE(offset);\n const hi32 = b.readInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32LE(split.lo32, offset);\n b.writeInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a signed 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64be|ns64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const hi32 = b.readInt32BE(offset);\n const lo32 = b.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeInt32BE(split.hi32, offset);\n b.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a 32-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f32|f32}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Float extends Layout {\n constructor(property) {\n super(4, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readFloatLE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeFloatLE(src, offset);\n return 4;\n }\n}\n\n/**\n * Represent a 32-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f32be|f32be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass FloatBE extends Layout {\n constructor(property) {\n super(4, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readFloatBE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeFloatBE(src, offset);\n return 4;\n }\n}\n\n/**\n * Represent a 64-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f64|f64}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Double extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readDoubleLE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeDoubleLE(src, offset);\n return 8;\n }\n}\n\n/**\n * Represent a 64-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f64be|f64be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass DoubleBE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readDoubleBE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeDoubleBE(src, offset);\n return 8;\n }\n}\n\n/**\n * Represent a contiguous sequence of a specific layout as an Array.\n *\n * *Factory*: {@link module:Layout.seq|seq}\n *\n * @param {Layout} elementLayout - initializer for {@link\n * Sequence#elementLayout|elementLayout}.\n *\n * @param {(Number|ExternalLayout)} count - initializer for {@link\n * Sequence#count|count}. The parameter must be either a positive\n * integer or an instance of {@link ExternalLayout}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Sequence extends Layout {\n constructor(elementLayout, count, property) {\n if (!(elementLayout instanceof Layout)) {\n throw new TypeError('elementLayout must be a Layout');\n }\n if (!(((count instanceof ExternalLayout) && count.isCount())\n || (Number.isInteger(count) && (0 <= count)))) {\n throw new TypeError('count must be non-negative integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if ((!(count instanceof ExternalLayout))\n && (0 < elementLayout.span)) {\n span = count * elementLayout.span;\n }\n\n super(span, property);\n\n /** The layout for individual elements of the sequence. */\n this.elementLayout = elementLayout;\n\n /** The number of elements in the sequence.\n *\n * This will be either a non-negative integer or an instance of\n * {@link ExternalLayout} for which {@link\n * ExternalLayout#isCount|isCount()} is `true`. */\n this.count = count;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let span = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n if (0 < this.elementLayout.span) {\n span = count * this.elementLayout.span;\n } else {\n let idx = 0;\n while (idx < count) {\n span += this.elementLayout.getSpan(b, offset + span);\n ++idx;\n }\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const rv = [];\n let i = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n while (i < count) {\n rv.push(this.elementLayout.decode(b, offset));\n offset += this.elementLayout.getSpan(b, offset);\n i += 1;\n }\n return rv;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Sequence}.\n *\n * **NOTE** If `src` is shorter than {@link Sequence#count|count} then\n * the unused space in the buffer is left unchanged. If `src` is\n * longer than {@link Sequence#count|count} the unneeded elements are\n * ignored.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const elo = this.elementLayout;\n const span = src.reduce((span, v) => {\n return span + elo.encode(v, b, offset + span);\n }, 0);\n if (this.count instanceof ExternalLayout) {\n this.count.encode(src.length, b, offset);\n }\n return span;\n }\n}\n\n/**\n * Represent a contiguous sequence of arbitrary layout elements as an\n * Object.\n *\n * *Factory*: {@link module:Layout.struct|struct}\n *\n * **NOTE** The {@link Layout#span|span} of the structure is variable\n * if any layout in {@link Structure#fields|fields} has a variable\n * span. When {@link Layout#encode|encoding} we must have a value for\n * all variable-length fields, or we wouldn't be able to figure out\n * how much space to use for storage. We can only identify the value\n * for a field when it has a {@link Layout#property|property}. As\n * such, although a structure may contain both unnamed fields and\n * variable-length fields, it cannot contain an unnamed\n * variable-length field.\n *\n * @param {Layout[]} fields - initializer for {@link\n * Structure#fields|fields}. An error is raised if this contains a\n * variable-length field for which a {@link Layout#property|property}\n * is not defined.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @param {Boolean} [decodePrefixes] - initializer for {@link\n * Structure#decodePrefixes|property}.\n *\n * @throws {Error} - if `fields` contains an unnamed variable-length\n * layout.\n *\n * @augments {Layout}\n */\nclass Structure extends Layout {\n constructor(fields, property, decodePrefixes) {\n if (!(Array.isArray(fields)\n && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {\n throw new TypeError('fields must be array of Layout instances');\n }\n if (('boolean' === typeof property)\n && (undefined === decodePrefixes)) {\n decodePrefixes = property;\n property = undefined;\n }\n\n /* Verify absence of unnamed variable-length fields. */\n for (const fd of fields) {\n if ((0 > fd.span)\n && (undefined === fd.property)) {\n throw new Error('fields cannot contain unnamed variable-length layout');\n }\n }\n\n let span = -1;\n try {\n span = fields.reduce((span, fd) => span + fd.getSpan(), 0);\n } catch (e) {\n }\n super(span, property);\n\n /** The sequence of {@link Layout} values that comprise the\n * structure.\n *\n * The individual elements need not be the same type, and may be\n * either scalar or aggregate layouts. If a member layout leaves\n * its {@link Layout#property|property} undefined the\n * corresponding region of the buffer associated with the element\n * will not be mutated.\n *\n * @type {Layout[]} */\n this.fields = fields;\n\n /** Control behavior of {@link Layout#decode|decode()} given short\n * buffers.\n *\n * In some situations a structure many be extended with additional\n * fields over time, with older installations providing only a\n * prefix of the full structure. If this property is `true`\n * decoding will accept those buffers and leave subsequent fields\n * undefined, as long as the buffer ends at a field boundary.\n * Defaults to `false`. */\n this.decodePrefixes = !!decodePrefixes;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let span = 0;\n try {\n span = this.fields.reduce((span, fd) => {\n const fsp = fd.getSpan(b, offset);\n offset += fsp;\n return span + fsp;\n }, 0);\n } catch (e) {\n throw new RangeError('indeterminate span');\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b, offset);\n }\n offset += fd.getSpan(b, offset);\n if (this.decodePrefixes\n && (b.length === offset)) {\n break;\n }\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Structure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the buffer is\n * left unmodified. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const firstOffset = offset;\n let lastOffset = 0;\n let lastWrote = 0;\n for (const fd of this.fields) {\n let span = fd.span;\n lastWrote = (0 < span) ? span : 0;\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n lastWrote = fd.encode(fv, b, offset);\n if (0 > span) {\n /* Read the as-encoded span, which is not necessarily the\n * same as what we wrote. */\n span = fd.getSpan(b, offset);\n }\n }\n }\n lastOffset = offset;\n offset += span;\n }\n /* Use (lastOffset + lastWrote) instead of offset because the last\n * item may have had a dynamic length and we don't want to include\n * the padding between it and the end of the space reserved for\n * it. */\n return (lastOffset + lastWrote) - firstOffset;\n }\n\n /** @override */\n fromArray(values) {\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if ((undefined !== fd.property)\n && (0 < values.length)) {\n dest[fd.property] = values.shift();\n }\n }\n return dest;\n }\n\n /**\n * Get access to the layout of a given property.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Layout} - the layout associated with `property`, or\n * undefined if there is no such property.\n */\n layoutFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n }\n\n /**\n * Get the offset of a structure member.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Number} - the offset in bytes to the start of `property`\n * within the structure, or undefined if `property` is not a field\n * within the structure. If the property is a member but follows a\n * variable-length structure member a negative number will be\n * returned.\n */\n offsetOf(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n let offset = 0;\n for (const fd of this.fields) {\n if (fd.property === property) {\n return offset;\n }\n if (0 > fd.span) {\n offset = -1;\n } else if (0 <= offset) {\n offset += fd.span;\n }\n }\n }\n}\n\n/**\n * An object that can provide a {@link\n * Union#discriminator|discriminator} API for {@link Union}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * UnionDiscriminator#encode|encode} or {@link\n * UnionDiscriminator#decode|decode} functions.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}.\n *\n * @abstract\n */\nclass UnionDiscriminator {\n constructor(property) {\n /** The {@link Layout#property|property} to be used when the\n * discriminator is referenced in isolation (generally when {@link\n * Union#decode|Union decode} cannot delegate to a specific\n * variant). */\n this.property = property;\n }\n\n /** Analog to {@link Layout#decode|Layout decode} for union discriminators.\n *\n * The implementation of this method need not reference the buffer if\n * variant information is available through other means. */\n decode() {\n throw new Error('UnionDiscriminator is abstract');\n }\n\n /** Analog to {@link Layout#decode|Layout encode} for union discriminators.\n *\n * The implementation of this method need not store the value if\n * variant information is maintained through other means. */\n encode() {\n throw new Error('UnionDiscriminator is abstract');\n }\n}\n\n/**\n * An object that can provide a {@link\n * UnionDiscriminator|discriminator API} for {@link Union} using an\n * unsigned integral {@link Layout} instance located either inside or\n * outside the union.\n *\n * @param {ExternalLayout} layout - initializes {@link\n * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link\n * ExternalLayout#isCount|isCount()}.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}, superseding the property\n * from `layout`, but defaulting to `variant` if neither `property`\n * nor layout provide a property name.\n *\n * @augments {UnionDiscriminator}\n */\nclass UnionLayoutDiscriminator extends UnionDiscriminator {\n constructor(layout, property) {\n if (!((layout instanceof ExternalLayout)\n && layout.isCount())) {\n throw new TypeError('layout must be an unsigned integer ExternalLayout');\n }\n\n super(property || layout.property || 'variant');\n\n /** The {@link ExternalLayout} used to access the discriminator\n * value. */\n this.layout = layout;\n }\n\n /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n decode(b, offset) {\n return this.layout.decode(b, offset);\n }\n\n /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n encode(src, b, offset) {\n return this.layout.encode(src, b, offset);\n }\n}\n\n/**\n * Represent any number of span-compatible layouts.\n *\n * *Factory*: {@link module:Layout.union|union}\n *\n * If the union has a {@link Union#defaultLayout|default layout} that\n * layout must have a non-negative {@link Layout#span|span}. The span\n * of a fixed-span union includes its {@link\n * Union#discriminator|discriminator} if the variant is a {@link\n * Union#usesPrefixDiscriminator|prefix of the union}, plus the span\n * of its {@link Union#defaultLayout|default layout}.\n *\n * If the union does not have a default layout then the encoded span\n * of the union depends on the encoded span of its variant (which may\n * be fixed or variable).\n *\n * {@link VariantLayout#layout|Variant layout}s are added through\n * {@link Union#addVariant|addVariant}. If the union has a default\n * layout, the span of the {@link VariantLayout#layout|layout\n * contained by the variant} must not exceed the span of the {@link\n * Union#defaultLayout|default layout} (minus the span of a {@link\n * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The\n * span of the variant will equal the span of the union itself.\n *\n * The variant for a buffer can only be identified from the {@link\n * Union#discriminator|discriminator} {@link\n * UnionDiscriminator#property|property} (in the case of the {@link\n * Union#defaultLayout|default layout}), or by using {@link\n * Union#getVariant|getVariant} and examining the resulting {@link\n * VariantLayout} instance.\n *\n * A variant compatible with a JavaScript object can be identified\n * using {@link Union#getSourceVariant|getSourceVariant}.\n *\n * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to\n * identify the layout used to interpret the union contents. The\n * parameter must be an instance of {@link UnionDiscriminator}, an\n * {@link ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link\n * UIntBE}). When a non-external layout element is passed the layout\n * appears at the start of the union. In all cases the (synthesized)\n * {@link UnionDiscriminator} instance is recorded as {@link\n * Union#discriminator|discriminator}.\n *\n * @param {(Layout|null)} defaultLayout - initializer for {@link\n * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.\n * If `null` there is no default layout: the union has data-dependent\n * length and attempts to decode or encode unrecognized variants will\n * throw an exception. A {@link Layout} instance must have a\n * non-negative {@link Layout#span|span}, and if it lacks a {@link\n * Layout#property|property} the {@link\n * Union#defaultLayout|defaultLayout} will be a {@link\n * Layout#replicate|replica} with property `content`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Union extends Layout {\n constructor(discr, defaultLayout, property) {\n const upv = ((discr instanceof UInt)\n || (discr instanceof UIntBE));\n if (upv) {\n discr = new UnionLayoutDiscriminator(new OffsetLayout(discr));\n } else if ((discr instanceof ExternalLayout)\n && discr.isCount()) {\n discr = new UnionLayoutDiscriminator(discr);\n } else if (!(discr instanceof UnionDiscriminator)) {\n throw new TypeError('discr must be a UnionDiscriminator '\n + 'or an unsigned integer layout');\n }\n if (undefined === defaultLayout) {\n defaultLayout = null;\n }\n if (!((null === defaultLayout)\n || (defaultLayout instanceof Layout))) {\n throw new TypeError('defaultLayout must be null or a Layout');\n }\n if (null !== defaultLayout) {\n if (0 > defaultLayout.span) {\n throw new Error('defaultLayout must have constant span');\n }\n if (undefined === defaultLayout.property) {\n defaultLayout = defaultLayout.replicate('content');\n }\n }\n\n /* The union span can be estimated only if there's a default\n * layout. The union spans its default layout, plus any prefix\n * variant layout. By construction both layouts, if present, have\n * non-negative span. */\n let span = -1;\n if (defaultLayout) {\n span = defaultLayout.span;\n if ((0 <= span) && upv) {\n span += discr.layout.span;\n }\n }\n super(span, property);\n\n /** The interface for the discriminator value in isolation.\n *\n * This a {@link UnionDiscriminator} either passed to the\n * constructor or synthesized from the `discr` constructor\n * argument. {@link\n * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be\n * `true` iff the `discr` parameter was a non-offset {@link\n * Layout} instance. */\n this.discriminator = discr;\n\n /** `true` if the {@link Union#discriminator|discriminator} is the\n * first field in the union.\n *\n * If `false` the discriminator is obtained from somewhere\n * else. */\n this.usesPrefixDiscriminator = upv;\n\n /** The layout for non-discriminator content when the value of the\n * discriminator is not recognized.\n *\n * This is the value passed to the constructor. It is\n * structurally equivalent to the second component of {@link\n * Union#layout|layout} but may have a different property\n * name. */\n this.defaultLayout = defaultLayout;\n\n /** A registry of allowed variants.\n *\n * The keys are unsigned integers which should be compatible with\n * {@link Union.discriminator|discriminator}. The property value\n * is the corresponding {@link VariantLayout} instances assigned\n * to this union by {@link Union#addVariant|addVariant}.\n *\n * **NOTE** The registry remains mutable so that variants can be\n * {@link Union#addVariant|added} at any time. Users should not\n * manipulate the content of this property. */\n this.registry = {};\n\n /* Private variable used when invoking getSourceVariant */\n let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);\n\n /** Function to infer the variant selected by a source object.\n *\n * Defaults to {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may\n * be overridden using {@link\n * Union#configGetSourceVariant|configGetSourceVariant}.\n *\n * @param {Object} src - as with {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * @returns {(undefined|VariantLayout)} The default variant\n * (`undefined`) or first registered variant that uses a property\n * available in `src`. */\n this.getSourceVariant = function(src) {\n return boundGetSourceVariant(src);\n };\n\n /** Function to override the implementation of {@link\n * Union#getSourceVariant|getSourceVariant}.\n *\n * Use this if the desired variant cannot be identified using the\n * algorithm of {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * **NOTE** The provided function will be invoked bound to this\n * Union instance, providing local access to {@link\n * Union#registry|registry}.\n *\n * @param {Function} gsv - a function that follows the API of\n * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */\n this.configGetSourceVariant = function(gsv) {\n boundGetSourceVariant = gsv.bind(this);\n };\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n /* Default layouts always have non-negative span, so we don't have\n * one and we have to recognize the variant which will in turn\n * determine the span. */\n const vlo = this.getVariant(b, offset);\n if (!vlo) {\n throw new Error('unable to determine span for unrecognized variant');\n }\n return vlo.getSpan(b, offset);\n }\n\n /**\n * Method to infer a registered Union variant compatible with `src`.\n *\n * The first satisified rule in the following sequence defines the\n * return value:\n * * If `src` has properties matching the Union discriminator and\n * the default layout, `undefined` is returned regardless of the\n * value of the discriminator property (this ensures the default\n * layout will be used);\n * * If `src` has a property matching the Union discriminator, the\n * value of the discriminator identifies a registered variant, and\n * either (a) the variant has no layout, or (b) `src` has the\n * variant's property, then the variant is returned (because the\n * source satisfies the constraints of the variant it identifies);\n * * If `src` does not have a property matching the Union\n * discriminator, but does have a property matching a registered\n * variant, then the variant is returned (because the source\n * matches a variant without an explicit conflict);\n * * An error is thrown (because we either can't identify a variant,\n * or we were explicitly told the variant but can't satisfy it).\n *\n * @param {Object} src - an object presumed to be compatible with\n * the content of the Union.\n *\n * @return {(undefined|VariantLayout)} - as described above.\n *\n * @throws {Error} - if `src` cannot be associated with a default or\n * registered variant.\n */\n defaultGetSourceVariant(src) {\n if (src.hasOwnProperty(this.discriminator.property)) {\n if (this.defaultLayout\n && src.hasOwnProperty(this.defaultLayout.property)) {\n return undefined;\n }\n const vlo = this.registry[src[this.discriminator.property]];\n if (vlo\n && ((!vlo.layout)\n || src.hasOwnProperty(vlo.property))) {\n return vlo;\n }\n } else {\n for (const tag in this.registry) {\n const vlo = this.registry[tag];\n if (src.hasOwnProperty(vlo.property)) {\n return vlo;\n }\n }\n }\n throw new Error('unable to infer src variant');\n }\n\n /** Implement {@link Layout#decode|decode} for {@link Union}.\n *\n * If the variant is {@link Union#addVariant|registered} the return\n * value is an instance of that variant, with no explicit\n * discriminator. Otherwise the {@link Union#defaultLayout|default\n * layout} is used to decode the content. */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let dest;\n const dlo = this.discriminator;\n const discr = dlo.decode(b, offset);\n let clo = this.registry[discr];\n if (undefined === clo) {\n let contentOffset = 0;\n clo = this.defaultLayout;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dest = this.makeDestinationObject();\n dest[dlo.property] = discr;\n dest[clo.property] = this.defaultLayout.decode(b, offset + contentOffset);\n } else {\n dest = clo.decode(b, offset);\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Union}.\n *\n * This API assumes the `src` object is consistent with the union's\n * {@link Union#defaultLayout|default layout}. To encode variants\n * use the appropriate variant-specific {@link VariantLayout#encode}\n * method. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const vlo = this.getSourceVariant(src);\n if (undefined === vlo) {\n const dlo = this.discriminator;\n const clo = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dlo.encode(src[dlo.property], b, offset);\n return contentOffset + clo.encode(src[clo.property], b,\n offset + contentOffset);\n }\n return vlo.encode(src, b, offset);\n }\n\n /** Register a new variant structure within a union. The newly\n * created variant is returned.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} layout - initializer for {@link\n * VariantLayout#layout|layout}.\n *\n * @param {String} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {VariantLayout} */\n addVariant(variant, layout, property) {\n const rv = new VariantLayout(this, variant, layout, property);\n this.registry[variant] = rv;\n return rv;\n }\n\n /**\n * Get the layout associated with a registered variant.\n *\n * If `vb` does not produce a registered variant the function returns\n * `undefined`.\n *\n * @param {(Number|Buffer)} vb - either the variant number, or a\n * buffer from which the discriminator is to be read.\n *\n * @param {Number} offset - offset into `vb` for the start of the\n * union. Used only when `vb` is an instance of {Buffer}.\n *\n * @return {({VariantLayout}|undefined)}\n */\n getVariant(vb, offset) {\n let variant = vb;\n if (Buffer.isBuffer(vb)) {\n if (undefined === offset) {\n offset = 0;\n }\n variant = this.discriminator.decode(vb, offset);\n }\n return this.registry[variant];\n }\n}\n\n/**\n * Represent a specific variant within a containing union.\n *\n * **NOTE** The {@link Layout#span|span} of the variant may include\n * the span of the {@link Union#discriminator|discriminator} used to\n * identify it, but values read and written using the variant strictly\n * conform to the content of {@link VariantLayout#layout|layout}.\n *\n * **NOTE** User code should not invoke this constructor directly. Use\n * the union {@link Union#addVariant|addVariant} helper method.\n *\n * @param {Union} union - initializer for {@link\n * VariantLayout#union|union}.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} [layout] - initializer for {@link\n * VariantLayout#layout|layout}. If absent the variant carries no\n * data.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}. Unlike many other layouts, variant\n * layouts normally include a property name so they can be identified\n * within their containing {@link Union}. The property identifier may\n * be absent only if `layout` is is absent.\n *\n * @augments {Layout}\n */\nclass VariantLayout extends Layout {\n constructor(union, variant, layout, property) {\n if (!(union instanceof Union)) {\n throw new TypeError('union must be a Union');\n }\n if ((!Number.isInteger(variant)) || (0 > variant)) {\n throw new TypeError('variant must be a (non-negative) integer');\n }\n if (('string' === typeof layout)\n && (undefined === property)) {\n property = layout;\n layout = null;\n }\n if (layout) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if ((null !== union.defaultLayout)\n && (0 <= layout.span)\n && (layout.span > union.defaultLayout.span)) {\n throw new Error('variant span exceeds span of containing union');\n }\n if ('string' !== typeof property) {\n throw new TypeError('variant must have a String property');\n }\n }\n let span = union.span;\n if (0 > union.span) {\n span = layout ? layout.span : 0;\n if ((0 <= span) && union.usesPrefixDiscriminator) {\n span += union.discriminator.layout.span;\n }\n }\n super(span, property);\n\n /** The {@link Union} to which this variant belongs. */\n this.union = union;\n\n /** The unsigned integral value identifying this variant within\n * the {@link Union#discriminator|discriminator} of the containing\n * union. */\n this.variant = variant;\n\n /** The {@link Layout} to be used when reading/writing the\n * non-discriminator part of the {@link\n * VariantLayout#union|union}. If `null` the variant carries no\n * data. */\n this.layout = layout || null;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n /* Will be equal to the containing union span if that is not\n * variable. */\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n /* Span is defined solely by the variant (and prefix discriminator) */\n return contentOffset + this.layout.getSpan(b, offset + contentOffset);\n }\n\n /** @override */\n decode(b, offset) {\n const dest = this.makeDestinationObject();\n if (undefined === offset) {\n offset = 0;\n }\n if (this !== this.union.getVariant(b, offset)) {\n throw new Error('variant mismatch');\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout) {\n dest[this.property] = this.layout.decode(b, offset + contentOffset);\n } else if (this.property) {\n dest[this.property] = true;\n } else if (this.union.usesPrefixDiscriminator) {\n dest[this.union.discriminator.property] = this.variant;\n }\n return dest;\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout\n && (!src.hasOwnProperty(this.property))) {\n throw new TypeError('variant lacks property ' + this.property);\n }\n this.union.discriminator.encode(this.variant, b, offset);\n let span = contentOffset;\n if (this.layout) {\n this.layout.encode(src[this.property], b, offset + contentOffset);\n span += this.layout.getSpan(b, offset + contentOffset);\n if ((0 <= this.union.span)\n && (span > this.union.span)) {\n throw new Error('encoded variant overruns containing union');\n }\n }\n return span;\n }\n\n /** Delegate {@link Layout#fromArray|fromArray} to {@link\n * VariantLayout#layout|layout}. */\n fromArray(values) {\n if (this.layout) {\n return this.layout.fromArray(values);\n }\n }\n}\n\n/** JavaScript chose to define bitwise operations as operating on\n * signed 32-bit values in 2's complement form, meaning any integer\n * with bit 31 set is going to look negative. For right shifts that's\n * not a problem, because `>>>` is a logical shift, but for every\n * other bitwise operator we have to compensate for possible negative\n * results. */\nfunction fixBitwiseResult(v) {\n if (0 > v) {\n v += 0x100000000;\n }\n return v;\n}\n\n/**\n * Contain a sequence of bit fields as an unsigned integer.\n *\n * *Factory*: {@link module:Layout.bits|bits}\n *\n * This is a container element; within it there are {@link BitField}\n * instances that provide the extracted properties. The container\n * simply defines the aggregate representation and its bit ordering.\n * The representation is an object containing properties with numeric\n * or {@link Boolean} values.\n *\n * {@link BitField}s are added with the {@link\n * BitStructure#addField|addField} and {@link\n * BitStructure#addBoolean|addBoolean} methods.\n\n * @param {Layout} word - initializer for {@link\n * BitStructure#word|word}. The parameter must be an instance of\n * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.\n *\n * @param {bool} [msb] - `true` if the bit numbering starts at the\n * most significant bit of the containing word; `false` (default) if\n * it starts at the least significant bit of the containing word. If\n * the parameter at this position is a string and `property` is\n * `undefined` the value of this argument will instead be used as the\n * value of `property`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass BitStructure extends Layout {\n constructor(word, msb, property) {\n if (!((word instanceof UInt)\n || (word instanceof UIntBE))) {\n throw new TypeError('word must be a UInt or UIntBE layout');\n }\n if (('string' === typeof msb)\n && (undefined === property)) {\n property = msb;\n msb = undefined;\n }\n if (4 < word.span) {\n throw new RangeError('word cannot exceed 32 bits');\n }\n super(word.span, property);\n\n /** The layout used for the packed value. {@link BitField}\n * instances are packed sequentially depending on {@link\n * BitStructure#msb|msb}. */\n this.word = word;\n\n /** Whether the bit sequences are packed starting at the most\n * significant bit growing down (`true`), or the least significant\n * bit growing up (`false`).\n *\n * **NOTE** Regardless of this value, the least significant bit of\n * any {@link BitField} value is the least significant bit of the\n * corresponding section of the packed value. */\n this.msb = !!msb;\n\n /** The sequence of {@link BitField} layouts that comprise the\n * packed structure.\n *\n * **NOTE** The array remains mutable to allow fields to be {@link\n * BitStructure#addField|added} after construction. Users should\n * not manipulate the content of this property.*/\n this.fields = [];\n\n /* Storage for the value. Capture a variable instead of using an\n * instance property because we don't want anything to change the\n * value without going through the mutator. */\n let value = 0;\n this._packedSetValue = function(v) {\n value = fixBitwiseResult(v);\n return this;\n };\n this._packedGetValue = function() {\n return value;\n };\n }\n\n /** @override */\n decode(b, offset) {\n const dest = this.makeDestinationObject();\n if (undefined === offset) {\n offset = 0;\n }\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(value);\n }\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link BitStructure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the packed\n * value is left unmodified. Unused bits are also left unmodified. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n fd.encode(fv);\n }\n }\n }\n return this.word.encode(this._packedGetValue(), b, offset);\n }\n\n /** Register a new bitfield with a containing bit structure. The\n * resulting bitfield is returned.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {BitField} */\n addField(bits, property) {\n const bf = new BitField(this, bits, property);\n this.fields.push(bf);\n return bf;\n }\n\n /** As with {@link BitStructure#addField|addField} for single-bit\n * fields with `boolean` value representation.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {Boolean} */\n addBoolean(property) {\n // This is my Boolean, not the Javascript one.\n // eslint-disable-next-line no-new-wrappers\n const bf = new Boolean(this, property);\n this.fields.push(bf);\n return bf;\n }\n\n /**\n * Get access to the bit field for a given property.\n *\n * @param {String} property - the bit field of interest.\n *\n * @return {BitField} - the field associated with `property`, or\n * undefined if there is no such property.\n */\n fieldFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n }\n}\n\n/**\n * Represent a sequence of bits within a {@link BitStructure}.\n *\n * All bit field values are represented as unsigned integers.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addField|addField} helper\n * method.\n *\n * **NOTE** BitField instances are not instances of {@link Layout}\n * since {@link Layout#span|span} measures 8-bit units.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n */\nclass BitField {\n constructor(container, bits, property) {\n if (!(container instanceof BitStructure)) {\n throw new TypeError('container must be a BitStructure');\n }\n if ((!Number.isInteger(bits)) || (0 >= bits)) {\n throw new TypeError('bits must be positive integer');\n }\n const totalBits = 8 * container.span;\n const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);\n if ((bits + usedBits) > totalBits) {\n throw new Error('bits too long for span remainder ('\n + (totalBits - usedBits) + ' of '\n + totalBits + ' remain)');\n }\n\n /** The {@link BitStructure} instance to which this bit field\n * belongs. */\n this.container = container;\n\n /** The span of this value in bits. */\n this.bits = bits;\n\n /** A mask of {@link BitField#bits|bits} bits isolating value bits\n * that fit within the field.\n *\n * That is, it masks a value that has not yet been shifted into\n * position within its containing packed integer. */\n this.valueMask = (1 << bits) - 1;\n if (32 === bits) { // shifted value out of range\n this.valueMask = 0xFFFFFFFF;\n }\n\n /** The offset of the value within the containing packed unsigned\n * integer. The least significant bit of the packed value is at\n * offset zero, regardless of bit ordering used. */\n this.start = usedBits;\n if (this.container.msb) {\n this.start = totalBits - usedBits - bits;\n }\n\n /** A mask of {@link BitField#bits|bits} isolating the field value\n * within the containing packed unsigned integer. */\n this.wordMask = fixBitwiseResult(this.valueMask << this.start);\n\n /** The property name used when this bitfield is represented in an\n * Object.\n *\n * Intended to be functionally equivalent to {@link\n * Layout#property}.\n *\n * If left undefined the corresponding span of bits will be\n * treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n\n /** Store a value into the corresponding subsequence of the containing\n * bit field. */\n decode() {\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(word & this.wordMask);\n const value = wordValue >>> this.start;\n return value;\n }\n\n /** Store a value into the corresponding subsequence of the containing\n * bit field.\n *\n * **NOTE** This is not a specialization of {@link\n * Layout#encode|Layout.encode} and there is no return value. */\n encode(value) {\n if ((!Number.isInteger(value))\n || (value !== fixBitwiseResult(value & this.valueMask))) {\n throw new TypeError(nameWithProperty('BitField.encode', this)\n + ' value must be integer not exceeding ' + this.valueMask);\n }\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(value << this.start);\n this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)\n | wordValue);\n };\n}\n\n/**\n * Represent a single bit within a {@link BitStructure} as a\n * JavaScript boolean.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addBoolean|addBoolean} helper\n * method.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {BitField}\n */\n/* eslint-disable no-extend-native */\nclass Boolean extends BitField {\n constructor(container, property) {\n super(container, 1, property);\n }\n\n /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.\n *\n * @returns {boolean} */\n decode(b, offset) {\n return !!BitField.prototype.decode.call(this, b, offset);\n }\n\n /** @override */\n encode(value) {\n if ('boolean' === typeof value) {\n // BitField requires integer values\n value = +value;\n }\n return BitField.prototype.encode.call(this, value);\n }\n}\n/* eslint-enable no-extend-native */\n\n/**\n * Contain a fixed-length block of arbitrary data, represented as a\n * Buffer.\n *\n * *Factory*: {@link module:Layout.blob|blob}\n *\n * @param {(Number|ExternalLayout)} length - initializes {@link\n * Blob#length|length}.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Blob extends Layout {\n constructor(length, property) {\n if (!(((length instanceof ExternalLayout) && length.isCount())\n || (Number.isInteger(length) && (0 <= length)))) {\n throw new TypeError('length must be positive integer '\n + 'or an unsigned integer ExternalLayout');\n }\n\n let span = -1;\n if (!(length instanceof ExternalLayout)) {\n span = length;\n }\n super(span, property);\n\n /** The number of bytes in the blob.\n *\n * This may be a non-negative integer, or an instance of {@link\n * ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}. */\n this.length = length;\n }\n\n /** @override */\n getSpan(b, offset) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return b.slice(offset, offset + span);\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Blob}.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n let span = this.length;\n if (this.length instanceof ExternalLayout) {\n span = src.length;\n }\n if (!(Buffer.isBuffer(src)\n && (span === src.length))) {\n throw new TypeError(nameWithProperty('Blob.encode', this)\n + ' requires (length ' + span + ') Buffer as src');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n b.write(src.toString('hex'), offset, span, 'hex');\n if (this.length instanceof ExternalLayout) {\n this.length.encode(span, b, offset);\n }\n return span;\n }\n}\n\n/**\n * Contain a `NUL`-terminated UTF8 string.\n *\n * *Factory*: {@link module:Layout.cstr|cstr}\n *\n * **NOTE** Any UTF8 string that incorporates a zero-valued byte will\n * not be correctly decoded by this layout.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass CString extends Layout {\n constructor(property) {\n super(-1, property);\n }\n\n /** @override */\n getSpan(b, offset) {\n if (!Buffer.isBuffer(b)) {\n throw new TypeError('b must be a Buffer');\n }\n if (undefined === offset) {\n offset = 0;\n }\n let idx = offset;\n while ((idx < b.length) && (0 !== b[idx])) {\n idx += 1;\n }\n return 1 + idx - offset;\n }\n\n /** @override */\n decode(b, offset, dest) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.getSpan(b, offset);\n return b.slice(offset, offset + span - 1).toString('utf-8');\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = src.toString();\n }\n const srcb = new Buffer(src, 'utf8');\n const span = srcb.length;\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(b, offset);\n b[offset + span] = 0;\n return span + 1;\n }\n}\n\n/**\n * Contain a UTF8 string with implicit length.\n *\n * *Factory*: {@link module:Layout.utf8|utf8}\n *\n * **NOTE** Because the length is implicit in the size of the buffer\n * this layout should be used only in isolation, or in a situation\n * where the length can be expressed by operating on a slice of the\n * containing buffer.\n *\n * @param {Number} [maxSpan] - the maximum length allowed for encoded\n * string content. If not provided there is no bound on the allowed\n * content.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UTF8 extends Layout {\n constructor(maxSpan, property) {\n if (('string' === typeof maxSpan)\n && (undefined === property)) {\n property = maxSpan;\n maxSpan = undefined;\n }\n if (undefined === maxSpan) {\n maxSpan = -1;\n } else if (!Number.isInteger(maxSpan)) {\n throw new TypeError('maxSpan must be an integer');\n }\n\n super(-1, property);\n\n /** The maximum span of the layout in bytes.\n *\n * Positive values are generally expected. Zero is abnormal.\n * Attempts to encode or decode a value that exceeds this length\n * will throw a `RangeError`.\n *\n * A negative value indicates that there is no bound on the length\n * of the content. */\n this.maxSpan = maxSpan;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (!Buffer.isBuffer(b)) {\n throw new TypeError('b must be a Buffer');\n }\n if (undefined === offset) {\n offset = 0;\n }\n return b.length - offset;\n }\n\n /** @override */\n decode(b, offset, dest) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.getSpan(b, offset);\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n return b.slice(offset, offset + span).toString('utf-8');\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = src.toString();\n }\n const srcb = new Buffer(src, 'utf8');\n const span = srcb.length;\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(b, offset);\n return span;\n }\n}\n\n/**\n * Contain a constant value.\n *\n * This layout may be used in cases where a JavaScript value can be\n * inferred without an expression in the binary encoding. An example\n * would be a {@link VariantLayout|variant layout} where the content\n * is implied by the union {@link Union#discriminator|discriminator}.\n *\n * @param {Object|Number|String} value - initializer for {@link\n * Constant#value|value}. If the value is an object (or array) and\n * the application intends the object to remain unchanged regardless\n * of what is done to values decoded by this layout, the value should\n * be frozen prior passing it to this constructor.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Constant extends Layout {\n constructor(value, property) {\n super(0, property);\n\n /** The value produced by this constant when the layout is {@link\n * Constant#decode|decoded}.\n *\n * Any JavaScript value including `null` and `undefined` is\n * permitted.\n *\n * **WARNING** If `value` passed in the constructor was not\n * frozen, it is possible for users of decoded values to change\n * the content of the value. */\n this.value = value;\n }\n\n /** @override */\n decode(b, offset, dest) {\n return this.value;\n }\n\n /** @override */\n encode(src, b, offset) {\n /* Constants take no space */\n return 0;\n }\n}\n\nexports.ExternalLayout = ExternalLayout;\nexports.GreedyCount = GreedyCount;\nexports.OffsetLayout = OffsetLayout;\nexports.UInt = UInt;\nexports.UIntBE = UIntBE;\nexports.Int = Int;\nexports.IntBE = IntBE;\nexports.Float = Float;\nexports.FloatBE = FloatBE;\nexports.Double = Double;\nexports.DoubleBE = DoubleBE;\nexports.Sequence = Sequence;\nexports.Structure = Structure;\nexports.UnionDiscriminator = UnionDiscriminator;\nexports.UnionLayoutDiscriminator = UnionLayoutDiscriminator;\nexports.Union = Union;\nexports.VariantLayout = VariantLayout;\nexports.BitStructure = BitStructure;\nexports.BitField = BitField;\nexports.Boolean = Boolean;\nexports.Blob = Blob;\nexports.CString = CString;\nexports.UTF8 = UTF8;\nexports.Constant = Constant;\n\n/** Factory for {@link GreedyCount}. */\nexports.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));\n\n/** Factory for {@link OffsetLayout}. */\nexports.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));\n\n/** Factory for {@link UInt|unsigned int layouts} spanning one\n * byte. */\nexports.u8 = (property => new UInt(1, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16 = (property => new UInt(2, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24 = (property => new UInt(3, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32 = (property => new UInt(4, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40 = (property => new UInt(5, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48 = (property => new UInt(6, property));\n\n/** Factory for {@link NearUInt64|little-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64 = (property => new NearUInt64(property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16be = (property => new UIntBE(2, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24be = (property => new UIntBE(3, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32be = (property => new UIntBE(4, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40be = (property => new UIntBE(5, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48be = (property => new UIntBE(6, property));\n\n/** Factory for {@link NearUInt64BE|big-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64be = (property => new NearUInt64BE(property));\n\n/** Factory for {@link Int|signed int layouts} spanning one\n * byte. */\nexports.s8 = (property => new Int(1, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning two bytes. */\nexports.s16 = (property => new Int(2, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning three bytes. */\nexports.s24 = (property => new Int(3, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning four bytes. */\nexports.s32 = (property => new Int(4, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning five bytes. */\nexports.s40 = (property => new Int(5, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning six bytes. */\nexports.s48 = (property => new Int(6, property));\n\n/** Factory for {@link NearInt64|little-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64 = (property => new NearInt64(property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning two bytes. */\nexports.s16be = (property => new IntBE(2, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning three bytes. */\nexports.s24be = (property => new IntBE(3, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning four bytes. */\nexports.s32be = (property => new IntBE(4, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning five bytes. */\nexports.s40be = (property => new IntBE(5, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning six bytes. */\nexports.s48be = (property => new IntBE(6, property));\n\n/** Factory for {@link NearInt64BE|big-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64be = (property => new NearInt64BE(property));\n\n/** Factory for {@link Float|little-endian 32-bit floating point} values. */\nexports.f32 = (property => new Float(property));\n\n/** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */\nexports.f32be = (property => new FloatBE(property));\n\n/** Factory for {@link Double|little-endian 64-bit floating point} values. */\nexports.f64 = (property => new Double(property));\n\n/** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */\nexports.f64be = (property => new DoubleBE(property));\n\n/** Factory for {@link Structure} values. */\nexports.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));\n\n/** Factory for {@link BitStructure} values. */\nexports.bits = ((word, msb, property) => new BitStructure(word, msb, property));\n\n/** Factory for {@link Sequence} values. */\nexports.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));\n\n/** Factory for {@link Union} values. */\nexports.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));\n\n/** Factory for {@link UnionLayoutDiscriminator} values. */\nexports.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));\n\n/** Factory for {@link Blob} values. */\nexports.blob = ((length, property) => new Blob(length, property));\n\n/** Factory for {@link CString} values. */\nexports.cstr = (property => new CString(property));\n\n/** Factory for {@link UTF8} values. */\nexports.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));\n\n/** Factory for {@link Constant} values. */\nexports.const = ((value, property) => new Constant(value, property));\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.map = exports.array = exports.rustEnum = exports.str = exports.vecU8 = exports.tagged = exports.vec = exports.bool = exports.option = exports.publicKey = exports.i256 = exports.u256 = exports.i128 = exports.u128 = exports.i64 = exports.u64 = exports.struct = exports.f64 = exports.f32 = exports.i32 = exports.u32 = exports.i16 = exports.u16 = exports.i8 = exports.u8 = void 0;\nconst buffer_layout_1 = require(\"buffer-layout\");\nconst web3_js_1 = require(\"@solana/web3.js\");\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nvar buffer_layout_2 = require(\"buffer-layout\");\nObject.defineProperty(exports, \"u8\", { enumerable: true, get: function () { return buffer_layout_2.u8; } });\nObject.defineProperty(exports, \"i8\", { enumerable: true, get: function () { return buffer_layout_2.s8; } });\nObject.defineProperty(exports, \"u16\", { enumerable: true, get: function () { return buffer_layout_2.u16; } });\nObject.defineProperty(exports, \"i16\", { enumerable: true, get: function () { return buffer_layout_2.s16; } });\nObject.defineProperty(exports, \"u32\", { enumerable: true, get: function () { return buffer_layout_2.u32; } });\nObject.defineProperty(exports, \"i32\", { enumerable: true, get: function () { return buffer_layout_2.s32; } });\nObject.defineProperty(exports, \"f32\", { enumerable: true, get: function () { return buffer_layout_2.f32; } });\nObject.defineProperty(exports, \"f64\", { enumerable: true, get: function () { return buffer_layout_2.f64; } });\nObject.defineProperty(exports, \"struct\", { enumerable: true, get: function () { return buffer_layout_2.struct; } });\nclass BNLayout extends buffer_layout_1.Layout {\n constructor(span, signed, property) {\n super(span, property);\n this.blob = (0, buffer_layout_1.blob)(span);\n this.signed = signed;\n }\n decode(b, offset = 0) {\n const num = new bn_js_1.default(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n encode(src, b, offset = 0) {\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\nfunction u64(property) {\n return new BNLayout(8, false, property);\n}\nexports.u64 = u64;\nfunction i64(property) {\n return new BNLayout(8, true, property);\n}\nexports.i64 = i64;\nfunction u128(property) {\n return new BNLayout(16, false, property);\n}\nexports.u128 = u128;\nfunction i128(property) {\n return new BNLayout(16, true, property);\n}\nexports.i128 = i128;\nfunction u256(property) {\n return new BNLayout(32, false, property);\n}\nexports.u256 = u256;\nfunction i256(property) {\n return new BNLayout(32, true, property);\n}\nexports.i256 = i256;\nclass WrappedLayout extends buffer_layout_1.Layout {\n constructor(layout, decoder, encoder, property) {\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n decode(b, offset) {\n return this.decoder(this.layout.decode(b, offset));\n }\n encode(src, b, offset) {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n getSpan(b, offset) {\n return this.layout.getSpan(b, offset);\n }\n}\nfunction publicKey(property) {\n return new WrappedLayout((0, buffer_layout_1.blob)(32), (b) => new web3_js_1.PublicKey(b), (key) => key.toBuffer(), property);\n}\nexports.publicKey = publicKey;\nclass OptionLayout extends buffer_layout_1.Layout {\n constructor(layout, property) {\n super(-1, property);\n this.layout = layout;\n this.discriminator = (0, buffer_layout_1.u8)();\n }\n encode(src, b, offset = 0) {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n decode(b, offset = 0) {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n }\n else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n getSpan(b, offset = 0) {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n }\n else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\nfunction option(layout, property) {\n return new OptionLayout(layout, property);\n}\nexports.option = option;\nfunction bool(property) {\n return new WrappedLayout((0, buffer_layout_1.u8)(), decodeBool, encodeBool, property);\n}\nexports.bool = bool;\nfunction decodeBool(value) {\n if (value === 0) {\n return false;\n }\n else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\nfunction encodeBool(value) {\n return value ? 1 : 0;\n}\nfunction vec(elementLayout, property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.seq)(elementLayout, (0, buffer_layout_1.offset)(length, -length.span), \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => values, (values) => ({ values }), property);\n}\nexports.vec = vec;\nfunction tagged(tag, layout, property) {\n const wrappedLayout = (0, buffer_layout_1.struct)([\n u64(\"tag\"),\n layout.replicate(\"data\"),\n ]);\n function decodeTag({ tag: receivedTag, data }) {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" +\n tag.toString(\"hex\") +\n \", got: \" +\n receivedTag.toString(\"hex\"));\n }\n return data;\n }\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\nexports.tagged = tagged;\nfunction vecU8(property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.blob)((0, buffer_layout_1.offset)(length, -length.span), \"data\"),\n ]);\n return new WrappedLayout(layout, ({ data }) => data, (data) => ({ data }), property);\n}\nexports.vecU8 = vecU8;\nfunction str(property) {\n return new WrappedLayout(vecU8(), (data) => data.toString(\"utf-8\"), (s) => Buffer.from(s, \"utf-8\"), property);\n}\nexports.str = str;\nfunction rustEnum(variants, property, discriminant) {\n const unionLayout = (0, buffer_layout_1.union)(discriminant !== null && discriminant !== void 0 ? discriminant : (0, buffer_layout_1.u8)(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout;\n}\nexports.rustEnum = rustEnum;\nfunction array(elementLayout, length, property) {\n const layout = (0, buffer_layout_1.struct)([\n (0, buffer_layout_1.seq)(elementLayout, length, \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => values, (values) => ({ values }), property);\n}\nexports.array = array;\nclass MapEntryLayout extends buffer_layout_1.Layout {\n constructor(keyLayout, valueLayout, property) {\n super(keyLayout.span + valueLayout.span, property);\n this.keyLayout = keyLayout;\n this.valueLayout = valueLayout;\n }\n decode(b, offset) {\n offset = offset || 0;\n const key = this.keyLayout.decode(b, offset);\n const value = this.valueLayout.decode(b, offset + this.keyLayout.getSpan(b, offset));\n return [key, value];\n }\n encode(src, b, offset) {\n offset = offset || 0;\n const keyBytes = this.keyLayout.encode(src[0], b, offset);\n const valueBytes = this.valueLayout.encode(src[1], b, offset + keyBytes);\n return keyBytes + valueBytes;\n }\n getSpan(b, offset) {\n return (this.keyLayout.getSpan(b, offset) + this.valueLayout.getSpan(b, offset));\n }\n}\nfunction map(keyLayout, valueLayout, property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.seq)(new MapEntryLayout(keyLayout, valueLayout), (0, buffer_layout_1.offset)(length, -length.span), \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => new Map(values), (values) => ({ values: Array.from(values.entries()) }), property);\n}\nexports.map = map;\n//# sourceMappingURL=index.js.map","import { Buffer } from 'buffer';\nimport { PublicKey, AccountMeta } from '@solana/web3.js';\nimport {\n struct,\n u8,\n u64,\n bool,\n vec,\n option,\n publicKey,\n array,\n u16,\n u32,\n Layout,\n vecU8,\n} from '@coral-xyz/borsh';\nimport {\n InstructionDataInvoke,\n InstructionDataInvokeCpi,\n PublicTransactionEvent,\n} from '../state';\nimport { LightSystemProgram } from './system';\nimport { INVOKE_CPI_DISCRIMINATOR, INVOKE_DISCRIMINATOR } from '../constants';\nimport { BN } from 'bn.js';\n\nexport const CompressedAccountLayout = struct(\n [\n publicKey('owner'),\n u64('lamports'),\n option(array(u8(), 32), 'address'),\n option(\n struct([\n array(u8(), 8, 'discriminator'),\n vecU8('data'),\n array(u8(), 32, 'dataHash'),\n ]),\n 'data',\n ),\n ],\n 'compressedAccount',\n);\n\nexport const MerkleContextLayout = struct(\n [\n u8('merkleTreePubkeyIndex'),\n u8('nullifierQueuePubkeyIndex'),\n u32('leafIndex'),\n option(struct([u8('queueId'), u16('index')]), 'queueIndex'),\n ],\n 'merkleContext',\n);\n\nexport const NewAddressParamsLayout = struct(\n [\n array(u8(), 32, 'seed'),\n u8('addressQueueAccountIndex'),\n u8('addressMerkleTreeAccountIndex'),\n u16('addressMerkleTreeRootIndex'),\n ],\n 'newAddressParams',\n);\n\nexport const InstructionDataInvokeLayout: Layout<InstructionDataInvoke> =\n struct([\n option(\n struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n ]),\n 'proof',\n ),\n vec(\n struct([\n CompressedAccountLayout,\n MerkleContextLayout,\n u16('rootIndex'),\n bool('readOnly'),\n ]),\n 'inputCompressedAccountsWithMerkleContext',\n ),\n vec(\n struct([CompressedAccountLayout, u8('merkleTreeIndex')]),\n 'outputCompressedAccounts',\n ),\n option(u64(), 'relayFee'),\n vec(NewAddressParamsLayout, 'newAddressParams'),\n option(u64(), 'compressOrDecompressLamports'),\n bool('isCompress'),\n ]);\n\nexport function encodeInstructionDataInvoke(\n data: InstructionDataInvoke,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = InstructionDataInvokeLayout.encode(data, buffer);\n const dataBuffer = Buffer.from(buffer.slice(0, len));\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n return Buffer.concat([INVOKE_DISCRIMINATOR, lengthBuffer, dataBuffer]);\n}\n\nexport const InstructionDataInvokeCpiLayout: Layout<InstructionDataInvokeCpi> =\n struct([\n option(\n struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n ]),\n 'proof',\n ),\n vec(NewAddressParamsLayout, 'newAddressParams'),\n vec(\n struct([\n CompressedAccountLayout,\n MerkleContextLayout,\n u16('rootIndex'),\n bool('readOnly'),\n ]),\n 'inputCompressedAccountsWithMerkleContext',\n ),\n vec(\n struct([CompressedAccountLayout, u8('merkleTreeIndex')]),\n 'outputCompressedAccounts',\n ),\n option(u64(), 'relayFee'),\n option(u64(), 'compressOrDecompressLamports'),\n bool('isCompress'),\n option(\n struct([\n bool('set_context'),\n bool('first_set_context'),\n u8('cpi_context_account_index'),\n ]),\n 'compressedCpiContext',\n ),\n ]);\n\nexport function decodeInstructionDataInvoke(\n buffer: Buffer,\n): InstructionDataInvoke {\n return InstructionDataInvokeLayout.decode(\n buffer.slice(INVOKE_DISCRIMINATOR.length + 4),\n );\n}\n\nexport function decodeInstructionDataInvokeCpi(\n buffer: Buffer,\n): InstructionDataInvokeCpi {\n return InstructionDataInvokeCpiLayout.decode(\n buffer.slice(INVOKE_CPI_DISCRIMINATOR.length + 4),\n );\n}\n\nexport type invokeAccountsLayoutParams = {\n feePayer: PublicKey;\n authority: PublicKey;\n registeredProgramPda: PublicKey;\n noopProgram: PublicKey;\n accountCompressionAuthority: PublicKey;\n accountCompressionProgram: PublicKey;\n solPoolPda: PublicKey | null;\n decompressionRecipient: PublicKey | null;\n systemProgram: PublicKey;\n};\n\nexport const invokeAccountsLayout = (\n accounts: invokeAccountsLayoutParams,\n): AccountMeta[] => {\n const defaultPubkey = LightSystemProgram.programId;\n const {\n feePayer,\n authority,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n solPoolPda,\n decompressionRecipient,\n systemProgram,\n } = accounts;\n\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: solPoolPda ?? defaultPubkey,\n isSigner: false,\n isWritable: solPoolPda !== null,\n },\n {\n pubkey: decompressionRecipient ?? defaultPubkey,\n isSigner: false,\n isWritable: true,\n },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n ];\n};\n\nexport const PublicTransactionEventLayout: Layout<PublicTransactionEvent> =\n struct([\n vec(array(u8(), 32), 'inputCompressedAccountHashes'),\n vec(array(u8(), 32), 'outputCompressedAccountHashes'),\n vec(\n struct([\n struct(\n [\n publicKey('owner'),\n u64('lamports'),\n option(array(u8(), 32), 'address'),\n option(\n struct([\n array(u8(), 8, 'discriminator'),\n vecU8('data'),\n array(u8(), 32, 'dataHash'),\n ]),\n 'data',\n ),\n ],\n 'compressedAccount',\n ),\n u8('merkleTreeIndex'),\n ]),\n 'outputCompressedAccounts',\n ),\n vec(u32(), 'outputLeafIndices'),\n vec(struct([publicKey('pubkey'), u64('seq')]), 'sequenceNumbers'),\n option(u64(), 'relayFee'),\n bool('isCompress'),\n option(u64(), 'compressOrDecompressLamports'),\n vec(publicKey(), 'pubkeyArray'),\n option(vecU8(), 'message'),\n ]);\n\nexport function encodePublicTransactionEvent(\n data: PublicTransactionEvent,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = PublicTransactionEventLayout.encode(data, buffer);\n\n return buffer.slice(0, len);\n}\n\nexport function decodePublicTransactionEvent(\n buffer: Buffer,\n): PublicTransactionEvent {\n return PublicTransactionEventLayout.decode(buffer);\n}\n\nexport const AppendNullifyCreateAddressInputsMetaLayout = struct(\n [\n u8('is_invoked_by_program'),\n u8('bump'),\n u8('num_queues'),\n u8('num_output_queues'),\n u8('start_output_appends'),\n u8('num_address_queues'),\n array(u8(), 32, 'tx_hash'),\n ],\n 'appendNullifyCreateAddressInputsMeta',\n);\n\nexport const AppendLeavesInputLayout = struct(\n [u8('index'), array(u8(), 32, 'leaf')],\n 'appendLeavesInput',\n);\n\nexport const InsertNullifierInputLayout = struct(\n [\n array(u8(), 32, 'account_hash'),\n u32('leaf_index'),\n u8('prove_by_index'),\n u8('tree_index'),\n u8('queue_index'),\n ],\n 'insertNullifierInput',\n);\nexport const InsertAddressInputLayout = struct(\n [array(u8(), 32, 'address'), u8('tree_index'), u8('queue_index')],\n 'insertAddressInput',\n);\n\nexport const MerkleTreeSequenceNumberLayout = struct(\n [publicKey('pubkey'), u64('seq')],\n 'merkleTreeSequenceNumber',\n);\n\nexport function deserializeAppendNullifyCreateAddressInputsIndexer(\n buffer: Buffer,\n) {\n let offset = 0;\n const meta = AppendNullifyCreateAddressInputsMetaLayout.decode(\n buffer,\n offset,\n );\n offset += AppendNullifyCreateAddressInputsMetaLayout.span;\n const leavesCount = buffer.readUInt8(offset);\n offset += 1;\n const leaves = [];\n for (let i = 0; i < leavesCount; i++) {\n const leaf = AppendLeavesInputLayout.decode(buffer, offset);\n leaves.push(leaf);\n offset += AppendLeavesInputLayout.span;\n }\n const nullifiersCount = buffer.readUInt8(offset);\n offset += 1;\n const nullifiers = [];\n for (let i = 0; i < nullifiersCount; i++) {\n const nullifier = InsertNullifierInputLayout.decode(buffer, offset);\n nullifiers.push(nullifier);\n offset += InsertNullifierInputLayout.span;\n }\n const addressesCount = buffer.readUInt8(offset);\n offset += 1;\n const addresses = [];\n for (let i = 0; i < addressesCount; i++) {\n const address = InsertAddressInputLayout.decode(buffer, offset);\n addresses.push(address);\n offset += InsertAddressInputLayout.span;\n }\n const sequenceNumbersCount = buffer.readUInt8(offset);\n offset += 1;\n const sequence_numbers = [];\n for (let i = 0; i < sequenceNumbersCount; i++) {\n const seq = MerkleTreeSequenceNumberLayout.decode(buffer, offset);\n sequence_numbers.push(seq);\n offset += MerkleTreeSequenceNumberLayout.span;\n }\n const outputLeafIndicesCount = buffer.readUInt8(offset);\n offset += 1;\n const output_leaf_indices = [];\n for (let i = 0; i < outputLeafIndicesCount; i++) {\n const index = u32().decode(buffer, offset);\n output_leaf_indices.push(index);\n offset += 4;\n }\n return {\n meta,\n leaves,\n nullifiers,\n addresses,\n sequence_numbers,\n output_leaf_indices,\n };\n}\n\nexport function convertToPublicTransactionEvent(\n decoded: any,\n remainingAccounts: PublicKey[],\n invokeData: InstructionDataInvoke,\n): PublicTransactionEvent {\n const convertByteArray = (arr: Uint8Array | Buffer): number[] =>\n Array.from(arr instanceof Buffer ? new Uint8Array(arr) : arr);\n\n const result = {\n inputCompressedAccountHashes: decoded.nullifiers.map((n: any) =>\n convertByteArray(n.account_hash),\n ),\n outputCompressedAccountHashes: decoded.leaves.map((l: any) =>\n convertByteArray(l.leaf),\n ),\n outputCompressedAccounts: decoded.leaves.map(\n (leaf: any, index: number) => ({\n compressedAccount: {\n owner: new PublicKey(\n invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.owner || PublicKey.default,\n ),\n lamports: new BN(\n invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.lamports || 0,\n ),\n address:\n invokeData?.outputCompressedAccounts[index]\n .compressedAccount.address,\n data: invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.data\n ? {\n discriminator: convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[index]\n .compressedAccount.data\n ?.discriminator,\n ),\n ),\n data:\n convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[\n index\n ].compressedAccount.data.data,\n ),\n ) ?? [],\n dataHash: convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[index]\n .compressedAccount.data?.dataHash,\n ),\n ),\n }\n : null,\n },\n merkleTreeIndex: leaf.index,\n }),\n ),\n outputLeafIndices: decoded.output_leaf_indices,\n sequenceNumbers: decoded.sequence_numbers.map((sn: any) => ({\n pubkey: new PublicKey(sn.pubkey),\n seq: new BN(sn.seq),\n })),\n pubkeyArray: remainingAccounts\n .slice(2)\n .filter(pk => !pk.equals(PublicKey.default)),\n isCompress: invokeData?.isCompress || false,\n relayFee: invokeData?.relayFee ? new BN(invokeData.relayFee) : null,\n compressOrDecompressLamports: invokeData?.compressOrDecompressLamports\n ? new BN(invokeData.compressOrDecompressLamports)\n : null,\n message: null,\n };\n\n return result;\n}\n","import BN from 'bn.js';\nimport {\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n CompressedAccount,\n CompressedAccountWithMerkleContext,\n CompressedProof,\n InstructionDataInvoke,\n bn,\n createCompressedAccount,\n} from '../state';\nimport { packCompressedAccounts, toAccountMetas } from '../instruction';\nimport { defaultStaticAccountsStruct } from '../constants';\nimport {\n validateSameOwner,\n validateSufficientBalance,\n} from '../utils/validation';\nimport { packNewAddressParams, NewAddressParams } from '../utils';\nimport { encodeInstructionDataInvoke, invokeAccountsLayout } from './layout';\n\nexport const sumUpLamports = (\n accounts: CompressedAccountWithMerkleContext[],\n): BN => {\n return accounts.reduce(\n (acc, account) => acc.add(bn(account.lamports)),\n bn(0),\n );\n};\n\n/**\n * Create compressed account system transaction params\n */\ntype CreateAccountWithSeedParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * Address params for the new compressed account\n */\n newAddressParams: NewAddressParams;\n newAddress: number[];\n /**\n * Recent validity proof proving that there's no existing compressed account\n * registered with newAccountAddress\n */\n recentValidityProof: CompressedProof;\n /**\n * State tree pubkey. Defaults to a public state tree if unspecified.\n */\n outputStateTree?: PublicKey;\n /**\n * Public key of the program to assign as the owner of the created account\n */\n programId?: PublicKey;\n /**\n * Optional input accounts to transfer lamports from into the new compressed\n * account.\n */\n inputCompressedAccounts?: CompressedAccountWithMerkleContext[];\n /**\n * Optional input state root indices of 'inputCompressedAccounts'. The\n * expiry is tied to the 'recentValidityProof'.\n */\n inputStateRootIndices?: number[];\n /**\n * Optional lamports to transfer into the new compressed account.\n */\n lamports?: number | BN;\n};\n\n/**\n * Defines the parameters for the transfer method\n */\ntype TransferParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * The input state to be consumed.\n */\n inputCompressedAccounts: CompressedAccountWithMerkleContext[];\n /**\n * Recipient address\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to transfer.\n */\n lamports: number | BN;\n /**\n * The recent state root indices of the input state. The expiry is tied to\n * the proof.\n *\n * TODO: Add support for passing recent-values after instruction creation.\n */\n recentInputStateRootIndices: number[];\n /**\n * The recent validity proof for state inclusion of the input state. It\n * expires after n slots.\n */\n recentValidityProof: CompressedProof;\n /**\n * The state trees that the tx output should be inserted into. This can be a\n * single PublicKey or an array of PublicKey. Defaults to the 0th state tree\n * of input state.\n */\n outputStateTrees?: PublicKey[] | PublicKey;\n};\n\n/// TODO:\n/// - add option to compress to another owner\n/// - add option to merge with input state\n/**\n * Defines the parameters for the transfer method\n */\ntype CompressParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * address that the lamports are attached to. also defaults to the recipient owner\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to compress.\n */\n lamports: number | BN;\n /**\n * The state tree that the tx output should be inserted into. Defaults to a\n * public state tree if unspecified.\n */\n outputStateTree?: PublicKey;\n};\n\n/**\n * Defines the parameters for the transfer method\n */\ntype DecompressParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * The input state to be consumed.\n */\n inputCompressedAccounts: CompressedAccountWithMerkleContext[];\n /**\n * Recipient address of uncompressed lamports\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to decompress.\n */\n lamports: number | BN;\n /**\n * The recent state root indices of the input state. The expiry is tied to\n * the proof.\n *\n * TODO: Add support for passing recent-values after instruction creation.\n */\n recentInputStateRootIndices: number[];\n /**\n * The recent validity proof for state inclusion of the input state. It\n * expires after n slots.\n */\n recentValidityProof: CompressedProof;\n /**\n * The state trees that the tx output should be inserted into. This can be a\n * single PublicKey or an array of PublicKey. Defaults to the 0th state tree\n * of input state.\n */\n outputStateTree?: PublicKey;\n};\n\nconst SOL_POOL_PDA_SEED = Buffer.from('sol_pool_pda');\n\nexport class LightSystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the CompressedPda program\n */\n static programId: PublicKey = new PublicKey(\n 'SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7',\n );\n\n /**\n * @internal\n * Cwct1kQLwJm8Z3HetLu8m4SXkhD6FZ5fXbJQCxTxPnGY\n *\n */\n static deriveCompressedSolPda(): PublicKey {\n const seeds = [SOL_POOL_PDA_SEED];\n const [address, _] = PublicKey.findProgramAddressSync(\n seeds,\n this.programId,\n );\n return address;\n }\n\n static createTransferOutputState(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n toAddress: PublicKey,\n lamports: number | BN,\n ): CompressedAccount[] {\n lamports = bn(lamports);\n const inputLamports = sumUpLamports(inputCompressedAccounts);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n if (changeLamports.eq(bn(0))) {\n return [createCompressedAccount(toAddress, lamports)];\n }\n\n validateSameOwner(inputCompressedAccounts);\n\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n\n changeLamports,\n ),\n createCompressedAccount(toAddress, lamports),\n ];\n return outputCompressedAccounts;\n }\n\n static createDecompressOutputState(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n lamports: number | BN,\n ): CompressedAccount[] {\n lamports = bn(lamports);\n const inputLamports = sumUpLamports(inputCompressedAccounts);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n /// lamports gets decompressed\n if (changeLamports.eq(bn(0))) {\n return [];\n }\n\n validateSameOwner(inputCompressedAccounts);\n\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n changeLamports,\n ),\n ];\n return outputCompressedAccounts;\n }\n\n /**\n * No data by default\n */\n static createNewAddressOutputState(\n address: number[],\n owner: PublicKey,\n lamports?: BN | number,\n inputCompressedAccounts?: CompressedAccountWithMerkleContext[],\n ): CompressedAccount[] {\n lamports = bn(lamports ?? 0);\n const inputLamports = sumUpLamports(inputCompressedAccounts ?? []);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n if (changeLamports.eq(bn(0)) || !inputCompressedAccounts) {\n return [\n createCompressedAccount(owner, lamports, undefined, address),\n ];\n }\n\n validateSameOwner(inputCompressedAccounts);\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n changeLamports,\n ),\n createCompressedAccount(owner, lamports, undefined, address),\n ];\n return outputCompressedAccounts;\n }\n\n /**\n * Creates instruction to create compressed account with PDA.\n * Cannot write data.\n *\n * TODO: support transfer of lamports to the new account.\n */\n static async createAccount({\n payer,\n newAddressParams,\n newAddress,\n recentValidityProof,\n outputStateTree,\n inputCompressedAccounts,\n inputStateRootIndices,\n lamports,\n }: CreateAccountWithSeedParams): Promise<TransactionInstruction> {\n const outputCompressedAccounts = this.createNewAddressOutputState(\n newAddress,\n payer,\n lamports,\n inputCompressedAccounts,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts: _remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts ?? [],\n inputStateRootIndices ?? [],\n outputCompressedAccounts,\n outputStateTree,\n );\n\n const { newAddressParamsPacked, remainingAccounts } =\n packNewAddressParams([newAddressParams], _remainingAccounts);\n\n const rawData: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: newAddressParamsPacked,\n compressOrDecompressLamports: null,\n isCompress: false,\n };\n const data = encodeInstructionDataInvoke(rawData);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: null,\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n static async transfer({\n payer,\n inputCompressedAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices,\n recentValidityProof,\n outputStateTrees,\n }: TransferParams): Promise<TransactionInstruction> {\n /// Create output state\n const outputCompressedAccounts = this.createTransferOutputState(\n inputCompressedAccounts,\n toAddress,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts,\n recentInputStateRootIndices,\n outputCompressedAccounts,\n outputStateTrees,\n );\n\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: [],\n compressOrDecompressLamports: null,\n isCompress: false,\n };\n\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: null,\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n // TODO: add support for non-fee-payer owner\n static async compress({\n payer,\n toAddress,\n lamports,\n outputStateTree,\n }: CompressParams): Promise<TransactionInstruction> {\n /// Create output state\n lamports = bn(lamports);\n\n const outputCompressedAccount = createCompressedAccount(\n toAddress,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n [],\n [],\n [outputCompressedAccount],\n outputStateTree,\n );\n\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: null,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n /// TODO: here and on-chain: option<newAddressInputs> or similar.\n newAddressParams: [],\n compressOrDecompressLamports: lamports,\n isCompress: true,\n };\n\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: LightSystemProgram.deriveCompressedSolPda(),\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n static async decompress({\n payer,\n inputCompressedAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices,\n recentValidityProof,\n outputStateTree,\n }: DecompressParams): Promise<TransactionInstruction> {\n /// Create output state\n lamports = bn(lamports);\n\n const outputCompressedAccounts = this.createDecompressOutputState(\n inputCompressedAccounts,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts,\n recentInputStateRootIndices,\n outputCompressedAccounts,\n outputStateTree,\n );\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: [],\n compressOrDecompressLamports: lamports,\n isCompress: false,\n };\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: LightSystemProgram.deriveCompressedSolPda(),\n decompressionRecipient: toAddress,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n}\n\n/**\n * Selects the minimal number of compressed SOL accounts for a transfer.\n *\n * 1. Sorts the accounts by amount in descending order\n * 2. Accumulates the amount until it is greater than or equal to the transfer\n * amount\n */\nexport function selectMinCompressedSolAccountsForTransfer(\n accounts: CompressedAccountWithMerkleContext[],\n transferLamports: BN | number,\n): [selectedAccounts: CompressedAccountWithMerkleContext[], total: BN] {\n let accumulatedLamports = bn(0);\n transferLamports = bn(transferLamports);\n\n const selectedAccounts: CompressedAccountWithMerkleContext[] = [];\n\n accounts.sort((a, b) => b.lamports.cmp(a.lamports));\n\n for (const account of accounts) {\n if (accumulatedLamports.gte(bn(transferLamports))) break;\n accumulatedLamports = accumulatedLamports.add(account.lamports);\n selectedAccounts.push(account);\n }\n\n if (accumulatedLamports.lt(bn(transferLamports))) {\n throw new Error(\n `Not enough balance for transfer. Required: ${transferLamports.toString()}, available: ${accumulatedLamports.toString()}`,\n );\n }\n\n return [selectedAccounts, accumulatedLamports];\n}\n","/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const { message, explanation, ...rest } = failure;\n const { path } = failure;\n const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`;\n super(explanation ?? msg);\n if (explanation != null)\n this.cause = msg;\n Object.assign(this, rest);\n this.name = this.constructor.name;\n this.failures = () => {\n return (cached ?? (cached = [failure, ...failures()]));\n };\n }\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a non-array object.\n */\nfunction isNonArrayObject(x) {\n return isObject(x) && !Array.isArray(x);\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\nfunction print(value) {\n if (typeof value === 'symbol') {\n return value.toString();\n }\n return typeof value === 'string' ? JSON.stringify(value) : `${value}`;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\nfunction shiftIterator(input) {\n const { done, value } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n }\n else if (result === false) {\n result = {};\n }\n else if (typeof result === 'string') {\n result = { message: result };\n }\n const { path, branch } = context;\n const { type } = struct;\n const { refinement, message = `Expected a value of type \\`${type}\\`${refinement ? ` with refinement \\`${refinement}\\`` : ''}, but received: \\`${print(value)}\\``, } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message,\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\nfunction* run(value, struct, options = {}) {\n const { path = [], branch = [value], coerce = false, mask = false } = options;\n const ctx = { path, branch, mask };\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n let status = 'valid';\n for (const failure of struct.validator(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_valid';\n yield [failure, undefined];\n }\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce,\n mask,\n message: options.message,\n });\n for (const t of ts) {\n if (t[0]) {\n status = t[0].refinement != null ? 'not_refined' : 'not_valid';\n yield [t[0], undefined];\n }\n else if (coerce) {\n v = t[1];\n if (k === undefined) {\n value = v;\n }\n else if (value instanceof Map) {\n value.set(k, v);\n }\n else if (value instanceof Set) {\n value.add(v);\n }\n else if (isObject(value)) {\n if (v !== undefined || k in value)\n value[k] = v;\n }\n }\n }\n }\n if (status !== 'not_valid') {\n for (const failure of struct.refiner(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_refined';\n yield [failure, undefined];\n }\n }\n if (status === 'valid') {\n yield [undefined, value];\n }\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\nclass Struct {\n constructor(props) {\n const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.validator = () => [];\n }\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n assert(value, message) {\n return assert(value, this, message);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n create(value, message) {\n return create(value, this, message);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema. Masking applies recursively to\n * props of `object` structs only.\n */\n mask(value, message) {\n return mask(value, this, message);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `coerce` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful. Also, `mask` will turn on\n * masking of the unknown `object` props recursively if passed.\n */\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\nfunction assert(value, struct, message) {\n const result = validate(value, struct, { message });\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\nfunction create(value, struct, message) {\n const result = validate(value, struct, { coerce: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\nfunction mask(value, struct, message) {\n const result = validate(value, struct, { coerce: true, mask: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Check if a value passes a struct.\n */\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n }\n else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\nfunction assign(...Structs) {\n const isType = Structs[0].type === 'type';\n const schemas = Structs.map((s) => s.schema);\n const schema = Object.assign({}, ...schemas);\n return isType ? type(schema) : object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\nfunction define(name, validator) {\n return new Struct({ type: name, schema: null, validator });\n}\n/**\n * Create a new struct based on an existing struct, but the value is allowed to\n * be `undefined`. `log` will be called if the value is not `undefined`.\n */\nfunction deprecated(struct, log) {\n return new Struct({\n ...struct,\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n validator(value, ctx) {\n if (value === undefined) {\n return true;\n }\n else {\n log(value, ctx);\n return struct.validator(value, ctx);\n }\n },\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n const struct = fn(value, ctx);\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n *entries(value, ctx) {\n struct ?? (struct = fn());\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n struct ?? (struct = fn());\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n struct ?? (struct = fn());\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n struct ?? (struct = fn());\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\nfunction omit(struct, keys) {\n const { schema } = struct;\n const subschema = { ...schema };\n for (const key of keys) {\n delete subschema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\nfunction partial(struct) {\n const isStruct = struct instanceof Struct;\n const schema = isStruct ? { ...struct.schema } : { ...struct };\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n if (isStruct && struct.type === 'type') {\n return type(schema);\n }\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\nfunction pick(struct, keys) {\n const { schema } = struct;\n const subschema = {};\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array value, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a bigint.\n */\nfunction bigint() {\n return define('bigint', (value) => {\n return typeof value === 'bigint';\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\nfunction boolean() {\n return define('boolean', (value) => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\nfunction date() {\n return define('date', (value) => {\n return ((value instanceof Date && !isNaN(value.getTime())) ||\n `Expected a valid \\`Date\\` object, but received: ${print(value)}`);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map((v) => print(v)).join();\n for (const key of values) {\n schema[key] = key;\n }\n return new Struct({\n type: 'enums',\n schema,\n validator(value) {\n return (values.includes(value) ||\n `Expected one of \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a function.\n */\nfunction func() {\n return define('func', (value) => {\n return (typeof value === 'function' ||\n `Expected a function, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\nfunction instance(Class) {\n return define('instance', (value) => {\n return (value instanceof Class ||\n `Expected a \\`${Class.name}\\` instance, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\nfunction integer() {\n return define('integer', (value) => {\n return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) ||\n `Expected an integer, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value matches all of a set of types.\n */\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n },\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n const t = typeof constant;\n return new Struct({\n type: 'literal',\n schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null,\n validator(value) {\n return (value === constant ||\n `Expected the literal \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n validator(value) {\n return (value instanceof Map ||\n `Expected a \\`Map\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\nfunction nullable(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is a number.\n */\nfunction number() {\n return define('number', (value) => {\n return ((typeof value === 'number' && !isNaN(value)) ||\n `Expected a number, but received: ${print(value)}`);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value, ctx) {\n if (!isNonArrayObject(value)) {\n return value;\n }\n const coerced = { ...value };\n // The `object` struct has special behaviour enabled by the mask flag.\n // When masking, properties that are not in the schema are deleted from\n // the coerced object instead of eventually failing validaiton.\n if (ctx.mask && schema) {\n for (const key in coerced) {\n if (schema[key] === undefined) {\n delete coerced[key];\n }\n }\n }\n return coerced;\n },\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\nfunction optional(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\nfunction regexp() {\n return define('regexp', (value) => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n validator(value) {\n return (value instanceof Set ||\n `Expected a \\`Set\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a string.\n */\nfunction string() {\n return define('string', (value) => {\n return (typeof value === 'string' ||\n `Expected a string, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is a tuple of a specific length, and that each of its\n * elements is of a specific type.\n */\nfunction tuple(Structs) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Structs.length, value.length);\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Structs[i] || Never];\n }\n }\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array, but received: ${print(value)}`);\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value matches one of a set of types.\n */\nfunction union(Structs) {\n const description = Structs.map((s) => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n coercer(value, ctx) {\n for (const S of Structs) {\n const [error, coerced] = S.validate(value, {\n coerce: true,\n mask: ctx.mask,\n });\n if (!error) {\n return coerced;\n }\n }\n return value;\n },\n validator(value, ctx) {\n const failures = [];\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n if (!first[0]) {\n return [];\n }\n else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n return [\n `Expected the value to satisfy a union of \\`${description}\\`, but received: ${print(value)}`,\n ...failures,\n ];\n },\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction coerce(struct, condition, coercer) {\n return new Struct({\n ...struct,\n coercer: (value, ctx) => {\n return is(value, condition)\n ? struct.coercer(coercer(value, ctx), ctx)\n : struct.coercer(value, ctx);\n },\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), (x) => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n if (x === undefined) {\n return f;\n }\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x };\n let changed = false;\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n if (changed) {\n return ret;\n }\n }\n return x;\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction trimmed(struct) {\n return coerce(struct, string(), (x) => x.trim());\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\nfunction empty(struct) {\n return refine(struct, 'empty', (value) => {\n const size = getSize(value);\n return (size === 0 ||\n `Expected an empty ${struct.type} but received one with a size of \\`${size}\\``);\n });\n}\nfunction getSize(value) {\n if (value instanceof Map || value instanceof Set) {\n return value.size;\n }\n else {\n return value.length;\n }\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\nfunction max(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'max', (value) => {\n return exclusive\n ? value < threshold\n : value <= threshold ||\n `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\nfunction min(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'min', (value) => {\n return exclusive\n ? value > threshold\n : value >= threshold ||\n `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a string, array, map or set is not empty.\n */\nfunction nonempty(struct) {\n return refine(struct, 'nonempty', (value) => {\n const size = getSize(value);\n return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`);\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', (value) => {\n return (regexp.test(value) ||\n `Expected a ${struct.type} matching \\`/${regexp.source}/\\` but received \"${value}\"`);\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\nfunction size(struct, min, max = min) {\n const expected = `Expected a ${struct.type}`;\n const of = min === max ? `of \\`${min}\\`` : `between \\`${min}\\` and \\`${max}\\``;\n return refine(struct, 'size', (value) => {\n if (typeof value === 'number' || value instanceof Date) {\n return ((min <= value && value <= max) ||\n `${expected} ${of} but received \\`${value}\\``);\n }\n else if (value instanceof Map || value instanceof Set) {\n const { size } = value;\n return ((min <= size && size <= max) ||\n `${expected} with a size ${of} but received one with a size of \\`${size}\\``);\n }\n else {\n const { length } = value;\n return ((min <= length && length <= max) ||\n `${expected} with a length ${of} but received one with a length of \\`${length}\\``);\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\nfunction refine(struct, name, refiner) {\n return new Struct({\n ...struct,\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n for (const failure of failures) {\n yield { ...failure, refinement: name };\n }\n },\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, bigint, boolean, coerce, create, date, defaulted, define, deprecated, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, max, min, never, nonempty, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.mjs.map\n","import { PublicKey, MemcmpFilter, DataSlice } from '@solana/web3.js';\nimport {\n type as pick,\n number,\n string,\n array,\n literal,\n union,\n coerce,\n instance,\n create,\n unknown,\n any,\n nullable,\n Struct,\n} from 'superstruct';\nimport {\n BN254,\n createBN254,\n CompressedProof,\n CompressedAccountWithMerkleContext,\n MerkleContextWithMerkleProof,\n bn,\n TokenData,\n} from './state';\nimport BN from 'bn.js';\n\nexport interface LatestNonVotingSignatures {\n context: { slot: number };\n value: {\n items: {\n signature: string;\n slot: number;\n blockTime: number;\n error: string | null;\n }[];\n };\n}\n\nexport interface GetCompressedAccountsByOwnerConfig {\n filters?: GetCompressedAccountsFilter[];\n dataSlice?: DataSlice;\n cursor?: string;\n limit?: BN;\n}\n\nexport interface CompressedMintTokenHolders {\n balance: BN;\n owner: PublicKey;\n}\n\nexport interface LatestNonVotingSignaturesPaginated {\n context: { slot: number };\n value: {\n items: {\n signature: string;\n slot: number;\n blockTime: number;\n }[];\n cursor: string | null;\n };\n}\n\nexport interface SignatureWithMetadata {\n blockTime: number;\n signature: string;\n slot: number;\n}\n\nexport interface HashWithTree {\n hash: BN254;\n tree: PublicKey;\n queue: PublicKey;\n}\n\nexport interface AddressWithTree {\n address: BN254;\n tree: PublicKey;\n queue: PublicKey;\n}\n\nexport interface CompressedTransaction {\n compressionInfo: {\n closedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[];\n openedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[];\n preTokenBalances?: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }[];\n postTokenBalances?: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }[];\n };\n transaction: any;\n}\n\nexport interface HexBatchInputsForProver {\n 'input-compressed-accounts': HexInputsForProver[];\n}\n\nexport interface HexInputsForProver {\n root: string;\n pathIndex: number;\n pathElements: string[];\n leaf: string;\n}\n\n// TODO: Rename Compressed -> ValidityProof\nexport type CompressedProofWithContext = {\n compressedProof: CompressedProof;\n roots: BN[];\n rootIndices: number[];\n leafIndices: number[];\n leaves: BN[];\n merkleTrees: PublicKey[];\n nullifierQueues: PublicKey[];\n};\n\nexport interface GetCompressedTokenAccountsByOwnerOrDelegateOptions {\n mint?: PublicKey;\n cursor?: string;\n limit?: BN;\n}\nexport type TokenBalance = { balance: BN; mint: PublicKey };\n\n/**\n * **Cursor** is a unique identifier for a page of results by which the next page can be fetched.\n *\n * **Limit** is the maximum number of results to return per page.\n */\nexport interface PaginatedOptions {\n cursor?: string;\n limit?: BN;\n}\n\n/**\n * Note, DataSizeFilter is currently not available.\n */\nexport type GetCompressedAccountsFilter = MemcmpFilter; // | DataSizeFilter;\n\nexport type GetCompressedAccountConfig = {\n encoding?: string;\n};\n\nexport type GetCompressedAccountsConfig = {\n dataSlice: DataSlice;\n filters?: GetCompressedAccountsFilter[];\n};\n\nexport interface ParsedTokenAccount {\n compressedAccount: CompressedAccountWithMerkleContext;\n parsed: TokenData;\n}\n\nexport type WithContext<T> = {\n /** context */\n context: {\n slot: number;\n };\n /** response value */\n value: T;\n};\n\nexport type WithCursor<T> = {\n /** context */\n cursor: string | null;\n /** response value */\n items: T;\n};\n\n/**\n * @internal\n */\nconst PublicKeyFromString = coerce(\n instance(PublicKey),\n string(),\n value => new PublicKey(value),\n);\n\n/**\n * @internal\n */\nconst ArrayFromString = coerce(instance(Array<number>), string(), value =>\n Array.from(new PublicKey(value).toBytes()),\n);\n\n/**\n * @internal\n */\nconst BN254FromString = coerce(instance(BN), string(), value => {\n return createBN254(value, 'base58');\n});\n\n/**\n *\n * @internal\n * expects bigints to be supplied as strings.\n */\nconst BNFromStringOrNumber = coerce(\n instance(BN),\n union([string(), number()]),\n value => {\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value)) {\n throw new Error(`Unsafe integer. Precision loss: ${value}`);\n }\n return new BN(value); // Safe number → BN\n }\n return new BN(value, 10); // String → BN\n },\n);\n\n/**\n *\n * @internal\n */\nconst Base64EncodedCompressedAccountDataResult = coerce(\n string(),\n string(),\n value => (value === '' ? null : value),\n);\n/**\n * @internal\n */\nexport function createRpcResult<T, U>(result: Struct<T, U>) {\n return union([\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n result,\n }),\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n error: pick({\n code: unknown(),\n message: string(),\n data: nullable(any()),\n }),\n }),\n ]) as Struct<RpcResult<T>, null>;\n}\n\n/**\n * @internal\n */\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nexport function jsonRpcResult<T, U>(schema: Struct<T, U>) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value as RpcResultError;\n } else {\n return {\n ...value,\n result: create(value.result, schema),\n } as RpcResultSuccess<T>;\n }\n }) as Struct<RpcResult<T>, null>;\n}\n\n// Add this type for the context wrapper\nexport type WithRpcContext<T> = {\n context: {\n slot: number;\n };\n value: T;\n};\n\n/**\n * @internal\n */\nexport function jsonRpcResultAndContext<T, U>(value: Struct<T, U>) {\n return jsonRpcResult(\n pick({\n context: pick({\n slot: number(),\n }),\n value,\n }),\n ) as Struct<RpcResult<WithRpcContext<T>>, null>;\n}\n\n/**\n * @internal\n */\nexport const CompressedAccountResult = pick({\n address: nullable(ArrayFromString),\n hash: BN254FromString,\n data: nullable(\n pick({\n data: Base64EncodedCompressedAccountDataResult,\n dataHash: BN254FromString,\n discriminator: BNFromStringOrNumber,\n }),\n ),\n lamports: BNFromStringOrNumber,\n owner: PublicKeyFromString,\n leafIndex: number(),\n tree: PublicKeyFromString,\n seq: nullable(BNFromStringOrNumber),\n slotCreated: BNFromStringOrNumber,\n});\n\nexport const TokenDataResult = pick({\n mint: PublicKeyFromString,\n owner: PublicKeyFromString,\n amount: BNFromStringOrNumber,\n delegate: nullable(PublicKeyFromString),\n state: string(),\n});\n\n/**\n * @internal\n */\nexport const CompressedTokenAccountResult = pick({\n tokenData: TokenDataResult,\n account: CompressedAccountResult,\n});\n\n/**\n * @internal\n */\nexport const MultipleCompressedAccountsResult = pick({\n items: array(CompressedAccountResult),\n});\n\n/**\n * @internal\n */\nexport const CompressedAccountsByOwnerResult = pick({\n items: array(CompressedAccountResult),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const CompressedTokenAccountsByOwnerOrDelegateResult = pick({\n items: array(CompressedTokenAccountResult),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const SlotResult = number();\n\n/**\n * @internal\n */\nexport const HealthResult = string();\n\n/**\n * @internal\n */\nexport const LatestNonVotingSignaturesResult = pick({\n items: array(\n pick({\n signature: string(),\n slot: number(),\n blockTime: number(),\n error: nullable(string()),\n }),\n ),\n});\n\n/**\n * @internal\n */\nexport const LatestNonVotingSignaturesResultPaginated = pick({\n items: array(\n pick({\n signature: string(),\n slot: number(),\n blockTime: number(),\n }),\n ),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const MerkeProofResult = pick({\n hash: BN254FromString,\n leafIndex: number(),\n merkleTree: PublicKeyFromString,\n proof: array(BN254FromString),\n rootSeq: number(),\n root: BN254FromString,\n});\n\n/**\n * @internal\n */\nexport const NewAddressProofResult = pick({\n address: BN254FromString,\n nextIndex: number(),\n merkleTree: PublicKeyFromString,\n proof: array(BN254FromString), // this is: merkleProofHashedIndexedElementLeaf\n rootSeq: number(),\n root: BN254FromString,\n lowerRangeAddress: BN254FromString, // this is: leafLowerRangeValue.\n higherRangeAddress: BN254FromString, // this is: leafHigherRangeValue\n lowElementLeafIndex: number(), // this is: indexHashedIndexedElementLeaf\n});\n\n/**\n * @internal\n */\nconst CompressedProofResult = pick({\n a: array(number()),\n b: array(number()),\n c: array(number()),\n});\n\n/**\n * @internal\n */\nexport const ValidityProofResult = pick({\n compressedProof: CompressedProofResult,\n leafIndices: array(number()),\n leaves: array(BN254FromString),\n rootIndices: array(number()),\n roots: array(BN254FromString),\n merkleTrees: array(PublicKeyFromString),\n // TODO: enable nullifierQueues\n // nullifierQueues: array(PublicKeyFromString),\n});\n\n/**\n * @internal\n */\nexport const MultipleMerkleProofsResult = array(MerkeProofResult);\n\n/**\n * @internal\n */\nexport const BalanceResult = pick({\n amount: BNFromStringOrNumber,\n});\n\nexport const NativeBalanceResult = BNFromStringOrNumber;\n\nexport const TokenBalanceResult = pick({\n balance: BNFromStringOrNumber,\n mint: PublicKeyFromString,\n});\n\nexport const TokenBalanceListResult = pick({\n tokenBalances: array(TokenBalanceResult),\n cursor: nullable(string()),\n});\n\nexport const TokenBalanceListResultV2 = pick({\n items: array(TokenBalanceResult),\n cursor: nullable(string()),\n});\n\nexport const CompressedMintTokenHoldersResult = pick({\n cursor: nullable(string()),\n items: array(\n pick({\n balance: BNFromStringOrNumber,\n owner: PublicKeyFromString,\n }),\n ),\n});\n\nexport const AccountProofResult = pick({\n hash: array(number()),\n root: array(number()),\n proof: array(array(number())),\n});\n\nexport const toUnixTimestamp = (blockTime: string): number => {\n return new Date(blockTime).getTime();\n};\n\nexport const SignatureListResult = pick({\n items: array(\n pick({\n blockTime: number(),\n signature: string(),\n slot: number(),\n }),\n ),\n});\n\nexport const SignatureListWithCursorResult = pick({\n items: array(\n pick({\n blockTime: number(),\n signature: string(),\n slot: number(),\n }),\n ),\n cursor: nullable(string()),\n});\n\nexport const CompressedTransactionResult = pick({\n compressionInfo: pick({\n closedAccounts: array(\n pick({\n account: CompressedAccountResult,\n optionalTokenData: nullable(TokenDataResult),\n }),\n ),\n openedAccounts: array(\n pick({\n account: CompressedAccountResult,\n optionalTokenData: nullable(TokenDataResult),\n }),\n ),\n }),\n /// TODO: add transaction struct\n /// https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/transaction-status/src/lib.rs#L1061\n transaction: any(),\n});\n\nexport interface CompressionApiInterface {\n getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null>;\n\n getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN | null>;\n\n getCompressedBalanceByOwner(owner: PublicKey): Promise<BN>;\n\n getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof>;\n\n getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]>;\n\n getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]>;\n\n getValidityProof(\n hashes: BN254[],\n newAddresses: BN254[],\n ): Promise<CompressedProofWithContext>;\n\n getValidityProofV0(\n hashes: HashWithTree[],\n newAddresses: AddressWithTree[],\n ): Promise<CompressedProofWithContext>;\n\n getValidityProofAndRpcContext(\n hashes: HashWithTree[],\n newAddresses: AddressWithTree[],\n ): Promise<WithContext<CompressedProofWithContext>>;\n\n getCompressedAccountsByOwner(\n owner: PublicKey,\n config?: GetCompressedAccountsByOwnerConfig,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>>;\n\n getCompressedMintTokenHolders(\n mint: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>>;\n\n getCompressedTokenAccountsByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>>;\n\n getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>>;\n\n getCompressedTokenAccountBalance(hash: BN254): Promise<{ amount: BN }>;\n\n getCompressedTokenBalancesByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<TokenBalance[]>>;\n\n getCompressedTokenBalancesByOwnerV2(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>>;\n\n getTransactionWithCompressionInfo(\n signature: string,\n ): Promise<CompressedTransaction | null>;\n\n getCompressionSignaturesForAccount(\n hash: BN254,\n ): Promise<SignatureWithMetadata[]>;\n\n getCompressionSignaturesForAddress(\n address: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getCompressionSignaturesForOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getCompressionSignaturesForTokenOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getLatestNonVotingSignatures(\n limit?: number,\n cursor?: string,\n ): Promise<LatestNonVotingSignatures>;\n\n getLatestCompressionSignatures(\n cursor?: string,\n limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated>;\n\n getIndexerHealth(): Promise<string>;\n\n getIndexerSlot(): Promise<number>;\n}\n\n// Public types for consumers\nexport type RpcResultSuccess<T> = {\n jsonrpc: '2.0';\n id: string;\n result: T;\n};\n\nexport type RpcResultError = {\n jsonrpc: '2.0';\n id: string;\n error: {\n code: unknown;\n message: string;\n data?: any;\n };\n};\n\nexport type RpcResult<T> = RpcResultSuccess<T> | RpcResultError;\n","import {\n Connection,\n ConnectionConfig,\n PublicKey,\n SolanaJSONRPCError,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n BalanceResult,\n CompressedAccountResult,\n CompressedAccountsByOwnerResult,\n CompressedProofWithContext,\n CompressedTokenAccountsByOwnerOrDelegateResult,\n CompressedTransaction,\n CompressedTransactionResult,\n CompressionApiInterface,\n GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n HealthResult,\n HexInputsForProver,\n MerkeProofResult,\n MultipleCompressedAccountsResult,\n NativeBalanceResult,\n ParsedTokenAccount,\n SignatureListResult,\n SignatureListWithCursorResult,\n SignatureWithMetadata,\n SlotResult,\n TokenBalanceListResult,\n jsonRpcResult,\n jsonRpcResultAndContext,\n ValidityProofResult,\n NewAddressProofResult,\n LatestNonVotingSignaturesResult,\n LatestNonVotingSignatures,\n LatestNonVotingSignaturesResultPaginated,\n LatestNonVotingSignaturesPaginated,\n WithContext,\n GetCompressedAccountsByOwnerConfig,\n WithCursor,\n AddressWithTree,\n HashWithTree,\n CompressedMintTokenHoldersResult,\n CompressedMintTokenHolders,\n TokenBalance,\n TokenBalanceListResultV2,\n PaginatedOptions,\n} from './rpc-interface';\nimport {\n MerkleContextWithMerkleProof,\n BN254,\n bn,\n CompressedAccountWithMerkleContext,\n encodeBN254toBase58,\n createCompressedAccountWithMerkleContext,\n createMerkleContext,\n TokenData,\n CompressedProof,\n} from './state';\nimport { array, create, nullable } from 'superstruct';\nimport {\n defaultTestStateTreeAccounts,\n localTestActiveStateTreeInfo,\n isLocalTest,\n defaultStateTreeLookupTables,\n} from './constants';\nimport BN from 'bn.js';\nimport { toCamelCase, toHex } from './utils/conversion';\n\nimport {\n proofFromJsonStruct,\n negateAndCompressProof,\n} from './utils/parse-validity-proof';\nimport { LightWasm } from './test-helpers';\nimport { getLightStateTreeInfo } from './utils/get-light-state-tree-info';\nimport { ActiveTreeBundle } from './state/types';\n\n/** @internal */\nexport function parseAccountData({\n discriminator,\n data,\n dataHash,\n}: {\n discriminator: BN;\n data: string;\n dataHash: BN;\n}) {\n return {\n discriminator: discriminator.toArray('le', 8),\n data: Buffer.from(data, 'base64'),\n dataHash: dataHash.toArray('le', 32),\n };\n}\n\n/** @internal */\nasync function getCompressedTokenAccountsByOwnerOrDelegate(\n rpc: Rpc,\n ownerOrDelegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n filterByDelegate: boolean = false,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const endpoint = filterByDelegate\n ? 'getCompressedTokenAccountsByDelegate'\n : 'getCompressedTokenAccountsByOwner';\n const propertyToCheck = filterByDelegate ? 'delegate' : 'owner';\n\n const unsafeRes = await rpcRequest(rpc.compressionApiEndpoint, endpoint, {\n [propertyToCheck]: ownerOrDelegate.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n });\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedTokenAccountsByOwnerOrDelegateResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts by ${propertyToCheck} ${ownerOrDelegate.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error('not implemented: NULL result');\n }\n const accounts: ParsedTokenAccount[] = [];\n\n const activeStateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n\n res.result.value.items.map(item => {\n const _account = item.account;\n const _tokenData = item.tokenData;\n\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n _account.tree!,\n );\n\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n _account.tree!,\n associatedQueue,\n _account.hash.toArray('be', 32),\n _account.leafIndex,\n ),\n _account.owner,\n bn(_account.lamports),\n _account.data ? parseAccountData(_account.data) : undefined,\n _account.address || undefined,\n );\n\n const parsed: TokenData = {\n mint: _tokenData.mint,\n owner: _tokenData.owner,\n amount: _tokenData.amount,\n delegate: _tokenData.delegate,\n state: ['uninitialized', 'initialized', 'frozen'].indexOf(\n _tokenData.state,\n ),\n tlv: null,\n };\n\n if (\n parsed[propertyToCheck]?.toBase58() !== ownerOrDelegate.toBase58()\n ) {\n throw new Error(\n `RPC returned token account with ${propertyToCheck} different from requested ${propertyToCheck}`,\n );\n }\n\n accounts.push({\n compressedAccount,\n parsed,\n });\n });\n /// TODO: consider custom or different sort. Most recent here.\n return {\n items: accounts.sort(\n (a, b) =>\n b.compressedAccount.leafIndex - a.compressedAccount.leafIndex,\n ),\n cursor: res.result.value.cursor,\n };\n}\n\n/** @internal */\nfunction buildCompressedAccountWithMaybeTokenData(\n accountStructWithOptionalTokenData: any,\n activeStateTreeInfo: ActiveTreeBundle[],\n): {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n} {\n const compressedAccountResult = accountStructWithOptionalTokenData.account;\n const tokenDataResult =\n accountStructWithOptionalTokenData.optionalTokenData;\n\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n compressedAccountResult.tree!,\n );\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n compressedAccountResult.merkleTree,\n associatedQueue,\n compressedAccountResult.hash.toArray('be', 32),\n compressedAccountResult.leafIndex,\n ),\n compressedAccountResult.owner,\n bn(compressedAccountResult.lamports),\n compressedAccountResult.data\n ? parseAccountData(compressedAccountResult.data)\n : undefined,\n compressedAccountResult.address || undefined,\n );\n\n if (tokenDataResult === null) {\n return { account: compressedAccount, maybeTokenData: null };\n }\n\n const parsed: TokenData = {\n mint: tokenDataResult.mint,\n owner: tokenDataResult.owner,\n amount: tokenDataResult.amount,\n delegate: tokenDataResult.delegate,\n state: ['uninitialized', 'initialized', 'frozen'].indexOf(\n tokenDataResult.state,\n ),\n tlv: null,\n };\n\n return { account: compressedAccount, maybeTokenData: parsed };\n}\n\n/**\n * Establish a Compression-compatible JSON RPC connection\n *\n * @param endpointOrWeb3JsConnection endpoint to the solana cluster or\n * Connection object\n * @param compressionApiEndpoint Endpoint to the compression server\n * @param proverEndpoint Endpoint to the prover server. defaults\n * to endpoint\n * @param connectionConfig Optional connection config\n */\nexport function createRpc(\n endpointOrWeb3JsConnection?: string | Connection,\n compressionApiEndpoint?: string,\n proverEndpoint?: string,\n config?: ConnectionConfig,\n): Rpc {\n const localEndpoint = 'http://127.0.0.1:8899';\n const localCompressionApiEndpoint = 'http://127.0.0.1:8784';\n const localProverEndpoint = 'http://127.0.0.1:3001';\n\n let endpoint: string;\n\n if (!endpointOrWeb3JsConnection) {\n // Local as default\n endpoint = localEndpoint;\n compressionApiEndpoint =\n compressionApiEndpoint || localCompressionApiEndpoint;\n proverEndpoint = proverEndpoint || localProverEndpoint;\n } else if (typeof endpointOrWeb3JsConnection === 'string') {\n endpoint = endpointOrWeb3JsConnection;\n compressionApiEndpoint = compressionApiEndpoint || endpoint;\n proverEndpoint = proverEndpoint || endpoint;\n } else if (endpointOrWeb3JsConnection instanceof Connection) {\n endpoint = endpointOrWeb3JsConnection.rpcEndpoint;\n compressionApiEndpoint = compressionApiEndpoint || endpoint;\n proverEndpoint = proverEndpoint || endpoint;\n }\n // 3\n else {\n throw new Error('Invalid endpoint or connection type');\n }\n\n return new Rpc(endpoint, compressionApiEndpoint, proverEndpoint, config);\n}\n\n/**\n * Helper function to preprocess the response to wrap numbers as strings\n * @param {string} text - The JSON string to preprocess\n * @returns {string} - The preprocessed JSON string with numbers wrapped as strings\n */\nexport function wrapBigNumbersAsStrings(text: string): string {\n return text.replace(/(\":\\s*)(-?\\d+)(\\s*[},])/g, (match, p1, p2, p3) => {\n const num = Number(p2);\n if (\n !Number.isNaN(num) &&\n (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER)\n ) {\n return `${p1}\"${p2}\"${p3}`;\n }\n return match;\n });\n}\n\n/** @internal */\nexport const rpcRequest = async (\n rpcEndpoint: string,\n method: string,\n params: any = [],\n convertToCamelCase = true,\n debug = false,\n): Promise<any> => {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: 'test-account',\n method: method,\n params: params,\n });\n\n if (debug) {\n const generateCurlSnippet = () => {\n const escapedBody = body.replace(/\"/g, '\\\\\"');\n return `curl -X POST ${rpcEndpoint} \\\\\n -H \"Content-Type: application/json\" \\\\\n -d \"${escapedBody}\"`;\n };\n\n console.log('Debug: Stack trace:');\n console.log(new Error().stack);\n console.log('\\nDebug: curl:');\n console.log(generateCurlSnippet());\n console.log('\\n');\n }\n\n const response = await fetch(rpcEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const text = await response.text();\n\n const wrappedJsonString = wrapBigNumbersAsStrings(text);\n\n if (convertToCamelCase) {\n return toCamelCase(JSON.parse(wrappedJsonString));\n }\n\n return JSON.parse(wrappedJsonString);\n};\n\n/** @internal */\nexport const proverRequest = async (\n proverEndpoint: string,\n method: 'inclusion' | 'new-address' | 'combined',\n params: any = [],\n log = false,\n publicInputHash: BN | undefined = undefined,\n): Promise<CompressedProof> => {\n let logMsg: string = '';\n\n if (log) {\n logMsg = `Proof generation for method:${method}`;\n console.time(logMsg);\n }\n\n let body;\n if (method === 'inclusion') {\n body = JSON.stringify({\n circuitType: 'inclusion',\n stateTreeHeight: 26,\n inputCompressedAccounts: params,\n // publicInputHash: publicInputHash.toString('hex'),\n });\n } else if (method === 'new-address') {\n body = JSON.stringify({\n circuitType: 'non-inclusion',\n addressTreeHeight: 26,\n // publicInputHash: publicInputHash.toString('hex'),\n newAddresses: params,\n });\n } else if (method === 'combined') {\n body = JSON.stringify({\n circuitType: 'combined',\n // publicInputHash: publicInputHash.toString('hex'),\n stateTreeHeight: 26,\n addressTreeHeight: 26,\n inputCompressedAccounts: params[0],\n newAddresses: params[1],\n });\n }\n\n const response = await fetch(`${proverEndpoint}/prove`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`Error fetching proof: ${response.statusText}`);\n }\n const data: any = await response.json();\n const parsed = proofFromJsonStruct(data);\n const compressedProof = negateAndCompressProof(parsed);\n\n if (log) console.timeEnd(logMsg);\n\n return compressedProof;\n};\n\nexport type NonInclusionMerkleProofInputs = {\n root: BN;\n value: BN;\n leaf_lower_range_value: BN;\n leaf_higher_range_value: BN;\n nextIndex: BN;\n merkle_proof_hashed_indexed_element_leaf: BN[];\n index_hashed_indexed_element_leaf: BN;\n};\n\nexport type MerkleContextWithNewAddressProof = {\n root: BN;\n rootIndex: number;\n value: BN;\n leafLowerRangeValue: BN;\n leafHigherRangeValue: BN;\n nextIndex: BN;\n merkleProofHashedIndexedElementLeaf: BN[];\n indexHashedIndexedElementLeaf: BN;\n merkleTree: PublicKey;\n nullifierQueue: PublicKey;\n};\n\nexport type NonInclusionJsonStruct = {\n root: string;\n value: string;\n pathIndex: number;\n pathElements: string[];\n leafLowerRangeValue: string;\n leafHigherRangeValue: string;\n nextIndex: number;\n};\n\nexport function convertMerkleProofsWithContextToHex(\n merkleProofsWithContext: MerkleContextWithMerkleProof[],\n): HexInputsForProver[] {\n const inputs: HexInputsForProver[] = [];\n\n for (let i = 0; i < merkleProofsWithContext.length; i++) {\n const input: HexInputsForProver = {\n root: toHex(merkleProofsWithContext[i].root),\n pathIndex: merkleProofsWithContext[i].leafIndex,\n pathElements: merkleProofsWithContext[i].merkleProof.map(hex =>\n toHex(hex),\n ),\n leaf: toHex(bn(merkleProofsWithContext[i].hash)),\n };\n inputs.push(input);\n }\n\n return inputs;\n}\n\nexport function convertNonInclusionMerkleProofInputsToHex(\n nonInclusionMerkleProofInputs: MerkleContextWithNewAddressProof[],\n): NonInclusionJsonStruct[] {\n const inputs: NonInclusionJsonStruct[] = [];\n for (let i = 0; i < nonInclusionMerkleProofInputs.length; i++) {\n const input: NonInclusionJsonStruct = {\n root: toHex(nonInclusionMerkleProofInputs[i].root),\n value: toHex(nonInclusionMerkleProofInputs[i].value),\n pathIndex:\n nonInclusionMerkleProofInputs[\n i\n ].indexHashedIndexedElementLeaf.toNumber(),\n pathElements: nonInclusionMerkleProofInputs[\n i\n ].merkleProofHashedIndexedElementLeaf.map(hex => toHex(hex)),\n nextIndex: nonInclusionMerkleProofInputs[i].nextIndex.toNumber(),\n leafLowerRangeValue: toHex(\n nonInclusionMerkleProofInputs[i].leafLowerRangeValue,\n ),\n leafHigherRangeValue: toHex(\n nonInclusionMerkleProofInputs[i].leafHigherRangeValue,\n ),\n };\n inputs.push(input);\n }\n return inputs;\n}\n\nfunction calculateTwoInputsHashChain(\n hashesFirst: BN[],\n hashesSecond: BN[],\n lightWasm: LightWasm,\n): BN {\n if (hashesFirst.length !== hashesSecond.length) {\n throw new Error('Input lengths must match.');\n }\n if (hashesFirst.length === 0) {\n return new BN(0);\n }\n\n let hashChain = lightWasm.poseidonHashBN([\n hashesFirst[0].toString(),\n hashesSecond[0].toString(),\n ]);\n\n for (let i = 1; i < hashesFirst.length; i++) {\n hashChain = lightWasm.poseidonHashBN([\n hashChain.toString(),\n hashesFirst[i].toString(),\n hashesSecond[i].toString(),\n ]);\n }\n\n return hashChain;\n}\n\nexport function getPublicInputHash(\n accountProofs: MerkleContextWithMerkleProof[],\n accountHashes: BN254[],\n newAddressProofs: MerkleContextWithNewAddressProof[],\n lightWasm: LightWasm,\n): BN {\n const accountRoots = accountProofs.map(x => x.root);\n const inclusionHashChain = calculateTwoInputsHashChain(\n accountRoots,\n accountHashes,\n lightWasm,\n );\n\n const newAddressHashes = newAddressProofs.map(x => x.value);\n const newAddressRoots = newAddressProofs.map(x => x.root);\n const nonInclusionHashChain = calculateTwoInputsHashChain(\n newAddressRoots,\n newAddressHashes,\n lightWasm,\n );\n\n if (!nonInclusionHashChain.isZero()) {\n return nonInclusionHashChain;\n } else if (!inclusionHashChain.isZero()) {\n return inclusionHashChain;\n } else {\n return calculateTwoInputsHashChain(\n [inclusionHashChain],\n [nonInclusionHashChain],\n lightWasm,\n );\n }\n}\n\n/**\n * Get the queue for a given tree\n *\n * @param info - The active state tree addresses\n * @param tree - The tree to get the queue for\n * @returns The queue for the given tree, or undefined if not found\n */\nexport function getQueueForTree(\n info: ActiveTreeBundle[],\n tree: PublicKey,\n): PublicKey {\n const index = info.findIndex(t => t.tree.equals(tree));\n if (index === -1) {\n throw new Error(\n 'No associated queue found for tree. Please set activeStateTreeInfo with latest Tree accounts. If you use custom state trees, set manually.',\n );\n }\n if (!info[index].queue) {\n throw new Error('Queue must not be null for state tree');\n }\n return info[index].queue;\n}\n\n/**\n * Get the tree for a given queue\n *\n * @param info - The active state tree addresses\n * @param queue - The queue to get the tree for\n * @returns The tree for the given queue, or undefined if not found\n */\nexport function getTreeForQueue(\n info: ActiveTreeBundle[],\n queue: PublicKey,\n): PublicKey {\n const index = info.findIndex(q => q.queue?.equals(queue));\n if (index === -1) {\n throw new Error(\n 'No associated tree found for queue. Please set activeStateTreeInfo with latest Tree accounts. If you use custom state trees, set manually.',\n );\n }\n if (!info[index].tree) {\n throw new Error('Tree must not be null for state tree');\n }\n return info[index].tree;\n}\n\n/**\n * Get a random tree and queue from the active state tree addresses.\n *\n * Prevents write lock contention on state trees.\n *\n * @param info - The active state tree addresses\n * @returns A random tree and queue\n */\nexport function pickRandomTreeAndQueue(info: ActiveTreeBundle[]): {\n tree: PublicKey;\n queue: PublicKey;\n} {\n const length = info.length;\n const index = Math.floor(Math.random() * length);\n\n if (!info[index].queue) {\n throw new Error('Queue must not be null for state tree');\n }\n return {\n tree: info[index].tree,\n queue: info[index].queue,\n };\n}\n\n/**\n *\n */\nexport class Rpc extends Connection implements CompressionApiInterface {\n compressionApiEndpoint: string;\n proverEndpoint: string;\n activeStateTreeInfo: ActiveTreeBundle[] | null = null;\n\n constructor(\n endpoint: string,\n compressionApiEndpoint: string,\n proverEndpoint: string,\n config?: ConnectionConfig,\n ) {\n super(endpoint, config || 'confirmed');\n this.compressionApiEndpoint = compressionApiEndpoint;\n this.proverEndpoint = proverEndpoint;\n }\n\n /**\n * Manually set state tree addresses\n */\n setStateTreeInfo(info: ActiveTreeBundle[]): void {\n this.activeStateTreeInfo = info;\n }\n\n /**\n * Get the active state tree addresses from the cluster.\n * If not already cached, fetches from the cluster.\n */\n async getCachedActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n if (isLocalTest(this.rpcEndpoint)) {\n return localTestActiveStateTreeInfo();\n }\n\n let info: ActiveTreeBundle[] | null = null;\n if (!this.activeStateTreeInfo) {\n const { mainnet, devnet } = defaultStateTreeLookupTables();\n try {\n info = await getLightStateTreeInfo({\n connection: this,\n stateTreeLookupTableAddress:\n mainnet[0].stateTreeLookupTable,\n nullifyTableAddress: mainnet[0].nullifyTable,\n });\n this.activeStateTreeInfo = info;\n } catch {\n info = await getLightStateTreeInfo({\n connection: this,\n stateTreeLookupTableAddress: devnet[0].stateTreeLookupTable,\n nullifyTableAddress: devnet[0].nullifyTable,\n });\n this.activeStateTreeInfo = info;\n }\n }\n if (!this.activeStateTreeInfo) {\n throw new Error(\n `activeStateTreeInfo should not be null ${JSON.stringify(\n this.activeStateTreeInfo,\n )}`,\n );\n }\n\n return this.activeStateTreeInfo!;\n }\n\n /**\n * Fetch the latest state tree addresses from the cluster.\n */\n async getLatestActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n this.activeStateTreeInfo = null;\n return await this.getCachedActiveStateTreeInfo();\n }\n\n /**\n * Fetch the compressed account for the specified account address or hash\n */\n async getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null> {\n if (!hash && !address) {\n throw new Error('Either hash or address must be provided');\n }\n if (hash && address) {\n throw new Error('Only one of hash or address must be provided');\n }\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccount',\n {\n hash: hash ? encodeBN254toBase58(hash) : undefined,\n address: address ? encodeBN254toBase58(address) : undefined,\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(CompressedAccountResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed account ${hash ? hash.toString() : address ? address.toString() : ''}`,\n );\n }\n if (res.result.value === null) {\n return null;\n }\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n res.result.value.tree!,\n );\n const item = res.result.value;\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n return account;\n }\n\n /**\n * Fetch the compressed balance for the specified account address or hash\n */\n async getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN> {\n if (!hash && !address) {\n throw new Error('Either hash or address must be provided');\n }\n if (hash && address) {\n throw new Error('Only one of hash or address must be provided');\n }\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedBalance',\n {\n hash: hash ? encodeBN254toBase58(hash) : undefined,\n address: address ? encodeBN254toBase58(address) : undefined,\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(NativeBalanceResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed account ${hash ? hash.toString() : address ? address.toString() : ''}`,\n );\n }\n if (res.result.value === null) {\n return bn(0);\n }\n\n return bn(res.result.value);\n }\n\n /// TODO: validate that this is just for sol accounts\n /**\n * Fetch the total compressed balance for the specified owner public key\n */\n async getCompressedBalanceByOwner(owner: PublicKey): Promise<BN> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedBalanceByOwner',\n { owner: owner.toBase58() },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(NativeBalanceResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed account ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n return bn(0);\n }\n return bn(res.result.value);\n }\n\n /**\n * Fetch the latest merkle proof for the specified account hash from the\n * cluster\n */\n async getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccountProof',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(MerkeProofResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proof for compressed account ${hash.toString()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proof for compressed account ${hash.toString()}`,\n );\n }\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n res.result.value.merkleTree,\n );\n\n const value: MerkleContextWithMerkleProof = {\n hash: res.result.value.hash.toArray('be', 32),\n merkleTree: res.result.value.merkleTree,\n leafIndex: res.result.value.leafIndex,\n merkleProof: res.result.value.proof,\n nullifierQueue: associatedQueue, // TODO(photon): support nullifierQueue in response.\n rootIndex: res.result.value.rootSeq % 2400,\n root: res.result.value.root,\n };\n return value;\n }\n\n /**\n * Fetch all the account info for multiple compressed accounts specified by\n * an array of account hashes\n */\n async getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleCompressedAccounts',\n { hashes: hashes.map(hash => encodeBN254toBase58(hash)) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(MultipleCompressedAccountsResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get info for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const accounts: CompressedAccountWithMerkleContext[] = [];\n res.result.value.items.map(item => {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n item.tree!,\n );\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n accounts.push(account);\n });\n\n return accounts.sort((a, b) => b.leafIndex - a.leafIndex);\n }\n\n /**\n * Fetch the latest merkle proofs for multiple compressed accounts specified\n * by an array account hashes\n */\n async getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleCompressedAccountProofs',\n hashes.map(hash => encodeBN254toBase58(hash)),\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(MerkeProofResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proofs for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proofs for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n\n const merkleProofs: MerkleContextWithMerkleProof[] = [];\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n for (const proof of res.result.value) {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n proof.merkleTree,\n );\n const value: MerkleContextWithMerkleProof = {\n hash: proof.hash.toArray('be', 32),\n merkleTree: proof.merkleTree,\n leafIndex: proof.leafIndex,\n merkleProof: proof.proof,\n nullifierQueue: associatedQueue,\n rootIndex: proof.rootSeq % 2400,\n root: proof.root,\n };\n merkleProofs.push(value);\n }\n return merkleProofs;\n }\n\n /**\n * Fetch all the compressed accounts owned by the specified public key.\n * Owner can be a program or user account\n */\n async getCompressedAccountsByOwner(\n owner: PublicKey,\n config?: GetCompressedAccountsByOwnerConfig | undefined,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccountsByOwner',\n {\n owner: owner.toBase58(),\n filters: config?.filters || [],\n dataSlice: config?.dataSlice,\n cursor: config?.cursor,\n limit: config?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedAccountsByOwnerResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts owned by ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n return {\n items: [],\n cursor: null,\n };\n }\n const accounts: CompressedAccountWithMerkleContext[] = [];\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n\n res.result.value.items.map(item => {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n item.tree!,\n );\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n\n accounts.push(account);\n });\n\n return {\n items: accounts.sort((a, b) => b.leafIndex - a.leafIndex),\n cursor: res.result.value.cursor,\n };\n }\n\n /**\n * Fetch all the compressed token accounts owned by the specified public\n * key. Owner can be a program or user account\n */\n async getCompressedTokenAccountsByOwner(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n if (!options) options = {};\n\n return await getCompressedTokenAccountsByOwnerOrDelegate(\n this,\n owner,\n options,\n false,\n );\n }\n\n /**\n * Fetch all the compressed accounts delegated to the specified public key.\n */\n async getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n if (!options) options = {};\n\n return await getCompressedTokenAccountsByOwnerOrDelegate(\n this,\n delegate,\n options,\n true,\n );\n }\n\n /**\n * Fetch the compressed token balance for the specified account hash\n */\n async getCompressedTokenAccountBalance(\n hash: BN254,\n ): Promise<{ amount: BN }> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenAccountBalance',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(unsafeRes, jsonRpcResultAndContext(BalanceResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed token account ${hash.toString()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get balance for compressed token account ${hash.toString()}`,\n );\n }\n\n return { amount: bn(res.result.value.amount) };\n }\n\n /**\n * @deprecated use {@link getCompressedTokenBalancesByOwnerV2} instead.\n *\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint. Returns without context.\n */\n async getCompressedTokenBalancesByOwner(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<TokenBalance[]>> {\n if (!options) options = {};\n\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenBalancesByOwner',\n {\n owner: owner.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(TokenBalanceListResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n\n const maybeFiltered = options.mint\n ? res.result.value.tokenBalances.filter(\n tokenBalance =>\n tokenBalance.mint.toBase58() === options.mint!.toBase58(),\n )\n : res.result.value.tokenBalances;\n\n return {\n items: maybeFiltered,\n cursor: res.result.value.cursor,\n };\n }\n\n /**\n * Fetch the compressed token balances owned by the specified public\n * key. Paginated. Can filter by mint. Returns with context.\n */\n async getCompressedTokenBalancesByOwnerV2(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>> {\n if (!options) options = {};\n\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenBalancesByOwnerV2',\n {\n owner: owner.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(TokenBalanceListResultV2),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n\n const maybeFiltered = options.mint\n ? res.result.value.items.filter(\n tokenBalance =>\n tokenBalance.mint.toBase58() === options.mint!.toBase58(),\n )\n : res.result.value.items;\n\n return {\n context: res.result.context,\n value: {\n items: maybeFiltered,\n cursor: res.result.value.cursor,\n },\n };\n }\n\n /**\n * Returns confirmed compression signatures for transactions involving the specified\n * account hash forward in time from genesis to the most recent confirmed\n * block\n *\n * @param hash queried account hash\n */\n async getCompressionSignaturesForAccount(\n hash: BN254,\n ): Promise<SignatureWithMetadata[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForAccount',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for compressed account ${hash.toString()}`,\n );\n }\n return res.result.value.items;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster. Return with\n * CompressionInfo\n */\n async getTransactionWithCompressionInfo(\n signature: string,\n ): Promise<CompressedTransaction | null> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getTransactionWithCompressionInfo',\n { signature },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResult(CompressedTransactionResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n\n if (res.result.transaction === null) return null;\n\n const closedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[] = [];\n\n const openedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[] = [];\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n\n res.result.compressionInfo.closedAccounts.map(item => {\n closedAccounts.push(\n buildCompressedAccountWithMaybeTokenData(\n item,\n activeStateTreeInfo,\n ),\n );\n });\n res.result.compressionInfo.openedAccounts.map(item => {\n openedAccounts.push(\n buildCompressedAccountWithMaybeTokenData(\n item,\n activeStateTreeInfo,\n ),\n );\n });\n\n const calculateTokenBalances = (\n accounts: Array<{\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }>,\n ):\n | Array<{\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }>\n | undefined => {\n const balances = Object.values(\n accounts.reduce(\n (acc, { maybeTokenData }) => {\n if (maybeTokenData) {\n const { owner, mint, amount } = maybeTokenData;\n const key = `${owner.toBase58()}_${mint.toBase58()}`;\n if (key in acc) {\n acc[key].amount = acc[key].amount.add(amount);\n } else {\n acc[key] = { owner, mint, amount };\n }\n }\n return acc;\n },\n {} as {\n [key: string]: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n };\n },\n ),\n );\n return balances.length > 0 ? balances : undefined;\n };\n\n const preTokenBalances = calculateTokenBalances(closedAccounts);\n const postTokenBalances = calculateTokenBalances(openedAccounts);\n\n return {\n compressionInfo: {\n closedAccounts,\n openedAccounts,\n preTokenBalances,\n postTokenBalances,\n },\n transaction: res.result.transaction,\n };\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * address forward in time from genesis to the most recent confirmed block\n *\n * @param address queried compressed account address\n */\n async getCompressionSignaturesForAddress(\n address: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForAddress',\n {\n address: address.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for address ${address.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for address ${address.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified account owner forward in time from genesis to the\n * most recent confirmed block\n *\n * @param owner queried owner public key\n */\n async getCompressionSignaturesForOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForOwner',\n {\n owner: owner.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified token account owner forward in time from genesis to the most\n * recent confirmed block\n */\n async getCompressionSignaturesForTokenOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForTokenOwner',\n {\n owner: owner.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Fetch the current indexer health status\n */\n async getIndexerHealth(): Promise<string> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getIndexerHealth',\n );\n const res = create(unsafeRes, jsonRpcResult(HealthResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get health');\n }\n return res.result;\n }\n\n /**\n * Ensure that the Compression Indexer has already indexed the transaction\n */\n async confirmTransactionIndexed(slot: number): Promise<boolean> {\n const startTime = Date.now();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const indexerSlot = await this.getIndexerSlot();\n\n if (indexerSlot >= slot) {\n return true;\n }\n if (Date.now() - startTime > 20000) {\n // 20 seconds\n throw new Error(\n 'Timeout: Indexer slot did not reach the required slot within 20 seconds',\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getIndexerSlot(): Promise<number> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getIndexerSlot',\n );\n const res = create(unsafeRes, jsonRpcResult(SlotResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch all the compressed token holders for a given mint. Paginated.\n */\n async getCompressedMintTokenHolders(\n mint: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedMintTokenHolders',\n {\n mint: mint.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedMintTokenHoldersResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get mint token holders',\n );\n }\n\n return res.result;\n }\n /**\n * Fetch the latest compression signatures on the cluster. Results are\n * paginated.\n */\n async getLatestCompressionSignatures(\n cursor?: string,\n limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getLatestCompressionSignatures',\n { limit, cursor },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(LatestNonVotingSignaturesResultPaginated),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get latest non-voting signatures',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all non-voting signatures\n */\n async getLatestNonVotingSignatures(\n limit?: number,\n cursor?: string,\n ): Promise<LatestNonVotingSignatures> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getLatestNonVotingSignatures',\n { limit, cursor },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(LatestNonVotingSignaturesResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get latest non-voting signatures',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the latest address proofs for new unique addresses specified by an\n * array of addresses.\n *\n * the proof states that said address have not yet been created in\n * respective address tree.\n * @param addresses Array of BN254 new addresses\n * @returns Array of validity proofs for new addresses\n */\n async getMultipleNewAddressProofs(addresses: BN254[]) {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleNewAddressProofs',\n addresses.map(address => encodeBN254toBase58(address)),\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(NewAddressProofResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proofs for new addresses ${addresses.map(address => encodeBN254toBase58(address)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proofs for new addresses ${addresses.map(address => encodeBN254toBase58(address)).join(', ')}`,\n );\n }\n\n /// Creates proof for each address\n const newAddressProofs: MerkleContextWithNewAddressProof[] = [];\n\n for (const proof of res.result.value) {\n const _proof: MerkleContextWithNewAddressProof = {\n root: proof.root,\n rootIndex: proof.rootSeq % 2400,\n value: proof.address,\n leafLowerRangeValue: proof.lowerRangeAddress,\n leafHigherRangeValue: proof.higherRangeAddress,\n nextIndex: bn(proof.nextIndex),\n merkleProofHashedIndexedElementLeaf: proof.proof,\n indexHashedIndexedElementLeaf: bn(proof.lowElementLeafIndex),\n merkleTree: proof.merkleTree,\n nullifierQueue: defaultTestStateTreeAccounts().addressQueue,\n };\n newAddressProofs.push(_proof);\n }\n return newAddressProofs;\n }\n\n /**\n * Advanced usage of getValidityProof: fetches ZKP directly from a custom\n * non-rpcprover. Note: This uses the proverEndpoint specified in the\n * constructor. For normal usage, please use {@link getValidityProof}\n * instead.\n *\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProofDirect(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n let validityProof: CompressedProofWithContext;\n\n if (hashes.length === 0 && newAddresses.length === 0) {\n throw new Error(\n 'Empty input. Provide hashes and/or new addresses.',\n );\n } else if (hashes.length > 0 && newAddresses.length === 0) {\n /// inclusion\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // [],\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'inclusion',\n inputs,\n false,\n // publicInputHash,\n );\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext.map(proof => proof.root),\n rootIndices: merkleProofsWithContext.map(\n proof => proof.rootIndex,\n ),\n leafIndices: merkleProofsWithContext.map(\n proof => proof.leafIndex,\n ),\n leaves: merkleProofsWithContext.map(proof => bn(proof.hash)),\n merkleTrees: merkleProofsWithContext.map(\n proof => proof.merkleTree,\n ),\n nullifierQueues: merkleProofsWithContext.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length === 0 && newAddresses.length > 0) {\n /// new-address\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const inputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // [],\n // [],\n // newAddressProofs,\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'new-address',\n inputs,\n false,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: newAddressProofs.map(proof => proof.root),\n rootIndices: newAddressProofs.map(proof => proof.rootIndex),\n leafIndices: newAddressProofs.map(proof =>\n proof.nextIndex.toNumber(),\n ),\n leaves: newAddressProofs.map(proof => bn(proof.value)),\n merkleTrees: newAddressProofs.map(proof => proof.merkleTree),\n nullifierQueues: newAddressProofs.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length > 0 && newAddresses.length > 0) {\n /// combined\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const newAddressInputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // newAddressProofs,\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'combined',\n [inputs, newAddressInputs],\n false,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext\n .map(proof => proof.root)\n .concat(newAddressProofs.map(proof => proof.root)),\n rootIndices: merkleProofsWithContext\n .map(proof => proof.rootIndex)\n .concat(newAddressProofs.map(proof => proof.rootIndex)),\n leafIndices: merkleProofsWithContext\n .map(proof => proof.leafIndex)\n .concat(\n newAddressProofs.map(\n proof => proof.nextIndex.toNumber(), // TODO: support >32bit\n ),\n ),\n leaves: merkleProofsWithContext\n .map(proof => bn(proof.hash))\n .concat(newAddressProofs.map(proof => bn(proof.value))),\n merkleTrees: merkleProofsWithContext\n .map(proof => proof.merkleTree)\n .concat(newAddressProofs.map(proof => proof.merkleTree)),\n nullifierQueues: merkleProofsWithContext\n .map(proof => proof.nullifierQueue)\n .concat(\n newAddressProofs.map(proof => proof.nullifierQueue),\n ),\n };\n } else throw new Error('Invalid input');\n\n return validityProof;\n }\n\n /**\n * @deprecated use {@link getValidityProofV0} instead.\n *\n *\n *\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProof(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n const accs = await this.getMultipleCompressedAccounts(hashes);\n const trees = accs.map(acc => acc.merkleTree);\n const queues = accs.map(acc => acc.nullifierQueue);\n\n // TODO: add dynamic address tree support here\n const defaultAddressTreePublicKey =\n defaultTestStateTreeAccounts().addressTree;\n const defaultAddressQueuePublicKey =\n defaultTestStateTreeAccounts().addressQueue;\n\n const formattedHashes = hashes.map((item, index) => {\n return {\n hash: item,\n tree: trees[index],\n queue: queues[index],\n };\n });\n\n const formattedNewAddresses = newAddresses.map(item => {\n return {\n address: item,\n tree: defaultAddressTreePublicKey,\n queue: defaultAddressQueuePublicKey,\n };\n });\n\n return this.getValidityProofV0(formattedHashes, formattedNewAddresses);\n }\n\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of { hash: BN254, tree: PublicKey, queue: PublicKey }.\n * @param newAddresses Array of { address: BN254, tree: PublicKey, queue: PublicKey }.\n * @returns validity proof with context\n */\n async getValidityProofV0(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<CompressedProofWithContext> {\n const { value } = await this.getValidityProofAndRpcContext(\n hashes,\n newAddresses,\n );\n return value;\n }\n\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses. Returns with context slot.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses. Optionally specify the\n * tree and queue for each address. Default to public\n * state tree/queue.\n * @returns validity proof with context\n */\n async getValidityProofAndRpcContext(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<WithContext<CompressedProofWithContext>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getValidityProof',\n {\n hashes: hashes.map(({ hash }) => encodeBN254toBase58(hash)),\n newAddressesWithTrees: newAddresses.map(\n ({ address, tree }) => ({\n address: encodeBN254toBase58(address),\n tree: tree.toBase58(),\n }),\n ),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(ValidityProofResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get ValidityProof for compressed accounts ${hashes.map(hash => hash.toString())}`,\n );\n }\n\n const result = res.result.value;\n\n if (result === null) {\n throw new Error(\n `failed to get ValidityProof for compressed accounts ${hashes.map(hash => hash.toString())}`,\n );\n }\n\n const value: CompressedProofWithContext = {\n compressedProof: result.compressedProof,\n merkleTrees: result.merkleTrees,\n leafIndices: result.leafIndices,\n nullifierQueues: [\n ...hashes.map(({ queue }) => queue),\n ...newAddresses.map(({ queue }) => queue),\n ],\n rootIndices: result.rootIndices,\n roots: result.roots,\n leaves: result.leaves,\n };\n return { value, context: res.result.context };\n }\n}\n","import { Signer } from '@solana/web3.js';\n\n/** @internal remove signer from signers if part of signers */\nexport function dedupeSigner(signer: Signer, signers: Signer[]): Signer[] {\n if (signers.includes(signer)) {\n return signers.filter(\n s => s.publicKey.toString() !== signer.publicKey.toString(),\n );\n }\n return signers;\n}\n","// TODO: Clean up\nexport enum UtxoErrorCode {\n NEGATIVE_LAMPORTS = 'NEGATIVE_LAMPORTS',\n NOT_U64 = 'NOT_U64',\n BLINDING_EXCEEDS_FIELD_SIZE = 'BLINDING_EXCEEDS_FIELD_SIZE',\n}\n\nexport enum SelectInUtxosErrorCode {\n FAILED_TO_FIND_UTXO_COMBINATION = 'FAILED_TO_FIND_UTXO_COMBINATION',\n INVALID_NUMBER_OF_IN_UTXOS = 'INVALID_NUMBER_OF_IN_UTXOS',\n}\n\nexport enum CreateUtxoErrorCode {\n OWNER_UNDEFINED = 'OWNER_UNDEFINED',\n INVALID_OUTPUT_UTXO_LENGTH = 'INVALID_OUTPUT_UTXO_LENGTH',\n UTXO_DATA_UNDEFINED = 'UTXO_DATA_UNDEFINED',\n}\n\nexport enum RpcErrorCode {\n CONNECTION_UNDEFINED = 'CONNECTION_UNDEFINED',\n RPC_PUBKEY_UNDEFINED = 'RPC_PUBKEY_UNDEFINED',\n RPC_METHOD_NOT_IMPLEMENTED = 'RPC_METHOD_NOT_IMPLEMENTED',\n RPC_INVALID = 'RPC_INVALID',\n}\n\nexport enum LookupTableErrorCode {\n LOOK_UP_TABLE_UNDEFINED = 'LOOK_UP_TABLE_UNDEFINED',\n LOOK_UP_TABLE_NOT_INITIALIZED = 'LOOK_UP_TABLE_NOT_INITIALIZED',\n}\n\nexport enum HashErrorCode {\n NO_POSEIDON_HASHER_PROVIDED = 'NO_POSEIDON_HASHER_PROVIDED',\n}\n\nexport enum ProofErrorCode {\n INVALID_PROOF = 'INVALID_PROOF',\n PROOF_INPUT_UNDEFINED = 'PROOF_INPUT_UNDEFINED',\n PROOF_GENERATION_FAILED = 'PROOF_GENERATION_FAILED',\n}\n\nexport enum MerkleTreeErrorCode {\n MERKLE_TREE_NOT_INITIALIZED = 'MERKLE_TREE_NOT_INITIALIZED',\n SOL_MERKLE_TREE_UNDEFINED = 'SOL_MERKLE_TREE_UNDEFINED',\n MERKLE_TREE_UNDEFINED = 'MERKLE_TREE_UNDEFINED',\n INPUT_UTXO_NOT_INSERTED_IN_MERKLE_TREE = 'INPUT_UTXO_NOT_INSERTED_IN_MERKLE_TREE',\n MERKLE_TREE_INDEX_UNDEFINED = 'MERKLE_TREE_INDEX_UNDEFINED',\n MERKLE_TREE_SET_SPACE_UNDEFINED = 'MERKLE_TREE_SET_SPACE_UNDEFINED',\n}\n\nexport enum UtilsErrorCode {\n ACCOUNT_NAME_UNDEFINED_IN_IDL = 'ACCOUNT_NAME_UNDEFINED_IN_IDL',\n PROPERTY_UNDEFINED = 'PROPERTY_UNDEFINED',\n LOOK_UP_TABLE_CREATION_FAILED = 'LOOK_UP_TABLE_CREATION_FAILED',\n UNSUPPORTED_ARCHITECTURE = 'UNSUPPORTED_ARCHITECTURE',\n UNSUPPORTED_PLATFORM = 'UNSUPPORTED_PLATFORM',\n ACCOUNTS_UNDEFINED = 'ACCOUNTS_UNDEFINED',\n INVALID_NUMBER = 'INVALID_NUMBER',\n}\n\nclass MetaError extends Error {\n code: string;\n functionName: string;\n codeMessage?: string;\n\n constructor(code: string, functionName: string, codeMessage?: string) {\n super(`${code}: ${codeMessage}`);\n this.code = code;\n this.functionName = functionName;\n this.codeMessage = codeMessage;\n }\n}\n\nexport class UtxoError extends MetaError {}\n\nexport class SelectInUtxosError extends MetaError {}\n\nexport class CreateUtxoError extends MetaError {}\n\nexport class RpcError extends MetaError {}\n\nexport class LookupTableError extends MetaError {}\n\nexport class HashError extends MetaError {}\n\nexport class ProofError extends MetaError {}\n\nexport class MerkleTreeError extends MetaError {}\n\nexport class UtilsError extends MetaError {}\n","import { LightWasm } from '../test-rpc/test-rpc';\nimport BN from 'bn.js';\nimport { bn } from '../../state';\nimport { HIGHEST_ADDRESS_PLUS_ONE } from '../../constants';\n\nexport class IndexedElement {\n public index: number;\n public value: BN;\n public nextIndex: number;\n\n constructor(index: number, value: BN, nextIndex: number) {\n this.index = index;\n this.value = value;\n this.nextIndex = nextIndex;\n }\n\n public equals(other: IndexedElement): boolean {\n return this.value.eq(other.value);\n }\n\n public compareTo(other: IndexedElement): number {\n return this.value.cmp(other.value);\n }\n\n public hash(lightWasm: LightWasm, nextValue: BN): Uint8Array {\n try {\n const hash = lightWasm.poseidonHash([\n bn(this.value.toArray('be', 32)).toString(),\n bn(this.nextIndex).toString(),\n bn(nextValue.toArray('be', 32)).toString(),\n ]);\n return hash;\n } catch (error) {\n throw new Error('Hashing failed');\n }\n }\n}\n\nexport class IndexedElementBundle {\n public newLowElement: IndexedElement;\n public newElement: IndexedElement;\n public newElementNextValue: BN;\n\n constructor(\n newLowElement: IndexedElement,\n newElement: IndexedElement,\n newElementNextValue: BN,\n ) {\n this.newLowElement = newLowElement;\n this.newElement = newElement;\n this.newElementNextValue = newElementNextValue;\n }\n}\n\n/**\n * This indexed array implementation mirrors the rust implementation of the\n * indexed merkle tree. It stores the elements of the indexed merkle tree.\n */\nexport class IndexedArray {\n public elements: Array<IndexedElement>;\n public currentNodeIndex: number;\n public highestElementIndex: number;\n\n constructor(\n elements: Array<IndexedElement>,\n currentNodeIndex: number,\n highestElementIndex: number,\n ) {\n this.elements = elements;\n this.currentNodeIndex = currentNodeIndex;\n this.highestElementIndex = highestElementIndex;\n }\n\n public static default(): IndexedArray {\n return new IndexedArray([new IndexedElement(0, bn(0), 0)], 0, 0);\n }\n\n public get(index: number): IndexedElement | undefined {\n return this.elements[index];\n }\n\n public length(): number {\n return Number(this.currentNodeIndex);\n }\n\n public isEmpty(): boolean {\n return this.currentNodeIndex === 0;\n }\n\n public findElement(value: BN): IndexedElement | undefined {\n return this.elements\n .slice(0, this.length() + 1)\n .find(node => node.value === value);\n }\n\n public init(): IndexedElementBundle {\n try {\n const init_value = HIGHEST_ADDRESS_PLUS_ONE;\n return this.append(init_value);\n } catch (error) {\n throw new Error(`Failed to initialize IndexedArray: ${error}`);\n }\n }\n\n /**\n * Finds the index of the low element for the given `value` which should not be part of the array.\n * Low element is the greatest element which still has a lower value than the provided one.\n * Low elements are used in non-membership proofs.\n */\n public findLowElementIndex(value: BN): number | undefined {\n // Try to find element whose next element is higher than the provided value.\n for (let i = 0; i <= this.length(); i++) {\n const node = this.elements[i];\n if (\n this.elements[node.nextIndex].value.gt(value) &&\n node.value.lt(value)\n ) {\n return i;\n } else if (node.value.eq(value)) {\n throw new Error('Element already exists in the array');\n }\n }\n // If no such element was found, it means that our value is going to be the greatest in the array.\n // This means that the currently greatest element is going to be the low element of our value.\n return this.highestElementIndex;\n }\n\n /**\n * Returns the low element for the given value and the next value for that low element.\n * Low element is the greatest element which still has lower value than the provided one.\n * Low elements are used in non-membership proofs.\n */\n public findLowElement(\n value: BN,\n ): [IndexedElement | undefined, BN | undefined] {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) return [undefined, undefined];\n const lowElement = this.elements[lowElementIndex];\n return [lowElement, this.elements[lowElement.nextIndex].value];\n }\n\n // /**\n // * Returns the index of the low element for the given `value`, which should be the part of the array.\n // * Low element is the greatest element which still has lower value than the provided one.\n // * Low elements are used in non-membership proofs.\n // */\n // public findLowElementIndexForExistingElement(\n // value: BN,\n // ): number | undefined {\n // for (let i = 0; i <= this.length(); i++) {\n // const node = this.elements[i];\n // if (this.elements[node.nextIndex].value === value) {\n // return i;\n // }\n // }\n // return undefined;\n // }\n\n /**\n * Returns the hash of the given element. That hash consists of:\n * - The value of the given element.\n * - The `nextIndex` of the given element.\n * - The value of the element pointed by `nextIndex`.\n */\n public hashElement(\n lightWasm: LightWasm,\n index: number,\n ): Uint8Array | undefined {\n const element = this.elements[index];\n if (!element) return undefined;\n const nextElement = this.elements[element.nextIndex];\n if (!nextElement) return undefined;\n\n const hash = lightWasm.poseidonHash([\n bn(element.value.toArray('be', 32)).toString(),\n bn(element.nextIndex).toString(),\n bn(nextElement.value.toArray('be', 32)).toString(),\n ]);\n\n return hash;\n }\n\n /**\n * Appends a new element with the given value to the indexed array.\n * It finds the low element index and uses it to append the new element correctly.\n * @param value The value of the new element to append.\n * @returns The new element and its low element after insertion.\n */\n public append(value: BN): IndexedElementBundle {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) {\n throw new Error('Low element index not found.');\n }\n return this.appendWithLowElementIndex(lowElementIndex, value);\n }\n\n /**\n * Appends a new element with the given value to the indexed array using a specific low element index.\n * This method ensures the new element is placed correctly relative to the low element.\n * @param lowElementIndex The index of the low element.\n * @param value The value of the new element to append.\n * @returns The new element and its updated low element.\n */\n public appendWithLowElementIndex(\n lowElementIndex: number,\n value: BN,\n ): IndexedElementBundle {\n const lowElement = this.elements[lowElementIndex];\n\n if (lowElement.nextIndex === 0) {\n if (value.lte(lowElement.value)) {\n throw new Error(\n 'New element value must be greater than the low element value.',\n );\n }\n } else {\n const nextElement = this.elements[lowElement.nextIndex];\n\n if (value.lte(lowElement.value)) {\n throw new Error(\n 'New element value must be greater than the low element value.',\n );\n }\n\n if (value.gte(nextElement.value)) {\n throw new Error(\n 'New element value must be less than the next element value.',\n );\n }\n }\n\n const newElementBundle = this.newElementWithLowElementIndex(\n lowElementIndex,\n value,\n );\n\n // If the old low element wasn't pointing to any element, it means that:\n //\n // * It used to be the highest element.\n // * Our new element, which we are appending, is going the be the\n // highest element.\n //\n // Therefore, we need to save the new element index as the highest\n // index.\n if (lowElement.nextIndex === 0) {\n this.highestElementIndex = newElementBundle.newElement.index;\n }\n\n // Insert new node.\n this.currentNodeIndex = newElementBundle.newElement.index;\n this.elements[this.length()] = newElementBundle.newElement;\n\n // Update low element.\n this.elements[lowElementIndex] = newElementBundle.newLowElement;\n\n return newElementBundle;\n }\n\n /**\n * Finds the lowest element in the array.\n * @returns The lowest element or undefined if the array is empty.\n */\n public lowest(): IndexedElement | undefined {\n return this.elements.length > 0 ? this.elements[0] : undefined;\n }\n\n /**\n * Creates a new element with the specified value and updates the low element index accordingly.\n * @param lowElementIndex The index of the low element.\n * @param value The value for the new element.\n * @returns A bundle containing the new element, the updated low element, and the value of the next element.\n */\n public newElementWithLowElementIndex(\n lowElementIndex: number,\n value: BN,\n ): IndexedElementBundle {\n const newLowElement = this.elements[lowElementIndex];\n\n const newElementIndex = this.currentNodeIndex + 1;\n const newElement = new IndexedElement(\n newElementIndex,\n value,\n newLowElement.nextIndex,\n );\n newLowElement.nextIndex = newElementIndex;\n\n const newElementNextValue = this.elements[newElement.nextIndex].value;\n\n return new IndexedElementBundle(\n newLowElement,\n newElement,\n newElementNextValue,\n );\n }\n\n /**\n * Creates a new element with the specified value by first finding the appropriate low element index.\n * @param value The value for the new element.\n * @returns A bundle containing the new element, the updated low element, and the value of the next element.\n */\n public newElement(value: BN): IndexedElementBundle {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) {\n throw new Error('Low element index not found.');\n }\n return this.newElementWithLowElementIndex(lowElementIndex, value);\n }\n}\n","import { LightWasm } from '../test-rpc/test-rpc';\n\nexport const DEFAULT_ZERO = '0';\n\n/**\n * @callback hashFunction\n * @param left Left leaf\n * @param right Right leaf\n */\n/**\n * Merkle tree\n */\nexport class MerkleTree {\n /**\n * Constructor\n * @param {number} levels Number of levels in the tree\n * @param {Array} [elements] Initial elements\n * @param {Object} options\n * @param {hashFunction} [options.hashFunction] Function used to hash 2 leaves\n * @param [options.zeroElement] Value for non-existent leaves\n */\n levels: number;\n capacity: number;\n zeroElement;\n _zeros: string[];\n _layers: string[][];\n _lightWasm: LightWasm;\n\n constructor(\n levels: number,\n lightWasm: LightWasm,\n elements: string[] = [],\n { zeroElement = DEFAULT_ZERO } = {},\n ) {\n this.levels = levels;\n this.capacity = 2 ** levels;\n this.zeroElement = zeroElement;\n this._lightWasm = lightWasm;\n if (elements.length > this.capacity) {\n throw new Error('Tree is full');\n }\n this._zeros = [];\n this._layers = [];\n this._layers[0] = elements;\n this._zeros[0] = this.zeroElement;\n\n for (let i = 1; i <= levels; i++) {\n this._zeros[i] = this._lightWasm.poseidonHashString([\n this._zeros[i - 1],\n this._zeros[i - 1],\n ]);\n }\n this._rebuild();\n }\n\n _rebuild() {\n for (let level = 1; level <= this.levels; level++) {\n this._layers[level] = [];\n for (\n let i = 0;\n i < Math.ceil(this._layers[level - 1].length / 2);\n i++\n ) {\n this._layers[level][i] = this._lightWasm.poseidonHashString([\n this._layers[level - 1][i * 2],\n i * 2 + 1 < this._layers[level - 1].length\n ? this._layers[level - 1][i * 2 + 1]\n : this._zeros[level - 1],\n ]);\n }\n }\n }\n\n /**\n * Get tree root\n * @returns {*}\n */\n root() {\n return this._layers[this.levels].length > 0\n ? this._layers[this.levels][0]\n : this._zeros[this.levels];\n }\n\n /**\n * Insert new element into the tree\n * @param element Element to insert\n */\n\n insert(element: string) {\n if (this._layers[0].length >= this.capacity) {\n throw new Error('Tree is full');\n }\n this.update(this._layers[0].length, element);\n }\n\n /**\n * Insert multiple elements into the tree. Tree will be fully rebuilt during this operation.\n * @param {Array} elements Elements to insert\n */\n bulkInsert(elements: string[]) {\n if (this._layers[0].length + elements.length > this.capacity) {\n throw new Error('Tree is full');\n }\n this._layers[0].push(...elements);\n this._rebuild();\n }\n\n // TODO: update does not work debug\n /**\n * Change an element in the tree\n * @param {number} index Index of element to change\n * @param element Updated element value\n */\n update(index: number, element: string) {\n // index 0 and 1 and element is the commitment hash\n if (\n isNaN(Number(index)) ||\n index < 0 ||\n index > this._layers[0].length ||\n index >= this.capacity\n ) {\n throw new Error('Insert index out of bounds: ' + index);\n }\n this._layers[0][index] = element;\n for (let level = 1; level <= this.levels; level++) {\n index >>= 1;\n this._layers[level][index] = this._lightWasm.poseidonHashString([\n this._layers[level - 1][index * 2],\n index * 2 + 1 < this._layers[level - 1].length\n ? this._layers[level - 1][index * 2 + 1]\n : this._zeros[level - 1],\n ]);\n }\n }\n\n /**\n * Get merkle path to a leaf\n * @param {number} index Leaf index to generate path for\n * @returns {{pathElements: number[], pathIndex: number[]}} An object containing adjacent elements and left-right index\n */\n path(index: number) {\n if (\n isNaN(Number(index)) ||\n index < 0 ||\n index >= this._layers[0].length\n ) {\n throw new Error('Index out of bounds: ' + index);\n }\n const pathElements: string[] = [];\n const pathIndices: number[] = [];\n for (let level = 0; level < this.levels; level++) {\n pathIndices[level] = index % 2;\n pathElements[level] =\n (index ^ 1) < this._layers[level].length\n ? this._layers[level][index ^ 1]\n : this._zeros[level];\n index >>= 1;\n }\n return {\n pathElements,\n pathIndices,\n };\n }\n\n /**\n * Find an element in the tree\n * @param element An element to find\n * @param comparator A function that checks leaf value equality\n * @returns {number} Index if element is found, otherwise -1\n */\n indexOf(\n element: string,\n comparator: ((element: string, el: string) => boolean) | null = null,\n ) {\n if (comparator) {\n return this._layers[0].findIndex((el: string) =>\n comparator(element, el),\n );\n } else {\n return this._layers[0].indexOf(element);\n }\n }\n\n /**\n * Returns a copy of non-zero tree elements\n * @returns {Object[]}\n */\n elements() {\n return this._layers[0].slice();\n }\n\n /**\n * Serialize entire tree state including intermediate layers into a plain object\n * Deserializing it back will not require to recompute any hashes\n * Elements are not converted to a plain type, this is responsibility of the caller\n */\n serialize() {\n return {\n levels: this.levels,\n _zeros: this._zeros,\n _layers: this._layers,\n };\n }\n\n /**\n * Deserialize data into a MerkleTree instance\n * Make sure to provide the same hashFunction as was used in the source tree,\n * otherwise the tree state will be invalid\n *\n * @param data\n * @param hashFunction\n * @returns {MerkleTree}\n */\n static deserialize(\n data: any,\n hashFunction: (left: string, right: string) => string,\n ) {\n const instance = Object.assign(Object.create(this.prototype), data);\n instance._hash = hashFunction;\n instance.capacity = 2 ** instance.levels;\n instance.zeroElement = instance._zeros[0];\n return instance;\n }\n}\n","import {\n GetVersionedTransactionConfig,\n MessageV0,\n ParsedMessageAccount,\n ParsedTransactionWithMeta,\n PublicKey,\n VersionedTransactionResponse,\n} from '@solana/web3.js';\nimport bs58 from 'bs58';\nimport {\n COMPUTE_BUDGET_PATTERN,\n defaultStaticAccountsStruct,\n INSERT_INTO_QUEUES_DISCRIMINATOR,\n INVOKE_CPI_DISCRIMINATOR,\n INVOKE_DISCRIMINATOR,\n} from '../../constants';\nimport {\n convertToPublicTransactionEvent,\n decodeInstructionDataInvoke,\n decodeInstructionDataInvokeCpi,\n deserializeAppendNullifyCreateAddressInputsIndexer,\n} from '../../programs';\nimport { Rpc } from '../../rpc';\nimport { InstructionDataInvoke, PublicTransactionEvent } from '../../state';\nimport { decodePublicTransactionEvent } from '../../programs/layout';\nimport { Buffer } from 'buffer';\n\ntype Deserializer<T> = (data: Buffer, tx: ParsedTransactionWithMeta) => T;\n\n/**\n * @internal\n * Returns newest first.\n *\n * */\nexport async function getParsedEvents(\n rpc: Rpc,\n): Promise<PublicTransactionEvent[]> {\n const events: PublicTransactionEvent[] = [];\n\n const { noopProgram, accountCompressionProgram } =\n defaultStaticAccountsStruct();\n\n const signatures = (\n await rpc.getConfirmedSignaturesForAddress2(\n accountCompressionProgram,\n undefined,\n 'confirmed',\n )\n ).map(s => s.signature);\n const txs = await rpc.getParsedTransactions(signatures, {\n maxSupportedTransactionVersion: 0,\n commitment: 'confirmed',\n });\n\n for (const txParsed of txs) {\n if (!txParsed || !txParsed.transaction || !txParsed.meta) continue;\n\n if (\n !txParsed.meta.innerInstructions ||\n txParsed.meta.innerInstructions.length == 0\n ) {\n continue;\n }\n\n const messageV0 = txParsed.transaction.message;\n const accKeys = messageV0.accountKeys;\n\n const allAccounts = accKeys.map(a => a.pubkey);\n const dataVec: Uint8Array[] = [];\n\n // get tx wth sig\n const txRaw = await rpc.getTransaction(\n txParsed.transaction.signatures[0],\n {\n commitment: 'confirmed',\n maxSupportedTransactionVersion: 0,\n },\n );\n\n for (const ix of txRaw?.transaction.message.compiledInstructions ||\n []) {\n if (ix.data && ix.data.length > 0) {\n const decodedData = Uint8Array.from(ix.data);\n if (\n decodedData.length === COMPUTE_BUDGET_PATTERN.length &&\n COMPUTE_BUDGET_PATTERN.every(\n (byte, idx) => byte === decodedData[idx],\n )\n ) {\n continue;\n }\n dataVec.push(decodedData);\n }\n }\n\n const groupedAccountVec: PublicKey[][] = [];\n\n if (\n txRaw!.meta!.innerInstructions &&\n txRaw!.meta!.innerInstructions.length > 0\n ) {\n for (const innerGroup of txRaw!.meta!.innerInstructions) {\n for (const ix of innerGroup.instructions) {\n const group = ix.accounts.map(\n (accountIdx: number) => allAccounts[accountIdx],\n );\n groupedAccountVec.push(group);\n if (ix.data && ix.data.length > 0) {\n const decodedData = bs58.decode(ix.data);\n dataVec.push(decodedData);\n }\n }\n }\n }\n\n const event = parseLightTransaction(dataVec, groupedAccountVec);\n if (event) {\n events.push(event);\n }\n }\n\n if (events.length > 0) {\n return events;\n }\n\n /// Filter by NOOP program\n const transactionEvents = txs.filter(\n (tx: ParsedTransactionWithMeta | null) => {\n if (!tx) {\n return false;\n }\n const accountKeys = tx.transaction.message.accountKeys;\n\n const hasSplNoopAddress = accountKeys.some(\n (item: ParsedMessageAccount) => {\n const itemStr =\n typeof item === 'string'\n ? item\n : item.pubkey.toBase58();\n return itemStr === noopProgram.toBase58();\n },\n );\n\n return hasSplNoopAddress;\n },\n );\n\n return parseEvents(transactionEvents, parsePublicTransactionEventWithIdl);\n}\n\nexport const parseEvents = <T>(\n indexerEventsTransactions: (ParsedTransactionWithMeta | null)[],\n deserializeFn: Deserializer<T>,\n): NonNullable<T>[] => {\n const { noopProgram } = defaultStaticAccountsStruct();\n\n const transactions: NonNullable<T>[] = [];\n indexerEventsTransactions.forEach(tx => {\n if (\n !tx ||\n !tx.meta ||\n tx.meta.err ||\n !tx.meta.innerInstructions ||\n tx.meta.innerInstructions.length <= 0\n ) {\n return;\n }\n\n /// We only care about the very last inner instruction as it contains the\n /// PublicTransactionEvent\n tx.meta.innerInstructions.forEach(ix => {\n if (ix.instructions.length > 0) {\n const ixInner = ix.instructions[ix.instructions.length - 1];\n // Type guard for partially parsed web3js types.\n if (\n 'data' in ixInner &&\n ixInner.data &&\n ixInner.programId.toBase58() === noopProgram.toBase58()\n ) {\n const data = bs58.decode(ixInner.data);\n\n const decodedEvent = deserializeFn(Buffer.from(data), tx);\n\n if (decodedEvent !== null && decodedEvent !== undefined) {\n transactions.push(decodedEvent as NonNullable<T>);\n }\n }\n }\n });\n });\n\n return transactions;\n};\n\n// TODO: make it type safe. have to reimplement the types from the IDL.\nexport const parsePublicTransactionEventWithIdl = (\n data: Buffer,\n): PublicTransactionEvent | null => {\n const numericData = Buffer.from(data.map(byte => byte));\n\n try {\n return decodePublicTransactionEvent(numericData);\n } catch (error) {\n console.error('Error deserializing event:', error);\n return null;\n }\n};\n\nexport function parseLightTransaction(\n dataVec: Uint8Array[],\n accountKeys: PublicKey[][],\n): PublicTransactionEvent | null | undefined {\n let foundSystemInstruction = false;\n\n let invokeData: InstructionDataInvoke | null = null;\n let appendInputsData = null;\n\n // First pass for system instructions\n for (const data of dataVec) {\n const discriminator = data.slice(0, 8);\n const discriminatorStr = bs58.encode(discriminator);\n const invokeDiscriminatorStr = bs58.encode(INVOKE_DISCRIMINATOR);\n const invokeCpiDiscriminatorStr = bs58.encode(INVOKE_CPI_DISCRIMINATOR);\n if (discriminatorStr === invokeDiscriminatorStr) {\n invokeData = decodeInstructionDataInvoke(Buffer.from(data));\n foundSystemInstruction = true;\n break;\n }\n if (discriminatorStr == invokeCpiDiscriminatorStr) {\n invokeData = decodeInstructionDataInvokeCpi(Buffer.from(data));\n foundSystemInstruction = true;\n break;\n }\n }\n if (!foundSystemInstruction) return null;\n\n for (const data of dataVec) {\n const discriminator = data.slice(0, 8);\n const discriminatorStr = bs58.encode(discriminator);\n const insertIntoQueuesDiscriminatorStr = bs58.encode(\n INSERT_INTO_QUEUES_DISCRIMINATOR,\n );\n if (discriminatorStr !== insertIntoQueuesDiscriminatorStr) {\n console.log('discriminator does not match');\n } else {\n const dataSlice = data.slice(12);\n appendInputsData =\n deserializeAppendNullifyCreateAddressInputsIndexer(\n Buffer.from(dataSlice),\n );\n }\n }\n\n if (invokeData) {\n return convertToPublicTransactionEvent(\n appendInputsData,\n accountKeys[accountKeys.length - 1],\n invokeData,\n );\n } else {\n return null;\n }\n}\n","import { PublicKey } from '@solana/web3.js';\n\nimport BN from 'bn.js';\nimport { getParsedEvents } from './get-parsed-events';\nimport { defaultTestStateTreeAccounts } from '../../constants';\nimport { Rpc } from '../../rpc';\nimport {\n CompressedAccountWithMerkleContext,\n bn,\n MerkleContext,\n createCompressedAccountWithMerkleContext,\n} from '../../state';\n\nexport async function getCompressedAccountsByOwnerTest(\n rpc: Rpc,\n owner: PublicKey,\n) {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n const byOwner = unspentAccounts.filter(acc => acc.owner.equals(owner));\n return byOwner;\n}\n\nexport async function getCompressedAccountByHashTest(\n rpc: Rpc,\n hash: BN,\n): Promise<CompressedAccountWithMerkleContext | undefined> {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n return unspentAccounts.find(acc => bn(acc.hash).eq(hash));\n}\n\nexport async function getMultipleCompressedAccountsByHashTest(\n rpc: Rpc,\n hashes: BN[],\n): Promise<CompressedAccountWithMerkleContext[]> {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n return unspentAccounts\n .filter(acc => hashes.some(hash => bn(acc.hash).eq(hash)))\n .sort((a, b) => b.leafIndex - a.leafIndex);\n}\n\n/// Returns all unspent compressed accounts\nasync function getCompressedAccountsForTest(rpc: Rpc) {\n const events = (await getParsedEvents(rpc)).reverse();\n const allOutputAccounts: CompressedAccountWithMerkleContext[] = [];\n const allInputAccountHashes: BN[] = [];\n\n for (const event of events) {\n for (\n let index = 0;\n index < event.outputCompressedAccounts.length;\n index++\n ) {\n const account = event.outputCompressedAccounts[index];\n const merkleContext: MerkleContext = {\n merkleTree: defaultTestStateTreeAccounts().merkleTree,\n nullifierQueue: defaultTestStateTreeAccounts().nullifierQueue,\n hash: event.outputCompressedAccountHashes[index],\n leafIndex: event.outputLeafIndices[index],\n };\n const withCtx: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n merkleContext,\n account.compressedAccount.owner,\n account.compressedAccount.lamports,\n account.compressedAccount.data ?? undefined,\n account.compressedAccount.address ?? undefined,\n );\n allOutputAccounts.push(withCtx);\n }\n for (\n let index = 0;\n index < event.inputCompressedAccountHashes.length;\n index++\n ) {\n const hash = event.inputCompressedAccountHashes[index];\n allInputAccountHashes.push(bn(hash));\n }\n }\n\n const unspentAccounts = allOutputAccounts.filter(\n account =>\n !allInputAccountHashes.some(hash => hash.eq(bn(account.hash))),\n );\n unspentAccounts.sort((a, b) => b.leafIndex - a.leafIndex);\n\n return unspentAccounts;\n}\n","import { PublicKey } from '@solana/web3.js';\nimport { getParsedEvents } from './get-parsed-events';\nimport BN from 'bn.js';\nimport { defaultTestStateTreeAccounts } from '../../constants';\nimport { Rpc } from '../../rpc';\nimport { ParsedTokenAccount, WithCursor } from '../../rpc-interface';\nimport {\n CompressedAccount,\n PublicTransactionEvent,\n MerkleContext,\n createCompressedAccountWithMerkleContext,\n bn,\n} from '../../state';\nimport {\n struct,\n publicKey,\n u64,\n option,\n vecU8,\n u8,\n Layout,\n} from '@coral-xyz/borsh';\n\nconst tokenProgramId: PublicKey = new PublicKey(\n 'cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m',\n);\n\ntype TokenData = {\n mint: PublicKey;\n owner: PublicKey;\n amount: BN;\n delegate: PublicKey | null;\n state: number;\n tlv: Buffer | null;\n};\n\n// for test-rpc\nexport const TokenDataLayout: Layout<TokenData> = struct([\n publicKey('mint'),\n publicKey('owner'),\n u64('amount'),\n option(publicKey(), 'delegate'),\n u8('state'),\n option(vecU8(), 'tlv'),\n]);\n\nexport type EventWithParsedTokenTlvData = {\n inputCompressedAccountHashes: number[][];\n outputCompressedAccounts: ParsedTokenAccount[];\n};\n/**\n * Manually parse the compressed token layout for a given compressed account.\n * @param compressedAccount - The compressed account\n * @returns The parsed token data\n */\nexport function parseTokenLayoutWithIdl(\n compressedAccount: CompressedAccount,\n programId: PublicKey = tokenProgramId,\n): TokenData | null {\n if (compressedAccount.data === null) return null;\n\n const { data } = compressedAccount.data;\n\n if (data.length === 0) return null;\n if (compressedAccount.owner.toBase58() !== programId.toBase58()) {\n throw new Error(\n `Invalid owner ${compressedAccount.owner.toBase58()} for token layout`,\n );\n }\n return TokenDataLayout.decode(Buffer.from(data));\n}\n\n/**\n * parse compressed accounts of an event with token layout\n * @internal\n * TODO: refactor\n */\nasync function parseEventWithTokenTlvData(\n event: PublicTransactionEvent,\n): Promise<EventWithParsedTokenTlvData> {\n const pubkeyArray = event.pubkeyArray;\n\n const outputHashes = event.outputCompressedAccountHashes;\n const outputCompressedAccountsWithParsedTokenData: ParsedTokenAccount[] =\n event.outputCompressedAccounts.map((compressedAccount, i) => {\n const merkleContext: MerkleContext = {\n merkleTree:\n pubkeyArray[\n event.outputCompressedAccounts[i].merkleTreeIndex\n ],\n nullifierQueue:\n // FIXME: fix make dynamic\n defaultTestStateTreeAccounts().nullifierQueue,\n hash: outputHashes[i],\n leafIndex: event.outputLeafIndices[i],\n };\n\n if (!compressedAccount.compressedAccount.data)\n throw new Error('No data');\n\n const parsedData = parseTokenLayoutWithIdl(\n compressedAccount.compressedAccount,\n );\n\n if (!parsedData) throw new Error('Invalid token data');\n\n const withMerkleContext = createCompressedAccountWithMerkleContext(\n merkleContext,\n compressedAccount.compressedAccount.owner,\n compressedAccount.compressedAccount.lamports,\n compressedAccount.compressedAccount.data,\n compressedAccount.compressedAccount.address ?? undefined,\n );\n return {\n compressedAccount: withMerkleContext,\n parsed: parsedData,\n };\n });\n\n return {\n inputCompressedAccountHashes: event.inputCompressedAccountHashes,\n outputCompressedAccounts: outputCompressedAccountsWithParsedTokenData,\n };\n}\n\n/**\n * Retrieves all compressed token accounts for a given mint and owner.\n *\n * Note: This function is intended for testing purposes only. For production, use rpc.getCompressedTokenAccounts.\n *\n * @param events Public transaction events\n * @param owner PublicKey of the token owner\n * @param mint PublicKey of the token mint\n */\nexport async function getCompressedTokenAccounts(\n events: PublicTransactionEvent[],\n): Promise<ParsedTokenAccount[]> {\n const eventsWithParsedTokenTlvData: EventWithParsedTokenTlvData[] =\n await Promise.all(\n events.map(event => parseEventWithTokenTlvData(event)),\n );\n\n /// strip spent compressed accounts if an output compressed account of tx n is\n /// an input compressed account of tx n+m, it is spent\n const allOutCompressedAccounts = eventsWithParsedTokenTlvData.flatMap(\n event => event.outputCompressedAccounts,\n );\n const allInCompressedAccountHashes = eventsWithParsedTokenTlvData.flatMap(\n event => event.inputCompressedAccountHashes,\n );\n const unspentCompressedAccounts = allOutCompressedAccounts.filter(\n outputCompressedAccount =>\n !allInCompressedAccountHashes.some(hash => {\n return (\n JSON.stringify(hash) ===\n JSON.stringify(\n outputCompressedAccount.compressedAccount.hash,\n )\n );\n }),\n );\n\n return unspentCompressedAccounts;\n}\n\n/** @internal */\nexport async function getCompressedTokenAccountsByOwnerTest(\n rpc: Rpc,\n owner: PublicKey,\n mint: PublicKey,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const events = await getParsedEvents(rpc);\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n const accounts = compressedTokenAccounts.filter(\n acc => acc.parsed.owner.equals(owner) && acc.parsed.mint.equals(mint),\n );\n return {\n items: accounts.sort(\n (a, b) =>\n b.compressedAccount.leafIndex - a.compressedAccount.leafIndex,\n ),\n cursor: null,\n };\n}\n\nexport async function getCompressedTokenAccountsByDelegateTest(\n rpc: Rpc,\n delegate: PublicKey,\n mint: PublicKey,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const events = await getParsedEvents(rpc);\n\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n return {\n items: compressedTokenAccounts.filter(\n acc =>\n acc.parsed.delegate?.equals(delegate) &&\n acc.parsed.mint.equals(mint),\n ),\n cursor: null,\n };\n}\n\nexport async function getCompressedTokenAccountByHashTest(\n rpc: Rpc,\n hash: BN,\n): Promise<ParsedTokenAccount> {\n const events = await getParsedEvents(rpc);\n\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n\n const filtered = compressedTokenAccounts.filter(acc =>\n bn(acc.compressedAccount.hash).eq(hash),\n );\n if (filtered.length === 0) {\n throw new Error('No compressed account found');\n }\n return filtered[0];\n}\n","import { Connection, ConnectionConfig, PublicKey } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport {\n getCompressedAccountByHashTest,\n getCompressedAccountsByOwnerTest,\n getMultipleCompressedAccountsByHashTest,\n} from './get-compressed-accounts';\nimport {\n getCompressedTokenAccountByHashTest,\n getCompressedTokenAccountsByDelegateTest,\n getCompressedTokenAccountsByOwnerTest,\n} from './get-compressed-token-accounts';\n\nimport { MerkleTree } from '../merkle-tree/merkle-tree';\nimport { getParsedEvents } from './get-parsed-events';\nimport {\n defaultTestStateTreeAccounts,\n localTestActiveStateTreeInfo,\n} from '../../constants';\nimport {\n AddressWithTree,\n CompressedMintTokenHolders,\n CompressedTransaction,\n GetCompressedAccountsByOwnerConfig,\n PaginatedOptions,\n HashWithTree,\n LatestNonVotingSignatures,\n LatestNonVotingSignaturesPaginated,\n SignatureWithMetadata,\n WithContext,\n WithCursor,\n} from '../../rpc-interface';\nimport {\n CompressedProofWithContext,\n CompressionApiInterface,\n GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ParsedTokenAccount,\n TokenBalance,\n} from '../../rpc-interface';\nimport {\n BN254,\n CompressedAccountWithMerkleContext,\n MerkleContextWithMerkleProof,\n PublicTransactionEvent,\n bn,\n} from '../../state';\nimport { IndexedArray } from '../merkle-tree';\nimport {\n MerkleContextWithNewAddressProof,\n convertMerkleProofsWithContextToHex,\n convertNonInclusionMerkleProofInputsToHex,\n proverRequest,\n} from '../../rpc';\nimport { ActiveTreeBundle } from '../../state/types';\n\nexport interface TestRpcConfig {\n /**\n * Address of the state tree to index. Default: public default test state\n * tree.\n */\n merkleTreeAddress?: PublicKey;\n /**\n * Nullifier queue associated with merkleTreeAddress\n */\n nullifierQueueAddress?: PublicKey;\n /**\n * Depth of state tree. Defaults to the public default test state tree depth\n */\n depth?: number;\n /**\n * Log proof generation time\n */\n log?: boolean;\n /**\n * Address of the address tree to index. Default: public default test\n * address tree.\n */\n addressTreeAddress?: PublicKey;\n /**\n * Address queue associated with addressTreeAddress\n */\n addressQueueAddress?: PublicKey;\n}\n\nexport type ClientSubscriptionId = number;\nexport interface LightWasm {\n blakeHash(input: string | Uint8Array, hashLength: number): Uint8Array;\n poseidonHash(input: string[] | BN[]): Uint8Array;\n poseidonHashString(input: string[] | BN[]): string;\n poseidonHashBN(input: string[] | BN[]): BN;\n}\n\n/**\n * Returns a mock RPC instance for use in unit tests.\n *\n * @param lightWasm Wasm hasher instance.\n * @param endpoint RPC endpoint URL. Defaults to\n * 'http://127.0.0.1:8899'.\n * @param proverEndpoint Prover server endpoint URL. Defaults to\n * 'http://localhost:3001'.\n * @param merkleTreeAddress Address of the merkle tree to index. Defaults\n * to the public default test state tree.\n * @param nullifierQueueAddress Optional address of the associated nullifier\n * queue.\n * @param depth Depth of the merkle tree.\n * @param log Log proof generation time.\n */\nexport async function getTestRpc(\n lightWasm: LightWasm,\n endpoint: string = 'http://127.0.0.1:8899',\n compressionApiEndpoint: string = 'http://127.0.0.1:8784',\n proverEndpoint: string = 'http://127.0.0.1:3001',\n merkleTreeAddress?: PublicKey,\n nullifierQueueAddress?: PublicKey,\n depth?: number,\n log = false,\n) {\n const defaultAccounts = defaultTestStateTreeAccounts();\n\n return new TestRpc(\n endpoint,\n lightWasm,\n compressionApiEndpoint,\n proverEndpoint,\n undefined,\n {\n merkleTreeAddress: merkleTreeAddress || defaultAccounts.merkleTree,\n nullifierQueueAddress:\n nullifierQueueAddress || defaultAccounts.nullifierQueue,\n depth: depth || defaultAccounts.merkleTreeHeight,\n log,\n },\n );\n}\n/**\n * Simple mock rpc for unit tests that simulates the compression rpc interface.\n * Fetches, parses events and builds merkletree on-demand, i.e. it does not persist state.\n * Constraints:\n * - Can only index 1 merkletree\n * - Can only index up to 1000 transactions\n *\n * For advanced testing use photon: https://github.com/helius-labs/photon\n */\nexport class TestRpc extends Connection implements CompressionApiInterface {\n compressionApiEndpoint: string;\n proverEndpoint: string;\n merkleTreeAddress: PublicKey;\n nullifierQueueAddress: PublicKey;\n addressTreeAddress: PublicKey;\n addressQueueAddress: PublicKey;\n lightWasm: LightWasm;\n depth: number;\n log = false;\n activeStateTreeInfo: ActiveTreeBundle[] | null = null;\n\n /**\n * Establish a Compression-compatible JSON RPC mock-connection\n *\n * @param endpoint endpoint to the solana cluster (use for\n * localnet only)\n * @param hasher light wasm hasher instance\n * @param compressionApiEndpoint Endpoint to the compression server.\n * @param proverEndpoint Endpoint to the prover server. defaults\n * to endpoint\n * @param connectionConfig Optional connection config\n * @param testRpcConfig Config for the mock rpc\n */\n constructor(\n endpoint: string,\n hasher: LightWasm,\n compressionApiEndpoint: string,\n proverEndpoint: string,\n connectionConfig?: ConnectionConfig,\n testRpcConfig?: TestRpcConfig,\n ) {\n super(endpoint, connectionConfig || 'confirmed');\n\n this.compressionApiEndpoint = compressionApiEndpoint;\n this.proverEndpoint = proverEndpoint;\n\n const {\n merkleTreeAddress,\n nullifierQueueAddress,\n depth,\n log,\n addressTreeAddress,\n addressQueueAddress,\n } = testRpcConfig ?? {};\n\n const {\n merkleTree,\n nullifierQueue,\n merkleTreeHeight,\n addressQueue,\n addressTree,\n } = defaultTestStateTreeAccounts();\n\n this.lightWasm = hasher;\n this.merkleTreeAddress = merkleTreeAddress ?? merkleTree;\n this.nullifierQueueAddress = nullifierQueueAddress ?? nullifierQueue;\n this.addressTreeAddress = addressTreeAddress ?? addressTree;\n this.addressQueueAddress = addressQueueAddress ?? addressQueue;\n this.depth = depth ?? merkleTreeHeight;\n this.log = log ?? false;\n }\n\n /**\n * Manually set state tree addresses\n */\n setStateTreeInfo(info: ActiveTreeBundle[]): void {\n this.activeStateTreeInfo = info;\n }\n\n /**\n * Returns local test state trees.\n */\n async getCachedActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n return localTestActiveStateTreeInfo();\n }\n\n /**\n * Returns local test state trees.\n */\n async getLatestActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n return localTestActiveStateTreeInfo();\n }\n\n /**\n * Fetch the compressed account for the specified account hash\n */\n async getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null> {\n if (address) {\n throw new Error('address is not supported in test-rpc');\n }\n if (!hash) {\n throw new Error('hash is required');\n }\n\n const account = await getCompressedAccountByHashTest(this, hash);\n return account ?? null;\n }\n\n /**\n * Fetch the compressed balance for the specified account hash\n */\n async getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN> {\n if (address) {\n throw new Error('address is not supported in test-rpc');\n }\n if (!hash) {\n throw new Error('hash is required');\n }\n\n const account = await getCompressedAccountByHashTest(this, hash);\n if (!account) {\n throw new Error('Account not found');\n }\n return bn(account.lamports);\n }\n\n /**\n * Fetch the total compressed balance for the specified owner public key\n */\n async getCompressedBalanceByOwner(owner: PublicKey): Promise<BN> {\n const accounts = await this.getCompressedAccountsByOwner(owner);\n return accounts.items.reduce(\n (acc, account) => acc.add(account.lamports),\n bn(0),\n );\n }\n\n /**\n * Fetch the latest merkle proof for the specified account hash from the\n * cluster\n */\n async getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof> {\n const proofs = await this.getMultipleCompressedAccountProofs([hash]);\n return proofs[0];\n }\n\n /**\n * Fetch all the account info for multiple compressed accounts specified by\n * an array of account hashes\n */\n async getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]> {\n return await getMultipleCompressedAccountsByHashTest(this, hashes);\n }\n /**\n * Ensure that the Compression Indexer has already indexed the transaction\n */\n async confirmTransactionIndexed(_slot: number): Promise<boolean> {\n return true;\n }\n /**\n * Fetch the latest merkle proofs for multiple compressed accounts specified\n * by an array account hashes\n */\n async getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]> {\n /// Build tree\n const events: PublicTransactionEvent[] = await getParsedEvents(\n this,\n ).then(events => events.reverse());\n const allLeaves: number[][] = [];\n const allLeafIndices: number[] = [];\n for (const event of events) {\n for (\n let index = 0;\n index < event.outputCompressedAccounts.length;\n index++\n ) {\n const hash = event.outputCompressedAccountHashes[index];\n\n allLeaves.push(hash);\n allLeafIndices.push(event.outputLeafIndices[index]);\n }\n }\n const tree = new MerkleTree(\n this.depth,\n this.lightWasm,\n allLeaves.map(leaf => bn(leaf).toString()),\n );\n\n /// create merkle proofs and assemble return type\n const merkleProofs: MerkleContextWithMerkleProof[] = [];\n\n for (let i = 0; i < hashes.length; i++) {\n const leafIndex = tree.indexOf(hashes[i].toString());\n const pathElements = tree.path(leafIndex).pathElements;\n const bnPathElements = pathElements.map(value => bn(value));\n const root = bn(tree.root());\n const merkleProof: MerkleContextWithMerkleProof = {\n hash: hashes[i].toArray('be', 32),\n merkleTree: this.merkleTreeAddress,\n leafIndex: leafIndex,\n merkleProof: bnPathElements,\n nullifierQueue: this.nullifierQueueAddress,\n rootIndex: allLeaves.length,\n root: root,\n };\n merkleProofs.push(merkleProof);\n }\n\n /// Validate\n merkleProofs.forEach((proof, index) => {\n const leafIndex = proof.leafIndex;\n const computedHash = tree.elements()[leafIndex];\n const hashArr = bn(computedHash).toArray('be', 32);\n if (!hashArr.every((val, index) => val === proof.hash[index])) {\n throw new Error(\n `Mismatch at index ${index}: expected ${proof.hash.toString()}, got ${hashArr.toString()}`,\n );\n }\n });\n\n return merkleProofs;\n }\n\n /**\n * Fetch all the compressed accounts owned by the specified public key.\n * Owner can be a program or user account\n */\n async getCompressedAccountsByOwner(\n owner: PublicKey,\n _config?: GetCompressedAccountsByOwnerConfig,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>> {\n const accounts = await getCompressedAccountsByOwnerTest(this, owner);\n return {\n items: accounts,\n cursor: null,\n };\n }\n\n /**\n * Fetch the latest compression signatures on the cluster. Results are\n * paginated.\n */\n async getLatestCompressionSignatures(\n _cursor?: string,\n _limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated> {\n throw new Error(\n 'getLatestNonVotingSignaturesWithContext not supported in test-rpc',\n );\n }\n /**\n * Fetch the latest non-voting signatures on the cluster. Results are\n * not paginated.\n */\n async getLatestNonVotingSignatures(\n _limit?: number,\n ): Promise<LatestNonVotingSignatures> {\n throw new Error(\n 'getLatestNonVotingSignaturesWithContext not supported in test-rpc',\n );\n }\n /**\n * Fetch all the compressed token accounts owned by the specified public\n * key. Owner can be a program or user account\n */\n async getCompressedTokenAccountsByOwner(\n owner: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n return await getCompressedTokenAccountsByOwnerTest(\n this,\n owner,\n options!.mint!,\n );\n }\n\n /**\n * Fetch all the compressed accounts delegated to the specified public key.\n */\n async getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n return await getCompressedTokenAccountsByDelegateTest(\n this,\n delegate,\n options.mint!,\n );\n }\n\n /**\n * Fetch the compressed token balance for the specified account hash\n */\n async getCompressedTokenAccountBalance(\n hash: BN254,\n ): Promise<{ amount: BN }> {\n const account = await getCompressedTokenAccountByHashTest(this, hash);\n return { amount: bn(account.parsed.amount) };\n }\n\n /**\n * @deprecated use {@link getCompressedTokenBalancesByOwnerV2}.\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint.\n */\n async getCompressedTokenBalancesByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<{ balance: BN; mint: PublicKey }[]>> {\n const accounts = await getCompressedTokenAccountsByOwnerTest(\n this,\n publicKey,\n options.mint!,\n );\n return {\n items: accounts.items.map(account => ({\n balance: bn(account.parsed.amount),\n mint: account.parsed.mint,\n })),\n cursor: null,\n };\n }\n\n /**\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint. Uses context.\n */\n async getCompressedTokenBalancesByOwnerV2(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>> {\n const accounts = await getCompressedTokenAccountsByOwnerTest(\n this,\n publicKey,\n options.mint!,\n );\n return {\n context: { slot: 1 },\n value: {\n items: accounts.items.map(account => ({\n balance: bn(account.parsed.amount),\n mint: account.parsed.mint,\n })),\n cursor: null,\n },\n };\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * account hash forward in time from genesis to the most recent confirmed\n * block\n *\n * @param hash queried account hash\n */\n async getCompressionSignaturesForAccount(\n _hash: BN254,\n ): Promise<SignatureWithMetadata[]> {\n throw new Error(\n 'getCompressionSignaturesForAccount not implemented in test-rpc',\n );\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster. Return with\n * CompressionInfo\n */\n async getTransactionWithCompressionInfo(\n _signature: string,\n ): Promise<CompressedTransaction | null> {\n throw new Error('getCompressedTransaction not implemented in test-rpc');\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * address forward in time from genesis to the most recent confirmed\n * block\n *\n * @param address queried compressed account address\n */\n async getCompressionSignaturesForAddress(\n _address: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForAddress3 not implemented');\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified account owner forward in time from genesis to the\n * most recent confirmed block\n *\n * @param owner queried owner public key\n */\n async getCompressionSignaturesForOwner(\n _owner: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForOwner not implemented');\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified token account owner forward in time from genesis to the most\n * recent confirmed block\n */\n async getCompressionSignaturesForTokenOwner(\n _owner: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForTokenOwner not implemented');\n }\n\n /**\n * Fetch the current indexer health status\n */\n async getIndexerHealth(): Promise<string> {\n return 'ok';\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getIndexerSlot(): Promise<number> {\n return 1;\n }\n\n /**\n * Fetch the latest address proofs for new unique addresses specified by an\n * array of addresses.\n *\n * the proof states that said address have not yet been created in respective address tree.\n * @param addresses Array of BN254 new addresses\n * @returns Array of validity proofs for new addresses\n */\n async getMultipleNewAddressProofs(addresses: BN254[]) {\n /// Build tree\n const indexedArray = IndexedArray.default();\n const allAddresses: BN[] = [];\n indexedArray.init();\n const hashes: BN[] = [];\n // TODO(crank): add support for cranked address tree in 'allAddresses'.\n // The Merkle tree root doesnt actually advance beyond init() unless we\n // start emptying the address queue.\n for (let i = 0; i < allAddresses.length; i++) {\n indexedArray.append(bn(allAddresses[i]));\n }\n for (let i = 0; i < indexedArray.elements.length; i++) {\n const hash = indexedArray.hashElement(this.lightWasm, i);\n hashes.push(bn(hash!));\n }\n const tree = new MerkleTree(\n this.depth,\n this.lightWasm,\n hashes.map(hash => bn(hash).toString()),\n );\n\n /// Creates proof for each address\n const newAddressProofs: MerkleContextWithNewAddressProof[] = [];\n\n for (let i = 0; i < addresses.length; i++) {\n const [lowElement] = indexedArray.findLowElement(addresses[i]);\n if (!lowElement) throw new Error('Address not found');\n\n const leafIndex = lowElement.index;\n\n const pathElements: string[] = tree.path(leafIndex).pathElements;\n const bnPathElements = pathElements.map(value => bn(value));\n\n const higherRangeValue = indexedArray.get(\n lowElement.nextIndex,\n )!.value;\n const root = bn(tree.root());\n\n const proof: MerkleContextWithNewAddressProof = {\n root,\n rootIndex: 3,\n value: addresses[i],\n leafLowerRangeValue: lowElement.value,\n leafHigherRangeValue: higherRangeValue,\n nextIndex: bn(lowElement.nextIndex),\n merkleProofHashedIndexedElementLeaf: bnPathElements,\n indexHashedIndexedElementLeaf: bn(lowElement.index),\n merkleTree: this.addressTreeAddress,\n nullifierQueue: this.addressQueueAddress,\n };\n newAddressProofs.push(proof);\n }\n return newAddressProofs;\n }\n\n async getCompressedMintTokenHolders(\n _mint: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>> {\n throw new Error(\n 'getCompressedMintTokenHolders not implemented in test-rpc',\n );\n }\n\n /**\n * Advanced usage of getValidityProof: fetches ZKP directly from a custom\n * non-rpcprover. Note: This uses the proverEndpoint specified in the\n * constructor. For normal usage, please use {@link getValidityProof}\n * instead.\n *\n * Note: Use RPC class for forested trees. TestRpc is only for custom\n * testing purposes.\n */\n async getValidityProofDirect(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n return this.getValidityProof(hashes, newAddresses);\n }\n /**\n * @deprecated This method is not available for TestRpc. Please use\n * {@link getValidityProof} instead.\n */\n async getValidityProofAndRpcContext(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<WithContext<CompressedProofWithContext>> {\n if (newAddresses.some(address => !(address instanceof BN))) {\n throw new Error('AddressWithTree is not supported in test-rpc');\n }\n return {\n value: await this.getValidityProofV0(hashes, newAddresses),\n context: { slot: 1 },\n };\n }\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProof(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n if (newAddresses.some(address => !(address instanceof BN))) {\n throw new Error('AddressWithTree is not supported in test-rpc');\n }\n let validityProof: CompressedProofWithContext;\n\n if (hashes.length === 0 && newAddresses.length === 0) {\n throw new Error(\n 'Empty input. Provide hashes and/or new addresses.',\n );\n } else if (hashes.length > 0 && newAddresses.length === 0) {\n /// inclusion\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n\n // TODO: reactivate to handle proofs of height 32\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // [],\n // this.lightWasm,\n // );\n\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'inclusion',\n inputs,\n this.log,\n // publicInputHash,\n );\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext.map(proof => proof.root),\n rootIndices: merkleProofsWithContext.map(\n proof => proof.rootIndex,\n ),\n leafIndices: merkleProofsWithContext.map(\n proof => proof.leafIndex,\n ),\n leaves: merkleProofsWithContext.map(proof => bn(proof.hash)),\n merkleTrees: merkleProofsWithContext.map(\n proof => proof.merkleTree,\n ),\n nullifierQueues: merkleProofsWithContext.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length === 0 && newAddresses.length > 0) {\n /// new-address\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const inputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const publicInputHash = getPublicInputHash(\n // [],\n // [],\n // newAddressProofs,\n // this.lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'new-address',\n inputs,\n this.log,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: newAddressProofs.map(proof => proof.root),\n // TODO(crank): make dynamic to enable forester support in\n // test-rpc.ts. Currently this is a static root because the\n // address tree doesn't advance.\n rootIndices: newAddressProofs.map(_ => 3),\n leafIndices: newAddressProofs.map(\n proof => proof.indexHashedIndexedElementLeaf.toNumber(), // TODO: support >32bit\n ),\n leaves: newAddressProofs.map(proof => bn(proof.value)),\n merkleTrees: newAddressProofs.map(proof => proof.merkleTree),\n nullifierQueues: newAddressProofs.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length > 0 && newAddresses.length > 0) {\n /// combined\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const newAddressInputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // newAddressProofs,\n // this.lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'combined',\n [inputs, newAddressInputs],\n this.log,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext\n .map(proof => proof.root)\n .concat(newAddressProofs.map(proof => proof.root)),\n rootIndices: merkleProofsWithContext\n .map(proof => proof.rootIndex)\n // TODO(crank): make dynamic to enable forester support in\n // test-rpc.ts. Currently this is a static root because the\n // address tree doesn't advance.\n .concat(newAddressProofs.map(_ => 3)),\n leafIndices: merkleProofsWithContext\n .map(proof => proof.leafIndex)\n .concat(\n newAddressProofs.map(\n proof =>\n proof.indexHashedIndexedElementLeaf.toNumber(), // TODO: support >32bit\n ),\n ),\n leaves: merkleProofsWithContext\n .map(proof => bn(proof.hash))\n .concat(newAddressProofs.map(proof => bn(proof.value))),\n merkleTrees: merkleProofsWithContext\n .map(proof => proof.merkleTree)\n .concat(newAddressProofs.map(proof => proof.merkleTree)),\n nullifierQueues: merkleProofsWithContext\n .map(proof => proof.nullifierQueue)\n .concat(\n newAddressProofs.map(proof => proof.nullifierQueue),\n ),\n };\n } else throw new Error('Invalid input');\n\n return validityProof;\n }\n\n async getValidityProofV0(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<CompressedProofWithContext> {\n /// TODO(swen): add support for custom trees\n return this.getValidityProof(\n hashes.map(hash => hash.hash),\n newAddresses.map(address => address.address),\n );\n }\n}\n","import { Connection, Keypair, Signer } from '@solana/web3.js';\nimport { confirmTx } from '../utils/send-and-confirm';\nimport { Rpc } from '../rpc';\nimport BN from 'bn.js';\n\nlet c = 1;\n\nexport const ALICE = getTestKeypair(255);\nexport const BOB = getTestKeypair(254);\nexport const CHARLIE = getTestKeypair(253);\nexport const DAVE = getTestKeypair(252);\n\n/**\n * Deep comparison of two objects. Handles BN comparison correctly.\n *\n * @param ref - The reference object to compare.\n * @param val - The value object to compare.\n * @returns True if the objects are deeply equal, false otherwise.\n */\nexport function deepEqual(ref: any, val: any) {\n if (typeof ref !== typeof val) {\n console.log(`Type mismatch: ${typeof ref} !== ${typeof val}`);\n return false;\n }\n\n if (ref instanceof BN && val instanceof BN) {\n return ref.eq(val);\n }\n\n if (typeof ref === 'object' && ref !== null && val !== null) {\n const refKeys = Object.keys(ref);\n const valKeys = Object.keys(val);\n\n if (refKeys.length !== valKeys.length) {\n console.log(\n `Key length mismatch: ${refKeys.length} !== ${valKeys.length}`,\n );\n return false;\n }\n\n for (const key of refKeys) {\n if (!valKeys.includes(key)) {\n console.log(`Key ${key} not found in value`);\n return false;\n }\n if (!deepEqual(ref[key], val[key])) {\n console.log(`Value mismatch at key ${key}`);\n return false;\n }\n }\n return true;\n }\n\n if (ref !== val) {\n console.log(`Value mismatch: ${ref} !== ${val}`);\n }\n\n return ref === val;\n}\n\n/**\n * Create a new account and airdrop lamports to it\n *\n * @param rpc connection to use\n * @param lamports amount of lamports to airdrop\n * @param counter counter to use for generating the keypair.\n * If undefined or >255, generates random keypair.\n */\nexport async function newAccountWithLamports(\n rpc: Rpc,\n lamports = 1000000000,\n counter: number | undefined = undefined,\n): Promise<Signer> {\n /// get random keypair\n if (counter === undefined || counter > 255) {\n counter = 256;\n }\n\n const account = getTestKeypair(counter);\n const sig = await rpc.requestAirdrop(account.publicKey, lamports);\n await confirmTx(rpc, sig);\n return account;\n}\n\nexport function getConnection(): Connection {\n const url = 'http://127.0.0.1:8899';\n const connection = new Connection(url, 'confirmed');\n return connection;\n}\n\n/**\n * For use in tests.\n * Generate a unique keypair by passing in a counter <255. If no counter\n * is supplied, it uses and increments a global counter.\n * if counter > 255, generates random keypair\n */\nexport function getTestKeypair(\n counter: number | undefined = undefined,\n): Keypair {\n if (!counter) {\n counter = c;\n c++;\n }\n if (counter > 255) {\n return Keypair.generate();\n }\n const seed = new Uint8Array(32);\n seed[31] = counter; // le\n\n return Keypair.fromSeed(seed);\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { describe, it, expect } = import.meta.vitest;\n\n describe('getTestKeypair', () => {\n it('should generate a keypair with a specific counter', () => {\n const keypair = getTestKeypair(10);\n const keypair2 = getTestKeypair(10);\n expect(keypair).toEqual(keypair2);\n expect(keypair).toBeInstanceOf(Keypair);\n expect(keypair.publicKey).toBeDefined();\n expect(keypair.secretKey).toBeDefined();\n });\n\n it('should generate random keypair if counter is greater than 255', () => {\n const testFn = () => getTestKeypair(256);\n const kp1 = testFn();\n const kp2 = testFn();\n expect(kp1).not.toEqual(kp2);\n });\n\n it('should increment the global counter if no counter is provided', () => {\n const initialKeypair = getTestKeypair();\n const nextKeypair = getTestKeypair();\n const nextNextKeypair = getTestKeypair();\n const nextNextNextKeypair = getTestKeypair(3);\n expect(initialKeypair).not.toEqual(nextKeypair);\n expect(nextKeypair).not.toEqual(nextNextKeypair);\n expect(nextNextKeypair).toEqual(nextNextNextKeypair);\n });\n });\n}\n","export type LightSystemProgram = {\n version: '1.2.0';\n name: 'light_system_program';\n constants: [\n {\n name: 'SOL_POOL_PDA_SEED';\n type: 'bytes';\n value: '[115, 111, 108, 95, 112, 111, 111, 108, 95, 112, 100, 97]';\n },\n ];\n instructions: [\n {\n name: 'initCpiContextAccount';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'associatedMerkleTree';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [];\n },\n {\n name: 'invoke';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n docs: [\n 'This pda is used to invoke the account compression program.',\n ];\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n docs: ['Merkle trees.'];\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ];\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'invokeCpi';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'invokingProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'invokeCpiWithReadOnly';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'invokingProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'stubIdlBuild';\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n docs: [\n 'This pda is used to invoke the account compression program.',\n ];\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n docs: ['Merkle trees.'];\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ];\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs1';\n type: {\n defined: 'InstructionDataInvoke';\n };\n },\n {\n name: 'inputs2';\n type: {\n defined: 'InstructionDataInvokeCpi';\n };\n },\n {\n name: 'inputs3';\n type: {\n defined: 'PublicTransactionEvent';\n };\n },\n ];\n },\n ];\n accounts: [\n {\n name: 'cpiContextAccount';\n docs: [\n 'Collects instruction data without executing a compressed transaction.',\n 'Signer checks are performed on instruction data.',\n 'Collected instruction data is combined with the instruction data of the executing cpi,',\n 'and executed as a single transaction.',\n 'This enables to use input compressed accounts that are owned by multiple programs,',\n 'with one zero-knowledge proof.',\n ];\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'feePayer';\n type: 'publicKey';\n },\n {\n name: 'associatedMerkleTree';\n type: 'publicKey';\n },\n {\n name: 'context';\n type: {\n vec: {\n defined: 'InstructionDataInvokeCpi';\n };\n };\n },\n ];\n };\n },\n ];\n types: [\n {\n name: 'InstructionDataInvoke';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'NewAddressParamsPacked';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'seed';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'addressQueueAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeRootIndex';\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'OutputCompressedAccountWithPackedContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleTreeIndex';\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedProof';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'a';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'b';\n type: {\n array: ['u8', 64];\n };\n },\n {\n name: 'c';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'InstructionDataInvokeCpi';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n ];\n };\n },\n {\n name: 'CompressedCpiContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'setContext';\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ];\n type: 'bool';\n },\n {\n name: 'firstSetContext';\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ];\n type: 'bool';\n },\n {\n name: 'cpiContextAccountIndex';\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ];\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedAccount';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'lamports';\n type: 'u64';\n },\n {\n name: 'address';\n type: {\n option: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'data';\n type: {\n option: {\n defined: 'CompressedAccountData';\n };\n };\n },\n ];\n };\n },\n {\n name: 'CompressedAccountData';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'discriminator';\n type: {\n array: ['u8', 8];\n };\n },\n {\n name: 'data';\n type: 'bytes';\n },\n {\n name: 'dataHash';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleContext';\n type: {\n defined: 'PackedMerkleContext';\n };\n },\n {\n name: 'rootIndex';\n docs: [\n 'Index of root used in inclusion validity proof.',\n ];\n type: 'u16';\n },\n {\n name: 'readOnly';\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ];\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'PackedMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'merkleTreePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'nullifierQueuePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'leafIndex';\n type: 'u32';\n },\n {\n name: 'queueIndex';\n type: {\n option: {\n defined: 'QueueIndex';\n };\n };\n },\n ];\n };\n },\n {\n name: 'QueueIndex';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'queueId';\n docs: ['Id of queue in queue account.'];\n type: 'u8';\n },\n {\n name: 'index';\n docs: ['Index of compressed account hash in queue.'];\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'MerkleTreeSequenceNumber';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'pubkey';\n type: 'publicKey';\n },\n {\n name: 'seq';\n type: 'u64';\n },\n ];\n };\n },\n {\n name: 'PublicTransactionEvent';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'inputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'outputLeafIndices';\n type: {\n vec: 'u32';\n };\n },\n {\n name: 'sequenceNumbers';\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'pubkeyArray';\n type: {\n vec: 'publicKey';\n };\n },\n {\n name: 'message';\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n ];\n errors: [\n {\n code: 6000;\n name: 'SumCheckFailed';\n msg: 'Sum check failed';\n },\n {\n code: 6001;\n name: 'SignerCheckFailed';\n msg: 'Signer check failed';\n },\n {\n code: 6002;\n name: 'CpiSignerCheckFailed';\n msg: 'Cpi signer check failed';\n },\n {\n code: 6003;\n name: 'ComputeInputSumFailed';\n msg: 'Computing input sum failed.';\n },\n {\n code: 6004;\n name: 'ComputeOutputSumFailed';\n msg: 'Computing output sum failed.';\n },\n {\n code: 6005;\n name: 'ComputeRpcSumFailed';\n msg: 'Computing rpc sum failed.';\n },\n {\n code: 6006;\n name: 'InvalidAddress';\n msg: 'InvalidAddress';\n },\n {\n code: 6007;\n name: 'DeriveAddressError';\n msg: 'DeriveAddressError';\n },\n {\n code: 6008;\n name: 'CompressedSolPdaUndefinedForCompressSol';\n msg: 'CompressedSolPdaUndefinedForCompressSol';\n },\n {\n code: 6009;\n name: 'DeCompressLamportsUndefinedForCompressSol';\n msg: 'DeCompressLamportsUndefinedForCompressSol';\n },\n {\n code: 6010;\n name: 'CompressedSolPdaUndefinedForDecompressSol';\n msg: 'CompressedSolPdaUndefinedForDecompressSol';\n },\n {\n code: 6011;\n name: 'DeCompressLamportsUndefinedForDecompressSol';\n msg: 'DeCompressLamportsUndefinedForDecompressSol';\n },\n {\n code: 6012;\n name: 'DecompressRecipientUndefinedForDecompressSol';\n msg: 'DecompressRecipientUndefinedForDecompressSol';\n },\n {\n code: 6013;\n name: 'WriteAccessCheckFailed';\n msg: 'WriteAccessCheckFailed';\n },\n {\n code: 6014;\n name: 'InvokingProgramNotProvided';\n msg: 'InvokingProgramNotProvided';\n },\n {\n code: 6015;\n name: 'InvalidCapacity';\n msg: 'InvalidCapacity';\n },\n {\n code: 6016;\n name: 'InvalidMerkleTreeOwner';\n msg: 'InvalidMerkleTreeOwner';\n },\n {\n code: 6017;\n name: 'ProofIsNone';\n msg: 'ProofIsNone';\n },\n {\n code: 6018;\n name: 'ProofIsSome';\n msg: 'Proof is some but no input compressed accounts or new addresses provided.';\n },\n {\n code: 6019;\n name: 'EmptyInputs';\n msg: 'EmptyInputs';\n },\n {\n code: 6020;\n name: 'CpiContextAccountUndefined';\n msg: 'CpiContextAccountUndefined';\n },\n {\n code: 6021;\n name: 'CpiContextEmpty';\n msg: 'CpiContextEmpty';\n },\n {\n code: 6022;\n name: 'CpiContextMissing';\n msg: 'CpiContextMissing';\n },\n {\n code: 6023;\n name: 'DecompressionRecipientDefined';\n msg: 'DecompressionRecipientDefined';\n },\n {\n code: 6024;\n name: 'SolPoolPdaDefined';\n msg: 'SolPoolPdaDefined';\n },\n {\n code: 6025;\n name: 'AppendStateFailed';\n msg: 'AppendStateFailed';\n },\n {\n code: 6026;\n name: 'InstructionNotCallable';\n msg: 'The instruction is not callable';\n },\n {\n code: 6027;\n name: 'CpiContextFeePayerMismatch';\n msg: 'CpiContextFeePayerMismatch';\n },\n {\n code: 6028;\n name: 'CpiContextAssociatedMerkleTreeMismatch';\n msg: 'CpiContextAssociatedMerkleTreeMismatch';\n },\n {\n code: 6029;\n name: 'NoInputs';\n msg: 'NoInputs';\n },\n {\n code: 6030;\n name: 'InputMerkleTreeIndicesNotInOrder';\n msg: 'Input merkle tree indices are not in ascending order.';\n },\n {\n code: 6031;\n name: 'OutputMerkleTreeIndicesNotInOrder';\n msg: 'Output merkle tree indices are not in ascending order.';\n },\n {\n code: 6032;\n name: 'OutputMerkleTreeNotUnique';\n },\n {\n code: 6033;\n name: 'DataFieldUndefined';\n },\n {\n code: 6034;\n name: 'ReadOnlyAddressAlreadyExists';\n },\n {\n code: 6035;\n name: 'ReadOnlyAccountDoesNotExist';\n },\n {\n code: 6036;\n name: 'HashChainInputsLenghtInconsistent';\n },\n {\n code: 6037;\n name: 'InvalidAddressTreeHeight';\n },\n {\n code: 6038;\n name: 'InvalidStateTreeHeight';\n },\n ];\n};\n\nexport const IDL: LightSystemProgram = {\n version: '1.2.0',\n name: 'light_system_program',\n constants: [\n {\n name: 'SOL_POOL_PDA_SEED',\n type: 'bytes',\n value: '[115, 111, 108, 95, 112, 111, 111, 108, 95, 112, 100, 97]',\n },\n ],\n instructions: [\n {\n name: 'initCpiContextAccount',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'associatedMerkleTree',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [],\n },\n {\n name: 'invoke',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n docs: [\n 'This pda is used to invoke the account compression program.',\n ],\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n docs: ['Merkle trees.'],\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ],\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'invokeCpi',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'invokingProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'invokeCpiWithReadOnly',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'invokingProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'stubIdlBuild',\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n docs: [\n 'This pda is used to invoke the account compression program.',\n ],\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n docs: ['Merkle trees.'],\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ],\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs1',\n type: {\n defined: 'InstructionDataInvoke',\n },\n },\n {\n name: 'inputs2',\n type: {\n defined: 'InstructionDataInvokeCpi',\n },\n },\n {\n name: 'inputs3',\n type: {\n defined: 'PublicTransactionEvent',\n },\n },\n ],\n },\n ],\n accounts: [\n {\n name: 'cpiContextAccount',\n docs: [\n 'Collects instruction data without executing a compressed transaction.',\n 'Signer checks are performed on instruction data.',\n 'Collected instruction data is combined with the instruction data of the executing cpi,',\n 'and executed as a single transaction.',\n 'This enables to use input compressed accounts that are owned by multiple programs,',\n 'with one zero-knowledge proof.',\n ],\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'feePayer',\n type: 'publicKey',\n },\n {\n name: 'associatedMerkleTree',\n type: 'publicKey',\n },\n {\n name: 'context',\n type: {\n vec: {\n defined: 'InstructionDataInvokeCpi',\n },\n },\n },\n ],\n },\n },\n ],\n types: [\n {\n name: 'InstructionDataInvoke',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'NewAddressParamsPacked',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'seed',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'addressQueueAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeRootIndex',\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'OutputCompressedAccountWithPackedContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleTreeIndex',\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedProof',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'a',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'b',\n type: {\n array: ['u8', 64],\n },\n },\n {\n name: 'c',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'InstructionDataInvokeCpi',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n ],\n },\n },\n {\n name: 'CompressedCpiContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'setContext',\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ],\n type: 'bool',\n },\n {\n name: 'firstSetContext',\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ],\n type: 'bool',\n },\n {\n name: 'cpiContextAccountIndex',\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ],\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedAccount',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'lamports',\n type: 'u64',\n },\n {\n name: 'address',\n type: {\n option: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'data',\n type: {\n option: {\n defined: 'CompressedAccountData',\n },\n },\n },\n ],\n },\n },\n {\n name: 'CompressedAccountData',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'discriminator',\n type: {\n array: ['u8', 8],\n },\n },\n {\n name: 'data',\n type: 'bytes',\n },\n {\n name: 'dataHash',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleContext',\n type: {\n defined: 'PackedMerkleContext',\n },\n },\n {\n name: 'rootIndex',\n docs: [\n 'Index of root used in inclusion validity proof.',\n ],\n type: 'u16',\n },\n {\n name: 'readOnly',\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ],\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'PackedMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'merkleTreePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'nullifierQueuePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'leafIndex',\n type: 'u32',\n },\n {\n name: 'queueIndex',\n type: {\n option: {\n defined: 'QueueIndex',\n },\n },\n },\n ],\n },\n },\n {\n name: 'QueueIndex',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'queueId',\n docs: ['Id of queue in queue account.'],\n type: 'u8',\n },\n {\n name: 'index',\n docs: ['Index of compressed account hash in queue.'],\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'MerkleTreeSequenceNumber',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'pubkey',\n type: 'publicKey',\n },\n {\n name: 'seq',\n type: 'u64',\n },\n ],\n },\n },\n {\n name: 'PublicTransactionEvent',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'inputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'outputLeafIndices',\n type: {\n vec: 'u32',\n },\n },\n {\n name: 'sequenceNumbers',\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'pubkeyArray',\n type: {\n vec: 'publicKey',\n },\n },\n {\n name: 'message',\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n ],\n errors: [\n {\n code: 6000,\n name: 'SumCheckFailed',\n msg: 'Sum check failed',\n },\n {\n code: 6001,\n name: 'SignerCheckFailed',\n msg: 'Signer check failed',\n },\n {\n code: 6002,\n name: 'CpiSignerCheckFailed',\n msg: 'Cpi signer check failed',\n },\n {\n code: 6003,\n name: 'ComputeInputSumFailed',\n msg: 'Computing input sum failed.',\n },\n {\n code: 6004,\n name: 'ComputeOutputSumFailed',\n msg: 'Computing output sum failed.',\n },\n {\n code: 6005,\n name: 'ComputeRpcSumFailed',\n msg: 'Computing rpc sum failed.',\n },\n {\n code: 6006,\n name: 'InvalidAddress',\n msg: 'InvalidAddress',\n },\n {\n code: 6007,\n name: 'DeriveAddressError',\n msg: 'DeriveAddressError',\n },\n {\n code: 6008,\n name: 'CompressedSolPdaUndefinedForCompressSol',\n msg: 'CompressedSolPdaUndefinedForCompressSol',\n },\n {\n code: 6009,\n name: 'DeCompressLamportsUndefinedForCompressSol',\n msg: 'DeCompressLamportsUndefinedForCompressSol',\n },\n {\n code: 6010,\n name: 'CompressedSolPdaUndefinedForDecompressSol',\n msg: 'CompressedSolPdaUndefinedForDecompressSol',\n },\n {\n code: 6011,\n name: 'DeCompressLamportsUndefinedForDecompressSol',\n msg: 'DeCompressLamportsUndefinedForDecompressSol',\n },\n {\n code: 6012,\n name: 'DecompressRecipientUndefinedForDecompressSol',\n msg: 'DecompressRecipientUndefinedForDecompressSol',\n },\n {\n code: 6013,\n name: 'WriteAccessCheckFailed',\n msg: 'WriteAccessCheckFailed',\n },\n {\n code: 6014,\n name: 'InvokingProgramNotProvided',\n msg: 'InvokingProgramNotProvided',\n },\n {\n code: 6015,\n name: 'InvalidCapacity',\n msg: 'InvalidCapacity',\n },\n {\n code: 6016,\n name: 'InvalidMerkleTreeOwner',\n msg: 'InvalidMerkleTreeOwner',\n },\n {\n code: 6017,\n name: 'ProofIsNone',\n msg: 'ProofIsNone',\n },\n {\n code: 6018,\n name: 'ProofIsSome',\n msg: 'Proof is some but no input compressed accounts or new addresses provided.',\n },\n {\n code: 6019,\n name: 'EmptyInputs',\n msg: 'EmptyInputs',\n },\n {\n code: 6020,\n name: 'CpiContextAccountUndefined',\n msg: 'CpiContextAccountUndefined',\n },\n {\n code: 6021,\n name: 'CpiContextEmpty',\n msg: 'CpiContextEmpty',\n },\n {\n code: 6022,\n name: 'CpiContextMissing',\n msg: 'CpiContextMissing',\n },\n {\n code: 6023,\n name: 'DecompressionRecipientDefined',\n msg: 'DecompressionRecipientDefined',\n },\n {\n code: 6024,\n name: 'SolPoolPdaDefined',\n msg: 'SolPoolPdaDefined',\n },\n {\n code: 6025,\n name: 'AppendStateFailed',\n msg: 'AppendStateFailed',\n },\n {\n code: 6026,\n name: 'InstructionNotCallable',\n msg: 'The instruction is not callable',\n },\n {\n code: 6027,\n name: 'CpiContextFeePayerMismatch',\n msg: 'CpiContextFeePayerMismatch',\n },\n {\n code: 6028,\n name: 'CpiContextAssociatedMerkleTreeMismatch',\n msg: 'CpiContextAssociatedMerkleTreeMismatch',\n },\n {\n code: 6029,\n name: 'NoInputs',\n msg: 'NoInputs',\n },\n {\n code: 6030,\n name: 'InputMerkleTreeIndicesNotInOrder',\n msg: 'Input merkle tree indices are not in ascending order.',\n },\n {\n code: 6031,\n name: 'OutputMerkleTreeIndicesNotInOrder',\n msg: 'Output merkle tree indices are not in ascending order.',\n },\n {\n code: 6032,\n name: 'OutputMerkleTreeNotUnique',\n },\n {\n code: 6033,\n name: 'DataFieldUndefined',\n },\n {\n code: 6034,\n name: 'ReadOnlyAddressAlreadyExists',\n },\n {\n code: 6035,\n name: 'ReadOnlyAccountDoesNotExist',\n },\n {\n code: 6036,\n name: 'HashChainInputsLenghtInconsistent',\n },\n {\n code: 6037,\n name: 'InvalidAddressTreeHeight',\n },\n {\n code: 6038,\n name: 'InvalidStateTreeHeight',\n },\n ],\n};\n","const winston = require('winston');\n\n// use only if winston is available in your environment, and if you know what\n// you are doing.\n//\n// call logger.info('text', { text: 'test' })\nexport const logger = winston.createLogger({\n level: 'info',\n format: winston.format.combine(\n winston.format.timestamp(),\n winston.format.prettyPrint(),\n ),\n transports: [\n new winston.transports.File({ filename: 'combined.log' }),\n new winston.transports.Console({\n format: winston.format.prettyPrint(),\n }),\n ],\n});\n","/**\n * @param targetLamports - Target priority fee in lamports\n * @param computeUnits - Expected compute units used by the transaction\n * @returns microLamports per compute unit (use in\n * `ComputeBudgetProgram.setComputeUnitPrice`)\n */\nexport function calculateComputeUnitPrice(\n targetLamports: number,\n computeUnits: number,\n): number {\n return Math.ceil((targetLamports * 1_000_000) / computeUnits);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\n\nimport { LightSystemProgram } from '../programs';\nimport { pickRandomTreeAndQueue, Rpc } from '../rpc';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport BN from 'bn.js';\n\n/**\n * Compress lamports to a solana address\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param lamports Amount of lamports to compress\n * @param toAddress Address of the recipient compressed account\n * @param outputStateTree Optional output state tree. Defaults to a current shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n/// TODO: add multisig support\n/// TODO: add support for payer != owner\nexport async function compress(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n toAddress: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const { blockhash } = await rpc.getLatestBlockhash();\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const ix = await LightSystemProgram.compress({\n payer: payer.publicKey,\n toAddress,\n lamports,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n LightSystemProgram,\n selectMinCompressedSolAccountsForTransfer,\n} from '../programs';\nimport { pickRandomTreeAndQueue, Rpc } from '../rpc';\nimport {\n NewAddressParams,\n buildAndSignTx,\n deriveAddress,\n deriveAddressSeed,\n sendAndConfirmTx,\n} from '../utils';\nimport { defaultTestStateTreeAccounts } from '../constants';\nimport { bn } from '../state';\nimport BN from 'bn.js';\n\n/**\n * Create compressed account with address\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param seeds Seeds to derive the new account address\n * @param programId Owner of the new account\n * @param addressTree Optional address tree. Defaults to a current shared\n * address tree.\n * @param addressQueue Optional address queue. Defaults to a current shared\n * address queue.\n * @param outputStateTree Optional output state tree. Defaults to a current\n * shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\nexport async function createAccount(\n rpc: Rpc,\n payer: Signer,\n seeds: Uint8Array[],\n programId: PublicKey,\n addressTree?: PublicKey,\n addressQueue?: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const { blockhash } = await rpc.getLatestBlockhash();\n\n addressTree = addressTree ?? defaultTestStateTreeAccounts().addressTree;\n addressQueue = addressQueue ?? defaultTestStateTreeAccounts().addressQueue;\n\n const seed = deriveAddressSeed(seeds, programId);\n const address = deriveAddress(seed, addressTree);\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const proof = await rpc.getValidityProofV0(undefined, [\n {\n address: bn(address.toBytes()),\n tree: addressTree,\n queue: addressQueue,\n },\n ]);\n\n const params: NewAddressParams = {\n seed: seed,\n addressMerkleTreeRootIndex: proof.rootIndices[0],\n addressMerkleTreePubkey: proof.merkleTrees[0],\n addressQueuePubkey: proof.nullifierQueues[0],\n };\n\n const ix = await LightSystemProgram.createAccount({\n payer: payer.publicKey,\n newAddressParams: params,\n newAddress: Array.from(address.toBytes()),\n recentValidityProof: proof.compressedProof,\n programId,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n\n/**\n * Create compressed account with address and lamports\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param seeds Seeds to derive the new account address\n * @param lamports Number of compressed lamports to initialize the\n * account with\n * @param programId Owner of the new account\n * @param addressTree Optional address tree. Defaults to a current shared\n * address tree.\n * @param addressQueue Optional address queue. Defaults to a current shared\n * address queue.\n * @param outputStateTree Optional output state tree. Defaults to a current\n * shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n// TODO: add support for payer != user owner\nexport async function createAccountWithLamports(\n rpc: Rpc,\n payer: Signer,\n seeds: Uint8Array[],\n lamports: number | BN,\n programId: PublicKey,\n addressTree?: PublicKey,\n addressQueue?: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n lamports = bn(lamports);\n\n const compressedAccounts = await rpc.getCompressedAccountsByOwner(\n payer.publicKey,\n );\n\n const [inputAccounts] = selectMinCompressedSolAccountsForTransfer(\n compressedAccounts.items,\n lamports,\n );\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const { blockhash } = await rpc.getLatestBlockhash();\n\n addressTree = addressTree ?? defaultTestStateTreeAccounts().addressTree;\n addressQueue = addressQueue ?? defaultTestStateTreeAccounts().addressQueue;\n\n const seed = deriveAddressSeed(seeds, programId);\n const address = deriveAddress(seed, addressTree);\n\n const proof = await rpc.getValidityProof(\n inputAccounts.map(account => bn(account.hash)),\n [bn(address.toBytes())],\n );\n\n /// TODO(crank): Adapt before supporting addresses in rpc / cranked address trees.\n /// Currently expects address roots to be consistent with one another and\n /// static. See test-rpc.ts for more details.\n const params: NewAddressParams = {\n seed: seed,\n addressMerkleTreeRootIndex:\n proof.rootIndices[proof.rootIndices.length - 1],\n addressMerkleTreePubkey:\n proof.merkleTrees[proof.merkleTrees.length - 1],\n addressQueuePubkey:\n proof.nullifierQueues[proof.nullifierQueues.length - 1],\n };\n\n const ix = await LightSystemProgram.createAccount({\n payer: payer.publicKey,\n newAddressParams: params,\n newAddress: Array.from(address.toBytes()),\n recentValidityProof: proof.compressedProof,\n inputCompressedAccounts: inputAccounts,\n inputStateRootIndices: proof.rootIndices,\n programId,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport { LightSystemProgram, sumUpLamports } from '../programs';\nimport { Rpc } from '../rpc';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport BN from 'bn.js';\nimport { CompressedAccountWithMerkleContext, bn } from '../state';\n\n/**\n * Decompress lamports into a solana account\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param lamports Amount of lamports to compress\n * @param toAddress Address of the recipient compressed account\n * @param outputStateTree Optional output state tree. Defaults to a current shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n/// TODO: add multisig support\n/// TODO: add support for payer != owner\nexport async function decompress(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n recipient: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n /// TODO: use dynamic state tree and nullifier queue\n\n const userCompressedAccountsWithMerkleContext: CompressedAccountWithMerkleContext[] =\n (await rpc.getCompressedAccountsByOwner(payer.publicKey)).items;\n\n lamports = bn(lamports);\n\n const inputLamports = sumUpLamports(\n userCompressedAccountsWithMerkleContext,\n );\n\n if (lamports.gt(inputLamports)) {\n throw new Error(\n `Not enough compressed lamports. Expected ${lamports}, got ${inputLamports}`,\n );\n }\n\n const proof = await rpc.getValidityProof(\n userCompressedAccountsWithMerkleContext.map(x => bn(x.hash)),\n );\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const ix = await LightSystemProgram.decompress({\n payer: payer.publicKey,\n toAddress: recipient,\n outputStateTree: outputStateTree,\n inputCompressedAccounts: userCompressedAccountsWithMerkleContext,\n recentValidityProof: proof.compressedProof,\n recentInputStateRootIndices: proof.rootIndices,\n lamports,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","/** pipe function */\nexport function pipe<T, R>(\n initialFunction: (arg: T) => R,\n ...functions: ((arg: R) => R)[]\n): (initialValue: T) => R {\n return (initialValue: T): R =>\n functions.reduce(\n (currentValue, currentFunction) => currentFunction(currentValue),\n initialFunction(initialValue),\n );\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n describe('pipe', () => {\n it('should return the result of applying all fns to the initial value', () => {\n const addOne = (x: number) => x + 1;\n const multiplyByTwo = (x: number) => x * 2;\n const subtractThree = (x: number) => x - 3;\n const addOneMultiplyByTwoSubtractThree = pipe(\n addOne,\n multiplyByTwo,\n subtractThree,\n );\n expect(addOneMultiplyByTwoSubtractThree(5)).toBe(9);\n });\n });\n}\n","// zzz\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\n\nimport BN from 'bn.js';\nimport {\n LightSystemProgram,\n selectMinCompressedSolAccountsForTransfer,\n} from '../programs';\nimport { Rpc } from '../rpc';\n\nimport { bn, CompressedAccountWithMerkleContext } from '../state';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport { GetCompressedAccountsByOwnerConfig } from '../rpc-interface';\n\n/**\n * Transfer compressed lamports from one owner to another\n *\n * @param rpc Rpc to use\n * @param payer Payer of transaction fees\n * @param lamports Number of lamports to transfer\n * @param owner Owner of the compressed lamports\n * @param toAddress Destination address of the recipient\n * @param merkleTree State tree account that the compressed lamports should be\n * inserted into. Defaults to the default state tree account.\n * @param confirmOptions Options for confirming the transaction\n * @param config Configuration for fetching compressed accounts\n *\n *\n * @return Signature of the confirmed transaction\n */\nexport async function transfer(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n merkleTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n let accumulatedLamports = bn(0);\n const compressedAccounts: CompressedAccountWithMerkleContext[] = [];\n let cursor: string | undefined;\n const batchSize = 1000; // Maximum allowed by the API\n lamports = bn(lamports);\n\n while (accumulatedLamports.lt(lamports)) {\n const batchConfig: GetCompressedAccountsByOwnerConfig = {\n filters: undefined,\n dataSlice: undefined,\n cursor,\n limit: new BN(batchSize),\n };\n\n const batch = await rpc.getCompressedAccountsByOwner(\n owner.publicKey,\n batchConfig,\n );\n\n for (const account of batch.items) {\n if (account.lamports.gt(new BN(0))) {\n compressedAccounts.push(account);\n accumulatedLamports = accumulatedLamports.add(account.lamports);\n }\n }\n\n cursor = batch.cursor ?? undefined;\n if (batch.items.length < batchSize || accumulatedLamports.gte(lamports))\n break;\n }\n\n if (accumulatedLamports.lt(lamports)) {\n throw new Error(\n `Not enough balance for transfer. Required: ${lamports.toString()}, available: ${accumulatedLamports.toString()}`,\n );\n }\n\n const [inputAccounts] = selectMinCompressedSolAccountsForTransfer(\n compressedAccounts,\n lamports,\n );\n\n const proof = await rpc.getValidityProof(\n inputAccounts.map(account => bn(account.hash)),\n );\n\n const ix = await LightSystemProgram.transfer({\n payer: payer.publicKey,\n inputCompressedAccounts: inputAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n outputStateTrees: merkleTree,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n );\n\n const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions);\n return txId;\n}\n"],"names":["module","exports","assert","val","msg","Error","inherits","ctor","superCtor","super_","TempCtor","prototype","constructor","BN","number","base","endian","isBN","this","negative","words","length","red","_init","Buffer","wordSize","window","require","e","parseHex4Bits","string","index","c","charCodeAt","parseHexByte","lowerBound","r","parseBase","str","start","end","mul","b","len","Math","min","i","move","dest","src","num","Array","isArray","max","left","right","cmp","_initNumber","_initArray","toString","replace","_parseHex","_parseBase","toArray","ceil","j","w","off","_strip","limbLen","limbPow","total","mod","word","imuln","_iaddn","pow","copy","_move","clone","_expand","size","_normSign","Symbol","for","inspect","zeros","groupSizes","groupBases","smallMulTo","self","out","a","lo","carry","k","ncarry","rword","maxJ","padding","groupSize","groupBase","isZero","modrn","idivn","toNumber","ret","toJSON","toBuffer","toArrayLike","ArrayType","byteLength","reqLength","res","allocUnsafe","allocate","_toArrayLikeLE","position","shift","_toArrayLikeBE","clz32","_countBits","t","_zeroBits","bitLength","hi","zeroBits","toTwos","width","abs","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","xor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","add","sub","comb10MulTo","mid","o","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","b1","bl1","bh1","b2","bl2","bh2","b3","bl3","bh3","b4","bl4","bh4","b5","bl5","bh5","b6","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","b9","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","bigMulTo","hncarry","jumboMulTo","mulTo","mulf","isNegNum","muln","sqr","isqr","toBitArray","q","iushln","bits","s","carryMask","newCarry","ishln","iushrn","hint","extended","h","mask","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","_wordDiv","mode","bhi","m","diff","qj","div","divmod","positive","divn","umod","divRound","dm","half","r2","andln","p","acc","modn","egcd","x","y","A","B","C","D","g","isEven","yp","xp","im","isOdd","jm","gcd","_invmp","x1","x2","delta","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","eq","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","name","n","tmp","_tmp","K256","call","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","split","imulK","undefined","strip","input","output","outLen","prev","next","mod3","one","nOne","lpow","z","inv","wnd","current","currentLen","mont","u","TreeType","FIELD_SIZE","HIGHEST_ADDRESS_PLUS_ONE","COMPUTE_BUDGET_PATTERN","INVOKE_DISCRIMINATOR","from","INVOKE_CPI_DISCRIMINATOR","INSERT_INTO_QUEUES_DISCRIMINATOR","noopProgram","lightProgram","accountCompressionProgram","getRegisteredProgramPda","PublicKey","getAccountCompressionAuthority","findProgramAddressSync","defaultStaticAccountsStruct","registeredProgramPda","accountCompressionAuthority","cpiSignatureAccount","defaultStateTreeLookupTables","mainnet","stateTreeLookupTable","stateTreeLookupTableMainnet","nullifyTable","nullifiedStateTreeLookupTableMainnet","devnet","stateTreeLookupTableDevnet","nullifiedStateTreeLookupTableDevnet","isLocalTest","url","includes","localTestActiveStateTreeInfo","tree","merkletreePubkey","queue","nullifierQueuePubkey","cpiContext","cpiContextPubkey","treeType","State","merkleTree2Pubkey","nullifierQueue2Pubkey","cpiContext2Pubkey","defaultTestStateTreeAccounts","nullifierQueue","merkleTree","merkleTreeHeight","DEFAULT_MERKLE_TREE_HEIGHT","addressTree","addressQueue","TRANSACTION_MERKLE_TREE_ROLLOVER_THRESHOLD","floor","STATE_MERKLE_TREE_ROLLOVER_FEE","ADDRESS_QUEUE_ROLLOVER_FEE","STATE_MERKLE_TREE_NETWORK_FEE","ADDRESS_TREE_NETWORK_FEE","basex","ALPHABET","BASE_MAP","Uint8Array","charAt","xc","TypeError","LEADER","FACTOR","log","iFACTOR","decodeUnsafe","source","psz","zeroes","b256","it3","it4","vch","encode","ArrayBuffer","isView","buffer","byteOffset","pbegin","pend","b58","it1","it2","repeat","decode","bn","createBN254","bs58","bigintNumber","enforceSize","encodeBN254toBase58","bn254Buffer","createCompressedAccount","owner","lamports","data","address","createCompressedAccountWithMerkleContext","merkleContext","Object","assign","readOnly","createMerkleContext","hash","leafIndex","Number","isSafeInteger","bytes","lengths","exists","instance","checkFinished","destroyed","finished","U32_MASK64","BigInt","_32n","fromBig","le","l","lst","Ah","Uint32Array","Al","isLE","byteSwap32","arr","toBytes","TextEncoder","utf8ToBytes","abytes","Hash","_cloneInto","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_0n","_1n","_2n","_7n","_256n","_0x71n","round","R","push","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlBH","rotlSH","rotlL","rotlBL","rotlSL","Keccak","blockLen","suffix","outputLen","enableXOF","rounds","super","pos","posOut","state","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","fill","keccakP","update","take","finish","writeInto","bufferOut","set","subarray","xofInto","xof","digestInto","destroy","digest","to","keccak_256","hashCons","hashC","create","wrapConstructor","gen","toHex","value","isSmallerThanBn254FieldSizeBe","hashToBn254FieldSizeBe","bumpSeed","inputWithBumpSeed","concat","hashvToBn254FieldSizeBe","hasher","toCamelCase","obj","map","v","entries","reduce","result","key","$1","toUpperCase","getIndexOrAdd","accountsArray","findIndex","existingKey","equals","padOutputStateMerkleTrees","outputStateMerkleTrees","numberOfOutputCompressedAccounts","inputCompressedAccountsWithMerkleContext","treesArray","slice","toAccountMetas","remainingAccounts","account","pubkey","isWritable","isSigner","packCompressedAccounts","inputCompressedAccounts","inputStateRootIndices","outputCompressedAccounts","_remainingAccounts","packedInputCompressedAccounts","packedOutputCompressedAccounts","forEach","merkleTreePubkeyIndex","nullifierQueuePubkeyIndex","compressedAccount","queueIndex","rootIndex","paddedOutputStateMerkleTrees","merkleTreeIndex","validateSufficientBalance","balance","validateSameOwner","compressedAccounts","zerothOwner","every","deriveAddressSeed","seeds","programId","deriveAddress","seed","addressMerkleTreePubkey","buf","packNewAddressParams","newAddressParams","newAddressParamsPacked","addressMerkleTreeRootIndex","addressMerkleTreeAccountIndex","addressQueueAccountIndex","params","addressQueuePubkey","async","confirmTransaction","connection","signature","confirmation","latestBlockHash","getLatestBlockhash","strategy","lastValidBlockHeight","blockhash","proofFromJsonStruct","json","proofAX","deserializeHexStringToBeBytes","ar","proofAY","proofA","proofBX0","bs","proofBX1","proofBY0","proofBY1","proofB","proofCX","krs","proofCY","negateAndCompressProof","proof","proofC","aXElement","proofAIsPositive","yElementIsPositiveG1","addBitmaskToByte","bXElement","bYElement","proofBIsPositive","yElement1","yElement2","fieldMidpoint","yElementIsPositiveG2","cXElement","cYElement","proofCIsPositive","hexStr","startsWith","substring","yElement","byte","yIsPositive","buildTx","instructions","payerPublicKey","lookupTableAccounts","messageV0","TransactionMessage","payerKey","recentBlockhash","compileToV0Message","VersionedTransaction","sendAndConfirmTx","rpc","tx","confirmOptions","blockHashCtx","txId","sendTransaction","transactionConfirmationStrategy0","slot","commitment","context","confirmTransactionIndexed","confirmTx","transactionConfirmationStrategy","buildAndSignTx","payer","additionalSigners","allSigners","publicKey","sign","getLightStateTreeInfo","stateTreeLookupTableAddress","nullifyTableAddress","getAddressLookupTable","addresses","stateTreePubkeys","nullifyTablePubkeys","bundles","Layout","span","property","isInteger","makeDestinationObject","offset","getSpan","RangeError","replicate","rv","fromArray","values","nameWithProperty","Layout_1","bindConstructorLayout","Class","layout","hasOwnProperty","layout_","boundConstructor_","defineProperty","writable","ExternalLayout","isCount","GreedyCount","elementSpan","rem","OffsetLayout","UInt","UIntBE","readUIntLE","writeUIntLE","readUIntBE","writeUIntBE","Int","readIntLE","writeIntLE","IntBE","readIntBE","writeIntBE","V2E32","divmodInt64","hi32","lo32","roundedInt64","NearUInt64","readUInt32LE","writeUInt32LE","NearUInt64BE","readUInt32BE","writeUInt32BE","NearInt64","readInt32LE","writeInt32LE","NearInt64BE","readInt32BE","writeInt32BE","Float","readFloatLE","writeFloatLE","FloatBE","readFloatBE","writeFloatBE","Double","readDoubleLE","writeDoubleLE","DoubleBE","readDoubleBE","writeDoubleBE","Sequence","elementLayout","count","idx","elo","Structure","fields","decodePrefixes","fd","fsp","firstOffset","lastOffset","lastWrote","fv","layoutFor","offsetOf","UnionDiscriminator","UnionLayoutDiscriminator","Union","discr","defaultLayout","upv","discriminator","usesPrefixDiscriminator","registry","boundGetSourceVariant","defaultGetSourceVariant","bind","getSourceVariant","configGetSourceVariant","gsv","vlo","getVariant","tag","dlo","clo","contentOffset","addVariant","variant","VariantLayout","vb","isBuffer","union","fixBitwiseResult","BitStructure","msb","_packedSetValue","_packedGetValue","addField","bf","BitField","addBoolean","Boolean","fieldFor","container","totalBits","usedBits","sum","valueMask","wordMask","wordValue","Blob","write","CString","srcb","UTF8","maxSpan","Constant","greedy","u8","u16","u24","u32","u40","u48","nu64","u16be","u24be","u32be","u40be","u48be","nu64be","s8","s16","s24","s32","s40","s48","ns64","s16be","s24be","s32be","s40be","s48be","ns64be","f32","f32be","f64","f64be","struct","seq","unionLayoutDiscriminator","blob","cstr","utf8","const","__importDefault","__esModule","default","array","rustEnum","vecU8","tagged","vec","bool","option","i256","u256","i128","u128","u64","i32","i16","i8","buffer_layout_1","require$$0","web3_js_1","require$$1","bn_js_1","require$$2","buffer_layout_2","enumerable","get","BNLayout","signed","i64","WrappedLayout","decoder","encoder","OptionLayout","decodeBool","encodeBool","wrappedLayout","receivedTag","variants","discriminant","unionLayout","MapEntryLayout","keyLayout","valueLayout","keyBytes","Map","CompressedAccountLayout","MerkleContextLayout","NewAddressParamsLayout","InstructionDataInvokeLayout","encodeInstructionDataInvoke","alloc","dataBuffer","lengthBuffer","InstructionDataInvokeCpiLayout","decodeInstructionDataInvoke","decodeInstructionDataInvokeCpi","invokeAccountsLayout","accounts","defaultPubkey","LightSystemProgram","feePayer","authority","solPoolPda","decompressionRecipient","systemProgram","PublicTransactionEventLayout","decodePublicTransactionEvent","AppendNullifyCreateAddressInputsMetaLayout","AppendLeavesInputLayout","InsertNullifierInputLayout","InsertAddressInputLayout","MerkleTreeSequenceNumberLayout","deserializeAppendNullifyCreateAddressInputsIndexer","meta","leavesCount","readUInt8","leaves","leaf","nullifiersCount","nullifiers","nullifier","addressesCount","sequenceNumbersCount","sequence_numbers","outputLeafIndicesCount","output_leaf_indices","convertToPublicTransactionEvent","decoded","invokeData","convertByteArray","inputCompressedAccountHashes","account_hash","outputCompressedAccountHashes","_a","_b","_c","_d","_e","dataHash","_f","outputLeafIndices","sequenceNumbers","sn","pubkeyArray","filter","pk","isCompress","relayFee","compressOrDecompressLamports","message","sumUpLamports","SOL_POOL_PDA_SEED","deriveCompressedSolPda","_","createTransferOutputState","toAddress","changeLamports","createDecompressOutputState","createNewAddressOutputState","createAccount","newAddress","recentValidityProof","outputStateTree","keys","SystemProgram","TransactionInstruction","transfer","recentInputStateRootIndices","outputStateTrees","compress","outputCompressedAccount","decompress","selectMinCompressedSolAccountsForTransfer","transferLamports","accumulatedLamports","selectedAccounts","sort","StructError","failure","failures","cached","explanation","rest","path","join","cause","isObject","isNonArrayObject","print","JSON","stringify","toFailure","branch","type","refinement","toFailures","iterator","run","options","coerce","coercer","status","validator","ts","Set","refiner","Struct","props","schema","validate","is","tuples","tuple","done","shiftIterator","define","any","Element","literal","constant","description","nullable","isNaN","Structs","S","error","coerced","first","unknown","condition","PublicKeyFromString","ArrayFromString","BN254FromString","BNFromStringOrNumber","Base64EncodedCompressedAccountDataResult","createRpcResult","pick","jsonrpc","id","code","UnknownRpcResult","jsonRpcResult","jsonRpcResultAndContext","CompressedAccountResult","slotCreated","TokenDataResult","mint","amount","delegate","CompressedTokenAccountResult","tokenData","MultipleCompressedAccountsResult","items","CompressedAccountsByOwnerResult","cursor","CompressedTokenAccountsByOwnerOrDelegateResult","SlotResult","HealthResult","LatestNonVotingSignaturesResult","blockTime","LatestNonVotingSignaturesResultPaginated","MerkeProofResult","rootSeq","root","NewAddressProofResult","nextIndex","lowerRangeAddress","higherRangeAddress","lowElementLeafIndex","CompressedProofResult","ValidityProofResult","compressedProof","leafIndices","rootIndices","roots","merkleTrees","MultipleMerkleProofsResult","BalanceResult","NativeBalanceResult","TokenBalanceResult","TokenBalanceListResult","tokenBalances","TokenBalanceListResultV2","CompressedMintTokenHoldersResult","AccountProofResult","SignatureListResult","SignatureListWithCursorResult","CompressedTransactionResult","compressionInfo","closedAccounts","optionalTokenData","openedAccounts","transaction","parseAccountData","getCompressedTokenAccountsByOwnerOrDelegate","ownerOrDelegate","filterByDelegate","endpoint","propertyToCheck","rpcRequest","compressionApiEndpoint","toBase58","limit","SolanaJSONRPCError","activeStateTreeInfo","getCachedActiveStateTreeInfo","item","_account","_tokenData","associatedQueue","getQueueForTree","parsed","indexOf","tlv","buildCompressedAccountWithMaybeTokenData","accountStructWithOptionalTokenData","compressedAccountResult","tokenDataResult","maybeTokenData","wrapBigNumbersAsStrings","text","match","p1","p2","p3","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","rpcEndpoint","method","convertToCamelCase","body","response","fetch","headers","ok","wrappedJsonString","parse","proverRequest","proverEndpoint","circuitType","stateTreeHeight","addressTreeHeight","newAddresses","statusText","convertMerkleProofsWithContextToHex","merkleProofsWithContext","inputs","pathIndex","pathElements","merkleProof","hex","convertNonInclusionMerkleProofInputsToHex","nonInclusionMerkleProofInputs","indexHashedIndexedElementLeaf","merkleProofHashedIndexedElementLeaf","leafLowerRangeValue","leafHigherRangeValue","calculateTwoInputsHashChain","hashesFirst","hashesSecond","lightWasm","hashChain","poseidonHashBN","info","pickRandomTreeAndQueue","random","Rpc","Connection","config","setStateTreeInfo","getLatestActiveStateTreeInfo","getCompressedAccount","getCompressedBalance","getCompressedBalanceByOwner","getCompressedAccountProof","getMultipleCompressedAccounts","hashes","getMultipleCompressedAccountProofs","merkleProofs","getCompressedAccountsByOwner","filters","dataSlice","getCompressedTokenAccountsByOwner","getCompressedTokenAccountsByDelegate","getCompressedTokenAccountBalance","getCompressedTokenBalancesByOwner","tokenBalance","getCompressedTokenBalancesByOwnerV2","maybeFiltered","getCompressionSignaturesForAccount","getTransactionWithCompressionInfo","calculateTokenBalances","balances","preTokenBalances","postTokenBalances","getCompressionSignaturesForAddress","getCompressionSignaturesForOwner","getCompressionSignaturesForTokenOwner","getIndexerHealth","startTime","Date","now","getIndexerSlot","Promise","resolve","setTimeout","getCompressedMintTokenHolders","getLatestCompressionSignatures","getLatestNonVotingSignatures","getMultipleNewAddressProofs","newAddressProofs","_proof","getValidityProofDirect","validityProof","nullifierQueues","newAddressInputs","getValidityProof","accs","trees","queues","defaultAddressTreePublicKey","defaultAddressQueuePublicKey","formattedHashes","formattedNewAddresses","getValidityProofV0","getValidityProofAndRpcContext","newAddressesWithTrees","dedupeSigner","signer","signers","UtxoErrorCode","SelectInUtxosErrorCode","CreateUtxoErrorCode","RpcErrorCode","LookupTableErrorCode","ProofErrorCode","MerkleTreeErrorCode","UtilsErrorCode","HashErrorCode","MetaError","functionName","codeMessage","IndexedElement","other","compareTo","nextValue","poseidonHash","IndexedElementBundle","newLowElement","newElement","newElementNextValue","IndexedArray","elements","currentNodeIndex","highestElementIndex","isEmpty","findElement","find","node","init","init_value","append","findLowElementIndex","findLowElement","lowElementIndex","lowElement","hashElement","element","nextElement","appendWithLowElementIndex","newElementBundle","newElementWithLowElementIndex","lowest","newElementIndex","MerkleTree","levels","zeroElement","capacity","_lightWasm","_zeros","_layers","poseidonHashString","_rebuild","level","insert","bulkInsert","pathIndices","comparator","el","serialize","deserialize","hashFunction","_hash","getParsedEvents","events","signatures","getConfirmedSignaturesForAddress2","txs","getParsedTransactions","maxSupportedTransactionVersion","txParsed","innerInstructions","allAccounts","accountKeys","dataVec","txRaw","getTransaction","ix","compiledInstructions","decodedData","groupedAccountVec","innerGroup","group","accountIdx","event","parseLightTransaction","transactionEvents","some","parseEvents","parsePublicTransactionEventWithIdl","indexerEventsTransactions","deserializeFn","transactions","err","ixInner","decodedEvent","numericData","foundSystemInstruction","appendInputsData","discriminatorStr","invokeDiscriminatorStr","invokeCpiDiscriminatorStr","getCompressedAccountByHashTest","getCompressedAccountsForTest","reverse","allOutputAccounts","allInputAccountHashes","withCtx","unspentAccounts","tokenProgramId","TokenDataLayout","parseTokenLayoutWithIdl","getCompressedTokenAccounts","eventsWithParsedTokenTlvData","all","outputHashes","outputCompressedAccountsWithParsedTokenData","parsedData","parseEventWithTokenTlvData","allOutCompressedAccounts","flatMap","allInCompressedAccountHashes","getCompressedTokenAccountsByOwnerTest","getCompressedTokenAccountsByDelegateTest","getCompressedTokenAccountByHashTest","filtered","TestRpc","connectionConfig","testRpcConfig","merkleTreeAddress","nullifierQueueAddress","depth","addressTreeAddress","addressQueueAddress","getMultipleCompressedAccountsByHashTest","_slot","then","allLeaves","allLeafIndices","bnPathElements","computedHash","hashArr","_config","getCompressedAccountsByOwnerTest","_cursor","_limit","_signature","_address","_options","_owner","indexedArray","allAddresses","higherRangeValue","_mint","ALICE","getTestKeypair","BOB","CHARLIE","DAVE","counter","Keypair","generate","fromSeed","winston","logger","createLogger","format","combine","timestamp","prettyPrint","transports","File","filename","Console","version","constants","isMut","args","docs","isOptional","defined","kind","types","errors","recipientPublicKey","txHash","requestAirdrop","byteArray","fromSecretKey","targetLamports","computeUnits","stateTreeInfo","ComputeBudgetProgram","setComputeUnitLimit","units","preflightCommitment","inputAccounts","endpointOrWeb3JsConnection","recentSlot","createInstruction1","lookupTableAddress1","AddressLookupTableProgram","createLookupTable","recipient","userCompressedAccountsWithMerkleContext","inputLamports","deepEqual","ref","refKeys","valKeys","nullifierQueue2","merkleTree2","tableAddress","newStateTreeAddresses","newQueueAddresses","newCpiContextAddresses","lutState","extendLookupTable","lookupTable","addr","accountProofs","accountHashes","inclusionHashChain","newAddressHashes","nonInclusionHashChain","defaultAccounts","sig","fullStateTreeAddress","initialFunction","functions","initialValue","currentValue","currentFunction","ms","getTime","batchConfig","batch","signedTx"],"mappings":"2UAAA,SAAWA,EAAQC,GAIjB,SAASC,EAAQC,EAAKC,GACpB,IAAKD,EAAK,MAAM,IAAIE,MAAMD,GAAO,mBAClC,CAID,SAASE,EAAUC,EAAMC,GACvBD,EAAKE,OAASD,EACd,IAAIE,EAAW,aACfA,EAASC,UAAYH,EAAUG,UAC/BJ,EAAKI,UAAY,IAAID,EACrBH,EAAKI,UAAUC,YAAcL,CAC9B,CAID,SAASM,EAAIC,EAAQC,EAAMC,GACzB,GAAIH,EAAGI,KAAKH,GACV,OAAOA,EAGTI,KAAKC,SAAW,EAChBD,KAAKE,MAAQ,KACbF,KAAKG,OAAS,EAGdH,KAAKI,IAAM,KAEI,OAAXR,IACW,OAATC,GAA0B,OAATA,IACnBC,EAASD,EACTA,EAAO,IAGTG,KAAKK,MAAMT,GAAU,EAAGC,GAAQ,GAAIC,GAAU,MAEjD,CAUD,IAAIQ,EATkB,qBACbvB,QAAUY,EAEjBZ,EAAQY,GAAKA,EAGfA,EAAGA,GAAKA,EACRA,EAAGY,SAAW,GAGd,IAEID,EADoB,oBAAXE,aAAmD,IAAlBA,OAAOF,OACxCE,OAAOF,OAEPG,QAAQ,UAAUH,MAE9B,CAAC,MAAOI,GACR,CAgID,SAASC,EAAeC,EAAQC,GAC9B,IAAIC,EAAIF,EAAOG,WAAWF,GAE1B,OAAIC,GAAK,IAAMA,GAAK,GACXA,EAAI,GAEFA,GAAK,IAAMA,GAAK,GAClBA,EAAI,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,KAAM,CACFjJ,OAAQ,QAGhB,CACIjkB,KAAM,aACNktB,KAAM,QAEV,CACIltB,KAAM,+BACNktB,KAAM,CACFjJ,OAAQ,QAGhB,CACIjkB,KAAM,cACNktB,KAAM,CACFnJ,IAAK,cAGb,CACI/jB,KAAM,UACNktB,KAAM,CACFjJ,OAAQ,cAOhCqjB,OAAQ,CACJ,CACItX,KAAM,IACNhwB,KAAM,iBACNpW,IAAK,oBAET,CACIomC,KAAM,KACNhwB,KAAM,oBACNpW,IAAK,uBAET,CACIomC,KAAM,KACNhwB,KAAM,uBACNpW,IAAK,2BAET,CACIomC,KAAM,KACNhwB,KAAM,wBACNpW,IAAK,+BAET,CACIomC,KAAM,KACNhwB,KAAM,yBACNpW,IAAK,gCAET,CACIomC,KAAM,KACNhwB,KAAM,sBACNpW,IAAK,6BAET,CACIomC,KAAM,KACNhwB,KAAM,iBACNpW,IAAK,kBAET,CACIomC,KAAM,KACNhwB,KAAM,qBACNpW,IAAK,sBAET,CACIomC,KAAM,KACNhwB,KAAM,0CACNpW,IAAK,2CAET,CACIomC,KAAM,KACNhwB,KAAM,4CACNpW,IAAK,6CAET,CACIomC,KAAM,KACNhwB,KAAM,4CACNpW,IAAK,6CAET,CACIomC,KAAM,KACNhwB,KAAM,8CACNpW,IAAK,+CAET,CACIomC,KAAM,KACNhwB,KAAM,+CACNpW,IAAK,gDAET,CACIomC,KAAM,KACNhwB,KAAM,yBACNpW,IAAK,0BAET,CACIomC,KAAM,KACNhwB,KAAM,6BACNpW,IAAK,8BAET,CACIomC,KAAM,KACNhwB,KAAM,kBACNpW,IAAK,mBAET,CACIomC,KAAM,KACNhwB,KAAM,yBACNpW,IAAK,0BAET,CACIomC,KAAM,KACNhwB,KAAM,cACNpW,IAAK,eAET,CACIomC,KAAM,KACNhwB,KAAM,cACNpW,IAAK,6EAET,CACIomC,KAAM,KACNhwB,KAAM,cACNpW,IAAK,eAET,CACIomC,KAAM,KACNhwB,KAAM,6BACNpW,IAAK,8BAET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":[0,3,4,7,8,9,10,19,20,23]}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../../node_modules/.pnpm/bn.js@5.2.1/node_modules/bn.js/lib/bn.js","../../../../../src/state/types.ts","../../../../../src/constants.ts","../../../../../node_modules/.pnpm/bs58@6.0.0/node_modules/bs58/src/esm/index.js","../../../../../node_modules/.pnpm/base-x@5.0.0/node_modules/base-x/src/esm/index.js","../../../../../src/state/BN254.ts","../../../../../src/state/compressed-account.ts","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/_assert.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/_u64.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/utils.js","../../../../../node_modules/.pnpm/@noble+hashes@1.5.0/node_modules/@noble/hashes/esm/sha3.js","../../../../../node_modules/.pnpm/map-obj@5.0.0/node_modules/map-obj/index.js","../../../../../node_modules/.pnpm/camelcase@8.0.0/node_modules/camelcase/index.js","../../../../../node_modules/.pnpm/quick-lru@6.1.2/node_modules/quick-lru/index.js","../../../../../node_modules/.pnpm/camelcase-keys@9.1.3/node_modules/camelcase-keys/index.js","../../../../../src/utils/conversion.ts","../../../../../src/instruction/pack-compressed-accounts.ts","../../../../../src/utils/validation.ts","../../../../../src/utils/address.ts","../../../../../src/utils/airdrop.ts","../../../../../src/utils/parse-validity-proof.ts","../../../../../src/utils/send-and-confirm.ts","../../../../../src/utils/get-light-state-tree-info.ts","../../../../../node_modules/.pnpm/buffer-layout@1.2.2/node_modules/buffer-layout/lib/Layout.js","../../../../../node_modules/.pnpm/@coral-xyz+borsh@0.29.0_@solana+web3.js@1.98.0/node_modules/@coral-xyz/borsh/dist/index.js","../../../../../src/programs/layout.ts","../../../../../src/programs/system.ts","../../../../../node_modules/.pnpm/superstruct@2.0.2/node_modules/superstruct/dist/index.mjs","../../../../../src/rpc-interface.ts","../../../../../src/rpc.ts","../../../../../src/actions/common.ts","../../../../../src/errors.ts","../../../../../src/test-helpers/merkle-tree/indexed-array.ts","../../../../../src/test-helpers/merkle-tree/merkle-tree.ts","../../../../../src/test-helpers/test-rpc/get-parsed-events.ts","../../../../../src/test-helpers/test-rpc/get-compressed-accounts.ts","../../../../../src/test-helpers/test-rpc/get-compressed-token-accounts.ts","../../../../../src/test-helpers/test-rpc/test-rpc.ts","../../../../../src/test-helpers/test-utils.ts","../../../../../src/idl.ts","../../../../../src/utils/calculate-compute-unit-price.ts","../../../../../src/actions/compress.ts","../../../../../src/actions/create-account.ts","../../../../../src/actions/decompress.ts","../../../../../src/utils/pipe.ts","../../../../../src/utils/sleep.ts","../../../../../src/actions/transfer.ts"],"sourcesContent":["(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import BN from 'bn.js';\nimport { PublicKey } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { NewAddressParamsPacked } from '../utils';\n\nexport enum TreeType {\n /**\n * v1 state merkle tree\n */\n State = 0,\n /**\n * v1 address merkle tree\n */\n Address = 1,\n /**\n * v2 state merkle tree\n */\n BatchedState = 2,\n /**\n * v2 address merkle tree\n */\n BatchedAddress = 3,\n}\n\nexport type ActiveTreeBundle = {\n tree: PublicKey;\n queue: PublicKey | null;\n cpiContext: PublicKey | null;\n treeType: TreeType;\n};\n\nexport interface PackedCompressedAccountWithMerkleContext {\n compressedAccount: CompressedAccount;\n merkleContext: PackedMerkleContext;\n rootIndex: number; // u16\n readOnly: boolean;\n}\n\nexport interface PackedMerkleContext {\n merkleTreePubkeyIndex: number; // u8\n nullifierQueuePubkeyIndex: number; // u8\n leafIndex: number; // u32\n queueIndex: null | QueueIndex; // Option<QueueIndex>\n}\n\nexport interface QueueIndex {\n queueId: number; // u8\n index: number; // u16\n}\n\n/**\n * Describe the generic compressed account details applicable to every\n * compressed account.\n * */\nexport interface CompressedAccount {\n /** Public key of program or user that owns the account */\n owner: PublicKey;\n /** Lamports attached to the account */\n lamports: BN; // u64 // FIXME: optional\n /**\n * TODO: use PublicKey. Optional unique account ID that is persistent across\n * transactions.\n */\n address: number[] | null; // Option<PublicKey>\n /** Optional data attached to the account */\n data: CompressedAccountData | null; // Option<CompressedAccountData>\n}\n\n/**\n * Describe the generic compressed account details applicable to every\n * compressed account.\n * */\nexport interface OutputCompressedAccountWithPackedContext {\n compressedAccount: CompressedAccount;\n merkleTreeIndex: number;\n}\n\nexport interface CompressedAccountData {\n discriminator: number[]; // [u8; 8] // TODO: test with uint8Array instead\n data: Buffer; // bytes\n dataHash: number[]; // [u8; 32]\n}\nexport interface MerkleTreeSequenceNumber {\n pubkey: PublicKey;\n seq: BN;\n}\n\nexport interface PublicTransactionEvent {\n inputCompressedAccountHashes: number[][]; // Vec<[u8; 32]>\n outputCompressedAccountHashes: number[][]; // Vec<[u8; 32]>\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n outputLeafIndices: number[]; // Vec<u32>\n sequenceNumbers: MerkleTreeSequenceNumber[]; // Vec<MerkleTreeSequenceNumber>\n relayFee: BN | null; // Option<u64>\n isCompress: boolean; // bool\n compressOrDecompressLamports: BN | null; // Option<u64>\n pubkeyArray: PublicKey[]; // Vec<PublicKey>\n message: Uint8Array | null; // Option<bytes>\n}\n\nexport interface InstructionDataInvoke {\n proof: CompressedProof | null; // Option<CompressedProof>\n inputCompressedAccountsWithMerkleContext: PackedCompressedAccountWithMerkleContext[];\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n relayFee: BN | null; // Option<u64>\n newAddressParams: NewAddressParamsPacked[]; // Vec<NewAddressParamsPacked>\n compressOrDecompressLamports: BN | null; // Option<u64>\n isCompress: boolean; // bool\n}\n\nexport interface InstructionDataInvokeCpi {\n proof: CompressedProof | null; // Option<CompressedProof>\n inputCompressedAccountsWithMerkleContext: PackedCompressedAccountWithMerkleContext[];\n outputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n relayFee: BN | null; // Option<u64>\n newAddressParams: NewAddressParamsPacked[]; // Vec<NewAddressParamsPacked>\n compressOrDecompressLamports: BN | null; // Option<u64>\n isCompress: boolean; // bool\n compressedCpiContext: CompressedCpiContext | null;\n}\n\nexport interface CompressedCpiContext {\n /// Is set by the program that is invoking the CPI to signal that is should\n /// set the cpi context.\n set_context: boolean;\n /// Is set to wipe the cpi context since someone could have set it before\n /// with unrelated data.\n first_set_context: boolean;\n /// Index of cpi context account in remaining accounts.\n cpi_context_account_index: number;\n}\n\nexport interface CompressedProof {\n a: number[]; // [u8; 32]\n b: number[]; // [u8; 64]\n c: number[]; // [u8; 32]\n}\n\nexport interface InputTokenDataWithContext {\n amount: BN;\n delegateIndex: number | null; // Option<u8>\n merkleContext: PackedMerkleContext;\n rootIndex: number; // u16\n lamports: BN | null;\n tlv: Buffer | null;\n}\nexport type TokenData = {\n /// The mint associated with this account\n mint: PublicKey;\n /// The owner of this account.\n owner: PublicKey;\n /// The amount of tokens this account holds.\n amount: BN;\n /// If `delegate` is `Some` then `delegated_amount` represents\n /// the amount authorized by the delegate\n delegate: PublicKey | null;\n /// The account's state\n state: number; // AccountState_IdlType;\n /// TokenExtension tlv\n tlv: Buffer | null;\n};\n","import BN from 'bn.js';\nimport { Buffer } from 'buffer';\nimport { ConfirmOptions, PublicKey } from '@solana/web3.js';\nimport { ActiveTreeBundle, TreeType } from './state/types';\n\nexport const FIELD_SIZE = new BN(\n '21888242871839275222246405745257275088548364400416034343698204186575808495617',\n);\nexport const HIGHEST_ADDRESS_PLUS_ONE = new BN(\n '452312848583266388373324160190187140051835877600158453279131187530910662655',\n);\n\nexport const COMPUTE_BUDGET_PATTERN = [2, 64, 66, 15, 0];\n\nexport const INVOKE_DISCRIMINATOR = Buffer.from([\n 26, 16, 169, 7, 21, 202, 242, 25,\n]);\n\nexport const INVOKE_CPI_DISCRIMINATOR = Buffer.from([\n 49, 212, 191, 129, 39, 194, 43, 196,\n]);\n\nexport const INSERT_INTO_QUEUES_DISCRIMINATOR = Buffer.from([\n 180, 143, 159, 153, 35, 46, 248, 163,\n]);\n\n// TODO: implement properly\nexport const noopProgram = 'noopb9bkMVfRPU8AsbpTUg8AQkHtKwMYZiFUjNRtMmV';\nexport const lightProgram = 'SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7';\nexport const accountCompressionProgram = // also: merkletree program\n 'compr6CUsB5m2jS4Y3831ztGSTnDpnKJTKS95d64XVq';\n\nexport const getRegisteredProgramPda = () =>\n new PublicKey('35hkDgaAKwMCaxRz2ocSZ6NaUrtKkyNqU6c4RV3tYJRh'); // TODO: better labelling. gov authority pda\n\nexport const getAccountCompressionAuthority = () =>\n PublicKey.findProgramAddressSync(\n [Buffer.from('cpi_authority')],\n new PublicKey(\n // TODO: can add check to ensure its consistent with the idl\n lightProgram,\n ),\n )[0];\n\nexport const defaultStaticAccounts = () => [\n new PublicKey(getRegisteredProgramPda()),\n new PublicKey(noopProgram),\n new PublicKey(accountCompressionProgram),\n new PublicKey(getAccountCompressionAuthority()),\n];\nexport const defaultStaticAccountsStruct = () => {\n return {\n registeredProgramPda: new PublicKey(getRegisteredProgramPda()),\n noopProgram: new PublicKey(noopProgram),\n accountCompressionProgram: new PublicKey(accountCompressionProgram),\n accountCompressionAuthority: new PublicKey(\n getAccountCompressionAuthority(),\n ),\n cpiSignatureAccount: null,\n };\n};\n\nexport type StateTreeLUTPair = {\n stateTreeLookupTable: PublicKey;\n nullifyTable: PublicKey;\n};\n\n/**\n * Returns the Default Public State Tree LUTs for Devnet and Mainnet-Beta.\n */\nexport const defaultStateTreeLookupTables = (): {\n mainnet: StateTreeLUTPair[];\n devnet: StateTreeLUTPair[];\n} => {\n return {\n mainnet: [\n {\n stateTreeLookupTable: new PublicKey(\n stateTreeLookupTableMainnet,\n ),\n nullifyTable: new PublicKey(\n nullifiedStateTreeLookupTableMainnet,\n ),\n },\n ],\n devnet: [\n {\n stateTreeLookupTable: new PublicKey(stateTreeLookupTableDevnet),\n nullifyTable: new PublicKey(\n nullifiedStateTreeLookupTableDevnet,\n ),\n },\n ],\n };\n};\n\n/**\n * @internal\n */\nexport const isLocalTest = (url: string) => {\n return url.includes('localhost') || url.includes('127.0.0.1');\n};\n\n/**\n * @internal\n */\nexport const localTestActiveStateTreeInfo = (): ActiveTreeBundle[] => {\n return [\n {\n tree: new PublicKey(merkletreePubkey),\n queue: new PublicKey(nullifierQueuePubkey),\n cpiContext: new PublicKey(cpiContextPubkey),\n treeType: TreeType.State,\n },\n {\n tree: new PublicKey(merkleTree2Pubkey),\n queue: new PublicKey(nullifierQueue2Pubkey),\n cpiContext: new PublicKey(cpiContext2Pubkey),\n treeType: TreeType.State,\n },\n ];\n};\n\n/**\n * Use only with Localnet testing.\n * For public networks, fetch via {@link defaultStateTreeLookupTables} and {@link getLightStateTreeInfo}.\n */\nexport const defaultTestStateTreeAccounts = () => {\n return {\n nullifierQueue: new PublicKey(nullifierQueuePubkey),\n merkleTree: new PublicKey(merkletreePubkey),\n merkleTreeHeight: DEFAULT_MERKLE_TREE_HEIGHT,\n addressTree: new PublicKey(addressTree),\n addressQueue: new PublicKey(addressQueue),\n };\n};\n\n/**\n * @internal testing only\n */\nexport const defaultTestStateTreeAccounts2 = () => {\n return {\n nullifierQueue2: new PublicKey(nullifierQueue2Pubkey),\n merkleTree2: new PublicKey(merkleTree2Pubkey),\n };\n};\n\nexport const stateTreeLookupTableMainnet =\n '7i86eQs3GSqHjN47WdWLTCGMW6gde1q96G2EVnUyK2st';\nexport const nullifiedStateTreeLookupTableMainnet =\n 'H9QD4u1fG7KmkAzn2tDXhheushxFe1EcrjGGyEFXeMqT';\n\nexport const stateTreeLookupTableDevnet =\n '8n8rH2bFRVA6cSGNDpgqcKHCndbFCT1bXxAQG89ejVsh';\nexport const nullifiedStateTreeLookupTableDevnet =\n '5dhaJLBjnVBQFErr8oiCJmcVsx3Zj6xDekGB2zULPsnP';\n\nexport const nullifierQueuePubkey =\n 'nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148';\nexport const cpiContextPubkey = 'cpi1uHzrEhBG733DoEJNgHCyRS3XmmyVNZx5fonubE4';\n\nexport const merkletreePubkey = 'smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT';\nexport const addressTree = 'amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2';\nexport const addressQueue = 'aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F';\n\nexport const merkleTree2Pubkey = 'smt2rJAFdyJJupwMKAqTNAJwvjhmiZ4JYGZmbVRw1Ho';\nexport const nullifierQueue2Pubkey =\n 'nfq2hgS7NYemXsFaFUCe3EMXSDSfnZnAe27jC6aPP1X';\nexport const cpiContext2Pubkey = 'cpi2cdhkH5roePvcudTgUL8ppEBfTay1desGh8G8QxK';\n\nexport const confirmConfig: ConfirmOptions = {\n commitment: 'confirmed',\n preflightCommitment: 'confirmed',\n};\n\nexport const DEFAULT_MERKLE_TREE_HEIGHT = 26;\nexport const DEFAULT_MERKLE_TREE_ROOTS = 2800;\n/** Threshold (per asset) at which new in-UTXOs get merged, in order to reduce UTXO pool size */\nexport const UTXO_MERGE_THRESHOLD = 20;\nexport const UTXO_MERGE_MAXIMUM = 10;\n\n/**\n * Treshold after which the currently used transaction Merkle tree is switched\n * to the next one\n */\nexport const TRANSACTION_MERKLE_TREE_ROLLOVER_THRESHOLD = new BN(\n Math.floor(2 ** DEFAULT_MERKLE_TREE_HEIGHT * 0.95),\n);\n\n/**\n * Fee to provide continous funding for the state Merkle tree.\n * Once the state Merkle tree is at 95% capacity the accumulated fees\n * will be used to fund the next state Merkle tree with the same parameters.\n *\n * Is charged per output compressed account.\n */\nexport const STATE_MERKLE_TREE_ROLLOVER_FEE = new BN(300);\n\n/**\n * Fee to provide continous funding for the address queue and address Merkle tree.\n * Once the address Merkle tree is at 95% capacity the accumulated fees\n * will be used to fund the next address queue and address tree with the same parameters.\n *\n * Is charged per newly created address.\n */\nexport const ADDRESS_QUEUE_ROLLOVER_FEE = new BN(392);\n\n/**\n * Is charged if the transaction nullifies at least one compressed account.\n */\nexport const STATE_MERKLE_TREE_NETWORK_FEE = new BN(5000);\n\n/**\n * Is charged if the transaction creates at least one address.\n */\nexport const ADDRESS_TREE_NETWORK_FEE = new BN(5000);\n","import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n let carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n","// TODO: consider implementing BN254 as wrapper class around _BN mirroring\n// PublicKey this would encapsulate our runtime checks and also enforce\n// typesafety at compile time\n\nimport { FIELD_SIZE } from '../constants';\nimport { PublicKey } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport bs58 from 'bs58';\nimport { Buffer } from 'buffer';\n\n/**\n * bignumber with <254-bit max size. Anchor serialization doesn't support native\n * bigint yet, so we wrap BN. This wrapper has simple base10 encoding which is\n * needed for zk circuit compat, in addition to the base58 encoding that users\n * are used to from working with the web3.js PublicKey type.\n */\nexport type BN254 = BN;\n\nexport const bn = (\n number: string | number | BN | Buffer | Uint8Array | number[],\n base?: number | 'hex' | undefined,\n endian?: BN.Endianness | undefined,\n): BN => new BN(number, base, endian);\n\n/** Create a bigint instance with <254-bit max size and base58 capabilities */\nexport const createBN254 = (\n number: string | number | BN | Buffer | Uint8Array | number[],\n base?: number | 'hex' | 'base58' | undefined,\n): BN254 => {\n if (base === 'base58') {\n if (typeof number !== 'string')\n throw new Error('Must be a base58 string');\n return createBN254(bs58.decode(number));\n }\n\n const bigintNumber = new BN(number, base);\n\n return enforceSize(bigintNumber);\n};\n\n/**\n * Enforces a maximum size of <254 bits for bigint instances. This is necessary\n * for compatibility with zk-SNARKs, where hashes must be less than the field\n * modulus (~2^254).\n */\nfunction enforceSize(bigintNumber: BN254): BN254 {\n if (bigintNumber.gte(FIELD_SIZE)) {\n throw new Error('Value is too large. Max <254 bits');\n }\n return bigintNumber;\n}\n\n/** Convert <254-bit bigint to Base58 string. */\nexport function encodeBN254toBase58(bigintNumber: BN): string {\n /// enforce size\n const bn254 = createBN254(bigintNumber);\n const bn254Buffer = bn254.toArrayLike(Buffer, undefined, 32);\n\n return bs58.encode(bn254Buffer);\n}\n","import BN from 'bn.js';\nimport { PublicKey } from '@solana/web3.js';\nimport { CompressedAccount, CompressedAccountData } from './types';\nimport { BN254, bn } from './BN254';\n\nexport type CompressedAccountWithMerkleContext = CompressedAccount &\n MerkleContext & {\n readOnly: boolean;\n };\n\n/**\n * Context for compressed account inserted into a state Merkle tree\n * */\nexport type MerkleContext = {\n /** State Merkle tree */\n merkleTree: PublicKey;\n /** The state nullfier queue belonging to merkleTree */\n nullifierQueue: PublicKey;\n /** Poseidon hash of the utxo preimage. Is a leaf in state merkle tree */\n hash: number[]; // TODO: BN254;\n /** 'hash' position within the Merkle tree */\n leafIndex: number;\n};\n\nexport type MerkleContextWithMerkleProof = MerkleContext & {\n /** Recent valid 'hash' proof path, expires after n slots */\n merkleProof: BN254[];\n /** Index of state root the merkleproof is valid for, expires after n slots */\n rootIndex: number;\n /** Current root */\n root: BN254;\n};\n\nexport const createCompressedAccount = (\n owner: PublicKey,\n lamports?: BN,\n data?: CompressedAccountData,\n address?: number[],\n): CompressedAccount => ({\n owner,\n lamports: lamports ?? bn(0),\n address: address ?? null,\n data: data ?? null,\n});\n\nexport const createCompressedAccountWithMerkleContext = (\n merkleContext: MerkleContext,\n owner: PublicKey,\n lamports?: BN,\n data?: CompressedAccountData,\n address?: number[],\n): CompressedAccountWithMerkleContext => ({\n ...createCompressedAccount(owner, lamports, data, address),\n ...merkleContext,\n readOnly: false,\n});\n\nexport const createMerkleContext = (\n merkleTree: PublicKey,\n nullifierQueue: PublicKey,\n hash: number[], // TODO: BN254,\n leafIndex: number,\n): MerkleContext => ({\n merkleTree,\n nullifierQueue,\n hash,\n leafIndex,\n});\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, isLE, byteSwap32, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","const isObject = value => typeof value === 'object' && value !== null;\n\n// Customized for this use-case\nconst isObjectCustom = value =>\n\tisObject(value)\n\t&& !(value instanceof RegExp)\n\t&& !(value instanceof Error)\n\t&& !(value instanceof Date);\n\nexport const mapObjectSkip = Symbol('mapObjectSkip');\n\nconst _mapObject = (object, mapper, options, isSeen = new WeakMap()) => {\n\toptions = {\n\t\tdeep: false,\n\t\ttarget: {},\n\t\t...options,\n\t};\n\n\tif (isSeen.has(object)) {\n\t\treturn isSeen.get(object);\n\t}\n\n\tisSeen.set(object, options.target);\n\n\tconst {target} = options;\n\tdelete options.target;\n\n\tconst mapArray = array => array.map(element => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);\n\tif (Array.isArray(object)) {\n\t\treturn mapArray(object);\n\t}\n\n\tfor (const [key, value] of Object.entries(object)) {\n\t\tconst mapResult = mapper(key, value, object);\n\n\t\tif (mapResult === mapObjectSkip) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [newKey, newValue, {shouldRecurse = true} = {}] = mapResult;\n\n\t\t// Drop `__proto__` keys.\n\t\tif (newKey === '__proto__') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (options.deep && shouldRecurse && isObjectCustom(newValue)) {\n\t\t\tnewValue = Array.isArray(newValue)\n\t\t\t\t? mapArray(newValue)\n\t\t\t\t: _mapObject(newValue, mapper, options, isSeen);\n\t\t}\n\n\t\ttarget[newKey] = newValue;\n\t}\n\n\treturn target;\n};\n\nexport default function mapObject(object, mapper, options) {\n\tif (!isObject(object)) {\n\t\tthrow new TypeError(`Expected an object, got \\`${object}\\` (${typeof object})`);\n\t}\n\n\treturn _mapObject(object, mapper, options);\n}\n","const UPPERCASE = /[\\p{Lu}]/u;\nconst LOWERCASE = /[\\p{Ll}]/u;\nconst LEADING_CAPITAL = /^[\\p{Lu}](?![\\p{Lu}])/gu;\nconst IDENTIFIER = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst SEPARATORS = /[_.\\- ]+/;\n\nconst LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);\nconst SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');\nconst NUMBERS_AND_IDENTIFIER = new RegExp('\\\\d+' + IDENTIFIER.source, 'gu');\n\nconst preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase) => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\tlet isLastLastCharPreserved = false;\n\n\tfor (let index = 0; index < string.length; index++) {\n\t\tconst character = string[index];\n\t\tisLastLastCharPreserved = index > 2 ? string[index - 3] === '-' : true;\n\n\t\tif (isLastCharLower && UPPERCASE.test(character)) {\n\t\t\tstring = string.slice(0, index) + '-' + string.slice(index);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\tindex++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase)) {\n\t\t\tstring = string.slice(0, index - 1) + '-' + string.slice(index - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst preserveConsecutiveUppercase = (input, toLowerCase) => {\n\tLEADING_CAPITAL.lastIndex = 0;\n\n\treturn input.replaceAll(LEADING_CAPITAL, match => toLowerCase(match));\n};\n\nconst postProcess = (input, toUpperCase) => {\n\tSEPARATORS_AND_IDENTIFIER.lastIndex = 0;\n\tNUMBERS_AND_IDENTIFIER.lastIndex = 0;\n\n\treturn input\n\t\t.replaceAll(NUMBERS_AND_IDENTIFIER, (match, pattern, offset) => ['_', '-'].includes(input.charAt(offset + match.length)) ? match : toUpperCase(match))\n\t\t.replaceAll(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier));\n};\n\nexport default function camelCase(input, options) {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = {\n\t\tpascalCase: false,\n\t\tpreserveConsecutiveUppercase: false,\n\t\t...options,\n\t};\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tconst toLowerCase = options.locale === false\n\t\t? string => string.toLowerCase()\n\t\t: string => string.toLocaleLowerCase(options.locale);\n\n\tconst toUpperCase = options.locale === false\n\t\t? string => string.toUpperCase()\n\t\t: string => string.toLocaleUpperCase(options.locale);\n\n\tif (input.length === 1) {\n\t\tif (SEPARATORS.test(input)) {\n\t\t\treturn '';\n\t\t}\n\n\t\treturn options.pascalCase ? toUpperCase(input) : toLowerCase(input);\n\t}\n\n\tconst hasUpperCase = input !== toLowerCase(input);\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);\n\t}\n\n\tinput = input.replace(LEADING_SEPARATORS, '');\n\tinput = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);\n\n\tif (options.pascalCase) {\n\t\tinput = toUpperCase(input.charAt(0)) + input.slice(1);\n\t}\n\n\treturn postProcess(input, toUpperCase);\n}\n","export default class QuickLRU extends Map {\n\tconstructor(options = {}) {\n\t\tsuper();\n\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tif (typeof options.maxAge === 'number' && options.maxAge === 0) {\n\t\t\tthrow new TypeError('`maxAge` must be a number greater than 0');\n\t\t}\n\n\t\t// TODO: Use private class fields when ESLint supports them.\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.maxAge = options.maxAge || Number.POSITIVE_INFINITY;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t// TODO: Use private class methods when targeting Node.js 16.\n\t_emitEvictions(cache) {\n\t\tif (typeof this.onEviction !== 'function') {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const [key, item] of cache) {\n\t\t\tthis.onEviction(key, item.value);\n\t\t}\n\t}\n\n\t_deleteIfExpired(key, item) {\n\t\tif (typeof item.expiry === 'number' && item.expiry <= Date.now()) {\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tthis.onEviction(key, item.value);\n\t\t\t}\n\n\t\t\treturn this.delete(key);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t_getOrDeleteIfExpired(key, item) {\n\t\tconst deleted = this._deleteIfExpired(key, item);\n\t\tif (deleted === false) {\n\t\t\treturn item.value;\n\t\t}\n\t}\n\n\t_getItemValue(key, item) {\n\t\treturn item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;\n\t}\n\n\t_peek(key, cache) {\n\t\tconst item = cache.get(key);\n\n\t\treturn this._getItemValue(key, item);\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\t\t\tthis._emitEvictions(this.oldCache);\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\t_moveToRecent(key, item) {\n\t\tthis.oldCache.delete(key);\n\t\tthis._set(key, item);\n\t}\n\n\t* _entriesAscending() {\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield item;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\tconst item = this.cache.get(key);\n\n\t\t\treturn this._getItemValue(key, item);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst item = this.oldCache.get(key);\n\t\t\tif (this._deleteIfExpired(key, item) === false) {\n\t\t\t\tthis._moveToRecent(key, item);\n\t\t\t\treturn item.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tset(key, value, {maxAge = this.maxAge} = {}) {\n\t\tconst expiry =\n\t\t\ttypeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?\n\t\t\t\tDate.now() + maxAge :\n\t\t\t\tundefined;\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, {\n\t\t\t\tvalue,\n\t\t\t\texpiry\n\t\t\t});\n\t\t} else {\n\t\t\tthis._set(key, {value, expiry});\n\t\t}\n\n\t\treturn this;\n\t}\n\n\thas(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.cache.get(key));\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn !this._deleteIfExpired(key, this.oldCache.get(key));\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this._peek(key, this.cache);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this._peek(key, this.oldCache);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\tresize(newSize) {\n\t\tif (!(newSize && newSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tconst items = [...this._entriesAscending()];\n\t\tconst removeCount = items.length - newSize;\n\t\tif (removeCount < 0) {\n\t\t\tthis.cache = new Map(items);\n\t\t\tthis.oldCache = new Map();\n\t\t\tthis._size = items.length;\n\t\t} else {\n\t\t\tif (removeCount > 0) {\n\t\t\t\tthis._emitEvictions(items.slice(0, removeCount));\n\t\t\t}\n\n\t\t\tthis.oldCache = new Map(items.slice(removeCount));\n\t\t\tthis.cache = new Map();\n\t\t\tthis._size = 0;\n\t\t}\n\n\t\tthis.maxSize = newSize;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesDescending() {\n\t\tlet items = [...this.cache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\tif (deleted === false) {\n\t\t\t\tyield [key, value.value];\n\t\t\t}\n\t\t}\n\n\t\titems = [...this.oldCache];\n\t\tfor (let i = items.length - 1; i >= 0; --i) {\n\t\t\tconst item = items[i];\n\t\t\tconst [key, value] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tconst deleted = this._deleteIfExpired(key, value);\n\t\t\t\tif (deleted === false) {\n\t\t\t\t\tyield [key, value.value];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t* entriesAscending() {\n\t\tfor (const [key, value] of this._entriesAscending()) {\n\t\t\tyield [key, value.value];\n\t\t}\n\t}\n\n\tget size() {\n\t\tif (!this._size) {\n\t\t\treturn this.oldCache.size;\n\t\t}\n\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n\n\tentries() {\n\t\treturn this.entriesAscending();\n\t}\n\n\tforEach(callbackFunction, thisArgument = this) {\n\t\tfor (const [key, value] of this.entriesAscending()) {\n\t\t\tcallbackFunction.call(thisArgument, value, key, this);\n\t\t}\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn JSON.stringify([...this.entriesAscending()]);\n\t}\n}\n","import mapObject from 'map-obj';\nimport camelCase from 'camelcase';\nimport QuickLru from 'quick-lru';\n\nconst has = (array, key) => array.some(element => {\n\tif (typeof element === 'string') {\n\t\treturn element === key;\n\t}\n\n\telement.lastIndex = 0;\n\n\treturn element.test(key);\n});\n\nconst cache = new QuickLru({maxSize: 100_000});\n\n// Reproduces behavior from `map-obj`.\nconst isObject = value =>\n\ttypeof value === 'object'\n\t\t&& value !== null\n\t\t&& !(value instanceof RegExp)\n\t\t&& !(value instanceof Error)\n\t\t&& !(value instanceof Date);\n\nconst transform = (input, options = {}) => {\n\tif (!isObject(input)) {\n\t\treturn input;\n\t}\n\n\tconst {\n\t\texclude,\n\t\tpascalCase = false,\n\t\tstopPaths,\n\t\tdeep = false,\n\t\tpreserveConsecutiveUppercase = false,\n\t} = options;\n\n\tconst stopPathsSet = new Set(stopPaths);\n\n\tconst makeMapper = parentPath => (key, value) => {\n\t\tif (deep && isObject(value)) {\n\t\t\tconst path = parentPath === undefined ? key : `${parentPath}.${key}`;\n\n\t\t\tif (!stopPathsSet.has(path)) {\n\t\t\t\tvalue = mapObject(value, makeMapper(path));\n\t\t\t}\n\t\t}\n\n\t\tif (!(exclude && has(exclude, key))) {\n\t\t\tconst cacheKey = pascalCase ? `${key}_` : key;\n\n\t\t\tif (cache.has(cacheKey)) {\n\t\t\t\tkey = cache.get(cacheKey);\n\t\t\t} else {\n\t\t\t\tconst returnValue = camelCase(key, {pascalCase, locale: false, preserveConsecutiveUppercase});\n\n\t\t\t\tif (key.length < 100) { // Prevent abuse\n\t\t\t\t\tcache.set(cacheKey, returnValue);\n\t\t\t\t}\n\n\t\t\t\tkey = returnValue;\n\t\t\t}\n\t\t}\n\n\t\treturn [key, value];\n\t};\n\n\treturn mapObject(input, makeMapper(undefined));\n};\n\nexport default function camelcaseKeys(input, options) {\n\tif (Array.isArray(input)) {\n\t\treturn Object.keys(input).map(key => transform(input[key], options));\n\t}\n\n\treturn transform(input, options);\n}\n","import { Buffer } from 'buffer';\nimport { bn, createBN254 } from '../state/BN254';\nimport { FIELD_SIZE } from '../constants';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { Keypair } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport camelcaseKeys from 'camelcase-keys';\n\nexport function byteArrayToKeypair(byteArray: number[]): Keypair {\n return Keypair.fromSecretKey(Uint8Array.from(byteArray));\n}\n/**\n * @internal\n * convert BN to hex with '0x' prefix\n */\nexport function toHex(bn: BN): string {\n return '0x' + bn.toString('hex');\n}\n\nexport const toArray = <T>(value: T | T[]) =>\n Array.isArray(value) ? value : [value];\n\nexport const bufToDecStr = (buf: Buffer): string => {\n return createBN254(buf).toString();\n};\nexport function isSmallerThanBn254FieldSizeBe(bytes: Buffer): boolean {\n const bigint = bn(bytes, undefined, 'be');\n return bigint.lt(FIELD_SIZE);\n}\n\nexport const toCamelCase = (object: any) =>\n camelcaseKeys(object, { deep: true });\n\n/**\n/**\n * Hash the provided `bytes` with Keccak256 and ensure the result fits in the\n * BN254 prime field by repeatedly hashing the inputs with various \"bump seeds\"\n * and truncating the resulting hash to 31 bytes.\n *\n * @deprecated Use `hashvToBn254FieldSizeBe` instead.\n */\nexport function hashToBn254FieldSizeBe(bytes: Buffer): [Buffer, number] | null {\n // TODO(vadorovsky, affects-onchain): Get rid of the bump mechanism, it\n // makes no sense. Doing the same as in the `hashvToBn254FieldSizeBe` below\n // - overwriting the most significant byte with zero - is sufficient for\n // truncation, it's also faster, doesn't force us to return `Option` and\n // care about handling an error which is practically never returned.\n //\n // The reason we can't do it now is that it would affect on-chain programs.\n // Once we can update programs, we can get rid of the seed bump (or even of\n // this function all together in favor of the `hashv` variant).\n let bumpSeed = 255;\n while (bumpSeed >= 0) {\n const inputWithBumpSeed = Buffer.concat([\n bytes,\n Buffer.from([bumpSeed]),\n ]);\n const hash = keccak_256(inputWithBumpSeed);\n if (hash.length !== 32) {\n throw new Error('Invalid hash length');\n }\n hash[0] = 0;\n\n if (isSmallerThanBn254FieldSizeBe(Buffer.from(hash))) {\n return [Buffer.from(hash), bumpSeed];\n }\n\n bumpSeed -= 1;\n }\n return null;\n}\n\n/**\n * Hash the provided `bytes` with Keccak256 and ensure that the result fits in\n * the BN254 prime field by truncating the resulting hash to 31 bytes.\n *\n * @param bytes Input bytes\n *\n * @returns Hash digest\n */\nexport function hashvToBn254FieldSizeBe(bytes: Uint8Array[]): Uint8Array {\n const hasher = keccak_256.create();\n for (const input of bytes) {\n hasher.update(input);\n }\n const hash = hasher.digest();\n hash[0] = 0;\n return hash;\n}\n\n/** Mutates array in place */\nexport function pushUniqueItems<T>(items: T[], map: T[]): void {\n items.forEach(item => {\n if (!map.includes(item)) {\n map.push(item);\n }\n });\n}\n","import { AccountMeta, PublicKey } from '@solana/web3.js';\nimport {\n CompressedAccount,\n OutputCompressedAccountWithPackedContext,\n PackedCompressedAccountWithMerkleContext,\n} from '../state';\nimport { CompressedAccountWithMerkleContext } from '../state/compressed-account';\nimport { toArray } from '../utils/conversion';\n\n/**\n * @internal Finds the index of a PublicKey in an array, or adds it if not\n * present\n * */\nexport function getIndexOrAdd(\n accountsArray: PublicKey[],\n key: PublicKey,\n): number {\n const index = accountsArray.findIndex(existingKey =>\n existingKey.equals(key),\n );\n if (index === -1) {\n accountsArray.push(key);\n return accountsArray.length - 1;\n }\n return index;\n}\n\n/**\n * @internal\n * Pads output state trees with the 0th state tree of the input state.\n *\n * @param outputStateMerkleTrees Optional output state trees to be\n * inserted into the output state.\n * Defaults to the 0th state tree of\n * the input state. Gets padded to the\n * length of outputCompressedAccounts.\n * @param numberOfOutputCompressedAccounts The number of output compressed\n * accounts.\n * @param inputCompressedAccountsWithMerkleContext The input compressed accounts\n * with merkle context.\n *\n * @returns Padded output state trees.\n */\nexport function padOutputStateMerkleTrees(\n outputStateMerkleTrees: PublicKey[] | PublicKey | undefined,\n numberOfOutputCompressedAccounts: number,\n inputCompressedAccountsWithMerkleContext: CompressedAccountWithMerkleContext[],\n): PublicKey[] {\n if (numberOfOutputCompressedAccounts <= 0) {\n return [];\n }\n\n /// Default: use the 0th state tree of input state for all output accounts\n if (outputStateMerkleTrees === undefined) {\n if (inputCompressedAccountsWithMerkleContext.length === 0) {\n throw new Error(\n 'No input compressed accounts nor output state trees provided. Please pass in at least one of the following: outputStateMerkleTree or inputCompressedAccount',\n );\n }\n return new Array(numberOfOutputCompressedAccounts).fill(\n inputCompressedAccountsWithMerkleContext[0].merkleTree,\n );\n /// Align the number of output state trees with the number of output\n /// accounts, and fill up with 0th output state tree\n } else {\n /// Into array\n const treesArray = toArray(outputStateMerkleTrees);\n if (treesArray.length >= numberOfOutputCompressedAccounts) {\n return treesArray.slice(0, numberOfOutputCompressedAccounts);\n } else {\n return treesArray.concat(\n new Array(\n numberOfOutputCompressedAccounts - treesArray.length,\n ).fill(treesArray[0]),\n );\n }\n }\n}\n\nexport function toAccountMetas(remainingAccounts: PublicKey[]): AccountMeta[] {\n return remainingAccounts.map(\n (account): AccountMeta => ({\n pubkey: account,\n isWritable: true,\n isSigner: false,\n }),\n );\n}\n\n/**\n * Packs Compressed Accounts.\n *\n * Replaces PublicKey with index pointer to remaining accounts.\n *\n *\n * @param inputCompressedAccounts Ix input state to be consumed\n * @param inputStateRootIndices The recent state root indices of the\n * input state. The expiry is tied to\n * the proof.\n * @param outputCompressedAccounts Ix output state to be created\n * @param outputStateMerkleTrees Optional output state trees to be\n * inserted into the output state.\n * Defaults to the 0th state tree of\n * the input state. Gets padded to the\n * length of outputCompressedAccounts.\n *\n * @param remainingAccounts Optional existing array of accounts\n * to append to.\n **/\nexport function packCompressedAccounts(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n inputStateRootIndices: number[],\n outputCompressedAccounts: CompressedAccount[],\n outputStateMerkleTrees?: PublicKey[] | PublicKey,\n remainingAccounts: PublicKey[] = [],\n): {\n packedInputCompressedAccounts: PackedCompressedAccountWithMerkleContext[];\n packedOutputCompressedAccounts: OutputCompressedAccountWithPackedContext[];\n remainingAccounts: PublicKey[];\n} {\n const _remainingAccounts = remainingAccounts.slice();\n\n const packedInputCompressedAccounts: PackedCompressedAccountWithMerkleContext[] =\n [];\n\n const packedOutputCompressedAccounts: OutputCompressedAccountWithPackedContext[] =\n [];\n\n /// input\n inputCompressedAccounts.forEach((account, index) => {\n const merkleTreePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.merkleTree,\n );\n\n const nullifierQueuePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.nullifierQueue,\n );\n\n packedInputCompressedAccounts.push({\n compressedAccount: {\n owner: account.owner,\n lamports: account.lamports,\n address: account.address,\n data: account.data,\n },\n merkleContext: {\n merkleTreePubkeyIndex,\n nullifierQueuePubkeyIndex,\n leafIndex: account.leafIndex,\n queueIndex: null,\n },\n rootIndex: inputStateRootIndices[index],\n readOnly: false,\n });\n });\n\n if (\n outputStateMerkleTrees === undefined &&\n inputCompressedAccounts.length === 0\n ) {\n throw new Error(\n 'No input compressed accounts nor output state trees provided. Please pass in at least one of the following: outputStateMerkleTree or inputCompressedAccount',\n );\n }\n /// output\n const paddedOutputStateMerkleTrees = padOutputStateMerkleTrees(\n outputStateMerkleTrees,\n outputCompressedAccounts.length,\n inputCompressedAccounts,\n );\n\n outputCompressedAccounts.forEach((account, index) => {\n const merkleTreePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n paddedOutputStateMerkleTrees[index],\n );\n packedOutputCompressedAccounts.push({\n compressedAccount: {\n owner: account.owner,\n lamports: account.lamports,\n address: account.address,\n data: account.data,\n },\n merkleTreeIndex: merkleTreePubkeyIndex,\n });\n });\n\n return {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts: _remainingAccounts,\n };\n}\n","import BN from 'bn.js';\nimport {\n CompressedAccount,\n CompressedAccountWithMerkleContext,\n bn,\n} from '../state';\n\nexport const validateSufficientBalance = (balance: BN) => {\n if (balance.lt(bn(0))) {\n throw new Error('Not enough balance for transfer');\n }\n};\n\nexport const validateSameOwner = (\n compressedAccounts:\n | CompressedAccount[]\n | CompressedAccountWithMerkleContext[],\n) => {\n if (compressedAccounts.length === 0) {\n throw new Error('No accounts provided for validation');\n }\n const zerothOwner = compressedAccounts[0].owner;\n if (\n !compressedAccounts.every(account => account.owner.equals(zerothOwner))\n ) {\n throw new Error('All input accounts must have the same owner');\n }\n};\n\n/// for V1 circuits.\nexport const validateNumbersForProof = (\n hashesLength: number,\n newAddressesLength: number,\n) => {\n if (hashesLength > 0 && newAddressesLength > 0) {\n if (hashesLength === 8) {\n throw new Error(\n `Invalid number of compressed accounts for proof: ${hashesLength}. Allowed numbers: ${[1, 2, 3, 4].join(', ')}`,\n );\n }\n validateNumbers(hashesLength, [1, 2, 3, 4], 'compressed accounts');\n validateNumbersForNonInclusionProof(newAddressesLength);\n } else {\n if (hashesLength > 0) {\n validateNumbersForInclusionProof(hashesLength);\n } else {\n validateNumbersForNonInclusionProof(newAddressesLength);\n }\n }\n};\n\n/// Ensure that the amount if compressed accounts is allowed.\nexport const validateNumbersForInclusionProof = (hashesLength: number) => {\n validateNumbers(hashesLength, [1, 2, 3, 4, 8], 'compressed accounts');\n};\n\n/// Ensure that the amount if new addresses is allowed.\nexport const validateNumbersForNonInclusionProof = (\n newAddressesLength: number,\n) => {\n validateNumbers(newAddressesLength, [1, 2], 'new addresses');\n};\n\n/// V1 circuit safeguards.\nexport const validateNumbers = (\n length: number,\n allowedNumbers: number[],\n type: string,\n) => {\n if (!allowedNumbers.includes(length)) {\n throw new Error(\n `Invalid number of ${type}: ${length}. Allowed numbers: ${allowedNumbers.join(', ')}`,\n );\n }\n};\n","import { AccountMeta, PublicKey } from '@solana/web3.js';\nimport { hashToBn254FieldSizeBe, hashvToBn254FieldSizeBe } from './conversion';\nimport { defaultTestStateTreeAccounts } from '../constants';\nimport { getIndexOrAdd } from '../instruction';\n\nexport function deriveAddressSeed(\n seeds: Uint8Array[],\n programId: PublicKey,\n): Uint8Array {\n const combinedSeeds: Uint8Array[] = [programId.toBytes(), ...seeds];\n const hash = hashvToBn254FieldSizeBe(combinedSeeds);\n return hash;\n}\n\n/**\n * Derive an address for a compressed account from a seed and an address Merkle\n * tree public key.\n *\n * @param seed Seed to derive the address from\n * @param addressMerkleTreePubkey Merkle tree public key. Defaults to\n * defaultTestStateTreeAccounts().addressTree\n * @returns Derived address\n */\nexport function deriveAddress(\n seed: Uint8Array,\n addressMerkleTreePubkey: PublicKey = defaultTestStateTreeAccounts()\n .addressTree,\n): PublicKey {\n if (seed.length != 32) {\n throw new Error('Seed length is not 32 bytes.');\n }\n const bytes = addressMerkleTreePubkey.toBytes();\n const combined = Buffer.from([...bytes, ...seed]);\n const hash = hashToBn254FieldSizeBe(combined);\n\n if (hash === null) {\n throw new Error('DeriveAddressError');\n }\n const buf = hash[0];\n return new PublicKey(buf);\n}\n\nexport interface NewAddressParams {\n /**\n * Seed for the compressed account. Must be seed used to derive\n * newAccountAddress\n */\n seed: Uint8Array;\n /**\n * Recent state root index of the address tree. The expiry is tied to the\n * validity proof.\n */\n addressMerkleTreeRootIndex: number;\n /**\n * Address tree pubkey. Must be base pubkey used to derive new address\n */\n addressMerkleTreePubkey: PublicKey;\n /**\n * Address space queue pubkey. Associated with the state tree.\n */\n addressQueuePubkey: PublicKey;\n}\n\nexport interface NewAddressParamsPacked {\n /**\n * Seed for the compressed account. Must be seed used to derive\n * newAccountAddress\n */\n seed: number[];\n /**\n * Recent state root index of the address tree. The expiry is tied to the\n * validity proof.\n */\n addressMerkleTreeRootIndex: number;\n /**\n * Index of the address merkle tree account in the remaining accounts array\n */\n addressMerkleTreeAccountIndex: number;\n /**\n * Index of the address queue account in the remaining accounts array\n */\n addressQueueAccountIndex: number;\n}\n\n/**\n * Packs new address params for instruction data in TypeScript clients\n *\n * @param newAddressParams New address params\n * @param remainingAccounts Remaining accounts\n * @returns Packed new address params\n */\nexport function packNewAddressParams(\n newAddressParams: NewAddressParams[],\n remainingAccounts: PublicKey[],\n): {\n newAddressParamsPacked: NewAddressParamsPacked[];\n remainingAccounts: PublicKey[];\n} {\n const _remainingAccounts = remainingAccounts.slice();\n\n const newAddressParamsPacked: NewAddressParamsPacked[] =\n newAddressParams.map(x => ({\n seed: Array.from(x.seed),\n addressMerkleTreeRootIndex: x.addressMerkleTreeRootIndex,\n addressMerkleTreeAccountIndex: 0, // will be assigned later\n addressQueueAccountIndex: 0, // will be assigned later\n }));\n\n newAddressParams.forEach((params, i) => {\n newAddressParamsPacked[i].addressMerkleTreeAccountIndex = getIndexOrAdd(\n _remainingAccounts,\n params.addressMerkleTreePubkey,\n );\n });\n\n newAddressParams.forEach((params, i) => {\n newAddressParamsPacked[i].addressQueueAccountIndex = getIndexOrAdd(\n _remainingAccounts,\n params.addressQueuePubkey,\n );\n });\n\n return { newAddressParamsPacked, remainingAccounts: _remainingAccounts };\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n const programId = new PublicKey(\n '7yucc7fL3JGbyMwg4neUaenNSdySS39hbAk89Ao3t1Hz',\n );\n\n describe('derive address seed', () => {\n it('should derive a valid address seed', () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('foo'),\n new TextEncoder().encode('bar'),\n ];\n expect(deriveAddressSeed(seeds, programId)).toStrictEqual(\n new Uint8Array([\n 0, 246, 150, 3, 192, 95, 53, 123, 56, 139, 206, 179, 253,\n 133, 115, 103, 120, 155, 251, 72, 250, 47, 117, 217, 118,\n 59, 174, 207, 49, 101, 201, 110,\n ]),\n );\n });\n\n it('should derive a valid address seed', () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('ayy'),\n new TextEncoder().encode('lmao'),\n ];\n expect(deriveAddressSeed(seeds, programId)).toStrictEqual(\n new Uint8Array([\n 0, 202, 44, 25, 221, 74, 144, 92, 69, 168, 38, 19, 206, 208,\n 29, 162, 53, 27, 120, 214, 152, 116, 15, 107, 212, 168, 33,\n 121, 187, 10, 76, 233,\n ]),\n );\n });\n });\n\n describe('deriveAddress function', () => {\n it('should derive a valid address from a seed and a merkle tree public key', async () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('foo'),\n new TextEncoder().encode('bar'),\n ];\n const seed = deriveAddressSeed(seeds, programId);\n const merkleTreePubkey = new PublicKey(\n '11111111111111111111111111111111',\n );\n const derivedAddress = deriveAddress(seed, merkleTreePubkey);\n expect(derivedAddress).toBeInstanceOf(PublicKey);\n expect(derivedAddress).toStrictEqual(\n new PublicKey('139uhyyBtEh4e1CBDJ68ooK5nCeWoncZf9HPyAfRrukA'),\n );\n });\n\n it('should derive a valid address from a seed and a merkle tree public key', async () => {\n const seeds: Uint8Array[] = [\n new TextEncoder().encode('ayy'),\n new TextEncoder().encode('lmao'),\n ];\n const seed = deriveAddressSeed(seeds, programId);\n const merkleTreePubkey = new PublicKey(\n '11111111111111111111111111111111',\n );\n const derivedAddress = deriveAddress(seed, merkleTreePubkey);\n expect(derivedAddress).toBeInstanceOf(PublicKey);\n expect(derivedAddress).toStrictEqual(\n new PublicKey('12bhHm6PQjbNmEn3Yu1Gq9k7XwVn2rZpzYokmLwbFazN'),\n );\n });\n });\n\n describe('packNewAddressParams function', () => {\n it('should pack new address params correctly', () => {\n const newAddressParams = [\n {\n seed: new Uint8Array([1, 2, 3, 4]),\n addressMerkleTreeRootIndex: 0,\n addressMerkleTreePubkey: new PublicKey(\n '11111111111111111111111111111111',\n ),\n addressQueuePubkey: new PublicKey(\n '11111111111111111111111111111112',\n ),\n },\n ];\n const remainingAccounts = [\n new PublicKey('11111111111111111111111111111112'),\n new PublicKey('11111111111111111111111111111111'),\n ];\n const packedParams = packNewAddressParams(\n newAddressParams,\n remainingAccounts,\n );\n expect(\n packedParams.newAddressParamsPacked[0]\n .addressMerkleTreeAccountIndex,\n ).toBe(1);\n expect(\n packedParams.newAddressParamsPacked[0].addressQueueAccountIndex,\n ).toBe(0);\n });\n });\n}\n","import {\n Commitment,\n Connection,\n PublicKey,\n TransactionConfirmationStrategy,\n} from '@solana/web3.js';\n\nexport async function airdropSol({\n connection,\n lamports,\n recipientPublicKey,\n}: {\n connection: Connection;\n lamports: number;\n recipientPublicKey: PublicKey;\n}) {\n const txHash = await connection.requestAirdrop(\n recipientPublicKey,\n lamports,\n );\n await confirmTransaction(connection, txHash);\n return txHash;\n}\n\nexport async function confirmTransaction(\n connection: Connection,\n signature: string,\n confirmation: Commitment = 'confirmed',\n) {\n const latestBlockHash = await connection.getLatestBlockhash(confirmation);\n const strategy: TransactionConfirmationStrategy = {\n signature: signature.toString(),\n lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,\n blockhash: latestBlockHash.blockhash,\n };\n return await connection.confirmTransaction(strategy, confirmation);\n}\n","import BN from 'bn.js';\nimport { FIELD_SIZE } from '../constants';\nimport { CompressedProof } from '../state';\n\ninterface GnarkProofJson {\n ar: string[];\n bs: string[][];\n krs: string[];\n}\n\ntype ProofABC = {\n a: Uint8Array;\n b: Uint8Array;\n c: Uint8Array;\n};\n\nexport const placeholderValidityProof = () => ({\n a: Array.from({ length: 32 }, (_, i) => i + 1),\n b: Array.from({ length: 64 }, (_, i) => i + 1),\n c: Array.from({ length: 32 }, (_, i) => i + 1),\n});\n\nexport const checkValidityProofShape = (proof: CompressedProof) => {\n if (\n proof.a.length !== 32 ||\n proof.b.length !== 64 ||\n proof.c.length !== 32\n ) {\n throw new Error('ValidityProof has invalid shape');\n }\n};\n\nexport function proofFromJsonStruct(json: GnarkProofJson): ProofABC {\n const proofAX = deserializeHexStringToBeBytes(json.ar[0]);\n const proofAY = deserializeHexStringToBeBytes(json.ar[1]);\n const proofA: Uint8Array = new Uint8Array([...proofAX, ...proofAY]);\n\n const proofBX0 = deserializeHexStringToBeBytes(json.bs[0][0]);\n const proofBX1 = deserializeHexStringToBeBytes(json.bs[0][1]);\n const proofBY0 = deserializeHexStringToBeBytes(json.bs[1][0]);\n const proofBY1 = deserializeHexStringToBeBytes(json.bs[1][1]);\n const proofB: Uint8Array = new Uint8Array([\n ...proofBX0,\n ...proofBX1,\n ...proofBY0,\n ...proofBY1,\n ]);\n\n const proofCX = deserializeHexStringToBeBytes(json.krs[0]);\n const proofCY = deserializeHexStringToBeBytes(json.krs[1]);\n const proofC: Uint8Array = new Uint8Array([...proofCX, ...proofCY]);\n\n const proofABC: ProofABC = { a: proofA, b: proofB, c: proofC };\n return proofABC;\n}\n\n// TODO: add unit test for negation\n// TODO: test if LE BE issue. unit test\nexport function negateAndCompressProof(proof: ProofABC): CompressedProof {\n const proofA = proof.a;\n const proofB = proof.b;\n const proofC = proof.c;\n\n const aXElement = proofA.slice(0, 32);\n const aYElement = new BN(proofA.slice(32, 64), 32, 'be');\n\n /// Negate\n const proofAIsPositive = yElementIsPositiveG1(aYElement) ? false : true;\n /// First byte of proofA is the bitmask\n aXElement[0] = addBitmaskToByte(aXElement[0], proofAIsPositive);\n\n const bXElement = proofB.slice(0, 64);\n const bYElement = proofB.slice(64, 128);\n\n const proofBIsPositive = yElementIsPositiveG2(\n new BN(bYElement.slice(0, 32), 32, 'be'),\n new BN(bYElement.slice(32, 64), 32, 'be'),\n );\n\n bXElement[0] = addBitmaskToByte(bXElement[0], proofBIsPositive);\n\n const cXElement = proofC.slice(0, 32);\n const cYElement = proofC.slice(32, 64);\n const proofCIsPositive = yElementIsPositiveG1(new BN(cYElement, 32, 'be'));\n cXElement[0] = addBitmaskToByte(cXElement[0], proofCIsPositive);\n\n const compressedProof: CompressedProof = {\n a: Array.from(aXElement),\n b: Array.from(bXElement),\n c: Array.from(cXElement),\n };\n\n return compressedProof;\n}\n\nfunction deserializeHexStringToBeBytes(hexStr: string): Uint8Array {\n // Using BN for simpler conversion from hex string to byte array\n const bn = new BN(\n hexStr.startsWith('0x') ? hexStr.substring(2) : hexStr,\n 'hex',\n );\n return new Uint8Array(bn.toArray('be', 32));\n}\n\nfunction yElementIsPositiveG1(yElement: BN): boolean {\n return yElement.lte(FIELD_SIZE.sub(yElement));\n}\n\nfunction yElementIsPositiveG2(yElement1: BN, yElement2: BN): boolean {\n const fieldMidpoint = FIELD_SIZE.div(new BN(2));\n\n // Compare the first component of the y coordinate\n if (yElement1.lt(fieldMidpoint)) {\n return true;\n } else if (yElement1.gt(fieldMidpoint)) {\n return false;\n }\n\n // If the first component is equal to the midpoint, compare the second component\n return yElement2.lt(fieldMidpoint);\n}\n// bitmask compatible with solana altbn128 compression syscall and arkworks' implementation\n// https://github.com/arkworks-rs/algebra/blob/master/ff/src/fields/models/fp/mod.rs#L580\n// https://github.com/arkworks-rs/algebra/blob/master/serialize/src/flags.rs#L18\n// fn u8_bitmask(value: u8, inf: bool, neg: bool) -> u8 {\n// let mut mask = 0;\n// match self {\n// inf => mask |= 1 << 6,\n// neg => mask |= 1 << 7,\n// _ => (),\n// }\n// mask\n// }\nfunction addBitmaskToByte(byte: number, yIsPositive: boolean): number {\n if (!yIsPositive) {\n return (byte |= 1 << 7);\n } else {\n return byte;\n }\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n // Unit test for addBitmaskToByte function\n describe('addBitmaskToByte', () => {\n it('should add a bitmask to the byte if yIsPositive is false', () => {\n const byte = 0b00000000;\n const yIsPositive = false;\n const result = addBitmaskToByte(byte, yIsPositive);\n expect(result).toBe(0b10000000); // 128 in binary, which is 1 << 7\n });\n\n it('should not modify the byte if yIsPositive is true', () => {\n const byte = 0b00000000;\n const yIsPositive = true;\n const result = addBitmaskToByte(byte, yIsPositive);\n expect(result).toBe(0b00000000);\n });\n });\n\n describe('test prover server', () => {\n const TEST_JSON = {\n ar: [\n '0x22bdaa3187d8fe294925a66fa0165a11bc9e07678fa2fc72402ebfd33d521c69',\n '0x2d18ff780b69898b4cdd8d7b6ac72d077799399f0f45e52665426456f3903584',\n ],\n bs: [\n [\n '0x138cc0962e49f76a701d2871d2799892c9782940095eb0429e979f336d2e162d',\n '0x2fe1bfbb15cbfb83d7e00ace23e45f890604003783eaf34affa35e0d6f4822bc',\n ],\n [\n '0x1a89264f82cc6e8ef1c696bea0b5803c28c0ba6ab61366bcb71e73a4135cae8d',\n '0xf778d857b3df01a4100265c9d014ce02d47425f0114685356165fa5ee3f3a26',\n ],\n ],\n krs: [\n '0x176b6ae9001f66832951e2d43a98a972667447bb1781f534b70cb010270dcdd3',\n '0xb748d5fac1686db28d94c02250af7eb4f28dfdabc8983305c45bcbc6e163eeb',\n ],\n };\n const COMPRESSED_PROOF_A = [\n 34, 189, 170, 49, 135, 216, 254, 41, 73, 37, 166, 111, 160, 22, 90,\n 17, 188, 158, 7, 103, 143, 162, 252, 114, 64, 46, 191, 211, 61, 82,\n 28, 105,\n ];\n const COMPRESSED_PROOF_B = [\n 147, 140, 192, 150, 46, 73, 247, 106, 112, 29, 40, 113, 210, 121,\n 152, 146, 201, 120, 41, 64, 9, 94, 176, 66, 158, 151, 159, 51, 109,\n 46, 22, 45, 47, 225, 191, 187, 21, 203, 251, 131, 215, 224, 10, 206,\n 35, 228, 95, 137, 6, 4, 0, 55, 131, 234, 243, 74, 255, 163, 94, 13,\n 111, 72, 34, 188,\n ];\n const COMPRESSED_PROOF_C = [\n 23, 107, 106, 233, 0, 31, 102, 131, 41, 81, 226, 212, 58, 152, 169,\n 114, 102, 116, 71, 187, 23, 129, 245, 52, 183, 12, 176, 16, 39, 13,\n 205, 211,\n ];\n\n it('should execute a compressed token mint', async () => {\n const proof = proofFromJsonStruct(TEST_JSON);\n const compressedProof = negateAndCompressProof(proof);\n expect(compressedProof.a).toEqual(COMPRESSED_PROOF_A);\n expect(compressedProof.b).toEqual(COMPRESSED_PROOF_B);\n expect(compressedProof.c).toEqual(COMPRESSED_PROOF_C);\n });\n });\n describe('Validity Proof Functions', () => {\n describe('placeholderValidityProof', () => {\n it('should create a validity proof with correct shape', () => {\n const validityProof = placeholderValidityProof();\n expect(validityProof.a.length).toBe(32);\n expect(validityProof.b.length).toBe(64);\n expect(validityProof.c.length).toBe(32);\n });\n });\n\n describe('checkValidityProofShape', () => {\n it('should not throw an error for valid proof shape', () => {\n const validProof = {\n a: Array.from(new Uint8Array(32)),\n b: Array.from(new Uint8Array(64)),\n c: Array.from(new Uint8Array(32)),\n };\n expect(() => checkValidityProofShape(validProof)).not.toThrow();\n });\n\n it('should throw an error for an invalid proof', () => {\n const invalidProof = {\n a: Array.from(new Uint8Array(31)), // incorrect length\n b: Array.from(new Uint8Array(64)),\n c: Array.from(new Uint8Array(32)),\n };\n expect(() => checkValidityProofShape(invalidProof)).toThrow(\n 'ValidityProof has invalid shape',\n );\n });\n });\n });\n}\n","import {\n VersionedTransaction,\n TransactionConfirmationStrategy,\n SignatureResult,\n RpcResponseAndContext,\n Signer,\n TransactionInstruction,\n TransactionMessage,\n ConfirmOptions,\n TransactionSignature,\n PublicKey,\n AddressLookupTableAccount,\n} from '@solana/web3.js';\nimport { Rpc } from '../rpc';\n\n/**\n * Builds a versioned Transaction from instructions.\n *\n * @param instructions instructions to include\n * @param payerPublicKey fee payer public key\n * @param blockhash blockhash to use\n * @param lookupTableAccounts lookup table accounts to include\n *\n * @return VersionedTransaction\n */\nexport function buildTx(\n instructions: TransactionInstruction[],\n payerPublicKey: PublicKey,\n blockhash: string,\n lookupTableAccounts?: AddressLookupTableAccount[],\n): VersionedTransaction {\n const messageV0 = new TransactionMessage({\n payerKey: payerPublicKey,\n recentBlockhash: blockhash,\n instructions,\n }).compileToV0Message(lookupTableAccounts);\n\n return new VersionedTransaction(messageV0);\n}\n\n/**\n * Sends a versioned transaction and confirms it.\n *\n * @param rpc connection to use\n * @param tx versioned transaction to send\n * @param confirmOptions confirmation options\n * @param blockHashCtx blockhash context for confirmation\n *\n * @return TransactionSignature\n */\nexport async function sendAndConfirmTx(\n rpc: Rpc,\n tx: VersionedTransaction,\n confirmOptions?: ConfirmOptions,\n blockHashCtx?: { blockhash: string; lastValidBlockHeight: number },\n): Promise<TransactionSignature> {\n const txId = await rpc.sendTransaction(tx, confirmOptions);\n\n if (!blockHashCtx) blockHashCtx = await rpc.getLatestBlockhash();\n\n const transactionConfirmationStrategy0: TransactionConfirmationStrategy = {\n signature: txId,\n blockhash: blockHashCtx.blockhash,\n lastValidBlockHeight: blockHashCtx.lastValidBlockHeight,\n };\n\n const ctxAndRes = await rpc.confirmTransaction(\n transactionConfirmationStrategy0,\n confirmOptions?.commitment || rpc.commitment || 'confirmed',\n );\n const slot = ctxAndRes.context.slot;\n await rpc.confirmTransactionIndexed(slot);\n return txId;\n}\n\n/**\n * Confirms a transaction with a given txId.\n *\n * @param rpc connection to use\n * @param txId transaction signature to confirm\n * @param confirmOptions confirmation options\n * @param blockHashCtx blockhash context for confirmation\n * @return SignatureResult\n */\nexport async function confirmTx(\n rpc: Rpc,\n txId: string,\n confirmOptions?: ConfirmOptions,\n blockHashCtx?: { blockhash: string; lastValidBlockHeight: number },\n): Promise<RpcResponseAndContext<SignatureResult>> {\n if (!blockHashCtx) blockHashCtx = await rpc.getLatestBlockhash();\n\n const transactionConfirmationStrategy: TransactionConfirmationStrategy = {\n signature: txId,\n blockhash: blockHashCtx.blockhash,\n lastValidBlockHeight: blockHashCtx.lastValidBlockHeight,\n };\n const res = await rpc.confirmTransaction(\n transactionConfirmationStrategy,\n confirmOptions?.commitment || rpc.commitment || 'confirmed',\n );\n const slot = res.context.slot;\n await rpc.confirmTransactionIndexed(slot);\n return res;\n}\n\n/**\n * Builds a versioned Transaction from instructions and signs it.\n *\n * @param instructions instructions to include in the transaction\n * @param payer payer of the transaction\n * @param blockhash recent blockhash to use in the transaction\n * @param additionalSigners non-feepayer signers to include in the\n * transaction\n * @param lookupTableAccounts lookup table accounts to include in the\n * transaction\n */\nexport function buildAndSignTx(\n instructions: TransactionInstruction[],\n payer: Signer,\n blockhash: string,\n additionalSigners: Signer[] = [],\n lookupTableAccounts?: AddressLookupTableAccount[],\n): VersionedTransaction {\n if (additionalSigners.includes(payer))\n throw new Error('payer must not be in additionalSigners');\n const allSigners = [payer, ...additionalSigners];\n\n const tx = buildTx(\n instructions,\n payer.publicKey,\n blockhash,\n lookupTableAccounts,\n );\n\n tx.sign(allSigners);\n\n return tx;\n}\n","import {\n AddressLookupTableProgram,\n Connection,\n Keypair,\n PublicKey,\n Signer,\n} from '@solana/web3.js';\nimport { buildAndSignTx, sendAndConfirmTx } from './send-and-confirm';\nimport { dedupeSigner } from '../actions';\nimport { ActiveTreeBundle, TreeType } from '../state/types';\n\n/**\n * Create two lookup tables storing all public state tree and queue addresses\n * returns lookup table addresses and txId\n *\n * @internal\n * @param connection - Connection to the Solana network\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n * @param recentSlot - Slot of the recent block\n */\nexport async function createStateTreeLookupTable({\n connection,\n payer,\n authority,\n recentSlot,\n}: {\n connection: Connection;\n payer: Keypair;\n authority: Keypair;\n recentSlot: number;\n}): Promise<{ address: PublicKey; txId: string }> {\n const [createInstruction1, lookupTableAddress1] =\n AddressLookupTableProgram.createLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n recentSlot,\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx(\n [createInstruction1],\n payer,\n blockhash.blockhash,\n dedupeSigner(payer as Signer, [authority]),\n );\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n address: lookupTableAddress1,\n txId,\n };\n}\n\n/**\n * Extend state tree lookup table with new state tree and queue addresses\n * @internal\n * @param connection - Connection to the Solana network\n * @param tableAddress - Address of the lookup table to extend\n * @param newStateTreeAddresses - Addresses of the new state trees to add\n * @param newQueueAddresses - Addresses of the new queues to add\n * @param newCpiContextAddresses - Addresses of the new cpi contexts to add\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n */\nexport async function extendStateTreeLookupTable({\n connection,\n tableAddress,\n newStateTreeAddresses,\n newQueueAddresses,\n newCpiContextAddresses,\n payer,\n authority,\n}: {\n connection: Connection;\n tableAddress: PublicKey;\n newStateTreeAddresses: PublicKey[];\n newQueueAddresses: PublicKey[];\n newCpiContextAddresses: PublicKey[];\n payer: Keypair;\n authority: Keypair;\n}): Promise<{ tableAddress: PublicKey; txId: string }> {\n const lutState = await connection.getAddressLookupTable(tableAddress);\n if (!lutState.value) {\n throw new Error('Lookup table not found');\n }\n if (lutState.value.state.addresses.length % 3 !== 0) {\n throw new Error('Lookup table must have a multiple of 3 addresses');\n }\n if (\n newStateTreeAddresses.length !== newQueueAddresses.length ||\n newStateTreeAddresses.length !== newCpiContextAddresses.length\n ) {\n throw new Error(\n 'Same number of newStateTreeAddresses, newQueueAddresses, and newCpiContextAddresses required',\n );\n }\n\n const instructions = AddressLookupTableProgram.extendLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n lookupTable: tableAddress,\n addresses: newStateTreeAddresses.flatMap((addr, index) => [\n addr,\n newQueueAddresses[index],\n newCpiContextAddresses[index],\n ]),\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx(\n [instructions],\n payer,\n blockhash.blockhash,\n dedupeSigner(payer as Signer, [authority]),\n );\n // we pass a Connection type so we don't have to depend on the Rpc module.\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n tableAddress,\n txId,\n };\n}\n\n/**\n * Adds state tree address to lookup table. Acts as nullifier lookup for rolled\n * over state trees.\n * @internal\n * @param connection - Connection to the Solana network\n * @param stateTreeAddress - Address of the state tree to nullify\n * @param nullifyTableAddress - Address of the nullifier lookup table to store\n * address in\n * @param stateTreeLookupTableAddress - lookup table storing all state tree\n * addresses\n * @param payer - Keypair of the payer\n * @param authority - Keypair of the authority\n */\nexport async function nullifyLookupTable({\n connection,\n fullStateTreeAddress,\n nullifyTableAddress,\n stateTreeLookupTableAddress,\n payer,\n authority,\n}: {\n connection: Connection;\n fullStateTreeAddress: PublicKey;\n nullifyTableAddress: PublicKey;\n stateTreeLookupTableAddress: PublicKey;\n payer: Keypair;\n authority: Keypair;\n}): Promise<{ txId: string }> {\n // to be nullified address must be part of stateTreeLookupTable set\n const stateTreeLookupTable = await connection.getAddressLookupTable(\n stateTreeLookupTableAddress,\n );\n\n if (!stateTreeLookupTable.value) {\n throw new Error('State tree lookup table not found');\n }\n\n if (\n !stateTreeLookupTable.value.state.addresses.includes(\n fullStateTreeAddress,\n )\n ) {\n throw new Error(\n 'State tree address not found in lookup table. Pass correct address or stateTreeLookupTable',\n );\n }\n\n const nullifyTable =\n await connection.getAddressLookupTable(nullifyTableAddress);\n\n if (!nullifyTable.value) {\n throw new Error('Nullify table not found');\n }\n if (nullifyTable.value.state.addresses.includes(fullStateTreeAddress)) {\n throw new Error('Address already exists in nullify lookup table');\n }\n\n const instructions = AddressLookupTableProgram.extendLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n lookupTable: nullifyTableAddress,\n addresses: [fullStateTreeAddress],\n });\n\n const blockhash = await connection.getLatestBlockhash();\n\n const tx = buildAndSignTx([instructions], payer, blockhash.blockhash);\n // we pass a Connection type so we don't have to depend on the Rpc module.\n // @ts-expect-error\n const txId = await sendAndConfirmTx(connection, tx);\n\n return {\n txId,\n };\n}\n\n/**\n * Get most recent , active state tree data\n * we store in lookup table for each public state tree\n */\nexport async function getLightStateTreeInfo({\n connection,\n stateTreeLookupTableAddress,\n nullifyTableAddress,\n}: {\n connection: Connection;\n stateTreeLookupTableAddress: PublicKey;\n nullifyTableAddress: PublicKey;\n}): Promise<ActiveTreeBundle[]> {\n const stateTreeLookupTable = await connection.getAddressLookupTable(\n stateTreeLookupTableAddress,\n );\n\n if (!stateTreeLookupTable.value) {\n throw new Error('State tree lookup table not found');\n }\n\n if (stateTreeLookupTable.value.state.addresses.length % 3 !== 0) {\n throw new Error(\n 'State tree lookup table must have a multiple of 3 addresses',\n );\n }\n\n const nullifyTable =\n await connection.getAddressLookupTable(nullifyTableAddress);\n if (!nullifyTable.value) {\n throw new Error('Nullify table not found');\n }\n const stateTreePubkeys = stateTreeLookupTable.value.state.addresses;\n const nullifyTablePubkeys = nullifyTable.value.state.addresses;\n\n const bundles: ActiveTreeBundle[] = [];\n\n for (let i = 0; i < stateTreePubkeys.length; i += 3) {\n const tree = stateTreePubkeys[i];\n // Skip rolledover (full or almost full) Merkle trees\n if (!nullifyTablePubkeys.includes(tree)) {\n bundles.push({\n tree,\n queue: stateTreePubkeys[i + 1],\n cpiContext: stateTreePubkeys[i + 2],\n treeType: TreeType.State,\n });\n }\n }\n\n return bundles;\n}\n","/* The MIT License (MIT)\n *\n * Copyright 2015-2018 Peter A. Bigot\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n/**\n * Support for translating between Buffer instances and JavaScript\n * native types.\n *\n * {@link module:Layout~Layout|Layout} is the basis of a class\n * hierarchy that associates property names with sequences of encoded\n * bytes.\n *\n * Layouts are supported for these scalar (numeric) types:\n * * {@link module:Layout~UInt|Unsigned integers in little-endian\n * format} with {@link module:Layout.u8|8-bit}, {@link\n * module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},\n * {@link module:Layout.u32|32-bit}, {@link\n * module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}\n * representation ranges;\n * * {@link module:Layout~UIntBE|Unsigned integers in big-endian\n * format} with {@link module:Layout.u16be|16-bit}, {@link\n * module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},\n * {@link module:Layout.u40be|40-bit}, and {@link\n * module:Layout.u48be|48-bit} representation ranges;\n * * {@link module:Layout~Int|Signed integers in little-endian\n * format} with {@link module:Layout.s8|8-bit}, {@link\n * module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},\n * {@link module:Layout.s32|32-bit}, {@link\n * module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}\n * representation ranges;\n * * {@link module:Layout~IntBE|Signed integers in big-endian format}\n * with {@link module:Layout.s16be|16-bit}, {@link\n * module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},\n * {@link module:Layout.s40be|40-bit}, and {@link\n * module:Layout.s48be|48-bit} representation ranges;\n * * 64-bit integral values that decode to an exact (if magnitude is\n * less than 2^53) or nearby integral Number in {@link\n * module:Layout.nu64|unsigned little-endian}, {@link\n * module:Layout.nu64be|unsigned big-endian}, {@link\n * module:Layout.ns64|signed little-endian}, and {@link\n * module:Layout.ns64be|unsigned big-endian} encodings;\n * * 32-bit floating point values with {@link\n * module:Layout.f32|little-endian} and {@link\n * module:Layout.f32be|big-endian} representations;\n * * 64-bit floating point values with {@link\n * module:Layout.f64|little-endian} and {@link\n * module:Layout.f64be|big-endian} representations;\n * * {@link module:Layout.const|Constants} that take no space in the\n * encoded expression.\n *\n * and for these aggregate types:\n * * {@link module:Layout.seq|Sequence}s of instances of a {@link\n * module:Layout~Layout|Layout}, with JavaScript representation as\n * an Array and constant or data-dependent {@link\n * module:Layout~Sequence#count|length};\n * * {@link module:Layout.struct|Structure}s that aggregate a\n * heterogeneous sequence of {@link module:Layout~Layout|Layout}\n * instances, with JavaScript representation as an Object;\n * * {@link module:Layout.union|Union}s that support multiple {@link\n * module:Layout~VariantLayout|variant layouts} over a fixed\n * (padded) or variable (not padded) span of bytes, using an\n * unsigned integer at the start of the data or a separate {@link\n * module:Layout.unionLayoutDiscriminator|layout element} to\n * determine which layout to use when interpreting the buffer\n * contents;\n * * {@link module:Layout.bits|BitStructure}s that contain a sequence\n * of individual {@link\n * module:Layout~BitStructure#addField|BitField}s packed into an 8,\n * 16, 24, or 32-bit unsigned integer starting at the least- or\n * most-significant bit;\n * * {@link module:Layout.cstr|C strings} of varying length;\n * * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link\n * module:Layout~Blob#length|length} raw data.\n *\n * All {@link module:Layout~Layout|Layout} instances are immutable\n * after construction, to prevent internal state from becoming\n * inconsistent.\n *\n * @local Layout\n * @local ExternalLayout\n * @local GreedyCount\n * @local OffsetLayout\n * @local UInt\n * @local UIntBE\n * @local Int\n * @local IntBE\n * @local NearUInt64\n * @local NearUInt64BE\n * @local NearInt64\n * @local NearInt64BE\n * @local Float\n * @local FloatBE\n * @local Double\n * @local DoubleBE\n * @local Sequence\n * @local Structure\n * @local UnionDiscriminator\n * @local UnionLayoutDiscriminator\n * @local Union\n * @local VariantLayout\n * @local BitStructure\n * @local BitField\n * @local Boolean\n * @local Blob\n * @local CString\n * @local Constant\n * @local bindConstructorLayout\n * @module Layout\n * @license MIT\n * @author Peter A. Bigot\n * @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}\n */\n\n'use strict';\n\n/**\n * Base class for layout objects.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * Layout#encode|encode} or {@link Layout#decode|decode} functions.\n *\n * @param {Number} span - Initializer for {@link Layout#span|span}. The\n * parameter must be an integer; a negative value signifies that the\n * span is {@link Layout#getSpan|value-specific}.\n *\n * @param {string} [property] - Initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n */\nclass Layout {\n constructor(span, property) {\n if (!Number.isInteger(span)) {\n throw new TypeError('span must be an integer');\n }\n\n /** The span of the layout in bytes.\n *\n * Positive values are generally expected.\n *\n * Zero will only appear in {@link Constant}s and in {@link\n * Sequence}s where the {@link Sequence#count|count} is zero.\n *\n * A negative value indicates that the span is value-specific, and\n * must be obtained using {@link Layout#getSpan|getSpan}. */\n this.span = span;\n\n /** The property name used when this layout is represented in an\n * Object.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances. If left undefined the span of the unnamed layout will\n * be treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n\n /** Function to create an Object into which decoded properties will\n * be written.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances, which means:\n * * {@link Structure}\n * * {@link Union}\n * * {@link VariantLayout}\n * * {@link BitStructure}\n *\n * If left undefined the JavaScript representation of these layouts\n * will be Object instances.\n *\n * See {@link bindConstructorLayout}.\n */\n makeDestinationObject() {\n return {};\n }\n\n /**\n * Decode from a Buffer into an JavaScript value.\n *\n * @param {Buffer} b - the buffer from which encoded data is read.\n *\n * @param {Number} [offset] - the offset at which the encoded data\n * starts. If absent a zero offset is inferred.\n *\n * @returns {(Number|Array|Object)} - the value of the decoded data.\n *\n * @abstract\n */\n decode(b, offset) {\n throw new Error('Layout is abstract');\n }\n\n /**\n * Encode a JavaScript value into a Buffer.\n *\n * @param {(Number|Array|Object)} src - the value to be encoded into\n * the buffer. The type accepted depends on the (sub-)type of {@link\n * Layout}.\n *\n * @param {Buffer} b - the buffer into which encoded data will be\n * written.\n *\n * @param {Number} [offset] - the offset at which the encoded data\n * starts. If absent a zero offset is inferred.\n *\n * @returns {Number} - the number of bytes encoded, including the\n * space skipped for internal padding, but excluding data such as\n * {@link Sequence#count|lengths} when stored {@link\n * ExternalLayout|externally}. This is the adjustment to `offset`\n * producing the offset where data for the next layout would be\n * written.\n *\n * @abstract\n */\n encode(src, b, offset) {\n throw new Error('Layout is abstract');\n }\n\n /**\n * Calculate the span of a specific instance of a layout.\n *\n * @param {Buffer} b - the buffer that contains an encoded instance.\n *\n * @param {Number} [offset] - the offset at which the encoded instance\n * starts. If absent a zero offset is inferred.\n *\n * @return {Number} - the number of bytes covered by the layout\n * instance. If this method is not overridden in a subclass the\n * definition-time constant {@link Layout#span|span} will be\n * returned.\n *\n * @throws {RangeError} - if the length of the value cannot be\n * determined.\n */\n getSpan(b, offset) {\n if (0 > this.span) {\n throw new RangeError('indeterminate span');\n }\n return this.span;\n }\n\n /**\n * Replicate the layout using a new property.\n *\n * This function must be used to get a structurally-equivalent layout\n * with a different name since all {@link Layout} instances are\n * immutable.\n *\n * **NOTE** This is a shallow copy. All fields except {@link\n * Layout#property|property} are strictly equal to the origin layout.\n *\n * @param {String} property - the value for {@link\n * Layout#property|property} in the replica.\n *\n * @returns {Layout} - the copy with {@link Layout#property|property}\n * set to `property`.\n */\n replicate(property) {\n const rv = Object.create(this.constructor.prototype);\n Object.assign(rv, this);\n rv.property = property;\n return rv;\n }\n\n /**\n * Create an object from layout properties and an array of values.\n *\n * **NOTE** This function returns `undefined` if invoked on a layout\n * that does not return its value as an Object. Objects are\n * returned for things that are a {@link Structure}, which includes\n * {@link VariantLayout|variant layouts} if they are structures, and\n * excludes {@link Union}s. If you want this feature for a union\n * you must use {@link Union.getVariant|getVariant} to select the\n * desired layout.\n *\n * @param {Array} values - an array of values that correspond to the\n * default order for properties. As with {@link Layout#decode|decode}\n * layout elements that have no property name are skipped when\n * iterating over the array values. Only the top-level properties are\n * assigned; arguments are not assigned to properties of contained\n * layouts. Any unused values are ignored.\n *\n * @return {(Object|undefined)}\n */\n fromArray(values) {\n return undefined;\n }\n}\nexports.Layout = Layout;\n\n/* Provide text that carries a name (such as for a function that will\n * be throwing an error) annotated with the property of a given layout\n * (such as one for which the value was unacceptable).\n *\n * @ignore */\nfunction nameWithProperty(name, lo) {\n if (lo.property) {\n return name + '[' + lo.property + ']';\n }\n return name;\n}\nexports.nameWithProperty = nameWithProperty;\n\n/**\n * Augment a class so that instances can be encoded/decoded using a\n * given layout.\n *\n * Calling this function couples `Class` with `layout` in several ways:\n *\n * * `Class.layout_` becomes a static member property equal to `layout`;\n * * `layout.boundConstructor_` becomes a static member property equal\n * to `Class`;\n * * The {@link Layout#makeDestinationObject|makeDestinationObject()}\n * property of `layout` is set to a function that returns a `new\n * Class()`;\n * * `Class.decode(b, offset)` becomes a static member function that\n * delegates to {@link Layout#decode|layout.decode}. The\n * synthesized function may be captured and extended.\n * * `Class.prototype.encode(b, offset)` provides an instance member\n * function that delegates to {@link Layout#encode|layout.encode}\n * with `src` set to `this`. The synthesized function may be\n * captured and extended, but when the extension is invoked `this`\n * must be explicitly bound to the instance.\n *\n * @param {class} Class - a JavaScript class with a nullary\n * constructor.\n *\n * @param {Layout} layout - the {@link Layout} instance used to encode\n * instances of `Class`.\n */\nfunction bindConstructorLayout(Class, layout) {\n if ('function' !== typeof Class) {\n throw new TypeError('Class must be constructor');\n }\n if (Class.hasOwnProperty('layout_')) {\n throw new Error('Class is already bound to a layout');\n }\n if (!(layout && (layout instanceof Layout))) {\n throw new TypeError('layout must be a Layout');\n }\n if (layout.hasOwnProperty('boundConstructor_')) {\n throw new Error('layout is already bound to a constructor');\n }\n Class.layout_ = layout;\n layout.boundConstructor_ = Class;\n layout.makeDestinationObject = (() => new Class());\n Object.defineProperty(Class.prototype, 'encode', {\n value: function(b, offset) {\n return layout.encode(this, b, offset);\n },\n writable: true,\n });\n Object.defineProperty(Class, 'decode', {\n value: function(b, offset) {\n return layout.decode(b, offset);\n },\n writable: true,\n });\n}\nexports.bindConstructorLayout = bindConstructorLayout;\n\n/**\n * An object that behaves like a layout but does not consume space\n * within its containing layout.\n *\n * This is primarily used to obtain metadata about a member, such as a\n * {@link OffsetLayout} that can provide data about a {@link\n * Layout#getSpan|value-specific span}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support {@link\n * ExternalLayout#isCount|isCount} or other {@link Layout} functions.\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n * @augments {Layout}\n */\nclass ExternalLayout extends Layout {\n /**\n * Return `true` iff the external layout decodes to an unsigned\n * integer layout.\n *\n * In that case it can be used as the source of {@link\n * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},\n * or as {@link UnionLayoutDiscriminator#layout|external union\n * discriminators}.\n *\n * @abstract\n */\n isCount() {\n throw new Error('ExternalLayout is abstract');\n }\n}\n\n/**\n * An {@link ExternalLayout} that determines its {@link\n * Layout#decode|value} based on offset into and length of the buffer\n * on which it is invoked.\n *\n * *Factory*: {@link module:Layout.greedy|greedy}\n *\n * @param {Number} [elementSpan] - initializer for {@link\n * GreedyCount#elementSpan|elementSpan}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {ExternalLayout}\n */\nclass GreedyCount extends ExternalLayout {\n constructor(elementSpan, property) {\n if (undefined === elementSpan) {\n elementSpan = 1;\n }\n if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {\n throw new TypeError('elementSpan must be a (positive) integer');\n }\n super(-1, property);\n\n /** The layout for individual elements of the sequence. The value\n * must be a positive integer. If not provided, the value will be\n * 1. */\n this.elementSpan = elementSpan;\n }\n\n /** @override */\n isCount() {\n return true;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const rem = b.length - offset;\n return Math.floor(rem / this.elementSpan);\n }\n\n /** @override */\n encode(src, b, offset) {\n return 0;\n }\n}\n\n/**\n * An {@link ExternalLayout} that supports accessing a {@link Layout}\n * at a fixed offset from the start of another Layout. The offset may\n * be before, within, or after the base layout.\n *\n * *Factory*: {@link module:Layout.offset|offset}\n *\n * @param {Layout} layout - initializer for {@link\n * OffsetLayout#layout|layout}, modulo `property`.\n *\n * @param {Number} [offset] - Initializes {@link\n * OffsetLayout#offset|offset}. Defaults to zero.\n *\n * @param {string} [property] - Optional new property name for a\n * {@link Layout#replicate| replica} of `layout` to be used as {@link\n * OffsetLayout#layout|layout}. If not provided the `layout` is used\n * unchanged.\n *\n * @augments {Layout}\n */\nclass OffsetLayout extends ExternalLayout {\n constructor(layout, offset, property) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n\n if (undefined === offset) {\n offset = 0;\n } else if (!Number.isInteger(offset)) {\n throw new TypeError('offset must be integer or undefined');\n }\n\n super(layout.span, property || layout.property);\n\n /** The subordinated layout. */\n this.layout = layout;\n\n /** The location of {@link OffsetLayout#layout} relative to the\n * start of another layout.\n *\n * The value may be positive or negative, but an error will thrown\n * if at the point of use it goes outside the span of the Buffer\n * being accessed. */\n this.offset = offset;\n }\n\n /** @override */\n isCount() {\n return ((this.layout instanceof UInt)\n || (this.layout instanceof UIntBE));\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return this.layout.decode(b, offset + this.offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return this.layout.encode(src, b, offset + this.offset);\n }\n}\n\n/**\n * Represent an unsigned integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.u8|u8}, {@link\n * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link\n * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link\n * module:Layout.u48|u48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UInt extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readUIntLE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeUIntLE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent an unsigned integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.u8be|u8be}, {@link\n * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},\n * {@link module:Layout.u32be|u32be}, {@link\n * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UIntBE extends Layout {\n constructor(span, property) {\n super( span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readUIntBE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeUIntBE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent a signed integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.s8|s8}, {@link\n * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link\n * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link\n * module:Layout.s48|s48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Int extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readIntLE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeIntLE(src, offset, this.span);\n return this.span;\n }\n}\n\n/**\n * Represent a signed integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.s8be|s8be}, {@link\n * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},\n * {@link module:Layout.s32be|s32be}, {@link\n * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass IntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readIntBE(offset, this.span);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeIntBE(src, offset, this.span);\n return this.span;\n }\n}\n\nconst V2E32 = Math.pow(2, 32);\n\n/* True modulus high and low 32-bit words, where low word is always\n * non-negative. */\nfunction divmodInt64(src) {\n const hi32 = Math.floor(src / V2E32);\n const lo32 = src - (hi32 * V2E32);\n return {hi32, lo32};\n}\n/* Reconstruct Number from quotient and non-negative remainder */\nfunction roundedInt64(hi32, lo32) {\n return hi32 * V2E32 + lo32;\n}\n\n/**\n * Represent an unsigned 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64|nu64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const lo32 = b.readUInt32LE(offset);\n const hi32 = b.readUInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32LE(split.lo32, offset);\n b.writeUInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent an unsigned 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64be|nu64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const hi32 = b.readUInt32BE(offset);\n const lo32 = b.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32BE(split.hi32, offset);\n b.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a signed 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64|ns64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const lo32 = b.readUInt32LE(offset);\n const hi32 = b.readInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeUInt32LE(split.lo32, offset);\n b.writeInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a signed 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64be|ns64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const hi32 = b.readInt32BE(offset);\n const lo32 = b.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const split = divmodInt64(src);\n b.writeInt32BE(split.hi32, offset);\n b.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\n\n/**\n * Represent a 32-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f32|f32}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Float extends Layout {\n constructor(property) {\n super(4, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readFloatLE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeFloatLE(src, offset);\n return 4;\n }\n}\n\n/**\n * Represent a 32-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f32be|f32be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass FloatBE extends Layout {\n constructor(property) {\n super(4, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readFloatBE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeFloatBE(src, offset);\n return 4;\n }\n}\n\n/**\n * Represent a 64-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f64|f64}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Double extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readDoubleLE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeDoubleLE(src, offset);\n return 8;\n }\n}\n\n/**\n * Represent a 64-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f64be|f64be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass DoubleBE extends Layout {\n constructor(property) {\n super(8, property);\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n return b.readDoubleBE(offset);\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n b.writeDoubleBE(src, offset);\n return 8;\n }\n}\n\n/**\n * Represent a contiguous sequence of a specific layout as an Array.\n *\n * *Factory*: {@link module:Layout.seq|seq}\n *\n * @param {Layout} elementLayout - initializer for {@link\n * Sequence#elementLayout|elementLayout}.\n *\n * @param {(Number|ExternalLayout)} count - initializer for {@link\n * Sequence#count|count}. The parameter must be either a positive\n * integer or an instance of {@link ExternalLayout}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Sequence extends Layout {\n constructor(elementLayout, count, property) {\n if (!(elementLayout instanceof Layout)) {\n throw new TypeError('elementLayout must be a Layout');\n }\n if (!(((count instanceof ExternalLayout) && count.isCount())\n || (Number.isInteger(count) && (0 <= count)))) {\n throw new TypeError('count must be non-negative integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if ((!(count instanceof ExternalLayout))\n && (0 < elementLayout.span)) {\n span = count * elementLayout.span;\n }\n\n super(span, property);\n\n /** The layout for individual elements of the sequence. */\n this.elementLayout = elementLayout;\n\n /** The number of elements in the sequence.\n *\n * This will be either a non-negative integer or an instance of\n * {@link ExternalLayout} for which {@link\n * ExternalLayout#isCount|isCount()} is `true`. */\n this.count = count;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let span = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n if (0 < this.elementLayout.span) {\n span = count * this.elementLayout.span;\n } else {\n let idx = 0;\n while (idx < count) {\n span += this.elementLayout.getSpan(b, offset + span);\n ++idx;\n }\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const rv = [];\n let i = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n while (i < count) {\n rv.push(this.elementLayout.decode(b, offset));\n offset += this.elementLayout.getSpan(b, offset);\n i += 1;\n }\n return rv;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Sequence}.\n *\n * **NOTE** If `src` is shorter than {@link Sequence#count|count} then\n * the unused space in the buffer is left unchanged. If `src` is\n * longer than {@link Sequence#count|count} the unneeded elements are\n * ignored.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const elo = this.elementLayout;\n const span = src.reduce((span, v) => {\n return span + elo.encode(v, b, offset + span);\n }, 0);\n if (this.count instanceof ExternalLayout) {\n this.count.encode(src.length, b, offset);\n }\n return span;\n }\n}\n\n/**\n * Represent a contiguous sequence of arbitrary layout elements as an\n * Object.\n *\n * *Factory*: {@link module:Layout.struct|struct}\n *\n * **NOTE** The {@link Layout#span|span} of the structure is variable\n * if any layout in {@link Structure#fields|fields} has a variable\n * span. When {@link Layout#encode|encoding} we must have a value for\n * all variable-length fields, or we wouldn't be able to figure out\n * how much space to use for storage. We can only identify the value\n * for a field when it has a {@link Layout#property|property}. As\n * such, although a structure may contain both unnamed fields and\n * variable-length fields, it cannot contain an unnamed\n * variable-length field.\n *\n * @param {Layout[]} fields - initializer for {@link\n * Structure#fields|fields}. An error is raised if this contains a\n * variable-length field for which a {@link Layout#property|property}\n * is not defined.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @param {Boolean} [decodePrefixes] - initializer for {@link\n * Structure#decodePrefixes|property}.\n *\n * @throws {Error} - if `fields` contains an unnamed variable-length\n * layout.\n *\n * @augments {Layout}\n */\nclass Structure extends Layout {\n constructor(fields, property, decodePrefixes) {\n if (!(Array.isArray(fields)\n && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {\n throw new TypeError('fields must be array of Layout instances');\n }\n if (('boolean' === typeof property)\n && (undefined === decodePrefixes)) {\n decodePrefixes = property;\n property = undefined;\n }\n\n /* Verify absence of unnamed variable-length fields. */\n for (const fd of fields) {\n if ((0 > fd.span)\n && (undefined === fd.property)) {\n throw new Error('fields cannot contain unnamed variable-length layout');\n }\n }\n\n let span = -1;\n try {\n span = fields.reduce((span, fd) => span + fd.getSpan(), 0);\n } catch (e) {\n }\n super(span, property);\n\n /** The sequence of {@link Layout} values that comprise the\n * structure.\n *\n * The individual elements need not be the same type, and may be\n * either scalar or aggregate layouts. If a member layout leaves\n * its {@link Layout#property|property} undefined the\n * corresponding region of the buffer associated with the element\n * will not be mutated.\n *\n * @type {Layout[]} */\n this.fields = fields;\n\n /** Control behavior of {@link Layout#decode|decode()} given short\n * buffers.\n *\n * In some situations a structure many be extended with additional\n * fields over time, with older installations providing only a\n * prefix of the full structure. If this property is `true`\n * decoding will accept those buffers and leave subsequent fields\n * undefined, as long as the buffer ends at a field boundary.\n * Defaults to `false`. */\n this.decodePrefixes = !!decodePrefixes;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let span = 0;\n try {\n span = this.fields.reduce((span, fd) => {\n const fsp = fd.getSpan(b, offset);\n offset += fsp;\n return span + fsp;\n }, 0);\n } catch (e) {\n throw new RangeError('indeterminate span');\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b, offset);\n }\n offset += fd.getSpan(b, offset);\n if (this.decodePrefixes\n && (b.length === offset)) {\n break;\n }\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Structure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the buffer is\n * left unmodified. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const firstOffset = offset;\n let lastOffset = 0;\n let lastWrote = 0;\n for (const fd of this.fields) {\n let span = fd.span;\n lastWrote = (0 < span) ? span : 0;\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n lastWrote = fd.encode(fv, b, offset);\n if (0 > span) {\n /* Read the as-encoded span, which is not necessarily the\n * same as what we wrote. */\n span = fd.getSpan(b, offset);\n }\n }\n }\n lastOffset = offset;\n offset += span;\n }\n /* Use (lastOffset + lastWrote) instead of offset because the last\n * item may have had a dynamic length and we don't want to include\n * the padding between it and the end of the space reserved for\n * it. */\n return (lastOffset + lastWrote) - firstOffset;\n }\n\n /** @override */\n fromArray(values) {\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if ((undefined !== fd.property)\n && (0 < values.length)) {\n dest[fd.property] = values.shift();\n }\n }\n return dest;\n }\n\n /**\n * Get access to the layout of a given property.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Layout} - the layout associated with `property`, or\n * undefined if there is no such property.\n */\n layoutFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n }\n\n /**\n * Get the offset of a structure member.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Number} - the offset in bytes to the start of `property`\n * within the structure, or undefined if `property` is not a field\n * within the structure. If the property is a member but follows a\n * variable-length structure member a negative number will be\n * returned.\n */\n offsetOf(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n let offset = 0;\n for (const fd of this.fields) {\n if (fd.property === property) {\n return offset;\n }\n if (0 > fd.span) {\n offset = -1;\n } else if (0 <= offset) {\n offset += fd.span;\n }\n }\n }\n}\n\n/**\n * An object that can provide a {@link\n * Union#discriminator|discriminator} API for {@link Union}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * UnionDiscriminator#encode|encode} or {@link\n * UnionDiscriminator#decode|decode} functions.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}.\n *\n * @abstract\n */\nclass UnionDiscriminator {\n constructor(property) {\n /** The {@link Layout#property|property} to be used when the\n * discriminator is referenced in isolation (generally when {@link\n * Union#decode|Union decode} cannot delegate to a specific\n * variant). */\n this.property = property;\n }\n\n /** Analog to {@link Layout#decode|Layout decode} for union discriminators.\n *\n * The implementation of this method need not reference the buffer if\n * variant information is available through other means. */\n decode() {\n throw new Error('UnionDiscriminator is abstract');\n }\n\n /** Analog to {@link Layout#decode|Layout encode} for union discriminators.\n *\n * The implementation of this method need not store the value if\n * variant information is maintained through other means. */\n encode() {\n throw new Error('UnionDiscriminator is abstract');\n }\n}\n\n/**\n * An object that can provide a {@link\n * UnionDiscriminator|discriminator API} for {@link Union} using an\n * unsigned integral {@link Layout} instance located either inside or\n * outside the union.\n *\n * @param {ExternalLayout} layout - initializes {@link\n * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link\n * ExternalLayout#isCount|isCount()}.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}, superseding the property\n * from `layout`, but defaulting to `variant` if neither `property`\n * nor layout provide a property name.\n *\n * @augments {UnionDiscriminator}\n */\nclass UnionLayoutDiscriminator extends UnionDiscriminator {\n constructor(layout, property) {\n if (!((layout instanceof ExternalLayout)\n && layout.isCount())) {\n throw new TypeError('layout must be an unsigned integer ExternalLayout');\n }\n\n super(property || layout.property || 'variant');\n\n /** The {@link ExternalLayout} used to access the discriminator\n * value. */\n this.layout = layout;\n }\n\n /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n decode(b, offset) {\n return this.layout.decode(b, offset);\n }\n\n /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n encode(src, b, offset) {\n return this.layout.encode(src, b, offset);\n }\n}\n\n/**\n * Represent any number of span-compatible layouts.\n *\n * *Factory*: {@link module:Layout.union|union}\n *\n * If the union has a {@link Union#defaultLayout|default layout} that\n * layout must have a non-negative {@link Layout#span|span}. The span\n * of a fixed-span union includes its {@link\n * Union#discriminator|discriminator} if the variant is a {@link\n * Union#usesPrefixDiscriminator|prefix of the union}, plus the span\n * of its {@link Union#defaultLayout|default layout}.\n *\n * If the union does not have a default layout then the encoded span\n * of the union depends on the encoded span of its variant (which may\n * be fixed or variable).\n *\n * {@link VariantLayout#layout|Variant layout}s are added through\n * {@link Union#addVariant|addVariant}. If the union has a default\n * layout, the span of the {@link VariantLayout#layout|layout\n * contained by the variant} must not exceed the span of the {@link\n * Union#defaultLayout|default layout} (minus the span of a {@link\n * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The\n * span of the variant will equal the span of the union itself.\n *\n * The variant for a buffer can only be identified from the {@link\n * Union#discriminator|discriminator} {@link\n * UnionDiscriminator#property|property} (in the case of the {@link\n * Union#defaultLayout|default layout}), or by using {@link\n * Union#getVariant|getVariant} and examining the resulting {@link\n * VariantLayout} instance.\n *\n * A variant compatible with a JavaScript object can be identified\n * using {@link Union#getSourceVariant|getSourceVariant}.\n *\n * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to\n * identify the layout used to interpret the union contents. The\n * parameter must be an instance of {@link UnionDiscriminator}, an\n * {@link ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link\n * UIntBE}). When a non-external layout element is passed the layout\n * appears at the start of the union. In all cases the (synthesized)\n * {@link UnionDiscriminator} instance is recorded as {@link\n * Union#discriminator|discriminator}.\n *\n * @param {(Layout|null)} defaultLayout - initializer for {@link\n * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.\n * If `null` there is no default layout: the union has data-dependent\n * length and attempts to decode or encode unrecognized variants will\n * throw an exception. A {@link Layout} instance must have a\n * non-negative {@link Layout#span|span}, and if it lacks a {@link\n * Layout#property|property} the {@link\n * Union#defaultLayout|defaultLayout} will be a {@link\n * Layout#replicate|replica} with property `content`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Union extends Layout {\n constructor(discr, defaultLayout, property) {\n const upv = ((discr instanceof UInt)\n || (discr instanceof UIntBE));\n if (upv) {\n discr = new UnionLayoutDiscriminator(new OffsetLayout(discr));\n } else if ((discr instanceof ExternalLayout)\n && discr.isCount()) {\n discr = new UnionLayoutDiscriminator(discr);\n } else if (!(discr instanceof UnionDiscriminator)) {\n throw new TypeError('discr must be a UnionDiscriminator '\n + 'or an unsigned integer layout');\n }\n if (undefined === defaultLayout) {\n defaultLayout = null;\n }\n if (!((null === defaultLayout)\n || (defaultLayout instanceof Layout))) {\n throw new TypeError('defaultLayout must be null or a Layout');\n }\n if (null !== defaultLayout) {\n if (0 > defaultLayout.span) {\n throw new Error('defaultLayout must have constant span');\n }\n if (undefined === defaultLayout.property) {\n defaultLayout = defaultLayout.replicate('content');\n }\n }\n\n /* The union span can be estimated only if there's a default\n * layout. The union spans its default layout, plus any prefix\n * variant layout. By construction both layouts, if present, have\n * non-negative span. */\n let span = -1;\n if (defaultLayout) {\n span = defaultLayout.span;\n if ((0 <= span) && upv) {\n span += discr.layout.span;\n }\n }\n super(span, property);\n\n /** The interface for the discriminator value in isolation.\n *\n * This a {@link UnionDiscriminator} either passed to the\n * constructor or synthesized from the `discr` constructor\n * argument. {@link\n * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be\n * `true` iff the `discr` parameter was a non-offset {@link\n * Layout} instance. */\n this.discriminator = discr;\n\n /** `true` if the {@link Union#discriminator|discriminator} is the\n * first field in the union.\n *\n * If `false` the discriminator is obtained from somewhere\n * else. */\n this.usesPrefixDiscriminator = upv;\n\n /** The layout for non-discriminator content when the value of the\n * discriminator is not recognized.\n *\n * This is the value passed to the constructor. It is\n * structurally equivalent to the second component of {@link\n * Union#layout|layout} but may have a different property\n * name. */\n this.defaultLayout = defaultLayout;\n\n /** A registry of allowed variants.\n *\n * The keys are unsigned integers which should be compatible with\n * {@link Union.discriminator|discriminator}. The property value\n * is the corresponding {@link VariantLayout} instances assigned\n * to this union by {@link Union#addVariant|addVariant}.\n *\n * **NOTE** The registry remains mutable so that variants can be\n * {@link Union#addVariant|added} at any time. Users should not\n * manipulate the content of this property. */\n this.registry = {};\n\n /* Private variable used when invoking getSourceVariant */\n let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);\n\n /** Function to infer the variant selected by a source object.\n *\n * Defaults to {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may\n * be overridden using {@link\n * Union#configGetSourceVariant|configGetSourceVariant}.\n *\n * @param {Object} src - as with {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * @returns {(undefined|VariantLayout)} The default variant\n * (`undefined`) or first registered variant that uses a property\n * available in `src`. */\n this.getSourceVariant = function(src) {\n return boundGetSourceVariant(src);\n };\n\n /** Function to override the implementation of {@link\n * Union#getSourceVariant|getSourceVariant}.\n *\n * Use this if the desired variant cannot be identified using the\n * algorithm of {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * **NOTE** The provided function will be invoked bound to this\n * Union instance, providing local access to {@link\n * Union#registry|registry}.\n *\n * @param {Function} gsv - a function that follows the API of\n * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */\n this.configGetSourceVariant = function(gsv) {\n boundGetSourceVariant = gsv.bind(this);\n };\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n /* Default layouts always have non-negative span, so we don't have\n * one and we have to recognize the variant which will in turn\n * determine the span. */\n const vlo = this.getVariant(b, offset);\n if (!vlo) {\n throw new Error('unable to determine span for unrecognized variant');\n }\n return vlo.getSpan(b, offset);\n }\n\n /**\n * Method to infer a registered Union variant compatible with `src`.\n *\n * The first satisified rule in the following sequence defines the\n * return value:\n * * If `src` has properties matching the Union discriminator and\n * the default layout, `undefined` is returned regardless of the\n * value of the discriminator property (this ensures the default\n * layout will be used);\n * * If `src` has a property matching the Union discriminator, the\n * value of the discriminator identifies a registered variant, and\n * either (a) the variant has no layout, or (b) `src` has the\n * variant's property, then the variant is returned (because the\n * source satisfies the constraints of the variant it identifies);\n * * If `src` does not have a property matching the Union\n * discriminator, but does have a property matching a registered\n * variant, then the variant is returned (because the source\n * matches a variant without an explicit conflict);\n * * An error is thrown (because we either can't identify a variant,\n * or we were explicitly told the variant but can't satisfy it).\n *\n * @param {Object} src - an object presumed to be compatible with\n * the content of the Union.\n *\n * @return {(undefined|VariantLayout)} - as described above.\n *\n * @throws {Error} - if `src` cannot be associated with a default or\n * registered variant.\n */\n defaultGetSourceVariant(src) {\n if (src.hasOwnProperty(this.discriminator.property)) {\n if (this.defaultLayout\n && src.hasOwnProperty(this.defaultLayout.property)) {\n return undefined;\n }\n const vlo = this.registry[src[this.discriminator.property]];\n if (vlo\n && ((!vlo.layout)\n || src.hasOwnProperty(vlo.property))) {\n return vlo;\n }\n } else {\n for (const tag in this.registry) {\n const vlo = this.registry[tag];\n if (src.hasOwnProperty(vlo.property)) {\n return vlo;\n }\n }\n }\n throw new Error('unable to infer src variant');\n }\n\n /** Implement {@link Layout#decode|decode} for {@link Union}.\n *\n * If the variant is {@link Union#addVariant|registered} the return\n * value is an instance of that variant, with no explicit\n * discriminator. Otherwise the {@link Union#defaultLayout|default\n * layout} is used to decode the content. */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let dest;\n const dlo = this.discriminator;\n const discr = dlo.decode(b, offset);\n let clo = this.registry[discr];\n if (undefined === clo) {\n let contentOffset = 0;\n clo = this.defaultLayout;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dest = this.makeDestinationObject();\n dest[dlo.property] = discr;\n dest[clo.property] = this.defaultLayout.decode(b, offset + contentOffset);\n } else {\n dest = clo.decode(b, offset);\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Union}.\n *\n * This API assumes the `src` object is consistent with the union's\n * {@link Union#defaultLayout|default layout}. To encode variants\n * use the appropriate variant-specific {@link VariantLayout#encode}\n * method. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const vlo = this.getSourceVariant(src);\n if (undefined === vlo) {\n const dlo = this.discriminator;\n const clo = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dlo.encode(src[dlo.property], b, offset);\n return contentOffset + clo.encode(src[clo.property], b,\n offset + contentOffset);\n }\n return vlo.encode(src, b, offset);\n }\n\n /** Register a new variant structure within a union. The newly\n * created variant is returned.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} layout - initializer for {@link\n * VariantLayout#layout|layout}.\n *\n * @param {String} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {VariantLayout} */\n addVariant(variant, layout, property) {\n const rv = new VariantLayout(this, variant, layout, property);\n this.registry[variant] = rv;\n return rv;\n }\n\n /**\n * Get the layout associated with a registered variant.\n *\n * If `vb` does not produce a registered variant the function returns\n * `undefined`.\n *\n * @param {(Number|Buffer)} vb - either the variant number, or a\n * buffer from which the discriminator is to be read.\n *\n * @param {Number} offset - offset into `vb` for the start of the\n * union. Used only when `vb` is an instance of {Buffer}.\n *\n * @return {({VariantLayout}|undefined)}\n */\n getVariant(vb, offset) {\n let variant = vb;\n if (Buffer.isBuffer(vb)) {\n if (undefined === offset) {\n offset = 0;\n }\n variant = this.discriminator.decode(vb, offset);\n }\n return this.registry[variant];\n }\n}\n\n/**\n * Represent a specific variant within a containing union.\n *\n * **NOTE** The {@link Layout#span|span} of the variant may include\n * the span of the {@link Union#discriminator|discriminator} used to\n * identify it, but values read and written using the variant strictly\n * conform to the content of {@link VariantLayout#layout|layout}.\n *\n * **NOTE** User code should not invoke this constructor directly. Use\n * the union {@link Union#addVariant|addVariant} helper method.\n *\n * @param {Union} union - initializer for {@link\n * VariantLayout#union|union}.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} [layout] - initializer for {@link\n * VariantLayout#layout|layout}. If absent the variant carries no\n * data.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}. Unlike many other layouts, variant\n * layouts normally include a property name so they can be identified\n * within their containing {@link Union}. The property identifier may\n * be absent only if `layout` is is absent.\n *\n * @augments {Layout}\n */\nclass VariantLayout extends Layout {\n constructor(union, variant, layout, property) {\n if (!(union instanceof Union)) {\n throw new TypeError('union must be a Union');\n }\n if ((!Number.isInteger(variant)) || (0 > variant)) {\n throw new TypeError('variant must be a (non-negative) integer');\n }\n if (('string' === typeof layout)\n && (undefined === property)) {\n property = layout;\n layout = null;\n }\n if (layout) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if ((null !== union.defaultLayout)\n && (0 <= layout.span)\n && (layout.span > union.defaultLayout.span)) {\n throw new Error('variant span exceeds span of containing union');\n }\n if ('string' !== typeof property) {\n throw new TypeError('variant must have a String property');\n }\n }\n let span = union.span;\n if (0 > union.span) {\n span = layout ? layout.span : 0;\n if ((0 <= span) && union.usesPrefixDiscriminator) {\n span += union.discriminator.layout.span;\n }\n }\n super(span, property);\n\n /** The {@link Union} to which this variant belongs. */\n this.union = union;\n\n /** The unsigned integral value identifying this variant within\n * the {@link Union#discriminator|discriminator} of the containing\n * union. */\n this.variant = variant;\n\n /** The {@link Layout} to be used when reading/writing the\n * non-discriminator part of the {@link\n * VariantLayout#union|union}. If `null` the variant carries no\n * data. */\n this.layout = layout || null;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (0 <= this.span) {\n /* Will be equal to the containing union span if that is not\n * variable. */\n return this.span;\n }\n if (undefined === offset) {\n offset = 0;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n /* Span is defined solely by the variant (and prefix discriminator) */\n return contentOffset + this.layout.getSpan(b, offset + contentOffset);\n }\n\n /** @override */\n decode(b, offset) {\n const dest = this.makeDestinationObject();\n if (undefined === offset) {\n offset = 0;\n }\n if (this !== this.union.getVariant(b, offset)) {\n throw new Error('variant mismatch');\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout) {\n dest[this.property] = this.layout.decode(b, offset + contentOffset);\n } else if (this.property) {\n dest[this.property] = true;\n } else if (this.union.usesPrefixDiscriminator) {\n dest[this.union.discriminator.property] = this.variant;\n }\n return dest;\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout\n && (!src.hasOwnProperty(this.property))) {\n throw new TypeError('variant lacks property ' + this.property);\n }\n this.union.discriminator.encode(this.variant, b, offset);\n let span = contentOffset;\n if (this.layout) {\n this.layout.encode(src[this.property], b, offset + contentOffset);\n span += this.layout.getSpan(b, offset + contentOffset);\n if ((0 <= this.union.span)\n && (span > this.union.span)) {\n throw new Error('encoded variant overruns containing union');\n }\n }\n return span;\n }\n\n /** Delegate {@link Layout#fromArray|fromArray} to {@link\n * VariantLayout#layout|layout}. */\n fromArray(values) {\n if (this.layout) {\n return this.layout.fromArray(values);\n }\n }\n}\n\n/** JavaScript chose to define bitwise operations as operating on\n * signed 32-bit values in 2's complement form, meaning any integer\n * with bit 31 set is going to look negative. For right shifts that's\n * not a problem, because `>>>` is a logical shift, but for every\n * other bitwise operator we have to compensate for possible negative\n * results. */\nfunction fixBitwiseResult(v) {\n if (0 > v) {\n v += 0x100000000;\n }\n return v;\n}\n\n/**\n * Contain a sequence of bit fields as an unsigned integer.\n *\n * *Factory*: {@link module:Layout.bits|bits}\n *\n * This is a container element; within it there are {@link BitField}\n * instances that provide the extracted properties. The container\n * simply defines the aggregate representation and its bit ordering.\n * The representation is an object containing properties with numeric\n * or {@link Boolean} values.\n *\n * {@link BitField}s are added with the {@link\n * BitStructure#addField|addField} and {@link\n * BitStructure#addBoolean|addBoolean} methods.\n\n * @param {Layout} word - initializer for {@link\n * BitStructure#word|word}. The parameter must be an instance of\n * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.\n *\n * @param {bool} [msb] - `true` if the bit numbering starts at the\n * most significant bit of the containing word; `false` (default) if\n * it starts at the least significant bit of the containing word. If\n * the parameter at this position is a string and `property` is\n * `undefined` the value of this argument will instead be used as the\n * value of `property`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass BitStructure extends Layout {\n constructor(word, msb, property) {\n if (!((word instanceof UInt)\n || (word instanceof UIntBE))) {\n throw new TypeError('word must be a UInt or UIntBE layout');\n }\n if (('string' === typeof msb)\n && (undefined === property)) {\n property = msb;\n msb = undefined;\n }\n if (4 < word.span) {\n throw new RangeError('word cannot exceed 32 bits');\n }\n super(word.span, property);\n\n /** The layout used for the packed value. {@link BitField}\n * instances are packed sequentially depending on {@link\n * BitStructure#msb|msb}. */\n this.word = word;\n\n /** Whether the bit sequences are packed starting at the most\n * significant bit growing down (`true`), or the least significant\n * bit growing up (`false`).\n *\n * **NOTE** Regardless of this value, the least significant bit of\n * any {@link BitField} value is the least significant bit of the\n * corresponding section of the packed value. */\n this.msb = !!msb;\n\n /** The sequence of {@link BitField} layouts that comprise the\n * packed structure.\n *\n * **NOTE** The array remains mutable to allow fields to be {@link\n * BitStructure#addField|added} after construction. Users should\n * not manipulate the content of this property.*/\n this.fields = [];\n\n /* Storage for the value. Capture a variable instead of using an\n * instance property because we don't want anything to change the\n * value without going through the mutator. */\n let value = 0;\n this._packedSetValue = function(v) {\n value = fixBitwiseResult(v);\n return this;\n };\n this._packedGetValue = function() {\n return value;\n };\n }\n\n /** @override */\n decode(b, offset) {\n const dest = this.makeDestinationObject();\n if (undefined === offset) {\n offset = 0;\n }\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(value);\n }\n }\n return dest;\n }\n\n /** Implement {@link Layout#encode|encode} for {@link BitStructure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the packed\n * value is left unmodified. Unused bits are also left unmodified. */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n fd.encode(fv);\n }\n }\n }\n return this.word.encode(this._packedGetValue(), b, offset);\n }\n\n /** Register a new bitfield with a containing bit structure. The\n * resulting bitfield is returned.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {BitField} */\n addField(bits, property) {\n const bf = new BitField(this, bits, property);\n this.fields.push(bf);\n return bf;\n }\n\n /** As with {@link BitStructure#addField|addField} for single-bit\n * fields with `boolean` value representation.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {Boolean} */\n addBoolean(property) {\n // This is my Boolean, not the Javascript one.\n // eslint-disable-next-line no-new-wrappers\n const bf = new Boolean(this, property);\n this.fields.push(bf);\n return bf;\n }\n\n /**\n * Get access to the bit field for a given property.\n *\n * @param {String} property - the bit field of interest.\n *\n * @return {BitField} - the field associated with `property`, or\n * undefined if there is no such property.\n */\n fieldFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n }\n}\n\n/**\n * Represent a sequence of bits within a {@link BitStructure}.\n *\n * All bit field values are represented as unsigned integers.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addField|addField} helper\n * method.\n *\n * **NOTE** BitField instances are not instances of {@link Layout}\n * since {@link Layout#span|span} measures 8-bit units.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n */\nclass BitField {\n constructor(container, bits, property) {\n if (!(container instanceof BitStructure)) {\n throw new TypeError('container must be a BitStructure');\n }\n if ((!Number.isInteger(bits)) || (0 >= bits)) {\n throw new TypeError('bits must be positive integer');\n }\n const totalBits = 8 * container.span;\n const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);\n if ((bits + usedBits) > totalBits) {\n throw new Error('bits too long for span remainder ('\n + (totalBits - usedBits) + ' of '\n + totalBits + ' remain)');\n }\n\n /** The {@link BitStructure} instance to which this bit field\n * belongs. */\n this.container = container;\n\n /** The span of this value in bits. */\n this.bits = bits;\n\n /** A mask of {@link BitField#bits|bits} bits isolating value bits\n * that fit within the field.\n *\n * That is, it masks a value that has not yet been shifted into\n * position within its containing packed integer. */\n this.valueMask = (1 << bits) - 1;\n if (32 === bits) { // shifted value out of range\n this.valueMask = 0xFFFFFFFF;\n }\n\n /** The offset of the value within the containing packed unsigned\n * integer. The least significant bit of the packed value is at\n * offset zero, regardless of bit ordering used. */\n this.start = usedBits;\n if (this.container.msb) {\n this.start = totalBits - usedBits - bits;\n }\n\n /** A mask of {@link BitField#bits|bits} isolating the field value\n * within the containing packed unsigned integer. */\n this.wordMask = fixBitwiseResult(this.valueMask << this.start);\n\n /** The property name used when this bitfield is represented in an\n * Object.\n *\n * Intended to be functionally equivalent to {@link\n * Layout#property}.\n *\n * If left undefined the corresponding span of bits will be\n * treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n\n /** Store a value into the corresponding subsequence of the containing\n * bit field. */\n decode() {\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(word & this.wordMask);\n const value = wordValue >>> this.start;\n return value;\n }\n\n /** Store a value into the corresponding subsequence of the containing\n * bit field.\n *\n * **NOTE** This is not a specialization of {@link\n * Layout#encode|Layout.encode} and there is no return value. */\n encode(value) {\n if ((!Number.isInteger(value))\n || (value !== fixBitwiseResult(value & this.valueMask))) {\n throw new TypeError(nameWithProperty('BitField.encode', this)\n + ' value must be integer not exceeding ' + this.valueMask);\n }\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(value << this.start);\n this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)\n | wordValue);\n };\n}\n\n/**\n * Represent a single bit within a {@link BitStructure} as a\n * JavaScript boolean.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addBoolean|addBoolean} helper\n * method.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {BitField}\n */\n/* eslint-disable no-extend-native */\nclass Boolean extends BitField {\n constructor(container, property) {\n super(container, 1, property);\n }\n\n /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.\n *\n * @returns {boolean} */\n decode(b, offset) {\n return !!BitField.prototype.decode.call(this, b, offset);\n }\n\n /** @override */\n encode(value) {\n if ('boolean' === typeof value) {\n // BitField requires integer values\n value = +value;\n }\n return BitField.prototype.encode.call(this, value);\n }\n}\n/* eslint-enable no-extend-native */\n\n/**\n * Contain a fixed-length block of arbitrary data, represented as a\n * Buffer.\n *\n * *Factory*: {@link module:Layout.blob|blob}\n *\n * @param {(Number|ExternalLayout)} length - initializes {@link\n * Blob#length|length}.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Blob extends Layout {\n constructor(length, property) {\n if (!(((length instanceof ExternalLayout) && length.isCount())\n || (Number.isInteger(length) && (0 <= length)))) {\n throw new TypeError('length must be positive integer '\n + 'or an unsigned integer ExternalLayout');\n }\n\n let span = -1;\n if (!(length instanceof ExternalLayout)) {\n span = length;\n }\n super(span, property);\n\n /** The number of bytes in the blob.\n *\n * This may be a non-negative integer, or an instance of {@link\n * ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}. */\n this.length = length;\n }\n\n /** @override */\n getSpan(b, offset) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return span;\n }\n\n /** @override */\n decode(b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return b.slice(offset, offset + span);\n }\n\n /** Implement {@link Layout#encode|encode} for {@link Blob}.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n let span = this.length;\n if (this.length instanceof ExternalLayout) {\n span = src.length;\n }\n if (!(Buffer.isBuffer(src)\n && (span === src.length))) {\n throw new TypeError(nameWithProperty('Blob.encode', this)\n + ' requires (length ' + span + ') Buffer as src');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n b.write(src.toString('hex'), offset, span, 'hex');\n if (this.length instanceof ExternalLayout) {\n this.length.encode(span, b, offset);\n }\n return span;\n }\n}\n\n/**\n * Contain a `NUL`-terminated UTF8 string.\n *\n * *Factory*: {@link module:Layout.cstr|cstr}\n *\n * **NOTE** Any UTF8 string that incorporates a zero-valued byte will\n * not be correctly decoded by this layout.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass CString extends Layout {\n constructor(property) {\n super(-1, property);\n }\n\n /** @override */\n getSpan(b, offset) {\n if (!Buffer.isBuffer(b)) {\n throw new TypeError('b must be a Buffer');\n }\n if (undefined === offset) {\n offset = 0;\n }\n let idx = offset;\n while ((idx < b.length) && (0 !== b[idx])) {\n idx += 1;\n }\n return 1 + idx - offset;\n }\n\n /** @override */\n decode(b, offset, dest) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.getSpan(b, offset);\n return b.slice(offset, offset + span - 1).toString('utf-8');\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = src.toString();\n }\n const srcb = new Buffer(src, 'utf8');\n const span = srcb.length;\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(b, offset);\n b[offset + span] = 0;\n return span + 1;\n }\n}\n\n/**\n * Contain a UTF8 string with implicit length.\n *\n * *Factory*: {@link module:Layout.utf8|utf8}\n *\n * **NOTE** Because the length is implicit in the size of the buffer\n * this layout should be used only in isolation, or in a situation\n * where the length can be expressed by operating on a slice of the\n * containing buffer.\n *\n * @param {Number} [maxSpan] - the maximum length allowed for encoded\n * string content. If not provided there is no bound on the allowed\n * content.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UTF8 extends Layout {\n constructor(maxSpan, property) {\n if (('string' === typeof maxSpan)\n && (undefined === property)) {\n property = maxSpan;\n maxSpan = undefined;\n }\n if (undefined === maxSpan) {\n maxSpan = -1;\n } else if (!Number.isInteger(maxSpan)) {\n throw new TypeError('maxSpan must be an integer');\n }\n\n super(-1, property);\n\n /** The maximum span of the layout in bytes.\n *\n * Positive values are generally expected. Zero is abnormal.\n * Attempts to encode or decode a value that exceeds this length\n * will throw a `RangeError`.\n *\n * A negative value indicates that there is no bound on the length\n * of the content. */\n this.maxSpan = maxSpan;\n }\n\n /** @override */\n getSpan(b, offset) {\n if (!Buffer.isBuffer(b)) {\n throw new TypeError('b must be a Buffer');\n }\n if (undefined === offset) {\n offset = 0;\n }\n return b.length - offset;\n }\n\n /** @override */\n decode(b, offset, dest) {\n if (undefined === offset) {\n offset = 0;\n }\n let span = this.getSpan(b, offset);\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n return b.slice(offset, offset + span).toString('utf-8');\n }\n\n /** @override */\n encode(src, b, offset) {\n if (undefined === offset) {\n offset = 0;\n }\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = src.toString();\n }\n const srcb = new Buffer(src, 'utf8');\n const span = srcb.length;\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(b, offset);\n return span;\n }\n}\n\n/**\n * Contain a constant value.\n *\n * This layout may be used in cases where a JavaScript value can be\n * inferred without an expression in the binary encoding. An example\n * would be a {@link VariantLayout|variant layout} where the content\n * is implied by the union {@link Union#discriminator|discriminator}.\n *\n * @param {Object|Number|String} value - initializer for {@link\n * Constant#value|value}. If the value is an object (or array) and\n * the application intends the object to remain unchanged regardless\n * of what is done to values decoded by this layout, the value should\n * be frozen prior passing it to this constructor.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Constant extends Layout {\n constructor(value, property) {\n super(0, property);\n\n /** The value produced by this constant when the layout is {@link\n * Constant#decode|decoded}.\n *\n * Any JavaScript value including `null` and `undefined` is\n * permitted.\n *\n * **WARNING** If `value` passed in the constructor was not\n * frozen, it is possible for users of decoded values to change\n * the content of the value. */\n this.value = value;\n }\n\n /** @override */\n decode(b, offset, dest) {\n return this.value;\n }\n\n /** @override */\n encode(src, b, offset) {\n /* Constants take no space */\n return 0;\n }\n}\n\nexports.ExternalLayout = ExternalLayout;\nexports.GreedyCount = GreedyCount;\nexports.OffsetLayout = OffsetLayout;\nexports.UInt = UInt;\nexports.UIntBE = UIntBE;\nexports.Int = Int;\nexports.IntBE = IntBE;\nexports.Float = Float;\nexports.FloatBE = FloatBE;\nexports.Double = Double;\nexports.DoubleBE = DoubleBE;\nexports.Sequence = Sequence;\nexports.Structure = Structure;\nexports.UnionDiscriminator = UnionDiscriminator;\nexports.UnionLayoutDiscriminator = UnionLayoutDiscriminator;\nexports.Union = Union;\nexports.VariantLayout = VariantLayout;\nexports.BitStructure = BitStructure;\nexports.BitField = BitField;\nexports.Boolean = Boolean;\nexports.Blob = Blob;\nexports.CString = CString;\nexports.UTF8 = UTF8;\nexports.Constant = Constant;\n\n/** Factory for {@link GreedyCount}. */\nexports.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));\n\n/** Factory for {@link OffsetLayout}. */\nexports.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));\n\n/** Factory for {@link UInt|unsigned int layouts} spanning one\n * byte. */\nexports.u8 = (property => new UInt(1, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16 = (property => new UInt(2, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24 = (property => new UInt(3, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32 = (property => new UInt(4, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40 = (property => new UInt(5, property));\n\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48 = (property => new UInt(6, property));\n\n/** Factory for {@link NearUInt64|little-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64 = (property => new NearUInt64(property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16be = (property => new UIntBE(2, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24be = (property => new UIntBE(3, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32be = (property => new UIntBE(4, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40be = (property => new UIntBE(5, property));\n\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48be = (property => new UIntBE(6, property));\n\n/** Factory for {@link NearUInt64BE|big-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64be = (property => new NearUInt64BE(property));\n\n/** Factory for {@link Int|signed int layouts} spanning one\n * byte. */\nexports.s8 = (property => new Int(1, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning two bytes. */\nexports.s16 = (property => new Int(2, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning three bytes. */\nexports.s24 = (property => new Int(3, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning four bytes. */\nexports.s32 = (property => new Int(4, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning five bytes. */\nexports.s40 = (property => new Int(5, property));\n\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning six bytes. */\nexports.s48 = (property => new Int(6, property));\n\n/** Factory for {@link NearInt64|little-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64 = (property => new NearInt64(property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning two bytes. */\nexports.s16be = (property => new IntBE(2, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning three bytes. */\nexports.s24be = (property => new IntBE(3, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning four bytes. */\nexports.s32be = (property => new IntBE(4, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning five bytes. */\nexports.s40be = (property => new IntBE(5, property));\n\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning six bytes. */\nexports.s48be = (property => new IntBE(6, property));\n\n/** Factory for {@link NearInt64BE|big-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64be = (property => new NearInt64BE(property));\n\n/** Factory for {@link Float|little-endian 32-bit floating point} values. */\nexports.f32 = (property => new Float(property));\n\n/** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */\nexports.f32be = (property => new FloatBE(property));\n\n/** Factory for {@link Double|little-endian 64-bit floating point} values. */\nexports.f64 = (property => new Double(property));\n\n/** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */\nexports.f64be = (property => new DoubleBE(property));\n\n/** Factory for {@link Structure} values. */\nexports.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));\n\n/** Factory for {@link BitStructure} values. */\nexports.bits = ((word, msb, property) => new BitStructure(word, msb, property));\n\n/** Factory for {@link Sequence} values. */\nexports.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));\n\n/** Factory for {@link Union} values. */\nexports.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));\n\n/** Factory for {@link UnionLayoutDiscriminator} values. */\nexports.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));\n\n/** Factory for {@link Blob} values. */\nexports.blob = ((length, property) => new Blob(length, property));\n\n/** Factory for {@link CString} values. */\nexports.cstr = (property => new CString(property));\n\n/** Factory for {@link UTF8} values. */\nexports.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));\n\n/** Factory for {@link Constant} values. */\nexports.const = ((value, property) => new Constant(value, property));\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.map = exports.array = exports.rustEnum = exports.str = exports.vecU8 = exports.tagged = exports.vec = exports.bool = exports.option = exports.publicKey = exports.i256 = exports.u256 = exports.i128 = exports.u128 = exports.i64 = exports.u64 = exports.struct = exports.f64 = exports.f32 = exports.i32 = exports.u32 = exports.i16 = exports.u16 = exports.i8 = exports.u8 = void 0;\nconst buffer_layout_1 = require(\"buffer-layout\");\nconst web3_js_1 = require(\"@solana/web3.js\");\nconst bn_js_1 = __importDefault(require(\"bn.js\"));\nvar buffer_layout_2 = require(\"buffer-layout\");\nObject.defineProperty(exports, \"u8\", { enumerable: true, get: function () { return buffer_layout_2.u8; } });\nObject.defineProperty(exports, \"i8\", { enumerable: true, get: function () { return buffer_layout_2.s8; } });\nObject.defineProperty(exports, \"u16\", { enumerable: true, get: function () { return buffer_layout_2.u16; } });\nObject.defineProperty(exports, \"i16\", { enumerable: true, get: function () { return buffer_layout_2.s16; } });\nObject.defineProperty(exports, \"u32\", { enumerable: true, get: function () { return buffer_layout_2.u32; } });\nObject.defineProperty(exports, \"i32\", { enumerable: true, get: function () { return buffer_layout_2.s32; } });\nObject.defineProperty(exports, \"f32\", { enumerable: true, get: function () { return buffer_layout_2.f32; } });\nObject.defineProperty(exports, \"f64\", { enumerable: true, get: function () { return buffer_layout_2.f64; } });\nObject.defineProperty(exports, \"struct\", { enumerable: true, get: function () { return buffer_layout_2.struct; } });\nclass BNLayout extends buffer_layout_1.Layout {\n constructor(span, signed, property) {\n super(span, property);\n this.blob = (0, buffer_layout_1.blob)(span);\n this.signed = signed;\n }\n decode(b, offset = 0) {\n const num = new bn_js_1.default(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n encode(src, b, offset = 0) {\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\nfunction u64(property) {\n return new BNLayout(8, false, property);\n}\nexports.u64 = u64;\nfunction i64(property) {\n return new BNLayout(8, true, property);\n}\nexports.i64 = i64;\nfunction u128(property) {\n return new BNLayout(16, false, property);\n}\nexports.u128 = u128;\nfunction i128(property) {\n return new BNLayout(16, true, property);\n}\nexports.i128 = i128;\nfunction u256(property) {\n return new BNLayout(32, false, property);\n}\nexports.u256 = u256;\nfunction i256(property) {\n return new BNLayout(32, true, property);\n}\nexports.i256 = i256;\nclass WrappedLayout extends buffer_layout_1.Layout {\n constructor(layout, decoder, encoder, property) {\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n decode(b, offset) {\n return this.decoder(this.layout.decode(b, offset));\n }\n encode(src, b, offset) {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n getSpan(b, offset) {\n return this.layout.getSpan(b, offset);\n }\n}\nfunction publicKey(property) {\n return new WrappedLayout((0, buffer_layout_1.blob)(32), (b) => new web3_js_1.PublicKey(b), (key) => key.toBuffer(), property);\n}\nexports.publicKey = publicKey;\nclass OptionLayout extends buffer_layout_1.Layout {\n constructor(layout, property) {\n super(-1, property);\n this.layout = layout;\n this.discriminator = (0, buffer_layout_1.u8)();\n }\n encode(src, b, offset = 0) {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n decode(b, offset = 0) {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n }\n else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n getSpan(b, offset = 0) {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n }\n else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\nfunction option(layout, property) {\n return new OptionLayout(layout, property);\n}\nexports.option = option;\nfunction bool(property) {\n return new WrappedLayout((0, buffer_layout_1.u8)(), decodeBool, encodeBool, property);\n}\nexports.bool = bool;\nfunction decodeBool(value) {\n if (value === 0) {\n return false;\n }\n else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\nfunction encodeBool(value) {\n return value ? 1 : 0;\n}\nfunction vec(elementLayout, property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.seq)(elementLayout, (0, buffer_layout_1.offset)(length, -length.span), \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => values, (values) => ({ values }), property);\n}\nexports.vec = vec;\nfunction tagged(tag, layout, property) {\n const wrappedLayout = (0, buffer_layout_1.struct)([\n u64(\"tag\"),\n layout.replicate(\"data\"),\n ]);\n function decodeTag({ tag: receivedTag, data }) {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" +\n tag.toString(\"hex\") +\n \", got: \" +\n receivedTag.toString(\"hex\"));\n }\n return data;\n }\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\nexports.tagged = tagged;\nfunction vecU8(property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.blob)((0, buffer_layout_1.offset)(length, -length.span), \"data\"),\n ]);\n return new WrappedLayout(layout, ({ data }) => data, (data) => ({ data }), property);\n}\nexports.vecU8 = vecU8;\nfunction str(property) {\n return new WrappedLayout(vecU8(), (data) => data.toString(\"utf-8\"), (s) => Buffer.from(s, \"utf-8\"), property);\n}\nexports.str = str;\nfunction rustEnum(variants, property, discriminant) {\n const unionLayout = (0, buffer_layout_1.union)(discriminant !== null && discriminant !== void 0 ? discriminant : (0, buffer_layout_1.u8)(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout;\n}\nexports.rustEnum = rustEnum;\nfunction array(elementLayout, length, property) {\n const layout = (0, buffer_layout_1.struct)([\n (0, buffer_layout_1.seq)(elementLayout, length, \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => values, (values) => ({ values }), property);\n}\nexports.array = array;\nclass MapEntryLayout extends buffer_layout_1.Layout {\n constructor(keyLayout, valueLayout, property) {\n super(keyLayout.span + valueLayout.span, property);\n this.keyLayout = keyLayout;\n this.valueLayout = valueLayout;\n }\n decode(b, offset) {\n offset = offset || 0;\n const key = this.keyLayout.decode(b, offset);\n const value = this.valueLayout.decode(b, offset + this.keyLayout.getSpan(b, offset));\n return [key, value];\n }\n encode(src, b, offset) {\n offset = offset || 0;\n const keyBytes = this.keyLayout.encode(src[0], b, offset);\n const valueBytes = this.valueLayout.encode(src[1], b, offset + keyBytes);\n return keyBytes + valueBytes;\n }\n getSpan(b, offset) {\n return (this.keyLayout.getSpan(b, offset) + this.valueLayout.getSpan(b, offset));\n }\n}\nfunction map(keyLayout, valueLayout, property) {\n const length = (0, buffer_layout_1.u32)(\"length\");\n const layout = (0, buffer_layout_1.struct)([\n length,\n (0, buffer_layout_1.seq)(new MapEntryLayout(keyLayout, valueLayout), (0, buffer_layout_1.offset)(length, -length.span), \"values\"),\n ]);\n return new WrappedLayout(layout, ({ values }) => new Map(values), (values) => ({ values: Array.from(values.entries()) }), property);\n}\nexports.map = map;\n//# sourceMappingURL=index.js.map","import { Buffer } from 'buffer';\nimport { PublicKey, AccountMeta } from '@solana/web3.js';\nimport {\n struct,\n u8,\n u64,\n bool,\n vec,\n option,\n publicKey,\n array,\n u16,\n u32,\n Layout,\n vecU8,\n} from '@coral-xyz/borsh';\nimport {\n InstructionDataInvoke,\n InstructionDataInvokeCpi,\n PublicTransactionEvent,\n} from '../state';\nimport { LightSystemProgram } from './system';\nimport { INVOKE_CPI_DISCRIMINATOR, INVOKE_DISCRIMINATOR } from '../constants';\nimport { BN } from 'bn.js';\n\nexport const CompressedAccountLayout = struct(\n [\n publicKey('owner'),\n u64('lamports'),\n option(array(u8(), 32), 'address'),\n option(\n struct([\n array(u8(), 8, 'discriminator'),\n vecU8('data'),\n array(u8(), 32, 'dataHash'),\n ]),\n 'data',\n ),\n ],\n 'compressedAccount',\n);\n\nexport const MerkleContextLayout = struct(\n [\n u8('merkleTreePubkeyIndex'),\n u8('nullifierQueuePubkeyIndex'),\n u32('leafIndex'),\n option(struct([u8('queueId'), u16('index')]), 'queueIndex'),\n ],\n 'merkleContext',\n);\n\nexport const NewAddressParamsLayout = struct(\n [\n array(u8(), 32, 'seed'),\n u8('addressQueueAccountIndex'),\n u8('addressMerkleTreeAccountIndex'),\n u16('addressMerkleTreeRootIndex'),\n ],\n 'newAddressParams',\n);\n\nexport const InstructionDataInvokeLayout: Layout<InstructionDataInvoke> =\n struct([\n option(\n struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n ]),\n 'proof',\n ),\n vec(\n struct([\n CompressedAccountLayout,\n MerkleContextLayout,\n u16('rootIndex'),\n bool('readOnly'),\n ]),\n 'inputCompressedAccountsWithMerkleContext',\n ),\n vec(\n struct([CompressedAccountLayout, u8('merkleTreeIndex')]),\n 'outputCompressedAccounts',\n ),\n option(u64(), 'relayFee'),\n vec(NewAddressParamsLayout, 'newAddressParams'),\n option(u64(), 'compressOrDecompressLamports'),\n bool('isCompress'),\n ]);\n\nexport function encodeInstructionDataInvoke(\n data: InstructionDataInvoke,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = InstructionDataInvokeLayout.encode(data, buffer);\n const dataBuffer = Buffer.from(buffer.slice(0, len));\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n return Buffer.concat([INVOKE_DISCRIMINATOR, lengthBuffer, dataBuffer]);\n}\n\nexport const InstructionDataInvokeCpiLayout: Layout<InstructionDataInvokeCpi> =\n struct([\n option(\n struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n ]),\n 'proof',\n ),\n vec(NewAddressParamsLayout, 'newAddressParams'),\n vec(\n struct([\n CompressedAccountLayout,\n MerkleContextLayout,\n u16('rootIndex'),\n bool('readOnly'),\n ]),\n 'inputCompressedAccountsWithMerkleContext',\n ),\n vec(\n struct([CompressedAccountLayout, u8('merkleTreeIndex')]),\n 'outputCompressedAccounts',\n ),\n option(u64(), 'relayFee'),\n option(u64(), 'compressOrDecompressLamports'),\n bool('isCompress'),\n option(\n struct([\n bool('set_context'),\n bool('first_set_context'),\n u8('cpi_context_account_index'),\n ]),\n 'compressedCpiContext',\n ),\n ]);\n\nexport function decodeInstructionDataInvoke(\n buffer: Buffer,\n): InstructionDataInvoke {\n return InstructionDataInvokeLayout.decode(\n buffer.slice(INVOKE_DISCRIMINATOR.length + 4),\n );\n}\n\nexport function decodeInstructionDataInvokeCpi(\n buffer: Buffer,\n): InstructionDataInvokeCpi {\n return InstructionDataInvokeCpiLayout.decode(\n buffer.slice(INVOKE_CPI_DISCRIMINATOR.length + 4),\n );\n}\n\nexport type invokeAccountsLayoutParams = {\n feePayer: PublicKey;\n authority: PublicKey;\n registeredProgramPda: PublicKey;\n noopProgram: PublicKey;\n accountCompressionAuthority: PublicKey;\n accountCompressionProgram: PublicKey;\n solPoolPda: PublicKey | null;\n decompressionRecipient: PublicKey | null;\n systemProgram: PublicKey;\n};\n\nexport const invokeAccountsLayout = (\n accounts: invokeAccountsLayoutParams,\n): AccountMeta[] => {\n const defaultPubkey = LightSystemProgram.programId;\n const {\n feePayer,\n authority,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n solPoolPda,\n decompressionRecipient,\n systemProgram,\n } = accounts;\n\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: solPoolPda ?? defaultPubkey,\n isSigner: false,\n isWritable: solPoolPda !== null,\n },\n {\n pubkey: decompressionRecipient ?? defaultPubkey,\n isSigner: false,\n isWritable: true,\n },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n ];\n};\n\nexport const PublicTransactionEventLayout: Layout<PublicTransactionEvent> =\n struct([\n vec(array(u8(), 32), 'inputCompressedAccountHashes'),\n vec(array(u8(), 32), 'outputCompressedAccountHashes'),\n vec(\n struct([\n struct(\n [\n publicKey('owner'),\n u64('lamports'),\n option(array(u8(), 32), 'address'),\n option(\n struct([\n array(u8(), 8, 'discriminator'),\n vecU8('data'),\n array(u8(), 32, 'dataHash'),\n ]),\n 'data',\n ),\n ],\n 'compressedAccount',\n ),\n u8('merkleTreeIndex'),\n ]),\n 'outputCompressedAccounts',\n ),\n vec(u32(), 'outputLeafIndices'),\n vec(struct([publicKey('pubkey'), u64('seq')]), 'sequenceNumbers'),\n option(u64(), 'relayFee'),\n bool('isCompress'),\n option(u64(), 'compressOrDecompressLamports'),\n vec(publicKey(), 'pubkeyArray'),\n option(vecU8(), 'message'),\n ]);\n\nexport function encodePublicTransactionEvent(\n data: PublicTransactionEvent,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = PublicTransactionEventLayout.encode(data, buffer);\n\n return buffer.slice(0, len);\n}\n\nexport function decodePublicTransactionEvent(\n buffer: Buffer,\n): PublicTransactionEvent {\n return PublicTransactionEventLayout.decode(buffer);\n}\n\nexport const AppendNullifyCreateAddressInputsMetaLayout = struct(\n [\n u8('is_invoked_by_program'),\n u8('bump'),\n u8('num_queues'),\n u8('num_output_queues'),\n u8('start_output_appends'),\n u8('num_address_queues'),\n array(u8(), 32, 'tx_hash'),\n ],\n 'appendNullifyCreateAddressInputsMeta',\n);\n\nexport const AppendLeavesInputLayout = struct(\n [u8('index'), array(u8(), 32, 'leaf')],\n 'appendLeavesInput',\n);\n\nexport const InsertNullifierInputLayout = struct(\n [\n array(u8(), 32, 'account_hash'),\n u32('leaf_index'),\n u8('prove_by_index'),\n u8('tree_index'),\n u8('queue_index'),\n ],\n 'insertNullifierInput',\n);\nexport const InsertAddressInputLayout = struct(\n [array(u8(), 32, 'address'), u8('tree_index'), u8('queue_index')],\n 'insertAddressInput',\n);\n\nexport const MerkleTreeSequenceNumberLayout = struct(\n [publicKey('pubkey'), u64('seq')],\n 'merkleTreeSequenceNumber',\n);\n\nexport function deserializeAppendNullifyCreateAddressInputsIndexer(\n buffer: Buffer,\n) {\n let offset = 0;\n const meta = AppendNullifyCreateAddressInputsMetaLayout.decode(\n buffer,\n offset,\n );\n offset += AppendNullifyCreateAddressInputsMetaLayout.span;\n const leavesCount = buffer.readUInt8(offset);\n offset += 1;\n const leaves = [];\n for (let i = 0; i < leavesCount; i++) {\n const leaf = AppendLeavesInputLayout.decode(buffer, offset);\n leaves.push(leaf);\n offset += AppendLeavesInputLayout.span;\n }\n const nullifiersCount = buffer.readUInt8(offset);\n offset += 1;\n const nullifiers = [];\n for (let i = 0; i < nullifiersCount; i++) {\n const nullifier = InsertNullifierInputLayout.decode(buffer, offset);\n nullifiers.push(nullifier);\n offset += InsertNullifierInputLayout.span;\n }\n const addressesCount = buffer.readUInt8(offset);\n offset += 1;\n const addresses = [];\n for (let i = 0; i < addressesCount; i++) {\n const address = InsertAddressInputLayout.decode(buffer, offset);\n addresses.push(address);\n offset += InsertAddressInputLayout.span;\n }\n const outputSequenceNumbersCount = buffer.readUInt8(offset);\n offset += 1;\n const output_sequence_numbers = [];\n for (let i = 0; i < outputSequenceNumbersCount; i++) {\n const seq = MerkleTreeSequenceNumberLayout.decode(buffer, offset);\n output_sequence_numbers.push(seq);\n offset += MerkleTreeSequenceNumberLayout.span;\n }\n const inputSequenceNumbersCount = buffer.readUInt8(offset);\n offset += 1;\n const inputSequence_numbers = [];\n for (let i = 0; i < inputSequenceNumbersCount; i++) {\n const seq = MerkleTreeSequenceNumberLayout.decode(buffer, offset);\n inputSequence_numbers.push(seq);\n offset += MerkleTreeSequenceNumberLayout.span;\n }\n const addressSequenceNumbersCount = buffer.readUInt8(offset);\n offset += 1;\n const addressSequence_numbers = [];\n for (let i = 0; i < addressSequenceNumbersCount; i++) {\n const seq = MerkleTreeSequenceNumberLayout.decode(buffer, offset);\n addressSequence_numbers.push(seq);\n offset += MerkleTreeSequenceNumberLayout.span;\n }\n const outputLeafIndicesCount = buffer.readUInt8(offset);\n offset += 1;\n const output_leaf_indices = [];\n for (let i = 0; i < outputLeafIndicesCount; i++) {\n const index = u32().decode(buffer, offset);\n output_leaf_indices.push(index);\n offset += 4;\n }\n return {\n meta,\n leaves,\n nullifiers,\n addresses,\n sequence_numbers: output_sequence_numbers,\n output_leaf_indices,\n };\n}\n\nexport function convertToPublicTransactionEvent(\n decoded: any,\n remainingAccounts: PublicKey[],\n invokeData: InstructionDataInvoke,\n): PublicTransactionEvent {\n const convertByteArray = (arr: Uint8Array | Buffer): number[] =>\n Array.from(arr instanceof Buffer ? new Uint8Array(arr) : arr);\n\n const result = {\n inputCompressedAccountHashes: decoded.nullifiers.map((n: any) =>\n convertByteArray(n.account_hash),\n ),\n outputCompressedAccountHashes: decoded.leaves.map((l: any) =>\n convertByteArray(l.leaf),\n ),\n outputCompressedAccounts: decoded.leaves.map(\n (leaf: any, index: number) => ({\n compressedAccount: {\n owner: new PublicKey(\n invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.owner || PublicKey.default,\n ),\n lamports: new BN(\n invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.lamports || 0,\n ),\n address:\n invokeData?.outputCompressedAccounts[index]\n .compressedAccount.address,\n data: invokeData?.outputCompressedAccounts[index]\n ?.compressedAccount.data\n ? {\n discriminator: convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[index]\n .compressedAccount.data\n ?.discriminator,\n ),\n ),\n data:\n convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[\n index\n ].compressedAccount.data.data,\n ),\n ) ?? [],\n dataHash: convertByteArray(\n Buffer.from(\n invokeData.outputCompressedAccounts[index]\n .compressedAccount.data?.dataHash,\n ),\n ),\n }\n : null,\n },\n merkleTreeIndex: leaf.index,\n }),\n ),\n outputLeafIndices: decoded.output_leaf_indices,\n sequenceNumbers: decoded.sequence_numbers.map((sn: any) => ({\n pubkey: new PublicKey(sn.pubkey),\n seq: new BN(sn.seq),\n })),\n pubkeyArray: remainingAccounts\n .slice(2)\n .filter(pk => !pk.equals(PublicKey.default)),\n isCompress: invokeData?.isCompress || false,\n relayFee: invokeData?.relayFee ? new BN(invokeData.relayFee) : null,\n compressOrDecompressLamports: invokeData?.compressOrDecompressLamports\n ? new BN(invokeData.compressOrDecompressLamports)\n : null,\n message: null,\n };\n\n return result;\n}\n","import BN from 'bn.js';\nimport {\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n CompressedAccount,\n CompressedAccountWithMerkleContext,\n CompressedProof,\n InstructionDataInvoke,\n bn,\n createCompressedAccount,\n} from '../state';\nimport { packCompressedAccounts, toAccountMetas } from '../instruction';\nimport { defaultStaticAccountsStruct } from '../constants';\nimport {\n validateSameOwner,\n validateSufficientBalance,\n} from '../utils/validation';\nimport { packNewAddressParams, NewAddressParams } from '../utils';\nimport { encodeInstructionDataInvoke, invokeAccountsLayout } from './layout';\n\nexport const sumUpLamports = (\n accounts: CompressedAccountWithMerkleContext[],\n): BN => {\n return accounts.reduce(\n (acc, account) => acc.add(bn(account.lamports)),\n bn(0),\n );\n};\n\n/**\n * Create compressed account system transaction params\n */\ntype CreateAccountWithSeedParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * Address params for the new compressed account\n */\n newAddressParams: NewAddressParams;\n newAddress: number[];\n /**\n * Recent validity proof proving that there's no existing compressed account\n * registered with newAccountAddress\n */\n recentValidityProof: CompressedProof;\n /**\n * State tree pubkey. Defaults to a public state tree if unspecified.\n */\n outputStateTree?: PublicKey;\n /**\n * Public key of the program to assign as the owner of the created account\n */\n programId?: PublicKey;\n /**\n * Optional input accounts to transfer lamports from into the new compressed\n * account.\n */\n inputCompressedAccounts?: CompressedAccountWithMerkleContext[];\n /**\n * Optional input state root indices of 'inputCompressedAccounts'. The\n * expiry is tied to the 'recentValidityProof'.\n */\n inputStateRootIndices?: number[];\n /**\n * Optional lamports to transfer into the new compressed account.\n */\n lamports?: number | BN;\n};\n\n/**\n * Defines the parameters for the transfer method\n */\ntype TransferParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * The input state to be consumed.\n */\n inputCompressedAccounts: CompressedAccountWithMerkleContext[];\n /**\n * Recipient address\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to transfer.\n */\n lamports: number | BN;\n /**\n * The recent state root indices of the input state. The expiry is tied to\n * the proof.\n *\n * TODO: Add support for passing recent-values after instruction creation.\n */\n recentInputStateRootIndices: number[];\n /**\n * The recent validity proof for state inclusion of the input state. It\n * expires after n slots.\n */\n recentValidityProof: CompressedProof;\n /**\n * The state trees that the tx output should be inserted into. This can be a\n * single PublicKey or an array of PublicKey. Defaults to the 0th state tree\n * of input state.\n */\n outputStateTrees?: PublicKey[] | PublicKey;\n};\n\n/// TODO:\n/// - add option to compress to another owner\n/// - add option to merge with input state\n/**\n * Defines the parameters for the transfer method\n */\ntype CompressParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * address that the lamports are attached to. also defaults to the recipient owner\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to compress.\n */\n lamports: number | BN;\n /**\n * The state tree that the tx output should be inserted into. Defaults to a\n * public state tree if unspecified.\n */\n outputStateTree?: PublicKey;\n};\n\n/**\n * Defines the parameters for the transfer method\n */\ntype DecompressParams = {\n /**\n * The payer of the transaction.\n */\n payer: PublicKey;\n /**\n * The input state to be consumed.\n */\n inputCompressedAccounts: CompressedAccountWithMerkleContext[];\n /**\n * Recipient address of uncompressed lamports\n */\n toAddress: PublicKey;\n /**\n * amount of lamports to decompress.\n */\n lamports: number | BN;\n /**\n * The recent state root indices of the input state. The expiry is tied to\n * the proof.\n *\n * TODO: Add support for passing recent-values after instruction creation.\n */\n recentInputStateRootIndices: number[];\n /**\n * The recent validity proof for state inclusion of the input state. It\n * expires after n slots.\n */\n recentValidityProof: CompressedProof;\n /**\n * The state trees that the tx output should be inserted into. This can be a\n * single PublicKey or an array of PublicKey. Defaults to the 0th state tree\n * of input state.\n */\n outputStateTree?: PublicKey;\n};\n\nconst SOL_POOL_PDA_SEED = Buffer.from('sol_pool_pda');\n\nexport class LightSystemProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the CompressedPda program\n */\n static programId: PublicKey = new PublicKey(\n 'SySTEM1eSU2p4BGQfQpimFEWWSC1XDFeun3Nqzz3rT7',\n );\n\n /**\n * @internal\n * Cwct1kQLwJm8Z3HetLu8m4SXkhD6FZ5fXbJQCxTxPnGY\n *\n */\n static deriveCompressedSolPda(): PublicKey {\n const seeds = [SOL_POOL_PDA_SEED];\n const [address, _] = PublicKey.findProgramAddressSync(\n seeds,\n this.programId,\n );\n return address;\n }\n\n static createTransferOutputState(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n toAddress: PublicKey,\n lamports: number | BN,\n ): CompressedAccount[] {\n lamports = bn(lamports);\n const inputLamports = sumUpLamports(inputCompressedAccounts);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n if (changeLamports.eq(bn(0))) {\n return [createCompressedAccount(toAddress, lamports)];\n }\n\n validateSameOwner(inputCompressedAccounts);\n\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n\n changeLamports,\n ),\n createCompressedAccount(toAddress, lamports),\n ];\n return outputCompressedAccounts;\n }\n\n static createDecompressOutputState(\n inputCompressedAccounts: CompressedAccountWithMerkleContext[],\n lamports: number | BN,\n ): CompressedAccount[] {\n lamports = bn(lamports);\n const inputLamports = sumUpLamports(inputCompressedAccounts);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n /// lamports gets decompressed\n if (changeLamports.eq(bn(0))) {\n return [];\n }\n\n validateSameOwner(inputCompressedAccounts);\n\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n changeLamports,\n ),\n ];\n return outputCompressedAccounts;\n }\n\n /**\n * No data by default\n */\n static createNewAddressOutputState(\n address: number[],\n owner: PublicKey,\n lamports?: BN | number,\n inputCompressedAccounts?: CompressedAccountWithMerkleContext[],\n ): CompressedAccount[] {\n lamports = bn(lamports ?? 0);\n const inputLamports = sumUpLamports(inputCompressedAccounts ?? []);\n const changeLamports = inputLamports.sub(lamports);\n\n validateSufficientBalance(changeLamports);\n\n if (changeLamports.eq(bn(0)) || !inputCompressedAccounts) {\n return [\n createCompressedAccount(owner, lamports, undefined, address),\n ];\n }\n\n validateSameOwner(inputCompressedAccounts);\n const outputCompressedAccounts: CompressedAccount[] = [\n createCompressedAccount(\n inputCompressedAccounts[0].owner,\n changeLamports,\n ),\n createCompressedAccount(owner, lamports, undefined, address),\n ];\n return outputCompressedAccounts;\n }\n\n /**\n * Creates instruction to create compressed account with PDA.\n * Cannot write data.\n *\n * TODO: support transfer of lamports to the new account.\n */\n static async createAccount({\n payer,\n newAddressParams,\n newAddress,\n recentValidityProof,\n outputStateTree,\n inputCompressedAccounts,\n inputStateRootIndices,\n lamports,\n }: CreateAccountWithSeedParams): Promise<TransactionInstruction> {\n const outputCompressedAccounts = this.createNewAddressOutputState(\n newAddress,\n payer,\n lamports,\n inputCompressedAccounts,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts: _remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts ?? [],\n inputStateRootIndices ?? [],\n outputCompressedAccounts,\n outputStateTree,\n );\n\n const { newAddressParamsPacked, remainingAccounts } =\n packNewAddressParams([newAddressParams], _remainingAccounts);\n\n const rawData: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: newAddressParamsPacked,\n compressOrDecompressLamports: null,\n isCompress: false,\n };\n const data = encodeInstructionDataInvoke(rawData);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: null,\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n static async transfer({\n payer,\n inputCompressedAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices,\n recentValidityProof,\n outputStateTrees,\n }: TransferParams): Promise<TransactionInstruction> {\n /// Create output state\n const outputCompressedAccounts = this.createTransferOutputState(\n inputCompressedAccounts,\n toAddress,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts,\n recentInputStateRootIndices,\n outputCompressedAccounts,\n outputStateTrees,\n );\n\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: [],\n compressOrDecompressLamports: null,\n isCompress: false,\n };\n\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: null,\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n // TODO: add support for non-fee-payer owner\n static async compress({\n payer,\n toAddress,\n lamports,\n outputStateTree,\n }: CompressParams): Promise<TransactionInstruction> {\n /// Create output state\n lamports = bn(lamports);\n\n const outputCompressedAccount = createCompressedAccount(\n toAddress,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n [],\n [],\n [outputCompressedAccount],\n outputStateTree,\n );\n\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: null,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n /// TODO: here and on-chain: option<newAddressInputs> or similar.\n newAddressParams: [],\n compressOrDecompressLamports: lamports,\n isCompress: true,\n };\n\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: LightSystemProgram.deriveCompressedSolPda(),\n decompressionRecipient: null,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Creates a transaction instruction that transfers compressed lamports from\n * one owner to another.\n */\n static async decompress({\n payer,\n inputCompressedAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices,\n recentValidityProof,\n outputStateTree,\n }: DecompressParams): Promise<TransactionInstruction> {\n /// Create output state\n lamports = bn(lamports);\n\n const outputCompressedAccounts = this.createDecompressOutputState(\n inputCompressedAccounts,\n lamports,\n );\n\n /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts,\n recentInputStateRootIndices,\n outputCompressedAccounts,\n outputStateTree,\n );\n /// Encode instruction data\n const rawInputs: InstructionDataInvoke = {\n proof: recentValidityProof,\n inputCompressedAccountsWithMerkleContext:\n packedInputCompressedAccounts,\n outputCompressedAccounts: packedOutputCompressedAccounts,\n relayFee: null,\n newAddressParams: [],\n compressOrDecompressLamports: lamports,\n isCompress: false,\n };\n const data = encodeInstructionDataInvoke(rawInputs);\n\n const accounts = invokeAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: payer,\n solPoolPda: LightSystemProgram.deriveCompressedSolPda(),\n decompressionRecipient: toAddress,\n systemProgram: SystemProgram.programId,\n });\n const keys = [...accounts, ...toAccountMetas(remainingAccounts)];\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n}\n\n/**\n * Selects the minimal number of compressed SOL accounts for a transfer.\n *\n * 1. Sorts the accounts by amount in descending order\n * 2. Accumulates the amount until it is greater than or equal to the transfer\n * amount\n */\nexport function selectMinCompressedSolAccountsForTransfer(\n accounts: CompressedAccountWithMerkleContext[],\n transferLamports: BN | number,\n): [selectedAccounts: CompressedAccountWithMerkleContext[], total: BN] {\n let accumulatedLamports = bn(0);\n transferLamports = bn(transferLamports);\n\n const selectedAccounts: CompressedAccountWithMerkleContext[] = [];\n\n accounts.sort((a, b) => b.lamports.cmp(a.lamports));\n\n for (const account of accounts) {\n if (accumulatedLamports.gte(bn(transferLamports))) break;\n accumulatedLamports = accumulatedLamports.add(account.lamports);\n selectedAccounts.push(account);\n }\n\n if (accumulatedLamports.lt(bn(transferLamports))) {\n throw new Error(\n `Not enough balance for transfer. Required: ${transferLamports.toString()}, available: ${accumulatedLamports.toString()}`,\n );\n }\n\n return [selectedAccounts, accumulatedLamports];\n}\n","/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const { message, explanation, ...rest } = failure;\n const { path } = failure;\n const msg = path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`;\n super(explanation ?? msg);\n if (explanation != null)\n this.cause = msg;\n Object.assign(this, rest);\n this.name = this.constructor.name;\n this.failures = () => {\n return (cached ?? (cached = [failure, ...failures()]));\n };\n }\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a non-array object.\n */\nfunction isNonArrayObject(x) {\n return isObject(x) && !Array.isArray(x);\n}\n/**\n * Check if a value is a plain object.\n */\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\nfunction print(value) {\n if (typeof value === 'symbol') {\n return value.toString();\n }\n return typeof value === 'string' ? JSON.stringify(value) : `${value}`;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\nfunction shiftIterator(input) {\n const { done, value } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n }\n else if (result === false) {\n result = {};\n }\n else if (typeof result === 'string') {\n result = { message: result };\n }\n const { path, branch } = context;\n const { type } = struct;\n const { refinement, message = `Expected a value of type \\`${type}\\`${refinement ? ` with refinement \\`${refinement}\\`` : ''}, but received: \\`${print(value)}\\``, } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message,\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\nfunction* run(value, struct, options = {}) {\n const { path = [], branch = [value], coerce = false, mask = false } = options;\n const ctx = { path, branch, mask };\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n let status = 'valid';\n for (const failure of struct.validator(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_valid';\n yield [failure, undefined];\n }\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce,\n mask,\n message: options.message,\n });\n for (const t of ts) {\n if (t[0]) {\n status = t[0].refinement != null ? 'not_refined' : 'not_valid';\n yield [t[0], undefined];\n }\n else if (coerce) {\n v = t[1];\n if (k === undefined) {\n value = v;\n }\n else if (value instanceof Map) {\n value.set(k, v);\n }\n else if (value instanceof Set) {\n value.add(v);\n }\n else if (isObject(value)) {\n if (v !== undefined || k in value)\n value[k] = v;\n }\n }\n }\n }\n if (status !== 'not_valid') {\n for (const failure of struct.refiner(value, ctx)) {\n failure.explanation = options.message;\n status = 'not_refined';\n yield [failure, undefined];\n }\n }\n if (status === 'valid') {\n yield [undefined, value];\n }\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\nclass Struct {\n constructor(props) {\n const { type, schema, validator, refiner, coercer = (value) => value, entries = function* () { }, } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.validator = () => [];\n }\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n }\n else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n assert(value, message) {\n return assert(value, this, message);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n create(value, message) {\n return create(value, this, message);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema. Masking applies recursively to\n * props of `object` structs only.\n */\n mask(value, message) {\n return mask(value, this, message);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `coerce` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful. Also, `mask` will turn on\n * masking of the unknown `object` props recursively if passed.\n */\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\nfunction assert(value, struct, message) {\n const result = validate(value, struct, { message });\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\nfunction create(value, struct, message) {\n const result = validate(value, struct, { coerce: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\nfunction mask(value, struct, message) {\n const result = validate(value, struct, { coerce: true, mask: true, message });\n if (result[0]) {\n throw result[0];\n }\n else {\n return result[1];\n }\n}\n/**\n * Check if a value passes a struct.\n */\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n }\n else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\nfunction assign(...Structs) {\n const isType = Structs[0].type === 'type';\n const schemas = Structs.map((s) => s.schema);\n const schema = Object.assign({}, ...schemas);\n return isType ? type(schema) : object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\nfunction define(name, validator) {\n return new Struct({ type: name, schema: null, validator });\n}\n/**\n * Create a new struct based on an existing struct, but the value is allowed to\n * be `undefined`. `log` will be called if the value is not `undefined`.\n */\nfunction deprecated(struct, log) {\n return new Struct({\n ...struct,\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n validator(value, ctx) {\n if (value === undefined) {\n return true;\n }\n else {\n log(value, ctx);\n return struct.validator(value, ctx);\n }\n },\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n const struct = fn(value, ctx);\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n *entries(value, ctx) {\n struct ?? (struct = fn());\n yield* struct.entries(value, ctx);\n },\n validator(value, ctx) {\n struct ?? (struct = fn());\n return struct.validator(value, ctx);\n },\n coercer(value, ctx) {\n struct ?? (struct = fn());\n return struct.coercer(value, ctx);\n },\n refiner(value, ctx) {\n struct ?? (struct = fn());\n return struct.refiner(value, ctx);\n },\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\nfunction omit(struct, keys) {\n const { schema } = struct;\n const subschema = { ...schema };\n for (const key of keys) {\n delete subschema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\nfunction partial(struct) {\n const isStruct = struct instanceof Struct;\n const schema = isStruct ? { ...struct.schema } : { ...struct };\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n if (isStruct && struct.type === 'type') {\n return type(schema);\n }\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\nfunction pick(struct, keys) {\n const { schema } = struct;\n const subschema = {};\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n switch (struct.type) {\n case 'type':\n return type(subschema);\n default:\n return object(subschema);\n }\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array value, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a bigint.\n */\nfunction bigint() {\n return define('bigint', (value) => {\n return typeof value === 'bigint';\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\nfunction boolean() {\n return define('boolean', (value) => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\nfunction date() {\n return define('date', (value) => {\n return ((value instanceof Date && !isNaN(value.getTime())) ||\n `Expected a valid \\`Date\\` object, but received: ${print(value)}`);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map((v) => print(v)).join();\n for (const key of values) {\n schema[key] = key;\n }\n return new Struct({\n type: 'enums',\n schema,\n validator(value) {\n return (values.includes(value) ||\n `Expected one of \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a function.\n */\nfunction func() {\n return define('func', (value) => {\n return (typeof value === 'function' ||\n `Expected a function, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\nfunction instance(Class) {\n return define('instance', (value) => {\n return (value instanceof Class ||\n `Expected a \\`${Class.name}\\` instance, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\nfunction integer() {\n return define('integer', (value) => {\n return ((typeof value === 'number' && !isNaN(value) && Number.isInteger(value)) ||\n `Expected an integer, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value matches all of a set of types.\n */\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n },\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n const t = typeof constant;\n return new Struct({\n type: 'literal',\n schema: t === 'string' || t === 'number' || t === 'boolean' ? constant : null,\n validator(value) {\n return (value === constant ||\n `Expected the literal \\`${description}\\`, but received: ${print(value)}`);\n },\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n validator(value) {\n return (value instanceof Map ||\n `Expected a \\`Map\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\nfunction nullable(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is a number.\n */\nfunction number() {\n return define('number', (value) => {\n return ((typeof value === 'number' && !isNaN(value)) ||\n `Expected a number, but received: ${print(value)}`);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value, ctx) {\n if (!isNonArrayObject(value)) {\n return value;\n }\n const coerced = { ...value };\n // The `object` struct has special behaviour enabled by the mask flag.\n // When masking, properties that are not in the schema are deleted from\n // the coerced object instead of eventually failing validaiton.\n if (ctx.mask && schema) {\n for (const key in coerced) {\n if (schema[key] === undefined) {\n delete coerced[key];\n }\n }\n }\n return coerced;\n },\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\nfunction optional(struct) {\n return new Struct({\n ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx),\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\nfunction regexp() {\n return define('regexp', (value) => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n validator(value) {\n return (value instanceof Set ||\n `Expected a \\`Set\\` object, but received: ${print(value)}`);\n },\n });\n}\n/**\n * Ensure that a value is a string.\n */\nfunction string() {\n return define('string', (value) => {\n return (typeof value === 'string' ||\n `Expected a string, but received: ${print(value)}`);\n });\n}\n/**\n * Ensure that a value is a tuple of a specific length, and that each of its\n * elements is of a specific type.\n */\nfunction tuple(Structs) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Structs.length, value.length);\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Structs[i] || Never];\n }\n }\n },\n validator(value) {\n return (Array.isArray(value) ||\n `Expected an array, but received: ${print(value)}`);\n },\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n validator(value) {\n return (isNonArrayObject(value) ||\n `Expected an object, but received: ${print(value)}`);\n },\n coercer(value) {\n return isNonArrayObject(value) ? { ...value } : value;\n },\n });\n}\n/**\n * Ensure that a value matches one of a set of types.\n */\nfunction union(Structs) {\n const description = Structs.map((s) => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n coercer(value, ctx) {\n for (const S of Structs) {\n const [error, coerced] = S.validate(value, {\n coerce: true,\n mask: ctx.mask,\n });\n if (!error) {\n return coerced;\n }\n }\n return value;\n },\n validator(value, ctx) {\n const failures = [];\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n if (!first[0]) {\n return [];\n }\n else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n return [\n `Expected the value to satisfy a union of \\`${description}\\`, but received: ${print(value)}`,\n ...failures,\n ];\n },\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction coerce(struct, condition, coercer) {\n return new Struct({\n ...struct,\n coercer: (value, ctx) => {\n return is(value, condition)\n ? struct.coercer(coercer(value, ctx), ctx)\n : struct.coercer(value, ctx);\n },\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), (x) => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n if (x === undefined) {\n return f;\n }\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x };\n let changed = false;\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n if (changed) {\n return ret;\n }\n }\n return x;\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\nfunction trimmed(struct) {\n return coerce(struct, string(), (x) => x.trim());\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\nfunction empty(struct) {\n return refine(struct, 'empty', (value) => {\n const size = getSize(value);\n return (size === 0 ||\n `Expected an empty ${struct.type} but received one with a size of \\`${size}\\``);\n });\n}\nfunction getSize(value) {\n if (value instanceof Map || value instanceof Set) {\n return value.size;\n }\n else {\n return value.length;\n }\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\nfunction max(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'max', (value) => {\n return exclusive\n ? value < threshold\n : value <= threshold ||\n `Expected a ${struct.type} less than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\nfunction min(struct, threshold, options = {}) {\n const { exclusive } = options;\n return refine(struct, 'min', (value) => {\n return exclusive\n ? value > threshold\n : value >= threshold ||\n `Expected a ${struct.type} greater than ${exclusive ? '' : 'or equal to '}${threshold} but received \\`${value}\\``;\n });\n}\n/**\n * Ensure that a string, array, map or set is not empty.\n */\nfunction nonempty(struct) {\n return refine(struct, 'nonempty', (value) => {\n const size = getSize(value);\n return (size > 0 || `Expected a nonempty ${struct.type} but received an empty one`);\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', (value) => {\n return (regexp.test(value) ||\n `Expected a ${struct.type} matching \\`/${regexp.source}/\\` but received \"${value}\"`);\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\nfunction size(struct, min, max = min) {\n const expected = `Expected a ${struct.type}`;\n const of = min === max ? `of \\`${min}\\`` : `between \\`${min}\\` and \\`${max}\\``;\n return refine(struct, 'size', (value) => {\n if (typeof value === 'number' || value instanceof Date) {\n return ((min <= value && value <= max) ||\n `${expected} ${of} but received \\`${value}\\``);\n }\n else if (value instanceof Map || value instanceof Set) {\n const { size } = value;\n return ((min <= size && size <= max) ||\n `${expected} with a size ${of} but received one with a size of \\`${size}\\``);\n }\n else {\n const { length } = value;\n return ((min <= length && length <= max) ||\n `${expected} with a length ${of} but received one with a length of \\`${length}\\``);\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\nfunction refine(struct, name, refiner) {\n return new Struct({\n ...struct,\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n for (const failure of failures) {\n yield { ...failure, refinement: name };\n }\n },\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, bigint, boolean, coerce, create, date, defaulted, define, deprecated, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, max, min, never, nonempty, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.mjs.map\n","import { PublicKey, MemcmpFilter, DataSlice } from '@solana/web3.js';\nimport {\n type as pick,\n number,\n string,\n array,\n literal,\n union,\n coerce,\n instance,\n create,\n unknown,\n any,\n nullable,\n Struct,\n} from 'superstruct';\nimport {\n BN254,\n createBN254,\n CompressedProof,\n CompressedAccountWithMerkleContext,\n MerkleContextWithMerkleProof,\n bn,\n TokenData,\n} from './state';\nimport BN from 'bn.js';\n\nexport interface LatestNonVotingSignatures {\n context: { slot: number };\n value: {\n items: {\n signature: string;\n slot: number;\n blockTime: number;\n error: string | null;\n }[];\n };\n}\n\nexport interface GetCompressedAccountsByOwnerConfig {\n filters?: GetCompressedAccountsFilter[];\n dataSlice?: DataSlice;\n cursor?: string;\n limit?: BN;\n}\n\nexport interface CompressedMintTokenHolders {\n balance: BN;\n owner: PublicKey;\n}\n\nexport interface LatestNonVotingSignaturesPaginated {\n context: { slot: number };\n value: {\n items: {\n signature: string;\n slot: number;\n blockTime: number;\n }[];\n cursor: string | null;\n };\n}\n\nexport interface SignatureWithMetadata {\n blockTime: number;\n signature: string;\n slot: number;\n}\n\nexport interface HashWithTree {\n hash: BN254;\n tree: PublicKey;\n queue: PublicKey;\n}\n\nexport interface AddressWithTree {\n address: BN254;\n tree: PublicKey;\n queue: PublicKey;\n}\n\nexport interface CompressedTransaction {\n compressionInfo: {\n closedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[];\n openedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[];\n preTokenBalances?: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }[];\n postTokenBalances?: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }[];\n };\n transaction: any;\n}\n\nexport interface HexBatchInputsForProver {\n 'input-compressed-accounts': HexInputsForProver[];\n}\n\nexport interface HexInputsForProver {\n root: string;\n pathIndex: number;\n pathElements: string[];\n leaf: string;\n}\n\n// TODO: Rename Compressed -> ValidityProof\nexport type CompressedProofWithContext = {\n compressedProof: CompressedProof;\n roots: BN[];\n rootIndices: number[];\n leafIndices: number[];\n leaves: BN[];\n merkleTrees: PublicKey[];\n nullifierQueues: PublicKey[];\n};\n\nexport interface GetCompressedTokenAccountsByOwnerOrDelegateOptions {\n mint?: PublicKey;\n cursor?: string;\n limit?: BN;\n}\nexport type TokenBalance = { balance: BN; mint: PublicKey };\n\n/**\n * **Cursor** is a unique identifier for a page of results by which the next page can be fetched.\n *\n * **Limit** is the maximum number of results to return per page.\n */\nexport interface PaginatedOptions {\n cursor?: string;\n limit?: BN;\n}\n\n/**\n * Note, DataSizeFilter is currently not available.\n */\nexport type GetCompressedAccountsFilter = MemcmpFilter; // | DataSizeFilter;\n\nexport type GetCompressedAccountConfig = {\n encoding?: string;\n};\n\nexport type GetCompressedAccountsConfig = {\n dataSlice: DataSlice;\n filters?: GetCompressedAccountsFilter[];\n};\n\nexport interface ParsedTokenAccount {\n compressedAccount: CompressedAccountWithMerkleContext;\n parsed: TokenData;\n}\n\nexport type WithContext<T> = {\n /** context */\n context: {\n slot: number;\n };\n /** response value */\n value: T;\n};\n\nexport type WithCursor<T> = {\n /** context */\n cursor: string | null;\n /** response value */\n items: T;\n};\n\n/**\n * @internal\n */\nconst PublicKeyFromString = coerce(\n instance(PublicKey),\n string(),\n value => new PublicKey(value),\n);\n\n/**\n * @internal\n */\nconst ArrayFromString = coerce(instance(Array<number>), string(), value =>\n Array.from(new PublicKey(value).toBytes()),\n);\n\n/**\n * @internal\n */\nconst BN254FromString = coerce(instance(BN), string(), value => {\n return createBN254(value, 'base58');\n});\n\n/**\n *\n * @internal\n * expects bigints to be supplied as strings.\n */\nconst BNFromStringOrNumber = coerce(\n instance(BN),\n union([string(), number()]),\n value => {\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value)) {\n throw new Error(`Unsafe integer. Precision loss: ${value}`);\n }\n return new BN(value); // Safe number → BN\n }\n return new BN(value, 10); // String → BN\n },\n);\n\n/**\n *\n * @internal\n */\nconst Base64EncodedCompressedAccountDataResult = coerce(\n string(),\n string(),\n value => (value === '' ? null : value),\n);\n/**\n * @internal\n */\nexport function createRpcResult<T, U>(result: Struct<T, U>) {\n return union([\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n result,\n }),\n pick({\n jsonrpc: literal('2.0'),\n id: string(),\n error: pick({\n code: unknown(),\n message: string(),\n data: nullable(any()),\n }),\n }),\n ]) as Struct<RpcResult<T>, null>;\n}\n\n/**\n * @internal\n */\nconst UnknownRpcResult = createRpcResult(unknown());\n\n/**\n * @internal\n */\nexport function jsonRpcResult<T, U>(schema: Struct<T, U>) {\n return coerce(createRpcResult(schema), UnknownRpcResult, value => {\n if ('error' in value) {\n return value as RpcResultError;\n } else {\n return {\n ...value,\n result: create(value.result, schema),\n } as RpcResultSuccess<T>;\n }\n }) as Struct<RpcResult<T>, null>;\n}\n\n// Add this type for the context wrapper\nexport type WithRpcContext<T> = {\n context: {\n slot: number;\n };\n value: T;\n};\n\n/**\n * @internal\n */\nexport function jsonRpcResultAndContext<T, U>(value: Struct<T, U>) {\n return jsonRpcResult(\n pick({\n context: pick({\n slot: number(),\n }),\n value,\n }),\n ) as Struct<RpcResult<WithRpcContext<T>>, null>;\n}\n\n/**\n * @internal\n */\nexport const CompressedAccountResult = pick({\n address: nullable(ArrayFromString),\n hash: BN254FromString,\n data: nullable(\n pick({\n data: Base64EncodedCompressedAccountDataResult,\n dataHash: BN254FromString,\n discriminator: BNFromStringOrNumber,\n }),\n ),\n lamports: BNFromStringOrNumber,\n owner: PublicKeyFromString,\n leafIndex: number(),\n tree: PublicKeyFromString,\n seq: nullable(BNFromStringOrNumber),\n slotCreated: BNFromStringOrNumber,\n});\n\nexport const TokenDataResult = pick({\n mint: PublicKeyFromString,\n owner: PublicKeyFromString,\n amount: BNFromStringOrNumber,\n delegate: nullable(PublicKeyFromString),\n state: string(),\n});\n\n/**\n * @internal\n */\nexport const CompressedTokenAccountResult = pick({\n tokenData: TokenDataResult,\n account: CompressedAccountResult,\n});\n\n/**\n * @internal\n */\nexport const MultipleCompressedAccountsResult = pick({\n items: array(CompressedAccountResult),\n});\n\n/**\n * @internal\n */\nexport const CompressedAccountsByOwnerResult = pick({\n items: array(CompressedAccountResult),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const CompressedTokenAccountsByOwnerOrDelegateResult = pick({\n items: array(CompressedTokenAccountResult),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const SlotResult = number();\n\n/**\n * @internal\n */\nexport const HealthResult = string();\n\n/**\n * @internal\n */\nexport const LatestNonVotingSignaturesResult = pick({\n items: array(\n pick({\n signature: string(),\n slot: number(),\n blockTime: number(),\n error: nullable(string()),\n }),\n ),\n});\n\n/**\n * @internal\n */\nexport const LatestNonVotingSignaturesResultPaginated = pick({\n items: array(\n pick({\n signature: string(),\n slot: number(),\n blockTime: number(),\n }),\n ),\n cursor: nullable(string()),\n});\n\n/**\n * @internal\n */\nexport const MerkeProofResult = pick({\n hash: BN254FromString,\n leafIndex: number(),\n merkleTree: PublicKeyFromString,\n proof: array(BN254FromString),\n rootSeq: number(),\n root: BN254FromString,\n});\n\n/**\n * @internal\n */\nexport const NewAddressProofResult = pick({\n address: BN254FromString,\n nextIndex: number(),\n merkleTree: PublicKeyFromString,\n proof: array(BN254FromString), // this is: merkleProofHashedIndexedElementLeaf\n rootSeq: number(),\n root: BN254FromString,\n lowerRangeAddress: BN254FromString, // this is: leafLowerRangeValue.\n higherRangeAddress: BN254FromString, // this is: leafHigherRangeValue\n lowElementLeafIndex: number(), // this is: indexHashedIndexedElementLeaf\n});\n\n/**\n * @internal\n */\nconst CompressedProofResult = pick({\n a: array(number()),\n b: array(number()),\n c: array(number()),\n});\n\n/**\n * @internal\n */\nexport const ValidityProofResult = pick({\n compressedProof: CompressedProofResult,\n leafIndices: array(number()),\n leaves: array(BN254FromString),\n rootIndices: array(number()),\n roots: array(BN254FromString),\n merkleTrees: array(PublicKeyFromString),\n // TODO: enable nullifierQueues\n // nullifierQueues: array(PublicKeyFromString),\n});\n\n/**\n * @internal\n */\nexport const MultipleMerkleProofsResult = array(MerkeProofResult);\n\n/**\n * @internal\n */\nexport const BalanceResult = pick({\n amount: BNFromStringOrNumber,\n});\n\nexport const NativeBalanceResult = BNFromStringOrNumber;\n\nexport const TokenBalanceResult = pick({\n balance: BNFromStringOrNumber,\n mint: PublicKeyFromString,\n});\n\nexport const TokenBalanceListResult = pick({\n tokenBalances: array(TokenBalanceResult),\n cursor: nullable(string()),\n});\n\nexport const TokenBalanceListResultV2 = pick({\n items: array(TokenBalanceResult),\n cursor: nullable(string()),\n});\n\nexport const CompressedMintTokenHoldersResult = pick({\n cursor: nullable(string()),\n items: array(\n pick({\n balance: BNFromStringOrNumber,\n owner: PublicKeyFromString,\n }),\n ),\n});\n\nexport const AccountProofResult = pick({\n hash: array(number()),\n root: array(number()),\n proof: array(array(number())),\n});\n\nexport const toUnixTimestamp = (blockTime: string): number => {\n return new Date(blockTime).getTime();\n};\n\nexport const SignatureListResult = pick({\n items: array(\n pick({\n blockTime: number(),\n signature: string(),\n slot: number(),\n }),\n ),\n});\n\nexport const SignatureListWithCursorResult = pick({\n items: array(\n pick({\n blockTime: number(),\n signature: string(),\n slot: number(),\n }),\n ),\n cursor: nullable(string()),\n});\n\nexport const CompressedTransactionResult = pick({\n compressionInfo: pick({\n closedAccounts: array(\n pick({\n account: CompressedAccountResult,\n optionalTokenData: nullable(TokenDataResult),\n }),\n ),\n openedAccounts: array(\n pick({\n account: CompressedAccountResult,\n optionalTokenData: nullable(TokenDataResult),\n }),\n ),\n }),\n /// TODO: add transaction struct\n /// https://github.com/solana-labs/solana/blob/27eff8408b7223bb3c4ab70523f8a8dca3ca6645/transaction-status/src/lib.rs#L1061\n transaction: any(),\n});\n\nexport interface CompressionApiInterface {\n getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null>;\n\n getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN | null>;\n\n getCompressedBalanceByOwner(owner: PublicKey): Promise<BN>;\n\n getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof>;\n\n getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]>;\n\n getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]>;\n\n getValidityProof(\n hashes: BN254[],\n newAddresses: BN254[],\n ): Promise<CompressedProofWithContext>;\n\n getValidityProofV0(\n hashes: HashWithTree[],\n newAddresses: AddressWithTree[],\n ): Promise<CompressedProofWithContext>;\n\n getValidityProofAndRpcContext(\n hashes: HashWithTree[],\n newAddresses: AddressWithTree[],\n ): Promise<WithContext<CompressedProofWithContext>>;\n\n getCompressedAccountsByOwner(\n owner: PublicKey,\n config?: GetCompressedAccountsByOwnerConfig,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>>;\n\n getCompressedMintTokenHolders(\n mint: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>>;\n\n getCompressedTokenAccountsByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>>;\n\n getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>>;\n\n getCompressedTokenAccountBalance(hash: BN254): Promise<{ amount: BN }>;\n\n getCompressedTokenBalancesByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<TokenBalance[]>>;\n\n getCompressedTokenBalancesByOwnerV2(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>>;\n\n getTransactionWithCompressionInfo(\n signature: string,\n ): Promise<CompressedTransaction | null>;\n\n getCompressionSignaturesForAccount(\n hash: BN254,\n ): Promise<SignatureWithMetadata[]>;\n\n getCompressionSignaturesForAddress(\n address: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getCompressionSignaturesForOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getCompressionSignaturesForTokenOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>>;\n\n getLatestNonVotingSignatures(\n limit?: number,\n cursor?: string,\n ): Promise<LatestNonVotingSignatures>;\n\n getLatestCompressionSignatures(\n cursor?: string,\n limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated>;\n\n getIndexerHealth(): Promise<string>;\n\n getIndexerSlot(): Promise<number>;\n}\n\n// Public types for consumers\nexport type RpcResultSuccess<T> = {\n jsonrpc: '2.0';\n id: string;\n result: T;\n};\n\nexport type RpcResultError = {\n jsonrpc: '2.0';\n id: string;\n error: {\n code: unknown;\n message: string;\n data?: any;\n };\n};\n\nexport type RpcResult<T> = RpcResultSuccess<T> | RpcResultError;\n","import {\n Connection,\n ConnectionConfig,\n PublicKey,\n SolanaJSONRPCError,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n BalanceResult,\n CompressedAccountResult,\n CompressedAccountsByOwnerResult,\n CompressedProofWithContext,\n CompressedTokenAccountsByOwnerOrDelegateResult,\n CompressedTransaction,\n CompressedTransactionResult,\n CompressionApiInterface,\n GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n HealthResult,\n HexInputsForProver,\n MerkeProofResult,\n MultipleCompressedAccountsResult,\n NativeBalanceResult,\n ParsedTokenAccount,\n SignatureListResult,\n SignatureListWithCursorResult,\n SignatureWithMetadata,\n SlotResult,\n TokenBalanceListResult,\n jsonRpcResult,\n jsonRpcResultAndContext,\n ValidityProofResult,\n NewAddressProofResult,\n LatestNonVotingSignaturesResult,\n LatestNonVotingSignatures,\n LatestNonVotingSignaturesResultPaginated,\n LatestNonVotingSignaturesPaginated,\n WithContext,\n GetCompressedAccountsByOwnerConfig,\n WithCursor,\n AddressWithTree,\n HashWithTree,\n CompressedMintTokenHoldersResult,\n CompressedMintTokenHolders,\n TokenBalance,\n TokenBalanceListResultV2,\n PaginatedOptions,\n} from './rpc-interface';\nimport {\n MerkleContextWithMerkleProof,\n BN254,\n bn,\n CompressedAccountWithMerkleContext,\n encodeBN254toBase58,\n createCompressedAccountWithMerkleContext,\n createMerkleContext,\n TokenData,\n CompressedProof,\n} from './state';\nimport { array, create, nullable } from 'superstruct';\nimport {\n defaultTestStateTreeAccounts,\n localTestActiveStateTreeInfo,\n isLocalTest,\n defaultStateTreeLookupTables,\n} from './constants';\nimport BN from 'bn.js';\nimport { toCamelCase, toHex } from './utils/conversion';\n\nimport {\n proofFromJsonStruct,\n negateAndCompressProof,\n} from './utils/parse-validity-proof';\nimport { LightWasm } from './test-helpers';\nimport { getLightStateTreeInfo } from './utils/get-light-state-tree-info';\nimport { ActiveTreeBundle } from './state/types';\nimport { validateNumbersForProof } from './utils';\n\n/** @internal */\nexport function parseAccountData({\n discriminator,\n data,\n dataHash,\n}: {\n discriminator: BN;\n data: string;\n dataHash: BN;\n}) {\n return {\n discriminator: discriminator.toArray('le', 8),\n data: Buffer.from(data, 'base64'),\n dataHash: dataHash.toArray('le', 32),\n };\n}\n\n/** @internal */\nasync function getCompressedTokenAccountsByOwnerOrDelegate(\n rpc: Rpc,\n ownerOrDelegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n filterByDelegate: boolean = false,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const endpoint = filterByDelegate\n ? 'getCompressedTokenAccountsByDelegate'\n : 'getCompressedTokenAccountsByOwner';\n const propertyToCheck = filterByDelegate ? 'delegate' : 'owner';\n\n const unsafeRes = await rpcRequest(rpc.compressionApiEndpoint, endpoint, {\n [propertyToCheck]: ownerOrDelegate.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n });\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedTokenAccountsByOwnerOrDelegateResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts by ${propertyToCheck} ${ownerOrDelegate.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error('not implemented: NULL result');\n }\n const accounts: ParsedTokenAccount[] = [];\n\n const activeStateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n\n res.result.value.items.map(item => {\n const _account = item.account;\n const _tokenData = item.tokenData;\n\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n _account.tree!,\n );\n\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n _account.tree!,\n associatedQueue,\n _account.hash.toArray('be', 32),\n _account.leafIndex,\n ),\n _account.owner,\n bn(_account.lamports),\n _account.data ? parseAccountData(_account.data) : undefined,\n _account.address || undefined,\n );\n\n const parsed: TokenData = {\n mint: _tokenData.mint,\n owner: _tokenData.owner,\n amount: _tokenData.amount,\n delegate: _tokenData.delegate,\n state: ['uninitialized', 'initialized', 'frozen'].indexOf(\n _tokenData.state,\n ),\n tlv: null,\n };\n\n if (\n parsed[propertyToCheck]?.toBase58() !== ownerOrDelegate.toBase58()\n ) {\n throw new Error(\n `RPC returned token account with ${propertyToCheck} different from requested ${propertyToCheck}`,\n );\n }\n\n accounts.push({\n compressedAccount,\n parsed,\n });\n });\n /// TODO: consider custom or different sort. Most recent here.\n return {\n items: accounts.sort(\n (a, b) =>\n b.compressedAccount.leafIndex - a.compressedAccount.leafIndex,\n ),\n cursor: res.result.value.cursor,\n };\n}\n\n/** @internal */\nfunction buildCompressedAccountWithMaybeTokenData(\n accountStructWithOptionalTokenData: any,\n activeStateTreeInfo: ActiveTreeBundle[],\n): {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n} {\n const compressedAccountResult = accountStructWithOptionalTokenData.account;\n const tokenDataResult =\n accountStructWithOptionalTokenData.optionalTokenData;\n\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n compressedAccountResult.tree!,\n );\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n compressedAccountResult.merkleTree,\n associatedQueue,\n compressedAccountResult.hash.toArray('be', 32),\n compressedAccountResult.leafIndex,\n ),\n compressedAccountResult.owner,\n bn(compressedAccountResult.lamports),\n compressedAccountResult.data\n ? parseAccountData(compressedAccountResult.data)\n : undefined,\n compressedAccountResult.address || undefined,\n );\n\n if (tokenDataResult === null) {\n return { account: compressedAccount, maybeTokenData: null };\n }\n\n const parsed: TokenData = {\n mint: tokenDataResult.mint,\n owner: tokenDataResult.owner,\n amount: tokenDataResult.amount,\n delegate: tokenDataResult.delegate,\n state: ['uninitialized', 'initialized', 'frozen'].indexOf(\n tokenDataResult.state,\n ),\n tlv: null,\n };\n\n return { account: compressedAccount, maybeTokenData: parsed };\n}\n\n/**\n * Establish a Compression-compatible JSON RPC connection\n *\n * @param endpointOrWeb3JsConnection endpoint to the solana cluster or\n * Connection object\n * @param compressionApiEndpoint Endpoint to the compression server\n * @param proverEndpoint Endpoint to the prover server. defaults\n * to endpoint\n * @param connectionConfig Optional connection config\n */\nexport function createRpc(\n endpointOrWeb3JsConnection?: string | Connection,\n compressionApiEndpoint?: string,\n proverEndpoint?: string,\n config?: ConnectionConfig,\n): Rpc {\n const localEndpoint = 'http://127.0.0.1:8899';\n const localCompressionApiEndpoint = 'http://127.0.0.1:8784';\n const localProverEndpoint = 'http://127.0.0.1:3001';\n\n let endpoint: string;\n\n if (!endpointOrWeb3JsConnection) {\n // Local as default\n endpoint = localEndpoint;\n compressionApiEndpoint =\n compressionApiEndpoint || localCompressionApiEndpoint;\n proverEndpoint = proverEndpoint || localProverEndpoint;\n } else if (typeof endpointOrWeb3JsConnection === 'string') {\n endpoint = endpointOrWeb3JsConnection;\n compressionApiEndpoint = compressionApiEndpoint || endpoint;\n proverEndpoint = proverEndpoint || endpoint;\n } else if (endpointOrWeb3JsConnection instanceof Connection) {\n endpoint = endpointOrWeb3JsConnection.rpcEndpoint;\n compressionApiEndpoint = compressionApiEndpoint || endpoint;\n proverEndpoint = proverEndpoint || endpoint;\n }\n // 3\n else {\n throw new Error('Invalid endpoint or connection type');\n }\n\n return new Rpc(endpoint, compressionApiEndpoint, proverEndpoint, config);\n}\n\n/**\n * Helper function to preprocess the response to wrap numbers as strings\n * @param {string} text - The JSON string to preprocess\n * @returns {string} - The preprocessed JSON string with numbers wrapped as strings\n */\nexport function wrapBigNumbersAsStrings(text: string): string {\n return text.replace(/(\":\\s*)(-?\\d+)(\\s*[},])/g, (match, p1, p2, p3) => {\n const num = Number(p2);\n if (\n !Number.isNaN(num) &&\n (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER)\n ) {\n return `${p1}\"${p2}\"${p3}`;\n }\n return match;\n });\n}\n\n/** @internal */\nexport const rpcRequest = async (\n rpcEndpoint: string,\n method: string,\n params: any = [],\n convertToCamelCase = true,\n debug = false,\n): Promise<any> => {\n const body = JSON.stringify({\n jsonrpc: '2.0',\n id: 'test-account',\n method: method,\n params: params,\n });\n\n if (debug) {\n const generateCurlSnippet = () => {\n const escapedBody = body.replace(/\"/g, '\\\\\"');\n return `curl -X POST ${rpcEndpoint} \\\\\n -H \"Content-Type: application/json\" \\\\\n -d \"${escapedBody}\"`;\n };\n\n console.log('Debug: Stack trace:');\n console.log(new Error().stack);\n console.log('\\nDebug: curl:');\n console.log(generateCurlSnippet());\n console.log('\\n');\n }\n\n const response = await fetch(rpcEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const text = await response.text();\n\n const wrappedJsonString = wrapBigNumbersAsStrings(text);\n\n if (convertToCamelCase) {\n return toCamelCase(JSON.parse(wrappedJsonString));\n }\n\n return JSON.parse(wrappedJsonString);\n};\n\n/** @internal */\nexport const proverRequest = async (\n proverEndpoint: string,\n method: 'inclusion' | 'new-address' | 'combined',\n params: any = [],\n log = false,\n publicInputHash: BN | undefined = undefined,\n): Promise<CompressedProof> => {\n let logMsg: string = '';\n\n if (log) {\n logMsg = `Proof generation for method:${method}`;\n console.time(logMsg);\n }\n\n let body;\n if (method === 'inclusion') {\n body = JSON.stringify({\n circuitType: 'inclusion',\n stateTreeHeight: 26,\n inputCompressedAccounts: params,\n // publicInputHash: publicInputHash.toString('hex'),\n });\n } else if (method === 'new-address') {\n body = JSON.stringify({\n circuitType: 'non-inclusion',\n addressTreeHeight: 26,\n // publicInputHash: publicInputHash.toString('hex'),\n newAddresses: params,\n });\n } else if (method === 'combined') {\n body = JSON.stringify({\n circuitType: 'combined',\n // publicInputHash: publicInputHash.toString('hex'),\n stateTreeHeight: 26,\n addressTreeHeight: 26,\n inputCompressedAccounts: params[0],\n newAddresses: params[1],\n });\n }\n\n const response = await fetch(`${proverEndpoint}/prove`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`Error fetching proof: ${response.statusText}`);\n }\n const data: any = await response.json();\n const parsed = proofFromJsonStruct(data);\n const compressedProof = negateAndCompressProof(parsed);\n\n if (log) console.timeEnd(logMsg);\n\n return compressedProof;\n};\n\nexport type NonInclusionMerkleProofInputs = {\n root: BN;\n value: BN;\n leaf_lower_range_value: BN;\n leaf_higher_range_value: BN;\n nextIndex: BN;\n merkle_proof_hashed_indexed_element_leaf: BN[];\n index_hashed_indexed_element_leaf: BN;\n};\n\nexport type MerkleContextWithNewAddressProof = {\n root: BN;\n rootIndex: number;\n value: BN;\n leafLowerRangeValue: BN;\n leafHigherRangeValue: BN;\n nextIndex: BN;\n merkleProofHashedIndexedElementLeaf: BN[];\n indexHashedIndexedElementLeaf: BN;\n merkleTree: PublicKey;\n nullifierQueue: PublicKey;\n};\n\nexport type NonInclusionJsonStruct = {\n root: string;\n value: string;\n pathIndex: number;\n pathElements: string[];\n leafLowerRangeValue: string;\n leafHigherRangeValue: string;\n nextIndex: number;\n};\n\nexport function convertMerkleProofsWithContextToHex(\n merkleProofsWithContext: MerkleContextWithMerkleProof[],\n): HexInputsForProver[] {\n const inputs: HexInputsForProver[] = [];\n\n for (let i = 0; i < merkleProofsWithContext.length; i++) {\n const input: HexInputsForProver = {\n root: toHex(merkleProofsWithContext[i].root),\n pathIndex: merkleProofsWithContext[i].leafIndex,\n pathElements: merkleProofsWithContext[i].merkleProof.map(hex =>\n toHex(hex),\n ),\n leaf: toHex(bn(merkleProofsWithContext[i].hash)),\n };\n inputs.push(input);\n }\n\n return inputs;\n}\n\nexport function convertNonInclusionMerkleProofInputsToHex(\n nonInclusionMerkleProofInputs: MerkleContextWithNewAddressProof[],\n): NonInclusionJsonStruct[] {\n const inputs: NonInclusionJsonStruct[] = [];\n for (let i = 0; i < nonInclusionMerkleProofInputs.length; i++) {\n const input: NonInclusionJsonStruct = {\n root: toHex(nonInclusionMerkleProofInputs[i].root),\n value: toHex(nonInclusionMerkleProofInputs[i].value),\n pathIndex:\n nonInclusionMerkleProofInputs[\n i\n ].indexHashedIndexedElementLeaf.toNumber(),\n pathElements: nonInclusionMerkleProofInputs[\n i\n ].merkleProofHashedIndexedElementLeaf.map(hex => toHex(hex)),\n nextIndex: nonInclusionMerkleProofInputs[i].nextIndex.toNumber(),\n leafLowerRangeValue: toHex(\n nonInclusionMerkleProofInputs[i].leafLowerRangeValue,\n ),\n leafHigherRangeValue: toHex(\n nonInclusionMerkleProofInputs[i].leafHigherRangeValue,\n ),\n };\n inputs.push(input);\n }\n return inputs;\n}\n\nfunction calculateTwoInputsHashChain(\n hashesFirst: BN[],\n hashesSecond: BN[],\n lightWasm: LightWasm,\n): BN {\n if (hashesFirst.length !== hashesSecond.length) {\n throw new Error('Input lengths must match.');\n }\n if (hashesFirst.length === 0) {\n return new BN(0);\n }\n\n let hashChain = lightWasm.poseidonHashBN([\n hashesFirst[0].toString(),\n hashesSecond[0].toString(),\n ]);\n\n for (let i = 1; i < hashesFirst.length; i++) {\n hashChain = lightWasm.poseidonHashBN([\n hashChain.toString(),\n hashesFirst[i].toString(),\n hashesSecond[i].toString(),\n ]);\n }\n\n return hashChain;\n}\n\nexport function getPublicInputHash(\n accountProofs: MerkleContextWithMerkleProof[],\n accountHashes: BN254[],\n newAddressProofs: MerkleContextWithNewAddressProof[],\n lightWasm: LightWasm,\n): BN {\n const accountRoots = accountProofs.map(x => x.root);\n const inclusionHashChain = calculateTwoInputsHashChain(\n accountRoots,\n accountHashes,\n lightWasm,\n );\n\n const newAddressHashes = newAddressProofs.map(x => x.value);\n const newAddressRoots = newAddressProofs.map(x => x.root);\n const nonInclusionHashChain = calculateTwoInputsHashChain(\n newAddressRoots,\n newAddressHashes,\n lightWasm,\n );\n\n if (!nonInclusionHashChain.isZero()) {\n return nonInclusionHashChain;\n } else if (!inclusionHashChain.isZero()) {\n return inclusionHashChain;\n } else {\n return calculateTwoInputsHashChain(\n [inclusionHashChain],\n [nonInclusionHashChain],\n lightWasm,\n );\n }\n}\n\n/**\n * Get the queue for a given tree\n *\n * @param info - The active state tree addresses\n * @param tree - The tree to get the queue for\n * @returns The queue for the given tree, or undefined if not found\n */\nexport function getQueueForTree(\n info: ActiveTreeBundle[],\n tree: PublicKey,\n): PublicKey {\n const index = info.findIndex(t => t.tree.equals(tree));\n if (index === -1) {\n throw new Error(\n 'No associated queue found for tree. Please set activeStateTreeInfo with latest Tree accounts. If you use custom state trees, set manually.',\n );\n }\n if (!info[index].queue) {\n throw new Error('Queue must not be null for state tree');\n }\n return info[index].queue;\n}\n\n/**\n * Get the tree for a given queue\n *\n * @param info - The active state tree addresses\n * @param queue - The queue to get the tree for\n * @returns The tree for the given queue, or undefined if not found\n */\nexport function getTreeForQueue(\n info: ActiveTreeBundle[],\n queue: PublicKey,\n): PublicKey {\n const index = info.findIndex(q => q.queue?.equals(queue));\n if (index === -1) {\n throw new Error(\n 'No associated tree found for queue. Please set activeStateTreeInfo with latest Tree accounts. If you use custom state trees, set manually.',\n );\n }\n if (!info[index].tree) {\n throw new Error('Tree must not be null for state tree');\n }\n return info[index].tree;\n}\n\n/**\n * Get a random tree and queue from the active state tree addresses.\n *\n * Prevents write lock contention on state trees.\n *\n * @param info - The active state tree addresses\n * @returns A random tree and queue\n */\nexport function pickRandomTreeAndQueue(info: ActiveTreeBundle[]): {\n tree: PublicKey;\n queue: PublicKey;\n} {\n const length = info.length;\n const index = Math.floor(Math.random() * length);\n\n if (!info[index].queue) {\n throw new Error('Queue must not be null for state tree');\n }\n return {\n tree: info[index].tree,\n queue: info[index].queue,\n };\n}\n\n/**\n *\n */\nexport class Rpc extends Connection implements CompressionApiInterface {\n compressionApiEndpoint: string;\n proverEndpoint: string;\n activeStateTreeInfo: ActiveTreeBundle[] | null = null;\n\n constructor(\n endpoint: string,\n compressionApiEndpoint: string,\n proverEndpoint: string,\n config?: ConnectionConfig,\n ) {\n super(endpoint, config || 'confirmed');\n this.compressionApiEndpoint = compressionApiEndpoint;\n this.proverEndpoint = proverEndpoint;\n }\n\n /**\n * Manually set state tree addresses\n */\n setStateTreeInfo(info: ActiveTreeBundle[]): void {\n this.activeStateTreeInfo = info;\n }\n\n /**\n * Get the active state tree addresses from the cluster.\n * If not already cached, fetches from the cluster.\n */\n async getCachedActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n if (isLocalTest(this.rpcEndpoint)) {\n return localTestActiveStateTreeInfo();\n }\n\n let info: ActiveTreeBundle[] | null = null;\n if (!this.activeStateTreeInfo) {\n const { mainnet, devnet } = defaultStateTreeLookupTables();\n try {\n info = await getLightStateTreeInfo({\n connection: this,\n stateTreeLookupTableAddress:\n mainnet[0].stateTreeLookupTable,\n nullifyTableAddress: mainnet[0].nullifyTable,\n });\n this.activeStateTreeInfo = info;\n } catch {\n info = await getLightStateTreeInfo({\n connection: this,\n stateTreeLookupTableAddress: devnet[0].stateTreeLookupTable,\n nullifyTableAddress: devnet[0].nullifyTable,\n });\n this.activeStateTreeInfo = info;\n }\n }\n if (!this.activeStateTreeInfo) {\n throw new Error(\n `activeStateTreeInfo should not be null ${JSON.stringify(\n this.activeStateTreeInfo,\n )}`,\n );\n }\n\n return this.activeStateTreeInfo!;\n }\n\n /**\n * Fetch the latest state tree addresses from the cluster.\n */\n async getLatestActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n this.activeStateTreeInfo = null;\n return await this.getCachedActiveStateTreeInfo();\n }\n\n /**\n * Fetch the compressed account for the specified account address or hash\n */\n async getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null> {\n if (!hash && !address) {\n throw new Error('Either hash or address must be provided');\n }\n if (hash && address) {\n throw new Error('Only one of hash or address must be provided');\n }\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccount',\n {\n hash: hash ? encodeBN254toBase58(hash) : undefined,\n address: address ? encodeBN254toBase58(address) : undefined,\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(nullable(CompressedAccountResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed account ${hash ? hash.toString() : address ? address.toString() : ''}`,\n );\n }\n if (res.result.value === null) {\n return null;\n }\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n res.result.value.tree!,\n );\n const item = res.result.value;\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n return account;\n }\n\n /**\n * Fetch the compressed balance for the specified account address or hash\n */\n async getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN> {\n if (!hash && !address) {\n throw new Error('Either hash or address must be provided');\n }\n if (hash && address) {\n throw new Error('Only one of hash or address must be provided');\n }\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedBalance',\n {\n hash: hash ? encodeBN254toBase58(hash) : undefined,\n address: address ? encodeBN254toBase58(address) : undefined,\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(NativeBalanceResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed account ${hash ? hash.toString() : address ? address.toString() : ''}`,\n );\n }\n if (res.result.value === null) {\n return bn(0);\n }\n\n return bn(res.result.value);\n }\n\n /// TODO: validate that this is just for sol accounts\n /**\n * Fetch the total compressed balance for the specified owner public key\n */\n async getCompressedBalanceByOwner(owner: PublicKey): Promise<BN> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedBalanceByOwner',\n { owner: owner.toBase58() },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(NativeBalanceResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed account ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n return bn(0);\n }\n return bn(res.result.value);\n }\n\n /**\n * Fetch the latest merkle proof for the specified account hash from the\n * cluster\n */\n async getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccountProof',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(MerkeProofResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proof for compressed account ${hash.toString()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proof for compressed account ${hash.toString()}`,\n );\n }\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n res.result.value.merkleTree,\n );\n\n const value: MerkleContextWithMerkleProof = {\n hash: res.result.value.hash.toArray('be', 32),\n merkleTree: res.result.value.merkleTree,\n leafIndex: res.result.value.leafIndex,\n merkleProof: res.result.value.proof,\n nullifierQueue: associatedQueue, // TODO(photon): support nullifierQueue in response.\n rootIndex: res.result.value.rootSeq % 2400,\n root: res.result.value.root,\n };\n return value;\n }\n\n /**\n * Fetch all the account info for multiple compressed accounts specified by\n * an array of account hashes\n */\n async getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleCompressedAccounts',\n { hashes: hashes.map(hash => encodeBN254toBase58(hash)) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(MultipleCompressedAccountsResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get info for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n const accounts: CompressedAccountWithMerkleContext[] = [];\n res.result.value.items.map(item => {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n item.tree!,\n );\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n accounts.push(account);\n });\n\n return accounts.sort((a, b) => b.leafIndex - a.leafIndex);\n }\n\n /**\n * Fetch the latest merkle proofs for multiple compressed accounts specified\n * by an array account hashes\n */\n async getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleCompressedAccountProofs',\n hashes.map(hash => encodeBN254toBase58(hash)),\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(MerkeProofResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proofs for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proofs for compressed accounts ${hashes.map(hash => encodeBN254toBase58(hash)).join(', ')}`,\n );\n }\n\n const merkleProofs: MerkleContextWithMerkleProof[] = [];\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n for (const proof of res.result.value) {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n proof.merkleTree,\n );\n const value: MerkleContextWithMerkleProof = {\n hash: proof.hash.toArray('be', 32),\n merkleTree: proof.merkleTree,\n leafIndex: proof.leafIndex,\n merkleProof: proof.proof,\n nullifierQueue: associatedQueue,\n rootIndex: proof.rootSeq % 2400,\n root: proof.root,\n };\n merkleProofs.push(value);\n }\n return merkleProofs;\n }\n\n /**\n * Fetch all the compressed accounts owned by the specified public key.\n * Owner can be a program or user account\n */\n async getCompressedAccountsByOwner(\n owner: PublicKey,\n config?: GetCompressedAccountsByOwnerConfig | undefined,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedAccountsByOwner',\n {\n owner: owner.toBase58(),\n filters: config?.filters || [],\n dataSlice: config?.dataSlice,\n cursor: config?.cursor,\n limit: config?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedAccountsByOwnerResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get info for compressed accounts owned by ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n return {\n items: [],\n cursor: null,\n };\n }\n const accounts: CompressedAccountWithMerkleContext[] = [];\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n\n res.result.value.items.map(item => {\n const associatedQueue = getQueueForTree(\n activeStateTreeInfo,\n item.tree!,\n );\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n associatedQueue,\n item.hash.toArray('be', 32),\n item.leafIndex,\n ),\n item.owner,\n bn(item.lamports),\n item.data ? parseAccountData(item.data) : undefined,\n item.address || undefined,\n );\n\n accounts.push(account);\n });\n\n return {\n items: accounts.sort((a, b) => b.leafIndex - a.leafIndex),\n cursor: res.result.value.cursor,\n };\n }\n\n /**\n * Fetch all the compressed token accounts owned by the specified public\n * key. Owner can be a program or user account\n */\n async getCompressedTokenAccountsByOwner(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n if (!options) options = {};\n\n return await getCompressedTokenAccountsByOwnerOrDelegate(\n this,\n owner,\n options,\n false,\n );\n }\n\n /**\n * Fetch all the compressed accounts delegated to the specified public key.\n */\n async getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n if (!options) options = {};\n\n return await getCompressedTokenAccountsByOwnerOrDelegate(\n this,\n delegate,\n options,\n true,\n );\n }\n\n /**\n * Fetch the compressed token balance for the specified account hash\n */\n async getCompressedTokenAccountBalance(\n hash: BN254,\n ): Promise<{ amount: BN }> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenAccountBalance',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(unsafeRes, jsonRpcResultAndContext(BalanceResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get balance for compressed token account ${hash.toString()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get balance for compressed token account ${hash.toString()}`,\n );\n }\n\n return { amount: bn(res.result.value.amount) };\n }\n\n /**\n * @deprecated use {@link getCompressedTokenBalancesByOwnerV2} instead.\n *\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint. Returns without context.\n */\n async getCompressedTokenBalancesByOwner(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<TokenBalance[]>> {\n if (!options) options = {};\n\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenBalancesByOwner',\n {\n owner: owner.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(TokenBalanceListResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n\n const maybeFiltered = options.mint\n ? res.result.value.tokenBalances.filter(\n tokenBalance =>\n tokenBalance.mint.toBase58() === options.mint!.toBase58(),\n )\n : res.result.value.tokenBalances;\n\n return {\n items: maybeFiltered,\n cursor: res.result.value.cursor,\n };\n }\n\n /**\n * Fetch the compressed token balances owned by the specified public\n * key. Paginated. Can filter by mint. Returns with context.\n */\n async getCompressedTokenBalancesByOwnerV2(\n owner: PublicKey,\n options?: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>> {\n if (!options) options = {};\n\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedTokenBalancesByOwnerV2',\n {\n owner: owner.toBase58(),\n mint: options.mint?.toBase58(),\n limit: options.limit?.toNumber(),\n cursor: options.cursor,\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(TokenBalanceListResultV2),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get compressed token balances for owner ${owner.toBase58()}`,\n );\n }\n\n const maybeFiltered = options.mint\n ? res.result.value.items.filter(\n tokenBalance =>\n tokenBalance.mint.toBase58() === options.mint!.toBase58(),\n )\n : res.result.value.items;\n\n return {\n context: res.result.context,\n value: {\n items: maybeFiltered,\n cursor: res.result.value.cursor,\n },\n };\n }\n\n /**\n * Returns confirmed compression signatures for transactions involving the specified\n * account hash forward in time from genesis to the most recent confirmed\n * block\n *\n * @param hash queried account hash\n */\n async getCompressionSignaturesForAccount(\n hash: BN254,\n ): Promise<SignatureWithMetadata[]> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForAccount',\n { hash: encodeBN254toBase58(hash) },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for compressed account ${hash.toString()}`,\n );\n }\n return res.result.value.items;\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster. Return with\n * CompressionInfo\n */\n async getTransactionWithCompressionInfo(\n signature: string,\n ): Promise<CompressedTransaction | null> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getTransactionWithCompressionInfo',\n { signature },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResult(CompressedTransactionResult),\n );\n\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n\n if (res.result.transaction === null) return null;\n\n const closedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[] = [];\n\n const openedAccounts: {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }[] = [];\n\n const activeStateTreeInfo = await this.getCachedActiveStateTreeInfo();\n\n res.result.compressionInfo.closedAccounts.map(item => {\n closedAccounts.push(\n buildCompressedAccountWithMaybeTokenData(\n item,\n activeStateTreeInfo,\n ),\n );\n });\n res.result.compressionInfo.openedAccounts.map(item => {\n openedAccounts.push(\n buildCompressedAccountWithMaybeTokenData(\n item,\n activeStateTreeInfo,\n ),\n );\n });\n\n const calculateTokenBalances = (\n accounts: Array<{\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n }>,\n ):\n | Array<{\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n }>\n | undefined => {\n const balances = Object.values(\n accounts.reduce(\n (acc, { maybeTokenData }) => {\n if (maybeTokenData) {\n const { owner, mint, amount } = maybeTokenData;\n const key = `${owner.toBase58()}_${mint.toBase58()}`;\n if (key in acc) {\n acc[key].amount = acc[key].amount.add(amount);\n } else {\n acc[key] = { owner, mint, amount };\n }\n }\n return acc;\n },\n {} as {\n [key: string]: {\n owner: PublicKey;\n mint: PublicKey;\n amount: BN;\n };\n },\n ),\n );\n return balances.length > 0 ? balances : undefined;\n };\n\n const preTokenBalances = calculateTokenBalances(closedAccounts);\n const postTokenBalances = calculateTokenBalances(openedAccounts);\n\n return {\n compressionInfo: {\n closedAccounts,\n openedAccounts,\n preTokenBalances,\n postTokenBalances,\n },\n transaction: res.result.transaction,\n };\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * address forward in time from genesis to the most recent confirmed block\n *\n * @param address queried compressed account address\n */\n async getCompressionSignaturesForAddress(\n address: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForAddress',\n {\n address: address.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for address ${address.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for address ${address.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified account owner forward in time from genesis to the\n * most recent confirmed block\n *\n * @param owner queried owner public key\n */\n async getCompressionSignaturesForOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForOwner',\n {\n owner: owner.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified token account owner forward in time from genesis to the most\n * recent confirmed block\n */\n async getCompressionSignaturesForTokenOwner(\n owner: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressionSignaturesForTokenOwner',\n {\n owner: owner.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(SignatureListWithCursorResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get signatures for owner ${owner.toBase58()}`,\n );\n }\n\n return res.result.value;\n }\n\n /**\n * Fetch the current indexer health status\n */\n async getIndexerHealth(): Promise<string> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getIndexerHealth',\n );\n const res = create(unsafeRes, jsonRpcResult(HealthResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get health');\n }\n return res.result;\n }\n\n /**\n * Ensure that the Compression Indexer has already indexed the transaction\n */\n async confirmTransactionIndexed(slot: number): Promise<boolean> {\n const startTime = Date.now();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const indexerSlot = await this.getIndexerSlot();\n\n if (indexerSlot >= slot) {\n return true;\n }\n if (Date.now() - startTime > 20000) {\n // 20 seconds\n throw new Error(\n 'Timeout: Indexer slot did not reach the required slot within 20 seconds',\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getIndexerSlot(): Promise<number> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getIndexerSlot',\n );\n const res = create(unsafeRes, jsonRpcResult(SlotResult));\n if ('error' in res) {\n throw new SolanaJSONRPCError(res.error, 'failed to get slot');\n }\n return res.result;\n }\n\n /**\n * Fetch all the compressed token holders for a given mint. Paginated.\n */\n async getCompressedMintTokenHolders(\n mint: PublicKey,\n options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getCompressedMintTokenHolders',\n {\n mint: mint.toBase58(),\n cursor: options?.cursor,\n limit: options?.limit?.toNumber(),\n },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(CompressedMintTokenHoldersResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get mint token holders',\n );\n }\n\n return res.result;\n }\n /**\n * Fetch the latest compression signatures on the cluster. Results are\n * paginated.\n */\n async getLatestCompressionSignatures(\n cursor?: string,\n limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getLatestCompressionSignatures',\n { limit, cursor },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(LatestNonVotingSignaturesResultPaginated),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get latest non-voting signatures',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch all non-voting signatures\n */\n async getLatestNonVotingSignatures(\n limit?: number,\n cursor?: string,\n ): Promise<LatestNonVotingSignatures> {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getLatestNonVotingSignatures',\n { limit, cursor },\n );\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(LatestNonVotingSignaturesResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n 'failed to get latest non-voting signatures',\n );\n }\n return res.result;\n }\n\n /**\n * Fetch the latest address proofs for new unique addresses specified by an\n * array of addresses.\n *\n * the proof states that said address have not yet been created in\n * respective address tree.\n * @param addresses Array of BN254 new addresses\n * @returns Array of validity proofs for new addresses\n */\n async getMultipleNewAddressProofs(addresses: BN254[]) {\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getMultipleNewAddressProofs',\n addresses.map(address => encodeBN254toBase58(address)),\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(array(NewAddressProofResult)),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get proofs for new addresses ${addresses.map(address => encodeBN254toBase58(address)).join(', ')}`,\n );\n }\n if (res.result.value === null) {\n throw new Error(\n `failed to get proofs for new addresses ${addresses.map(address => encodeBN254toBase58(address)).join(', ')}`,\n );\n }\n\n /// Creates proof for each address\n const newAddressProofs: MerkleContextWithNewAddressProof[] = [];\n\n for (const proof of res.result.value) {\n const _proof: MerkleContextWithNewAddressProof = {\n root: proof.root,\n rootIndex: proof.rootSeq % 2400,\n value: proof.address,\n leafLowerRangeValue: proof.lowerRangeAddress,\n leafHigherRangeValue: proof.higherRangeAddress,\n nextIndex: bn(proof.nextIndex),\n merkleProofHashedIndexedElementLeaf: proof.proof,\n indexHashedIndexedElementLeaf: bn(proof.lowElementLeafIndex),\n merkleTree: proof.merkleTree,\n nullifierQueue: defaultTestStateTreeAccounts().addressQueue,\n };\n newAddressProofs.push(_proof);\n }\n return newAddressProofs;\n }\n\n /**\n * Advanced usage of getValidityProof: fetches ZKP directly from a custom\n * non-rpcprover. Note: This uses the proverEndpoint specified in the\n * constructor. For normal usage, please use {@link getValidityProof}\n * instead.\n *\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProofDirect(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n let validityProof: CompressedProofWithContext;\n\n if (hashes.length === 0 && newAddresses.length === 0) {\n throw new Error(\n 'Empty input. Provide hashes and/or new addresses.',\n );\n } else if (hashes.length > 0 && newAddresses.length === 0) {\n /// inclusion\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // [],\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'inclusion',\n inputs,\n false,\n // publicInputHash,\n );\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext.map(proof => proof.root),\n rootIndices: merkleProofsWithContext.map(\n proof => proof.rootIndex,\n ),\n leafIndices: merkleProofsWithContext.map(\n proof => proof.leafIndex,\n ),\n leaves: merkleProofsWithContext.map(proof => bn(proof.hash)),\n merkleTrees: merkleProofsWithContext.map(\n proof => proof.merkleTree,\n ),\n nullifierQueues: merkleProofsWithContext.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length === 0 && newAddresses.length > 0) {\n /// new-address\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const inputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // [],\n // [],\n // newAddressProofs,\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'new-address',\n inputs,\n false,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: newAddressProofs.map(proof => proof.root),\n rootIndices: newAddressProofs.map(proof => proof.rootIndex),\n leafIndices: newAddressProofs.map(proof =>\n proof.nextIndex.toNumber(),\n ),\n leaves: newAddressProofs.map(proof => bn(proof.value)),\n merkleTrees: newAddressProofs.map(proof => proof.merkleTree),\n nullifierQueues: newAddressProofs.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length > 0 && newAddresses.length > 0) {\n /// combined\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const newAddressInputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const lightWasm = await WasmFactory.getInstance();\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // newAddressProofs,\n // lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'combined',\n [inputs, newAddressInputs],\n false,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext\n .map(proof => proof.root)\n .concat(newAddressProofs.map(proof => proof.root)),\n rootIndices: merkleProofsWithContext\n .map(proof => proof.rootIndex)\n .concat(newAddressProofs.map(proof => proof.rootIndex)),\n leafIndices: merkleProofsWithContext\n .map(proof => proof.leafIndex)\n .concat(\n newAddressProofs.map(\n proof => proof.nextIndex.toNumber(), // TODO: support >32bit\n ),\n ),\n leaves: merkleProofsWithContext\n .map(proof => bn(proof.hash))\n .concat(newAddressProofs.map(proof => bn(proof.value))),\n merkleTrees: merkleProofsWithContext\n .map(proof => proof.merkleTree)\n .concat(newAddressProofs.map(proof => proof.merkleTree)),\n nullifierQueues: merkleProofsWithContext\n .map(proof => proof.nullifierQueue)\n .concat(\n newAddressProofs.map(proof => proof.nullifierQueue),\n ),\n };\n } else throw new Error('Invalid input');\n\n return validityProof;\n }\n\n /**\n * @deprecated use {@link getValidityProofV0} instead.\n *\n *\n *\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProof(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n const accs = await this.getMultipleCompressedAccounts(hashes);\n const trees = accs.map(acc => acc.merkleTree);\n const queues = accs.map(acc => acc.nullifierQueue);\n\n // TODO: add dynamic address tree support here\n const defaultAddressTreePublicKey =\n defaultTestStateTreeAccounts().addressTree;\n const defaultAddressQueuePublicKey =\n defaultTestStateTreeAccounts().addressQueue;\n\n const formattedHashes = hashes.map((item, index) => {\n return {\n hash: item,\n tree: trees[index],\n queue: queues[index],\n };\n });\n\n const formattedNewAddresses = newAddresses.map(item => {\n return {\n address: item,\n tree: defaultAddressTreePublicKey,\n queue: defaultAddressQueuePublicKey,\n };\n });\n\n return this.getValidityProofV0(formattedHashes, formattedNewAddresses);\n }\n\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of { hash: BN254, tree: PublicKey, queue: PublicKey }.\n * @param newAddresses Array of { address: BN254, tree: PublicKey, queue: PublicKey }.\n * @returns validity proof with context\n */\n async getValidityProofV0(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<CompressedProofWithContext> {\n const { value } = await this.getValidityProofAndRpcContext(\n hashes,\n newAddresses,\n );\n return value;\n }\n\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses. Returns with context slot.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses. Optionally specify the\n * tree and queue for each address. Default to public\n * state tree/queue.\n * @returns validity proof with context\n */\n async getValidityProofAndRpcContext(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<WithContext<CompressedProofWithContext>> {\n validateNumbersForProof(hashes.length, newAddresses.length);\n\n const unsafeRes = await rpcRequest(\n this.compressionApiEndpoint,\n 'getValidityProof',\n {\n hashes: hashes.map(({ hash }) => encodeBN254toBase58(hash)),\n newAddressesWithTrees: newAddresses.map(\n ({ address, tree }) => ({\n address: encodeBN254toBase58(address),\n tree: tree.toBase58(),\n }),\n ),\n },\n );\n\n const res = create(\n unsafeRes,\n jsonRpcResultAndContext(ValidityProofResult),\n );\n if ('error' in res) {\n throw new SolanaJSONRPCError(\n res.error,\n `failed to get ValidityProof for compressed accounts ${hashes.map(hash => hash.toString())}`,\n );\n }\n\n const result = res.result.value;\n\n if (result === null) {\n throw new Error(\n `failed to get ValidityProof for compressed accounts ${hashes.map(hash => hash.toString())}`,\n );\n }\n\n const value: CompressedProofWithContext = {\n compressedProof: result.compressedProof,\n merkleTrees: result.merkleTrees,\n leafIndices: result.leafIndices,\n nullifierQueues: [\n ...hashes.map(({ queue }) => queue),\n ...newAddresses.map(({ queue }) => queue),\n ],\n rootIndices: result.rootIndices,\n roots: result.roots,\n leaves: result.leaves,\n };\n return { value, context: res.result.context };\n }\n}\n","import { Signer } from '@solana/web3.js';\n\n/** @internal remove signer from signers if part of signers */\nexport function dedupeSigner(signer: Signer, signers: Signer[]): Signer[] {\n if (signers.includes(signer)) {\n return signers.filter(\n s => s.publicKey.toString() !== signer.publicKey.toString(),\n );\n }\n return signers;\n}\n","// TODO: Clean up\nexport enum UtxoErrorCode {\n NEGATIVE_LAMPORTS = 'NEGATIVE_LAMPORTS',\n NOT_U64 = 'NOT_U64',\n BLINDING_EXCEEDS_FIELD_SIZE = 'BLINDING_EXCEEDS_FIELD_SIZE',\n}\n\nexport enum SelectInUtxosErrorCode {\n FAILED_TO_FIND_UTXO_COMBINATION = 'FAILED_TO_FIND_UTXO_COMBINATION',\n INVALID_NUMBER_OF_IN_UTXOS = 'INVALID_NUMBER_OF_IN_UTXOS',\n}\n\nexport enum CreateUtxoErrorCode {\n OWNER_UNDEFINED = 'OWNER_UNDEFINED',\n INVALID_OUTPUT_UTXO_LENGTH = 'INVALID_OUTPUT_UTXO_LENGTH',\n UTXO_DATA_UNDEFINED = 'UTXO_DATA_UNDEFINED',\n}\n\nexport enum RpcErrorCode {\n CONNECTION_UNDEFINED = 'CONNECTION_UNDEFINED',\n RPC_PUBKEY_UNDEFINED = 'RPC_PUBKEY_UNDEFINED',\n RPC_METHOD_NOT_IMPLEMENTED = 'RPC_METHOD_NOT_IMPLEMENTED',\n RPC_INVALID = 'RPC_INVALID',\n}\n\nexport enum LookupTableErrorCode {\n LOOK_UP_TABLE_UNDEFINED = 'LOOK_UP_TABLE_UNDEFINED',\n LOOK_UP_TABLE_NOT_INITIALIZED = 'LOOK_UP_TABLE_NOT_INITIALIZED',\n}\n\nexport enum HashErrorCode {\n NO_POSEIDON_HASHER_PROVIDED = 'NO_POSEIDON_HASHER_PROVIDED',\n}\n\nexport enum ProofErrorCode {\n INVALID_PROOF = 'INVALID_PROOF',\n PROOF_INPUT_UNDEFINED = 'PROOF_INPUT_UNDEFINED',\n PROOF_GENERATION_FAILED = 'PROOF_GENERATION_FAILED',\n}\n\nexport enum MerkleTreeErrorCode {\n MERKLE_TREE_NOT_INITIALIZED = 'MERKLE_TREE_NOT_INITIALIZED',\n SOL_MERKLE_TREE_UNDEFINED = 'SOL_MERKLE_TREE_UNDEFINED',\n MERKLE_TREE_UNDEFINED = 'MERKLE_TREE_UNDEFINED',\n INPUT_UTXO_NOT_INSERTED_IN_MERKLE_TREE = 'INPUT_UTXO_NOT_INSERTED_IN_MERKLE_TREE',\n MERKLE_TREE_INDEX_UNDEFINED = 'MERKLE_TREE_INDEX_UNDEFINED',\n MERKLE_TREE_SET_SPACE_UNDEFINED = 'MERKLE_TREE_SET_SPACE_UNDEFINED',\n}\n\nexport enum UtilsErrorCode {\n ACCOUNT_NAME_UNDEFINED_IN_IDL = 'ACCOUNT_NAME_UNDEFINED_IN_IDL',\n PROPERTY_UNDEFINED = 'PROPERTY_UNDEFINED',\n LOOK_UP_TABLE_CREATION_FAILED = 'LOOK_UP_TABLE_CREATION_FAILED',\n UNSUPPORTED_ARCHITECTURE = 'UNSUPPORTED_ARCHITECTURE',\n UNSUPPORTED_PLATFORM = 'UNSUPPORTED_PLATFORM',\n ACCOUNTS_UNDEFINED = 'ACCOUNTS_UNDEFINED',\n INVALID_NUMBER = 'INVALID_NUMBER',\n}\n\nclass MetaError extends Error {\n code: string;\n functionName: string;\n codeMessage?: string;\n\n constructor(code: string, functionName: string, codeMessage?: string) {\n super(`${code}: ${codeMessage}`);\n this.code = code;\n this.functionName = functionName;\n this.codeMessage = codeMessage;\n }\n}\n\nexport class UtxoError extends MetaError {}\n\nexport class SelectInUtxosError extends MetaError {}\n\nexport class CreateUtxoError extends MetaError {}\n\nexport class RpcError extends MetaError {}\n\nexport class LookupTableError extends MetaError {}\n\nexport class HashError extends MetaError {}\n\nexport class ProofError extends MetaError {}\n\nexport class MerkleTreeError extends MetaError {}\n\nexport class UtilsError extends MetaError {}\n","import { LightWasm } from '../test-rpc/test-rpc';\nimport BN from 'bn.js';\nimport { bn } from '../../state';\nimport { HIGHEST_ADDRESS_PLUS_ONE } from '../../constants';\n\nexport class IndexedElement {\n public index: number;\n public value: BN;\n public nextIndex: number;\n\n constructor(index: number, value: BN, nextIndex: number) {\n this.index = index;\n this.value = value;\n this.nextIndex = nextIndex;\n }\n\n public equals(other: IndexedElement): boolean {\n return this.value.eq(other.value);\n }\n\n public compareTo(other: IndexedElement): number {\n return this.value.cmp(other.value);\n }\n\n public hash(lightWasm: LightWasm, nextValue: BN): Uint8Array {\n try {\n const hash = lightWasm.poseidonHash([\n bn(this.value.toArray('be', 32)).toString(),\n bn(this.nextIndex).toString(),\n bn(nextValue.toArray('be', 32)).toString(),\n ]);\n return hash;\n } catch (error) {\n throw new Error('Hashing failed');\n }\n }\n}\n\nexport class IndexedElementBundle {\n public newLowElement: IndexedElement;\n public newElement: IndexedElement;\n public newElementNextValue: BN;\n\n constructor(\n newLowElement: IndexedElement,\n newElement: IndexedElement,\n newElementNextValue: BN,\n ) {\n this.newLowElement = newLowElement;\n this.newElement = newElement;\n this.newElementNextValue = newElementNextValue;\n }\n}\n\n/**\n * This indexed array implementation mirrors the rust implementation of the\n * indexed merkle tree. It stores the elements of the indexed merkle tree.\n */\nexport class IndexedArray {\n public elements: Array<IndexedElement>;\n public currentNodeIndex: number;\n public highestElementIndex: number;\n\n constructor(\n elements: Array<IndexedElement>,\n currentNodeIndex: number,\n highestElementIndex: number,\n ) {\n this.elements = elements;\n this.currentNodeIndex = currentNodeIndex;\n this.highestElementIndex = highestElementIndex;\n }\n\n public static default(): IndexedArray {\n return new IndexedArray([new IndexedElement(0, bn(0), 0)], 0, 0);\n }\n\n public get(index: number): IndexedElement | undefined {\n return this.elements[index];\n }\n\n public length(): number {\n return Number(this.currentNodeIndex);\n }\n\n public isEmpty(): boolean {\n return this.currentNodeIndex === 0;\n }\n\n public findElement(value: BN): IndexedElement | undefined {\n return this.elements\n .slice(0, this.length() + 1)\n .find(node => node.value === value);\n }\n\n public init(): IndexedElementBundle {\n try {\n const init_value = HIGHEST_ADDRESS_PLUS_ONE;\n return this.append(init_value);\n } catch (error) {\n throw new Error(`Failed to initialize IndexedArray: ${error}`);\n }\n }\n\n /**\n * Finds the index of the low element for the given `value` which should not be part of the array.\n * Low element is the greatest element which still has a lower value than the provided one.\n * Low elements are used in non-membership proofs.\n */\n public findLowElementIndex(value: BN): number | undefined {\n // Try to find element whose next element is higher than the provided value.\n for (let i = 0; i <= this.length(); i++) {\n const node = this.elements[i];\n if (\n this.elements[node.nextIndex].value.gt(value) &&\n node.value.lt(value)\n ) {\n return i;\n } else if (node.value.eq(value)) {\n throw new Error('Element already exists in the array');\n }\n }\n // If no such element was found, it means that our value is going to be the greatest in the array.\n // This means that the currently greatest element is going to be the low element of our value.\n return this.highestElementIndex;\n }\n\n /**\n * Returns the low element for the given value and the next value for that low element.\n * Low element is the greatest element which still has lower value than the provided one.\n * Low elements are used in non-membership proofs.\n */\n public findLowElement(\n value: BN,\n ): [IndexedElement | undefined, BN | undefined] {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) return [undefined, undefined];\n const lowElement = this.elements[lowElementIndex];\n return [lowElement, this.elements[lowElement.nextIndex].value];\n }\n\n // /**\n // * Returns the index of the low element for the given `value`, which should be the part of the array.\n // * Low element is the greatest element which still has lower value than the provided one.\n // * Low elements are used in non-membership proofs.\n // */\n // public findLowElementIndexForExistingElement(\n // value: BN,\n // ): number | undefined {\n // for (let i = 0; i <= this.length(); i++) {\n // const node = this.elements[i];\n // if (this.elements[node.nextIndex].value === value) {\n // return i;\n // }\n // }\n // return undefined;\n // }\n\n /**\n * Returns the hash of the given element. That hash consists of:\n * - The value of the given element.\n * - The `nextIndex` of the given element.\n * - The value of the element pointed by `nextIndex`.\n */\n public hashElement(\n lightWasm: LightWasm,\n index: number,\n ): Uint8Array | undefined {\n const element = this.elements[index];\n if (!element) return undefined;\n const nextElement = this.elements[element.nextIndex];\n if (!nextElement) return undefined;\n\n const hash = lightWasm.poseidonHash([\n bn(element.value.toArray('be', 32)).toString(),\n bn(element.nextIndex).toString(),\n bn(nextElement.value.toArray('be', 32)).toString(),\n ]);\n\n return hash;\n }\n\n /**\n * Appends a new element with the given value to the indexed array.\n * It finds the low element index and uses it to append the new element correctly.\n * @param value The value of the new element to append.\n * @returns The new element and its low element after insertion.\n */\n public append(value: BN): IndexedElementBundle {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) {\n throw new Error('Low element index not found.');\n }\n return this.appendWithLowElementIndex(lowElementIndex, value);\n }\n\n /**\n * Appends a new element with the given value to the indexed array using a specific low element index.\n * This method ensures the new element is placed correctly relative to the low element.\n * @param lowElementIndex The index of the low element.\n * @param value The value of the new element to append.\n * @returns The new element and its updated low element.\n */\n public appendWithLowElementIndex(\n lowElementIndex: number,\n value: BN,\n ): IndexedElementBundle {\n const lowElement = this.elements[lowElementIndex];\n\n if (lowElement.nextIndex === 0) {\n if (value.lte(lowElement.value)) {\n throw new Error(\n 'New element value must be greater than the low element value.',\n );\n }\n } else {\n const nextElement = this.elements[lowElement.nextIndex];\n\n if (value.lte(lowElement.value)) {\n throw new Error(\n 'New element value must be greater than the low element value.',\n );\n }\n\n if (value.gte(nextElement.value)) {\n throw new Error(\n 'New element value must be less than the next element value.',\n );\n }\n }\n\n const newElementBundle = this.newElementWithLowElementIndex(\n lowElementIndex,\n value,\n );\n\n // If the old low element wasn't pointing to any element, it means that:\n //\n // * It used to be the highest element.\n // * Our new element, which we are appending, is going the be the\n // highest element.\n //\n // Therefore, we need to save the new element index as the highest\n // index.\n if (lowElement.nextIndex === 0) {\n this.highestElementIndex = newElementBundle.newElement.index;\n }\n\n // Insert new node.\n this.currentNodeIndex = newElementBundle.newElement.index;\n this.elements[this.length()] = newElementBundle.newElement;\n\n // Update low element.\n this.elements[lowElementIndex] = newElementBundle.newLowElement;\n\n return newElementBundle;\n }\n\n /**\n * Finds the lowest element in the array.\n * @returns The lowest element or undefined if the array is empty.\n */\n public lowest(): IndexedElement | undefined {\n return this.elements.length > 0 ? this.elements[0] : undefined;\n }\n\n /**\n * Creates a new element with the specified value and updates the low element index accordingly.\n * @param lowElementIndex The index of the low element.\n * @param value The value for the new element.\n * @returns A bundle containing the new element, the updated low element, and the value of the next element.\n */\n public newElementWithLowElementIndex(\n lowElementIndex: number,\n value: BN,\n ): IndexedElementBundle {\n const newLowElement = this.elements[lowElementIndex];\n\n const newElementIndex = this.currentNodeIndex + 1;\n const newElement = new IndexedElement(\n newElementIndex,\n value,\n newLowElement.nextIndex,\n );\n newLowElement.nextIndex = newElementIndex;\n\n const newElementNextValue = this.elements[newElement.nextIndex].value;\n\n return new IndexedElementBundle(\n newLowElement,\n newElement,\n newElementNextValue,\n );\n }\n\n /**\n * Creates a new element with the specified value by first finding the appropriate low element index.\n * @param value The value for the new element.\n * @returns A bundle containing the new element, the updated low element, and the value of the next element.\n */\n public newElement(value: BN): IndexedElementBundle {\n const lowElementIndex = this.findLowElementIndex(value);\n if (lowElementIndex === undefined) {\n throw new Error('Low element index not found.');\n }\n return this.newElementWithLowElementIndex(lowElementIndex, value);\n }\n}\n","import { LightWasm } from '../test-rpc/test-rpc';\n\nexport const DEFAULT_ZERO = '0';\n\n/**\n * @callback hashFunction\n * @param left Left leaf\n * @param right Right leaf\n */\n/**\n * Merkle tree\n */\nexport class MerkleTree {\n /**\n * Constructor\n * @param {number} levels Number of levels in the tree\n * @param {Array} [elements] Initial elements\n * @param {Object} options\n * @param {hashFunction} [options.hashFunction] Function used to hash 2 leaves\n * @param [options.zeroElement] Value for non-existent leaves\n */\n levels: number;\n capacity: number;\n zeroElement;\n _zeros: string[];\n _layers: string[][];\n _lightWasm: LightWasm;\n\n constructor(\n levels: number,\n lightWasm: LightWasm,\n elements: string[] = [],\n { zeroElement = DEFAULT_ZERO } = {},\n ) {\n this.levels = levels;\n this.capacity = 2 ** levels;\n this.zeroElement = zeroElement;\n this._lightWasm = lightWasm;\n if (elements.length > this.capacity) {\n throw new Error('Tree is full');\n }\n this._zeros = [];\n this._layers = [];\n this._layers[0] = elements;\n this._zeros[0] = this.zeroElement;\n\n for (let i = 1; i <= levels; i++) {\n this._zeros[i] = this._lightWasm.poseidonHashString([\n this._zeros[i - 1],\n this._zeros[i - 1],\n ]);\n }\n this._rebuild();\n }\n\n _rebuild() {\n for (let level = 1; level <= this.levels; level++) {\n this._layers[level] = [];\n for (\n let i = 0;\n i < Math.ceil(this._layers[level - 1].length / 2);\n i++\n ) {\n this._layers[level][i] = this._lightWasm.poseidonHashString([\n this._layers[level - 1][i * 2],\n i * 2 + 1 < this._layers[level - 1].length\n ? this._layers[level - 1][i * 2 + 1]\n : this._zeros[level - 1],\n ]);\n }\n }\n }\n\n /**\n * Get tree root\n * @returns {*}\n */\n root() {\n return this._layers[this.levels].length > 0\n ? this._layers[this.levels][0]\n : this._zeros[this.levels];\n }\n\n /**\n * Insert new element into the tree\n * @param element Element to insert\n */\n\n insert(element: string) {\n if (this._layers[0].length >= this.capacity) {\n throw new Error('Tree is full');\n }\n this.update(this._layers[0].length, element);\n }\n\n /**\n * Insert multiple elements into the tree. Tree will be fully rebuilt during this operation.\n * @param {Array} elements Elements to insert\n */\n bulkInsert(elements: string[]) {\n if (this._layers[0].length + elements.length > this.capacity) {\n throw new Error('Tree is full');\n }\n this._layers[0].push(...elements);\n this._rebuild();\n }\n\n // TODO: update does not work debug\n /**\n * Change an element in the tree\n * @param {number} index Index of element to change\n * @param element Updated element value\n */\n update(index: number, element: string) {\n // index 0 and 1 and element is the commitment hash\n if (\n isNaN(Number(index)) ||\n index < 0 ||\n index > this._layers[0].length ||\n index >= this.capacity\n ) {\n throw new Error('Insert index out of bounds: ' + index);\n }\n this._layers[0][index] = element;\n for (let level = 1; level <= this.levels; level++) {\n index >>= 1;\n this._layers[level][index] = this._lightWasm.poseidonHashString([\n this._layers[level - 1][index * 2],\n index * 2 + 1 < this._layers[level - 1].length\n ? this._layers[level - 1][index * 2 + 1]\n : this._zeros[level - 1],\n ]);\n }\n }\n\n /**\n * Get merkle path to a leaf\n * @param {number} index Leaf index to generate path for\n * @returns {{pathElements: number[], pathIndex: number[]}} An object containing adjacent elements and left-right index\n */\n path(index: number) {\n if (\n isNaN(Number(index)) ||\n index < 0 ||\n index >= this._layers[0].length\n ) {\n throw new Error('Index out of bounds: ' + index);\n }\n const pathElements: string[] = [];\n const pathIndices: number[] = [];\n for (let level = 0; level < this.levels; level++) {\n pathIndices[level] = index % 2;\n pathElements[level] =\n (index ^ 1) < this._layers[level].length\n ? this._layers[level][index ^ 1]\n : this._zeros[level];\n index >>= 1;\n }\n return {\n pathElements,\n pathIndices,\n };\n }\n\n /**\n * Find an element in the tree\n * @param element An element to find\n * @param comparator A function that checks leaf value equality\n * @returns {number} Index if element is found, otherwise -1\n */\n indexOf(\n element: string,\n comparator: ((element: string, el: string) => boolean) | null = null,\n ) {\n if (comparator) {\n return this._layers[0].findIndex((el: string) =>\n comparator(element, el),\n );\n } else {\n return this._layers[0].indexOf(element);\n }\n }\n\n /**\n * Returns a copy of non-zero tree elements\n * @returns {Object[]}\n */\n elements() {\n return this._layers[0].slice();\n }\n\n /**\n * Serialize entire tree state including intermediate layers into a plain object\n * Deserializing it back will not require to recompute any hashes\n * Elements are not converted to a plain type, this is responsibility of the caller\n */\n serialize() {\n return {\n levels: this.levels,\n _zeros: this._zeros,\n _layers: this._layers,\n };\n }\n\n /**\n * Deserialize data into a MerkleTree instance\n * Make sure to provide the same hashFunction as was used in the source tree,\n * otherwise the tree state will be invalid\n *\n * @param data\n * @param hashFunction\n * @returns {MerkleTree}\n */\n static deserialize(\n data: any,\n hashFunction: (left: string, right: string) => string,\n ) {\n const instance = Object.assign(Object.create(this.prototype), data);\n instance._hash = hashFunction;\n instance.capacity = 2 ** instance.levels;\n instance.zeroElement = instance._zeros[0];\n return instance;\n }\n}\n","import {\n GetVersionedTransactionConfig,\n MessageV0,\n ParsedMessageAccount,\n ParsedTransactionWithMeta,\n PublicKey,\n VersionedTransactionResponse,\n} from '@solana/web3.js';\nimport bs58 from 'bs58';\nimport {\n COMPUTE_BUDGET_PATTERN,\n defaultStaticAccountsStruct,\n INSERT_INTO_QUEUES_DISCRIMINATOR,\n INVOKE_CPI_DISCRIMINATOR,\n INVOKE_DISCRIMINATOR,\n} from '../../constants';\nimport {\n convertToPublicTransactionEvent,\n decodeInstructionDataInvoke,\n decodeInstructionDataInvokeCpi,\n deserializeAppendNullifyCreateAddressInputsIndexer,\n} from '../../programs';\nimport { Rpc } from '../../rpc';\nimport { InstructionDataInvoke, PublicTransactionEvent } from '../../state';\nimport { decodePublicTransactionEvent } from '../../programs/layout';\nimport { Buffer } from 'buffer';\n\ntype Deserializer<T> = (data: Buffer, tx: ParsedTransactionWithMeta) => T;\n\n/**\n * @internal\n * Returns newest first.\n *\n * */\nexport async function getParsedEvents(\n rpc: Rpc,\n): Promise<PublicTransactionEvent[]> {\n const events: PublicTransactionEvent[] = [];\n\n const { noopProgram, accountCompressionProgram } =\n defaultStaticAccountsStruct();\n\n const signatures = (\n await rpc.getConfirmedSignaturesForAddress2(\n accountCompressionProgram,\n undefined,\n 'confirmed',\n )\n ).map(s => s.signature);\n const txs = await rpc.getParsedTransactions(signatures, {\n maxSupportedTransactionVersion: 0,\n commitment: 'confirmed',\n });\n\n for (const txParsed of txs) {\n if (!txParsed || !txParsed.transaction || !txParsed.meta) continue;\n\n if (\n !txParsed.meta.innerInstructions ||\n txParsed.meta.innerInstructions.length == 0\n ) {\n continue;\n }\n\n const messageV0 = txParsed.transaction.message;\n const accKeys = messageV0.accountKeys;\n\n const allAccounts = accKeys.map(a => a.pubkey);\n const dataVec: Uint8Array[] = [];\n\n // get tx wth sig\n const txRaw = await rpc.getTransaction(\n txParsed.transaction.signatures[0],\n {\n commitment: 'confirmed',\n maxSupportedTransactionVersion: 0,\n },\n );\n\n for (const ix of txRaw?.transaction.message.compiledInstructions ||\n []) {\n if (ix.data && ix.data.length > 0) {\n const decodedData = Uint8Array.from(ix.data);\n if (\n decodedData.length === COMPUTE_BUDGET_PATTERN.length &&\n COMPUTE_BUDGET_PATTERN.every(\n (byte, idx) => byte === decodedData[idx],\n )\n ) {\n continue;\n }\n dataVec.push(decodedData);\n }\n }\n\n const groupedAccountVec: PublicKey[][] = [];\n\n if (\n txRaw!.meta!.innerInstructions &&\n txRaw!.meta!.innerInstructions.length > 0\n ) {\n for (const innerGroup of txRaw!.meta!.innerInstructions) {\n for (const ix of innerGroup.instructions) {\n const group = ix.accounts.map(\n (accountIdx: number) => allAccounts[accountIdx],\n );\n groupedAccountVec.push(group);\n if (ix.data && ix.data.length > 0) {\n const decodedData = bs58.decode(ix.data);\n dataVec.push(decodedData);\n }\n }\n }\n }\n\n const event = parseLightTransaction(dataVec, groupedAccountVec);\n if (event) {\n events.push(event);\n }\n }\n\n if (events.length > 0) {\n return events;\n }\n\n /// Filter by NOOP program\n const transactionEvents = txs.filter(\n (tx: ParsedTransactionWithMeta | null) => {\n if (!tx) {\n return false;\n }\n const accountKeys = tx.transaction.message.accountKeys;\n\n const hasSplNoopAddress = accountKeys.some(\n (item: ParsedMessageAccount) => {\n const itemStr =\n typeof item === 'string'\n ? item\n : item.pubkey.toBase58();\n return itemStr === noopProgram.toBase58();\n },\n );\n\n return hasSplNoopAddress;\n },\n );\n\n return parseEvents(transactionEvents, parsePublicTransactionEventWithIdl);\n}\n\nexport const parseEvents = <T>(\n indexerEventsTransactions: (ParsedTransactionWithMeta | null)[],\n deserializeFn: Deserializer<T>,\n): NonNullable<T>[] => {\n const { noopProgram } = defaultStaticAccountsStruct();\n\n const transactions: NonNullable<T>[] = [];\n indexerEventsTransactions.forEach(tx => {\n if (\n !tx ||\n !tx.meta ||\n tx.meta.err ||\n !tx.meta.innerInstructions ||\n tx.meta.innerInstructions.length <= 0\n ) {\n return;\n }\n\n /// We only care about the very last inner instruction as it contains the\n /// PublicTransactionEvent\n tx.meta.innerInstructions.forEach(ix => {\n if (ix.instructions.length > 0) {\n const ixInner = ix.instructions[ix.instructions.length - 1];\n // Type guard for partially parsed web3js types.\n if (\n 'data' in ixInner &&\n ixInner.data &&\n ixInner.programId.toBase58() === noopProgram.toBase58()\n ) {\n const data = bs58.decode(ixInner.data);\n\n const decodedEvent = deserializeFn(Buffer.from(data), tx);\n\n if (decodedEvent !== null && decodedEvent !== undefined) {\n transactions.push(decodedEvent as NonNullable<T>);\n }\n }\n }\n });\n });\n\n return transactions;\n};\n\n// TODO: make it type safe. have to reimplement the types from the IDL.\nexport const parsePublicTransactionEventWithIdl = (\n data: Buffer,\n): PublicTransactionEvent | null => {\n const numericData = Buffer.from(data.map(byte => byte));\n\n try {\n return decodePublicTransactionEvent(numericData);\n } catch (error) {\n console.error('Error deserializing event:', error);\n return null;\n }\n};\n\nexport function parseLightTransaction(\n dataVec: Uint8Array[],\n accountKeys: PublicKey[][],\n): PublicTransactionEvent | null | undefined {\n let foundSystemInstruction = false;\n\n let invokeData: InstructionDataInvoke | null = null;\n let appendInputsData = null;\n\n // First pass for system instructions\n for (const data of dataVec) {\n const discriminator = data.slice(0, 8);\n const discriminatorStr = bs58.encode(discriminator);\n const invokeDiscriminatorStr = bs58.encode(INVOKE_DISCRIMINATOR);\n const invokeCpiDiscriminatorStr = bs58.encode(INVOKE_CPI_DISCRIMINATOR);\n if (discriminatorStr === invokeDiscriminatorStr) {\n invokeData = decodeInstructionDataInvoke(Buffer.from(data));\n foundSystemInstruction = true;\n break;\n }\n if (discriminatorStr == invokeCpiDiscriminatorStr) {\n invokeData = decodeInstructionDataInvokeCpi(Buffer.from(data));\n foundSystemInstruction = true;\n break;\n }\n }\n if (!foundSystemInstruction) return null;\n\n for (const data of dataVec) {\n const discriminator = data.slice(0, 8);\n const discriminatorStr = bs58.encode(discriminator);\n const insertIntoQueuesDiscriminatorStr = bs58.encode(\n INSERT_INTO_QUEUES_DISCRIMINATOR,\n );\n if (discriminatorStr !== insertIntoQueuesDiscriminatorStr) {\n console.log('discriminator does not match');\n } else {\n const dataSlice = data.slice(12);\n appendInputsData =\n deserializeAppendNullifyCreateAddressInputsIndexer(\n Buffer.from(dataSlice),\n );\n }\n }\n\n if (invokeData) {\n return convertToPublicTransactionEvent(\n appendInputsData,\n accountKeys[accountKeys.length - 1],\n invokeData,\n );\n } else {\n return null;\n }\n}\n","import { PublicKey } from '@solana/web3.js';\n\nimport BN from 'bn.js';\nimport { getParsedEvents } from './get-parsed-events';\nimport { defaultTestStateTreeAccounts } from '../../constants';\nimport { Rpc } from '../../rpc';\nimport {\n CompressedAccountWithMerkleContext,\n bn,\n MerkleContext,\n createCompressedAccountWithMerkleContext,\n} from '../../state';\n\nexport async function getCompressedAccountsByOwnerTest(\n rpc: Rpc,\n owner: PublicKey,\n) {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n const byOwner = unspentAccounts.filter(acc => acc.owner.equals(owner));\n return byOwner;\n}\n\nexport async function getCompressedAccountByHashTest(\n rpc: Rpc,\n hash: BN,\n): Promise<CompressedAccountWithMerkleContext | undefined> {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n return unspentAccounts.find(acc => bn(acc.hash).eq(hash));\n}\n\nexport async function getMultipleCompressedAccountsByHashTest(\n rpc: Rpc,\n hashes: BN[],\n): Promise<CompressedAccountWithMerkleContext[]> {\n const unspentAccounts = await getCompressedAccountsForTest(rpc);\n return unspentAccounts\n .filter(acc => hashes.some(hash => bn(acc.hash).eq(hash)))\n .sort((a, b) => b.leafIndex - a.leafIndex);\n}\n\n/// Returns all unspent compressed accounts\nasync function getCompressedAccountsForTest(rpc: Rpc) {\n const events = (await getParsedEvents(rpc)).reverse();\n const allOutputAccounts: CompressedAccountWithMerkleContext[] = [];\n const allInputAccountHashes: BN[] = [];\n\n for (const event of events) {\n for (\n let index = 0;\n index < event.outputCompressedAccounts.length;\n index++\n ) {\n const account = event.outputCompressedAccounts[index];\n const merkleContext: MerkleContext = {\n merkleTree: defaultTestStateTreeAccounts().merkleTree,\n nullifierQueue: defaultTestStateTreeAccounts().nullifierQueue,\n hash: event.outputCompressedAccountHashes[index],\n leafIndex: event.outputLeafIndices[index],\n };\n const withCtx: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n merkleContext,\n account.compressedAccount.owner,\n account.compressedAccount.lamports,\n account.compressedAccount.data ?? undefined,\n account.compressedAccount.address ?? undefined,\n );\n allOutputAccounts.push(withCtx);\n }\n for (\n let index = 0;\n index < event.inputCompressedAccountHashes.length;\n index++\n ) {\n const hash = event.inputCompressedAccountHashes[index];\n allInputAccountHashes.push(bn(hash));\n }\n }\n\n const unspentAccounts = allOutputAccounts.filter(\n account =>\n !allInputAccountHashes.some(hash => hash.eq(bn(account.hash))),\n );\n unspentAccounts.sort((a, b) => b.leafIndex - a.leafIndex);\n\n return unspentAccounts;\n}\n","import { PublicKey } from '@solana/web3.js';\nimport { getParsedEvents } from './get-parsed-events';\nimport BN from 'bn.js';\nimport { defaultTestStateTreeAccounts } from '../../constants';\nimport { Rpc } from '../../rpc';\nimport { ParsedTokenAccount, WithCursor } from '../../rpc-interface';\nimport {\n CompressedAccount,\n PublicTransactionEvent,\n MerkleContext,\n createCompressedAccountWithMerkleContext,\n bn,\n} from '../../state';\nimport {\n struct,\n publicKey,\n u64,\n option,\n vecU8,\n u8,\n Layout,\n} from '@coral-xyz/borsh';\n\nconst tokenProgramId: PublicKey = new PublicKey(\n 'cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m',\n);\n\ntype TokenData = {\n mint: PublicKey;\n owner: PublicKey;\n amount: BN;\n delegate: PublicKey | null;\n state: number;\n tlv: Buffer | null;\n};\n\n// for test-rpc\nexport const TokenDataLayout: Layout<TokenData> = struct([\n publicKey('mint'),\n publicKey('owner'),\n u64('amount'),\n option(publicKey(), 'delegate'),\n u8('state'),\n option(vecU8(), 'tlv'),\n]);\n\nexport type EventWithParsedTokenTlvData = {\n inputCompressedAccountHashes: number[][];\n outputCompressedAccounts: ParsedTokenAccount[];\n};\n/**\n * Manually parse the compressed token layout for a given compressed account.\n * @param compressedAccount - The compressed account\n * @returns The parsed token data\n */\nexport function parseTokenLayoutWithIdl(\n compressedAccount: CompressedAccount,\n programId: PublicKey = tokenProgramId,\n): TokenData | null {\n if (compressedAccount.data === null) return null;\n\n const { data } = compressedAccount.data;\n\n if (data.length === 0) return null;\n if (compressedAccount.owner.toBase58() !== programId.toBase58()) {\n throw new Error(\n `Invalid owner ${compressedAccount.owner.toBase58()} for token layout`,\n );\n }\n return TokenDataLayout.decode(Buffer.from(data));\n}\n\n/**\n * parse compressed accounts of an event with token layout\n * @internal\n * TODO: refactor\n */\nasync function parseEventWithTokenTlvData(\n event: PublicTransactionEvent,\n): Promise<EventWithParsedTokenTlvData> {\n const pubkeyArray = event.pubkeyArray;\n\n const outputHashes = event.outputCompressedAccountHashes;\n const outputCompressedAccountsWithParsedTokenData: ParsedTokenAccount[] =\n event.outputCompressedAccounts.map((compressedAccount, i) => {\n const merkleContext: MerkleContext = {\n merkleTree:\n pubkeyArray[\n event.outputCompressedAccounts[i].merkleTreeIndex\n ],\n nullifierQueue:\n // FIXME: fix make dynamic\n defaultTestStateTreeAccounts().nullifierQueue,\n hash: outputHashes[i],\n leafIndex: event.outputLeafIndices[i],\n };\n\n if (!compressedAccount.compressedAccount.data)\n throw new Error('No data');\n\n const parsedData = parseTokenLayoutWithIdl(\n compressedAccount.compressedAccount,\n );\n\n if (!parsedData) throw new Error('Invalid token data');\n\n const withMerkleContext = createCompressedAccountWithMerkleContext(\n merkleContext,\n compressedAccount.compressedAccount.owner,\n compressedAccount.compressedAccount.lamports,\n compressedAccount.compressedAccount.data,\n compressedAccount.compressedAccount.address ?? undefined,\n );\n return {\n compressedAccount: withMerkleContext,\n parsed: parsedData,\n };\n });\n\n return {\n inputCompressedAccountHashes: event.inputCompressedAccountHashes,\n outputCompressedAccounts: outputCompressedAccountsWithParsedTokenData,\n };\n}\n\n/**\n * Retrieves all compressed token accounts for a given mint and owner.\n *\n * Note: This function is intended for testing purposes only. For production, use rpc.getCompressedTokenAccounts.\n *\n * @param events Public transaction events\n * @param owner PublicKey of the token owner\n * @param mint PublicKey of the token mint\n */\nexport async function getCompressedTokenAccounts(\n events: PublicTransactionEvent[],\n): Promise<ParsedTokenAccount[]> {\n const eventsWithParsedTokenTlvData: EventWithParsedTokenTlvData[] =\n await Promise.all(\n events.map(event => parseEventWithTokenTlvData(event)),\n );\n\n /// strip spent compressed accounts if an output compressed account of tx n is\n /// an input compressed account of tx n+m, it is spent\n const allOutCompressedAccounts = eventsWithParsedTokenTlvData.flatMap(\n event => event.outputCompressedAccounts,\n );\n const allInCompressedAccountHashes = eventsWithParsedTokenTlvData.flatMap(\n event => event.inputCompressedAccountHashes,\n );\n const unspentCompressedAccounts = allOutCompressedAccounts.filter(\n outputCompressedAccount =>\n !allInCompressedAccountHashes.some(hash => {\n return (\n JSON.stringify(hash) ===\n JSON.stringify(\n outputCompressedAccount.compressedAccount.hash,\n )\n );\n }),\n );\n\n return unspentCompressedAccounts;\n}\n\n/** @internal */\nexport async function getCompressedTokenAccountsByOwnerTest(\n rpc: Rpc,\n owner: PublicKey,\n mint: PublicKey,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const events = await getParsedEvents(rpc);\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n const accounts = compressedTokenAccounts.filter(\n acc => acc.parsed.owner.equals(owner) && acc.parsed.mint.equals(mint),\n );\n return {\n items: accounts.sort(\n (a, b) =>\n b.compressedAccount.leafIndex - a.compressedAccount.leafIndex,\n ),\n cursor: null,\n };\n}\n\nexport async function getCompressedTokenAccountsByDelegateTest(\n rpc: Rpc,\n delegate: PublicKey,\n mint: PublicKey,\n): Promise<WithCursor<ParsedTokenAccount[]>> {\n const events = await getParsedEvents(rpc);\n\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n return {\n items: compressedTokenAccounts.filter(\n acc =>\n acc.parsed.delegate?.equals(delegate) &&\n acc.parsed.mint.equals(mint),\n ),\n cursor: null,\n };\n}\n\nexport async function getCompressedTokenAccountByHashTest(\n rpc: Rpc,\n hash: BN,\n): Promise<ParsedTokenAccount> {\n const events = await getParsedEvents(rpc);\n\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n\n const filtered = compressedTokenAccounts.filter(acc =>\n bn(acc.compressedAccount.hash).eq(hash),\n );\n if (filtered.length === 0) {\n throw new Error('No compressed account found');\n }\n return filtered[0];\n}\n","import { Connection, ConnectionConfig, PublicKey } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport {\n getCompressedAccountByHashTest,\n getCompressedAccountsByOwnerTest,\n getMultipleCompressedAccountsByHashTest,\n} from './get-compressed-accounts';\nimport {\n getCompressedTokenAccountByHashTest,\n getCompressedTokenAccountsByDelegateTest,\n getCompressedTokenAccountsByOwnerTest,\n} from './get-compressed-token-accounts';\n\nimport { MerkleTree } from '../merkle-tree/merkle-tree';\nimport { getParsedEvents } from './get-parsed-events';\nimport {\n defaultTestStateTreeAccounts,\n localTestActiveStateTreeInfo,\n} from '../../constants';\nimport {\n AddressWithTree,\n CompressedMintTokenHolders,\n CompressedTransaction,\n GetCompressedAccountsByOwnerConfig,\n PaginatedOptions,\n HashWithTree,\n LatestNonVotingSignatures,\n LatestNonVotingSignaturesPaginated,\n SignatureWithMetadata,\n WithContext,\n WithCursor,\n} from '../../rpc-interface';\nimport {\n CompressedProofWithContext,\n CompressionApiInterface,\n GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ParsedTokenAccount,\n TokenBalance,\n} from '../../rpc-interface';\nimport {\n BN254,\n CompressedAccountWithMerkleContext,\n MerkleContextWithMerkleProof,\n PublicTransactionEvent,\n bn,\n} from '../../state';\nimport { IndexedArray } from '../merkle-tree';\nimport {\n MerkleContextWithNewAddressProof,\n convertMerkleProofsWithContextToHex,\n convertNonInclusionMerkleProofInputsToHex,\n proverRequest,\n} from '../../rpc';\nimport { ActiveTreeBundle } from '../../state/types';\n\nexport interface TestRpcConfig {\n /**\n * Address of the state tree to index. Default: public default test state\n * tree.\n */\n merkleTreeAddress?: PublicKey;\n /**\n * Nullifier queue associated with merkleTreeAddress\n */\n nullifierQueueAddress?: PublicKey;\n /**\n * Depth of state tree. Defaults to the public default test state tree depth\n */\n depth?: number;\n /**\n * Log proof generation time\n */\n log?: boolean;\n /**\n * Address of the address tree to index. Default: public default test\n * address tree.\n */\n addressTreeAddress?: PublicKey;\n /**\n * Address queue associated with addressTreeAddress\n */\n addressQueueAddress?: PublicKey;\n}\n\nexport type ClientSubscriptionId = number;\nexport interface LightWasm {\n blakeHash(input: string | Uint8Array, hashLength: number): Uint8Array;\n poseidonHash(input: string[] | BN[]): Uint8Array;\n poseidonHashString(input: string[] | BN[]): string;\n poseidonHashBN(input: string[] | BN[]): BN;\n}\n\n/**\n * Returns a mock RPC instance for use in unit tests.\n *\n * @param lightWasm Wasm hasher instance.\n * @param endpoint RPC endpoint URL. Defaults to\n * 'http://127.0.0.1:8899'.\n * @param proverEndpoint Prover server endpoint URL. Defaults to\n * 'http://localhost:3001'.\n * @param merkleTreeAddress Address of the merkle tree to index. Defaults\n * to the public default test state tree.\n * @param nullifierQueueAddress Optional address of the associated nullifier\n * queue.\n * @param depth Depth of the merkle tree.\n * @param log Log proof generation time.\n */\nexport async function getTestRpc(\n lightWasm: LightWasm,\n endpoint: string = 'http://127.0.0.1:8899',\n compressionApiEndpoint: string = 'http://127.0.0.1:8784',\n proverEndpoint: string = 'http://127.0.0.1:3001',\n merkleTreeAddress?: PublicKey,\n nullifierQueueAddress?: PublicKey,\n depth?: number,\n log = false,\n) {\n const defaultAccounts = defaultTestStateTreeAccounts();\n\n return new TestRpc(\n endpoint,\n lightWasm,\n compressionApiEndpoint,\n proverEndpoint,\n undefined,\n {\n merkleTreeAddress: merkleTreeAddress || defaultAccounts.merkleTree,\n nullifierQueueAddress:\n nullifierQueueAddress || defaultAccounts.nullifierQueue,\n depth: depth || defaultAccounts.merkleTreeHeight,\n log,\n },\n );\n}\n/**\n * Simple mock rpc for unit tests that simulates the compression rpc interface.\n * Fetches, parses events and builds merkletree on-demand, i.e. it does not persist state.\n * Constraints:\n * - Can only index 1 merkletree\n * - Can only index up to 1000 transactions\n *\n * For advanced testing use photon: https://github.com/helius-labs/photon\n */\nexport class TestRpc extends Connection implements CompressionApiInterface {\n compressionApiEndpoint: string;\n proverEndpoint: string;\n merkleTreeAddress: PublicKey;\n nullifierQueueAddress: PublicKey;\n addressTreeAddress: PublicKey;\n addressQueueAddress: PublicKey;\n lightWasm: LightWasm;\n depth: number;\n log = false;\n activeStateTreeInfo: ActiveTreeBundle[] | null = null;\n\n /**\n * Establish a Compression-compatible JSON RPC mock-connection\n *\n * @param endpoint endpoint to the solana cluster (use for\n * localnet only)\n * @param hasher light wasm hasher instance\n * @param compressionApiEndpoint Endpoint to the compression server.\n * @param proverEndpoint Endpoint to the prover server. defaults\n * to endpoint\n * @param connectionConfig Optional connection config\n * @param testRpcConfig Config for the mock rpc\n */\n constructor(\n endpoint: string,\n hasher: LightWasm,\n compressionApiEndpoint: string,\n proverEndpoint: string,\n connectionConfig?: ConnectionConfig,\n testRpcConfig?: TestRpcConfig,\n ) {\n super(endpoint, connectionConfig || 'confirmed');\n\n this.compressionApiEndpoint = compressionApiEndpoint;\n this.proverEndpoint = proverEndpoint;\n\n const {\n merkleTreeAddress,\n nullifierQueueAddress,\n depth,\n log,\n addressTreeAddress,\n addressQueueAddress,\n } = testRpcConfig ?? {};\n\n const {\n merkleTree,\n nullifierQueue,\n merkleTreeHeight,\n addressQueue,\n addressTree,\n } = defaultTestStateTreeAccounts();\n\n this.lightWasm = hasher;\n this.merkleTreeAddress = merkleTreeAddress ?? merkleTree;\n this.nullifierQueueAddress = nullifierQueueAddress ?? nullifierQueue;\n this.addressTreeAddress = addressTreeAddress ?? addressTree;\n this.addressQueueAddress = addressQueueAddress ?? addressQueue;\n this.depth = depth ?? merkleTreeHeight;\n this.log = log ?? false;\n }\n\n /**\n * Manually set state tree addresses\n */\n setStateTreeInfo(info: ActiveTreeBundle[]): void {\n this.activeStateTreeInfo = info;\n }\n\n /**\n * Returns local test state trees.\n */\n async getCachedActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n return localTestActiveStateTreeInfo();\n }\n\n /**\n * Returns local test state trees.\n */\n async getLatestActiveStateTreeInfo(): Promise<ActiveTreeBundle[]> {\n return localTestActiveStateTreeInfo();\n }\n\n /**\n * Fetch the compressed account for the specified account hash\n */\n async getCompressedAccount(\n address?: BN254,\n hash?: BN254,\n ): Promise<CompressedAccountWithMerkleContext | null> {\n if (address) {\n throw new Error('address is not supported in test-rpc');\n }\n if (!hash) {\n throw new Error('hash is required');\n }\n\n const account = await getCompressedAccountByHashTest(this, hash);\n return account ?? null;\n }\n\n /**\n * Fetch the compressed balance for the specified account hash\n */\n async getCompressedBalance(address?: BN254, hash?: BN254): Promise<BN> {\n if (address) {\n throw new Error('address is not supported in test-rpc');\n }\n if (!hash) {\n throw new Error('hash is required');\n }\n\n const account = await getCompressedAccountByHashTest(this, hash);\n if (!account) {\n throw new Error('Account not found');\n }\n return bn(account.lamports);\n }\n\n /**\n * Fetch the total compressed balance for the specified owner public key\n */\n async getCompressedBalanceByOwner(owner: PublicKey): Promise<BN> {\n const accounts = await this.getCompressedAccountsByOwner(owner);\n return accounts.items.reduce(\n (acc, account) => acc.add(account.lamports),\n bn(0),\n );\n }\n\n /**\n * Fetch the latest merkle proof for the specified account hash from the\n * cluster\n */\n async getCompressedAccountProof(\n hash: BN254,\n ): Promise<MerkleContextWithMerkleProof> {\n const proofs = await this.getMultipleCompressedAccountProofs([hash]);\n return proofs[0];\n }\n\n /**\n * Fetch all the account info for multiple compressed accounts specified by\n * an array of account hashes\n */\n async getMultipleCompressedAccounts(\n hashes: BN254[],\n ): Promise<CompressedAccountWithMerkleContext[]> {\n return await getMultipleCompressedAccountsByHashTest(this, hashes);\n }\n /**\n * Ensure that the Compression Indexer has already indexed the transaction\n */\n async confirmTransactionIndexed(_slot: number): Promise<boolean> {\n return true;\n }\n /**\n * Fetch the latest merkle proofs for multiple compressed accounts specified\n * by an array account hashes\n */\n async getMultipleCompressedAccountProofs(\n hashes: BN254[],\n ): Promise<MerkleContextWithMerkleProof[]> {\n /// Build tree\n const events: PublicTransactionEvent[] = await getParsedEvents(\n this,\n ).then(events => events.reverse());\n const allLeaves: number[][] = [];\n const allLeafIndices: number[] = [];\n for (const event of events) {\n for (\n let index = 0;\n index < event.outputCompressedAccounts.length;\n index++\n ) {\n const hash = event.outputCompressedAccountHashes[index];\n\n allLeaves.push(hash);\n allLeafIndices.push(event.outputLeafIndices[index]);\n }\n }\n const tree = new MerkleTree(\n this.depth,\n this.lightWasm,\n allLeaves.map(leaf => bn(leaf).toString()),\n );\n\n /// create merkle proofs and assemble return type\n const merkleProofs: MerkleContextWithMerkleProof[] = [];\n\n for (let i = 0; i < hashes.length; i++) {\n const leafIndex = tree.indexOf(hashes[i].toString());\n const pathElements = tree.path(leafIndex).pathElements;\n const bnPathElements = pathElements.map(value => bn(value));\n const root = bn(tree.root());\n const merkleProof: MerkleContextWithMerkleProof = {\n hash: hashes[i].toArray('be', 32),\n merkleTree: this.merkleTreeAddress,\n leafIndex: leafIndex,\n merkleProof: bnPathElements,\n nullifierQueue: this.nullifierQueueAddress,\n rootIndex: allLeaves.length,\n root: root,\n };\n merkleProofs.push(merkleProof);\n }\n\n /// Validate\n merkleProofs.forEach((proof, index) => {\n const leafIndex = proof.leafIndex;\n const computedHash = tree.elements()[leafIndex];\n const hashArr = bn(computedHash).toArray('be', 32);\n if (!hashArr.every((val, index) => val === proof.hash[index])) {\n throw new Error(\n `Mismatch at index ${index}: expected ${proof.hash.toString()}, got ${hashArr.toString()}`,\n );\n }\n });\n\n return merkleProofs;\n }\n\n /**\n * Fetch all the compressed accounts owned by the specified public key.\n * Owner can be a program or user account\n */\n async getCompressedAccountsByOwner(\n owner: PublicKey,\n _config?: GetCompressedAccountsByOwnerConfig,\n ): Promise<WithCursor<CompressedAccountWithMerkleContext[]>> {\n const accounts = await getCompressedAccountsByOwnerTest(this, owner);\n return {\n items: accounts,\n cursor: null,\n };\n }\n\n /**\n * Fetch the latest compression signatures on the cluster. Results are\n * paginated.\n */\n async getLatestCompressionSignatures(\n _cursor?: string,\n _limit?: number,\n ): Promise<LatestNonVotingSignaturesPaginated> {\n throw new Error(\n 'getLatestNonVotingSignaturesWithContext not supported in test-rpc',\n );\n }\n /**\n * Fetch the latest non-voting signatures on the cluster. Results are\n * not paginated.\n */\n async getLatestNonVotingSignatures(\n _limit?: number,\n ): Promise<LatestNonVotingSignatures> {\n throw new Error(\n 'getLatestNonVotingSignaturesWithContext not supported in test-rpc',\n );\n }\n /**\n * Fetch all the compressed token accounts owned by the specified public\n * key. Owner can be a program or user account\n */\n async getCompressedTokenAccountsByOwner(\n owner: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n return await getCompressedTokenAccountsByOwnerTest(\n this,\n owner,\n options!.mint!,\n );\n }\n\n /**\n * Fetch all the compressed accounts delegated to the specified public key.\n */\n async getCompressedTokenAccountsByDelegate(\n delegate: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<ParsedTokenAccount[]>> {\n return await getCompressedTokenAccountsByDelegateTest(\n this,\n delegate,\n options.mint!,\n );\n }\n\n /**\n * Fetch the compressed token balance for the specified account hash\n */\n async getCompressedTokenAccountBalance(\n hash: BN254,\n ): Promise<{ amount: BN }> {\n const account = await getCompressedTokenAccountByHashTest(this, hash);\n return { amount: bn(account.parsed.amount) };\n }\n\n /**\n * @deprecated use {@link getCompressedTokenBalancesByOwnerV2}.\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint.\n */\n async getCompressedTokenBalancesByOwner(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithCursor<{ balance: BN; mint: PublicKey }[]>> {\n const accounts = await getCompressedTokenAccountsByOwnerTest(\n this,\n publicKey,\n options.mint!,\n );\n return {\n items: accounts.items.map(account => ({\n balance: bn(account.parsed.amount),\n mint: account.parsed.mint,\n })),\n cursor: null,\n };\n }\n\n /**\n * Fetch all the compressed token balances owned by the specified public\n * key. Can filter by mint. Uses context.\n */\n async getCompressedTokenBalancesByOwnerV2(\n publicKey: PublicKey,\n options: GetCompressedTokenAccountsByOwnerOrDelegateOptions,\n ): Promise<WithContext<WithCursor<TokenBalance[]>>> {\n const accounts = await getCompressedTokenAccountsByOwnerTest(\n this,\n publicKey,\n options.mint!,\n );\n return {\n context: { slot: 1 },\n value: {\n items: accounts.items.map(account => ({\n balance: bn(account.parsed.amount),\n mint: account.parsed.mint,\n })),\n cursor: null,\n },\n };\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * account hash forward in time from genesis to the most recent confirmed\n * block\n *\n * @param hash queried account hash\n */\n async getCompressionSignaturesForAccount(\n _hash: BN254,\n ): Promise<SignatureWithMetadata[]> {\n throw new Error(\n 'getCompressionSignaturesForAccount not implemented in test-rpc',\n );\n }\n\n /**\n * Fetch a confirmed or finalized transaction from the cluster. Return with\n * CompressionInfo\n */\n async getTransactionWithCompressionInfo(\n _signature: string,\n ): Promise<CompressedTransaction | null> {\n throw new Error('getCompressedTransaction not implemented in test-rpc');\n }\n\n /**\n * Returns confirmed signatures for transactions involving the specified\n * address forward in time from genesis to the most recent confirmed\n * block\n *\n * @param address queried compressed account address\n */\n async getCompressionSignaturesForAddress(\n _address: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForAddress3 not implemented');\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified account owner forward in time from genesis to the\n * most recent confirmed block\n *\n * @param owner queried owner public key\n */\n async getCompressionSignaturesForOwner(\n _owner: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForOwner not implemented');\n }\n\n /**\n * Returns confirmed signatures for compression transactions involving the\n * specified token account owner forward in time from genesis to the most\n * recent confirmed block\n */\n async getCompressionSignaturesForTokenOwner(\n _owner: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithCursor<SignatureWithMetadata[]>> {\n throw new Error('getSignaturesForTokenOwner not implemented');\n }\n\n /**\n * Fetch the current indexer health status\n */\n async getIndexerHealth(): Promise<string> {\n return 'ok';\n }\n\n /**\n * Fetch the current slot that the node is processing\n */\n async getIndexerSlot(): Promise<number> {\n return 1;\n }\n\n /**\n * Fetch the latest address proofs for new unique addresses specified by an\n * array of addresses.\n *\n * the proof states that said address have not yet been created in respective address tree.\n * @param addresses Array of BN254 new addresses\n * @returns Array of validity proofs for new addresses\n */\n async getMultipleNewAddressProofs(addresses: BN254[]) {\n /// Build tree\n const indexedArray = IndexedArray.default();\n const allAddresses: BN[] = [];\n indexedArray.init();\n const hashes: BN[] = [];\n // TODO(crank): add support for cranked address tree in 'allAddresses'.\n // The Merkle tree root doesnt actually advance beyond init() unless we\n // start emptying the address queue.\n for (let i = 0; i < allAddresses.length; i++) {\n indexedArray.append(bn(allAddresses[i]));\n }\n for (let i = 0; i < indexedArray.elements.length; i++) {\n const hash = indexedArray.hashElement(this.lightWasm, i);\n hashes.push(bn(hash!));\n }\n const tree = new MerkleTree(\n this.depth,\n this.lightWasm,\n hashes.map(hash => bn(hash).toString()),\n );\n\n /// Creates proof for each address\n const newAddressProofs: MerkleContextWithNewAddressProof[] = [];\n\n for (let i = 0; i < addresses.length; i++) {\n const [lowElement] = indexedArray.findLowElement(addresses[i]);\n if (!lowElement) throw new Error('Address not found');\n\n const leafIndex = lowElement.index;\n\n const pathElements: string[] = tree.path(leafIndex).pathElements;\n const bnPathElements = pathElements.map(value => bn(value));\n\n const higherRangeValue = indexedArray.get(\n lowElement.nextIndex,\n )!.value;\n const root = bn(tree.root());\n\n const proof: MerkleContextWithNewAddressProof = {\n root,\n rootIndex: 3,\n value: addresses[i],\n leafLowerRangeValue: lowElement.value,\n leafHigherRangeValue: higherRangeValue,\n nextIndex: bn(lowElement.nextIndex),\n merkleProofHashedIndexedElementLeaf: bnPathElements,\n indexHashedIndexedElementLeaf: bn(lowElement.index),\n merkleTree: this.addressTreeAddress,\n nullifierQueue: this.addressQueueAddress,\n };\n newAddressProofs.push(proof);\n }\n return newAddressProofs;\n }\n\n async getCompressedMintTokenHolders(\n _mint: PublicKey,\n _options?: PaginatedOptions,\n ): Promise<WithContext<WithCursor<CompressedMintTokenHolders[]>>> {\n throw new Error(\n 'getCompressedMintTokenHolders not implemented in test-rpc',\n );\n }\n\n /**\n * Advanced usage of getValidityProof: fetches ZKP directly from a custom\n * non-rpcprover. Note: This uses the proverEndpoint specified in the\n * constructor. For normal usage, please use {@link getValidityProof}\n * instead.\n *\n * Note: Use RPC class for forested trees. TestRpc is only for custom\n * testing purposes.\n */\n async getValidityProofDirect(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n return this.getValidityProof(hashes, newAddresses);\n }\n /**\n * @deprecated This method is not available for TestRpc. Please use\n * {@link getValidityProof} instead.\n */\n async getValidityProofAndRpcContext(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<WithContext<CompressedProofWithContext>> {\n if (newAddresses.some(address => !(address instanceof BN))) {\n throw new Error('AddressWithTree is not supported in test-rpc');\n }\n return {\n value: await this.getValidityProofV0(hashes, newAddresses),\n context: { slot: 1 },\n };\n }\n /**\n * Fetch the latest validity proof for (1) compressed accounts specified by\n * an array of account hashes. (2) new unique addresses specified by an\n * array of addresses.\n *\n * Validity proofs prove the presence of compressed accounts in state trees\n * and the non-existence of addresses in address trees, respectively. They\n * enable verification without recomputing the merkle proof path, thus\n * lowering verification and data costs.\n *\n * @param hashes Array of BN254 hashes.\n * @param newAddresses Array of BN254 new addresses.\n * @returns validity proof with context\n */\n async getValidityProof(\n hashes: BN254[] = [],\n newAddresses: BN254[] = [],\n ): Promise<CompressedProofWithContext> {\n if (newAddresses.some(address => !(address instanceof BN))) {\n throw new Error('AddressWithTree is not supported in test-rpc');\n }\n let validityProof: CompressedProofWithContext;\n\n if (hashes.length === 0 && newAddresses.length === 0) {\n throw new Error(\n 'Empty input. Provide hashes and/or new addresses.',\n );\n } else if (hashes.length > 0 && newAddresses.length === 0) {\n /// inclusion\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n\n // TODO: reactivate to handle proofs of height 32\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // [],\n // this.lightWasm,\n // );\n\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'inclusion',\n inputs,\n this.log,\n // publicInputHash,\n );\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext.map(proof => proof.root),\n rootIndices: merkleProofsWithContext.map(\n proof => proof.rootIndex,\n ),\n leafIndices: merkleProofsWithContext.map(\n proof => proof.leafIndex,\n ),\n leaves: merkleProofsWithContext.map(proof => bn(proof.hash)),\n merkleTrees: merkleProofsWithContext.map(\n proof => proof.merkleTree,\n ),\n nullifierQueues: merkleProofsWithContext.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length === 0 && newAddresses.length > 0) {\n /// new-address\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const inputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const publicInputHash = getPublicInputHash(\n // [],\n // [],\n // newAddressProofs,\n // this.lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'new-address',\n inputs,\n this.log,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: newAddressProofs.map(proof => proof.root),\n // TODO(crank): make dynamic to enable forester support in\n // test-rpc.ts. Currently this is a static root because the\n // address tree doesn't advance.\n rootIndices: newAddressProofs.map(_ => 3),\n leafIndices: newAddressProofs.map(\n proof => proof.indexHashedIndexedElementLeaf.toNumber(), // TODO: support >32bit\n ),\n leaves: newAddressProofs.map(proof => bn(proof.value)),\n merkleTrees: newAddressProofs.map(proof => proof.merkleTree),\n nullifierQueues: newAddressProofs.map(\n proof => proof.nullifierQueue,\n ),\n };\n } else if (hashes.length > 0 && newAddresses.length > 0) {\n /// combined\n const merkleProofsWithContext =\n await this.getMultipleCompressedAccountProofs(hashes);\n const inputs = convertMerkleProofsWithContextToHex(\n merkleProofsWithContext,\n );\n const newAddressProofs: MerkleContextWithNewAddressProof[] =\n await this.getMultipleNewAddressProofs(newAddresses);\n\n const newAddressInputs =\n convertNonInclusionMerkleProofInputsToHex(newAddressProofs);\n // const publicInputHash = getPublicInputHash(\n // merkleProofsWithContext,\n // hashes,\n // newAddressProofs,\n // this.lightWasm,\n // );\n const compressedProof = await proverRequest(\n this.proverEndpoint,\n 'combined',\n [inputs, newAddressInputs],\n this.log,\n // publicInputHash,\n );\n\n validityProof = {\n compressedProof,\n roots: merkleProofsWithContext\n .map(proof => proof.root)\n .concat(newAddressProofs.map(proof => proof.root)),\n rootIndices: merkleProofsWithContext\n .map(proof => proof.rootIndex)\n // TODO(crank): make dynamic to enable forester support in\n // test-rpc.ts. Currently this is a static root because the\n // address tree doesn't advance.\n .concat(newAddressProofs.map(_ => 3)),\n leafIndices: merkleProofsWithContext\n .map(proof => proof.leafIndex)\n .concat(\n newAddressProofs.map(\n proof =>\n proof.indexHashedIndexedElementLeaf.toNumber(), // TODO: support >32bit\n ),\n ),\n leaves: merkleProofsWithContext\n .map(proof => bn(proof.hash))\n .concat(newAddressProofs.map(proof => bn(proof.value))),\n merkleTrees: merkleProofsWithContext\n .map(proof => proof.merkleTree)\n .concat(newAddressProofs.map(proof => proof.merkleTree)),\n nullifierQueues: merkleProofsWithContext\n .map(proof => proof.nullifierQueue)\n .concat(\n newAddressProofs.map(proof => proof.nullifierQueue),\n ),\n };\n } else throw new Error('Invalid input');\n\n return validityProof;\n }\n\n async getValidityProofV0(\n hashes: HashWithTree[] = [],\n newAddresses: AddressWithTree[] = [],\n ): Promise<CompressedProofWithContext> {\n /// TODO(swen): add support for custom trees\n return this.getValidityProof(\n hashes.map(hash => hash.hash),\n newAddresses.map(address => address.address),\n );\n }\n}\n","import { Connection, Keypair, Signer } from '@solana/web3.js';\nimport { confirmTx } from '../utils/send-and-confirm';\nimport { Rpc } from '../rpc';\nimport BN from 'bn.js';\n\nlet c = 1;\n\nexport const ALICE = getTestKeypair(255);\nexport const BOB = getTestKeypair(254);\nexport const CHARLIE = getTestKeypair(253);\nexport const DAVE = getTestKeypair(252);\n\n/**\n * Deep comparison of two objects. Handles BN comparison correctly.\n *\n * @param ref - The reference object to compare.\n * @param val - The value object to compare.\n * @returns True if the objects are deeply equal, false otherwise.\n */\nexport function deepEqual(ref: any, val: any) {\n if (typeof ref !== typeof val) {\n console.log(`Type mismatch: ${typeof ref} !== ${typeof val}`);\n return false;\n }\n\n if (ref instanceof BN && val instanceof BN) {\n return ref.eq(val);\n }\n\n if (typeof ref === 'object' && ref !== null && val !== null) {\n const refKeys = Object.keys(ref);\n const valKeys = Object.keys(val);\n\n if (refKeys.length !== valKeys.length) {\n console.log(\n `Key length mismatch: ${refKeys.length} !== ${valKeys.length}`,\n );\n return false;\n }\n\n for (const key of refKeys) {\n if (!valKeys.includes(key)) {\n console.log(`Key ${key} not found in value`);\n return false;\n }\n if (!deepEqual(ref[key], val[key])) {\n console.log(`Value mismatch at key ${key}`);\n return false;\n }\n }\n return true;\n }\n\n if (ref !== val) {\n console.log(`Value mismatch: ${ref} !== ${val}`);\n }\n\n return ref === val;\n}\n\n/**\n * Create a new account and airdrop lamports to it\n *\n * @param rpc connection to use\n * @param lamports amount of lamports to airdrop\n * @param counter counter to use for generating the keypair.\n * If undefined or >255, generates random keypair.\n */\nexport async function newAccountWithLamports(\n rpc: Rpc,\n lamports = 1000000000,\n counter: number | undefined = undefined,\n): Promise<Signer> {\n /// get random keypair\n if (counter === undefined || counter > 255) {\n counter = 256;\n }\n\n const account = getTestKeypair(counter);\n const sig = await rpc.requestAirdrop(account.publicKey, lamports);\n await confirmTx(rpc, sig);\n return account;\n}\n\nexport function getConnection(): Connection {\n const url = 'http://127.0.0.1:8899';\n const connection = new Connection(url, 'confirmed');\n return connection;\n}\n\n/**\n * For use in tests.\n * Generate a unique keypair by passing in a counter <255. If no counter\n * is supplied, it uses and increments a global counter.\n * if counter > 255, generates random keypair\n */\nexport function getTestKeypair(\n counter: number | undefined = undefined,\n): Keypair {\n if (!counter) {\n counter = c;\n c++;\n }\n if (counter > 255) {\n return Keypair.generate();\n }\n const seed = new Uint8Array(32);\n seed[31] = counter; // le\n\n return Keypair.fromSeed(seed);\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { describe, it, expect } = import.meta.vitest;\n\n describe('getTestKeypair', () => {\n it('should generate a keypair with a specific counter', () => {\n const keypair = getTestKeypair(10);\n const keypair2 = getTestKeypair(10);\n expect(keypair).toEqual(keypair2);\n expect(keypair).toBeInstanceOf(Keypair);\n expect(keypair.publicKey).toBeDefined();\n expect(keypair.secretKey).toBeDefined();\n });\n\n it('should generate random keypair if counter is greater than 255', () => {\n const testFn = () => getTestKeypair(256);\n const kp1 = testFn();\n const kp2 = testFn();\n expect(kp1).not.toEqual(kp2);\n });\n\n it('should increment the global counter if no counter is provided', () => {\n const initialKeypair = getTestKeypair();\n const nextKeypair = getTestKeypair();\n const nextNextKeypair = getTestKeypair();\n const nextNextNextKeypair = getTestKeypair(3);\n expect(initialKeypair).not.toEqual(nextKeypair);\n expect(nextKeypair).not.toEqual(nextNextKeypair);\n expect(nextNextKeypair).toEqual(nextNextNextKeypair);\n });\n });\n}\n","export type LightSystemProgram = {\n version: '1.2.0';\n name: 'light_system_program';\n constants: [\n {\n name: 'SOL_POOL_PDA_SEED';\n type: 'bytes';\n value: '[115, 111, 108, 95, 112, 111, 111, 108, 95, 112, 100, 97]';\n },\n ];\n instructions: [\n {\n name: 'initCpiContextAccount';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'associatedMerkleTree';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [];\n },\n {\n name: 'invoke';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n docs: [\n 'This pda is used to invoke the account compression program.',\n ];\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n docs: ['Merkle trees.'];\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ];\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'invokeCpi';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'invokingProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'invokeCpiWithReadOnly';\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'invokingProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiContextAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'stubIdlBuild';\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n docs: [\n 'This pda is used to invoke the account compression program.',\n ];\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n docs: ['Merkle trees.'];\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ];\n },\n {\n name: 'decompressionRecipient';\n isMut: true;\n isSigner: false;\n isOptional: true;\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs1';\n type: {\n defined: 'InstructionDataInvoke';\n };\n },\n {\n name: 'inputs2';\n type: {\n defined: 'InstructionDataInvokeCpi';\n };\n },\n {\n name: 'inputs3';\n type: {\n defined: 'PublicTransactionEvent';\n };\n },\n ];\n },\n ];\n accounts: [\n {\n name: 'cpiContextAccount';\n docs: [\n 'Collects instruction data without executing a compressed transaction.',\n 'Signer checks are performed on instruction data.',\n 'Collected instruction data is combined with the instruction data of the executing cpi,',\n 'and executed as a single transaction.',\n 'This enables to use input compressed accounts that are owned by multiple programs,',\n 'with one zero-knowledge proof.',\n ];\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'feePayer';\n type: 'publicKey';\n },\n {\n name: 'associatedMerkleTree';\n type: 'publicKey';\n },\n {\n name: 'context';\n type: {\n vec: {\n defined: 'InstructionDataInvokeCpi';\n };\n };\n },\n ];\n };\n },\n ];\n types: [\n {\n name: 'InstructionDataInvoke';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'NewAddressParamsPacked';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'seed';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'addressQueueAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeRootIndex';\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'OutputCompressedAccountWithPackedContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleTreeIndex';\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedProof';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'a';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'b';\n type: {\n array: ['u8', 64];\n };\n },\n {\n name: 'c';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'InstructionDataInvokeCpi';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n ];\n };\n },\n {\n name: 'CompressedCpiContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'setContext';\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ];\n type: 'bool';\n },\n {\n name: 'firstSetContext';\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ];\n type: 'bool';\n },\n {\n name: 'cpiContextAccountIndex';\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ];\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedAccount';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'lamports';\n type: 'u64';\n },\n {\n name: 'address';\n type: {\n option: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'data';\n type: {\n option: {\n defined: 'CompressedAccountData';\n };\n };\n },\n ];\n };\n },\n {\n name: 'CompressedAccountData';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'discriminator';\n type: {\n array: ['u8', 8];\n };\n },\n {\n name: 'data';\n type: 'bytes';\n },\n {\n name: 'dataHash';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleContext';\n type: {\n defined: 'PackedMerkleContext';\n };\n },\n {\n name: 'rootIndex';\n docs: [\n 'Index of root used in inclusion validity proof.',\n ];\n type: 'u16';\n },\n {\n name: 'readOnly';\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ];\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'PackedMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'merkleTreePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'nullifierQueuePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'leafIndex';\n type: 'u32';\n },\n {\n name: 'queueIndex';\n type: {\n option: {\n defined: 'QueueIndex';\n };\n };\n },\n ];\n };\n },\n {\n name: 'QueueIndex';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'queueId';\n docs: ['Id of queue in queue account.'];\n type: 'u8';\n },\n {\n name: 'index';\n docs: ['Index of compressed account hash in queue.'];\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'MerkleTreeSequenceNumber';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'pubkey';\n type: 'publicKey';\n },\n {\n name: 'seq';\n type: 'u64';\n },\n ];\n };\n },\n {\n name: 'PublicTransactionEvent';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'inputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'outputLeafIndices';\n type: {\n vec: 'u32';\n };\n },\n {\n name: 'sequenceNumbers';\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'pubkeyArray';\n type: {\n vec: 'publicKey';\n };\n },\n {\n name: 'message';\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n ];\n errors: [\n {\n code: 6000;\n name: 'SumCheckFailed';\n msg: 'Sum check failed';\n },\n {\n code: 6001;\n name: 'SignerCheckFailed';\n msg: 'Signer check failed';\n },\n {\n code: 6002;\n name: 'CpiSignerCheckFailed';\n msg: 'Cpi signer check failed';\n },\n {\n code: 6003;\n name: 'ComputeInputSumFailed';\n msg: 'Computing input sum failed.';\n },\n {\n code: 6004;\n name: 'ComputeOutputSumFailed';\n msg: 'Computing output sum failed.';\n },\n {\n code: 6005;\n name: 'ComputeRpcSumFailed';\n msg: 'Computing rpc sum failed.';\n },\n {\n code: 6006;\n name: 'InvalidAddress';\n msg: 'InvalidAddress';\n },\n {\n code: 6007;\n name: 'DeriveAddressError';\n msg: 'DeriveAddressError';\n },\n {\n code: 6008;\n name: 'CompressedSolPdaUndefinedForCompressSol';\n msg: 'CompressedSolPdaUndefinedForCompressSol';\n },\n {\n code: 6009;\n name: 'DeCompressLamportsUndefinedForCompressSol';\n msg: 'DeCompressLamportsUndefinedForCompressSol';\n },\n {\n code: 6010;\n name: 'CompressedSolPdaUndefinedForDecompressSol';\n msg: 'CompressedSolPdaUndefinedForDecompressSol';\n },\n {\n code: 6011;\n name: 'DeCompressLamportsUndefinedForDecompressSol';\n msg: 'DeCompressLamportsUndefinedForDecompressSol';\n },\n {\n code: 6012;\n name: 'DecompressRecipientUndefinedForDecompressSol';\n msg: 'DecompressRecipientUndefinedForDecompressSol';\n },\n {\n code: 6013;\n name: 'WriteAccessCheckFailed';\n msg: 'WriteAccessCheckFailed';\n },\n {\n code: 6014;\n name: 'InvokingProgramNotProvided';\n msg: 'InvokingProgramNotProvided';\n },\n {\n code: 6015;\n name: 'InvalidCapacity';\n msg: 'InvalidCapacity';\n },\n {\n code: 6016;\n name: 'InvalidMerkleTreeOwner';\n msg: 'InvalidMerkleTreeOwner';\n },\n {\n code: 6017;\n name: 'ProofIsNone';\n msg: 'ProofIsNone';\n },\n {\n code: 6018;\n name: 'ProofIsSome';\n msg: 'Proof is some but no input compressed accounts or new addresses provided.';\n },\n {\n code: 6019;\n name: 'EmptyInputs';\n msg: 'EmptyInputs';\n },\n {\n code: 6020;\n name: 'CpiContextAccountUndefined';\n msg: 'CpiContextAccountUndefined';\n },\n {\n code: 6021;\n name: 'CpiContextEmpty';\n msg: 'CpiContextEmpty';\n },\n {\n code: 6022;\n name: 'CpiContextMissing';\n msg: 'CpiContextMissing';\n },\n {\n code: 6023;\n name: 'DecompressionRecipientDefined';\n msg: 'DecompressionRecipientDefined';\n },\n {\n code: 6024;\n name: 'SolPoolPdaDefined';\n msg: 'SolPoolPdaDefined';\n },\n {\n code: 6025;\n name: 'AppendStateFailed';\n msg: 'AppendStateFailed';\n },\n {\n code: 6026;\n name: 'InstructionNotCallable';\n msg: 'The instruction is not callable';\n },\n {\n code: 6027;\n name: 'CpiContextFeePayerMismatch';\n msg: 'CpiContextFeePayerMismatch';\n },\n {\n code: 6028;\n name: 'CpiContextAssociatedMerkleTreeMismatch';\n msg: 'CpiContextAssociatedMerkleTreeMismatch';\n },\n {\n code: 6029;\n name: 'NoInputs';\n msg: 'NoInputs';\n },\n {\n code: 6030;\n name: 'InputMerkleTreeIndicesNotInOrder';\n msg: 'Input merkle tree indices are not in ascending order.';\n },\n {\n code: 6031;\n name: 'OutputMerkleTreeIndicesNotInOrder';\n msg: 'Output merkle tree indices are not in ascending order.';\n },\n {\n code: 6032;\n name: 'OutputMerkleTreeNotUnique';\n },\n {\n code: 6033;\n name: 'DataFieldUndefined';\n },\n {\n code: 6034;\n name: 'ReadOnlyAddressAlreadyExists';\n },\n {\n code: 6035;\n name: 'ReadOnlyAccountDoesNotExist';\n },\n {\n code: 6036;\n name: 'HashChainInputsLenghtInconsistent';\n },\n {\n code: 6037;\n name: 'InvalidAddressTreeHeight';\n },\n {\n code: 6038;\n name: 'InvalidStateTreeHeight';\n },\n ];\n};\n\nexport const IDL: LightSystemProgram = {\n version: '1.2.0',\n name: 'light_system_program',\n constants: [\n {\n name: 'SOL_POOL_PDA_SEED',\n type: 'bytes',\n value: '[115, 111, 108, 95, 112, 111, 111, 108, 95, 112, 100, 97]',\n },\n ],\n instructions: [\n {\n name: 'initCpiContextAccount',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'associatedMerkleTree',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [],\n },\n {\n name: 'invoke',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n docs: [\n 'This pda is used to invoke the account compression program.',\n ],\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n docs: ['Merkle trees.'],\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ],\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'invokeCpi',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'invokingProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'invokeCpiWithReadOnly',\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'invokingProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiContextAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'stubIdlBuild',\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: [\n 'Fee payer needs to be mutable to pay rollover and protocol fees.',\n ],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n docs: [\n 'This pda is used to invoke the account compression program.',\n ],\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n docs: ['Merkle trees.'],\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Sol pool pda is used to store the native sol that has been compressed.',\n \"It's only required when compressing or decompressing sol.\",\n ],\n },\n {\n name: 'decompressionRecipient',\n isMut: true,\n isSigner: false,\n isOptional: true,\n docs: [\n 'Only needs to be provided for decompression as a recipient for the',\n 'decompressed sol.',\n 'Compressed sol originate from authority.',\n ],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs1',\n type: {\n defined: 'InstructionDataInvoke',\n },\n },\n {\n name: 'inputs2',\n type: {\n defined: 'InstructionDataInvokeCpi',\n },\n },\n {\n name: 'inputs3',\n type: {\n defined: 'PublicTransactionEvent',\n },\n },\n ],\n },\n ],\n accounts: [\n {\n name: 'cpiContextAccount',\n docs: [\n 'Collects instruction data without executing a compressed transaction.',\n 'Signer checks are performed on instruction data.',\n 'Collected instruction data is combined with the instruction data of the executing cpi,',\n 'and executed as a single transaction.',\n 'This enables to use input compressed accounts that are owned by multiple programs,',\n 'with one zero-knowledge proof.',\n ],\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'feePayer',\n type: 'publicKey',\n },\n {\n name: 'associatedMerkleTree',\n type: 'publicKey',\n },\n {\n name: 'context',\n type: {\n vec: {\n defined: 'InstructionDataInvokeCpi',\n },\n },\n },\n ],\n },\n },\n ],\n types: [\n {\n name: 'InstructionDataInvoke',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'NewAddressParamsPacked',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'seed',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'addressQueueAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeRootIndex',\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'OutputCompressedAccountWithPackedContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleTreeIndex',\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedProof',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'a',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'b',\n type: {\n array: ['u8', 64],\n },\n },\n {\n name: 'c',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'InstructionDataInvokeCpi',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n ],\n },\n },\n {\n name: 'CompressedCpiContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'setContext',\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ],\n type: 'bool',\n },\n {\n name: 'firstSetContext',\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ],\n type: 'bool',\n },\n {\n name: 'cpiContextAccountIndex',\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ],\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedAccount',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'lamports',\n type: 'u64',\n },\n {\n name: 'address',\n type: {\n option: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'data',\n type: {\n option: {\n defined: 'CompressedAccountData',\n },\n },\n },\n ],\n },\n },\n {\n name: 'CompressedAccountData',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'discriminator',\n type: {\n array: ['u8', 8],\n },\n },\n {\n name: 'data',\n type: 'bytes',\n },\n {\n name: 'dataHash',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleContext',\n type: {\n defined: 'PackedMerkleContext',\n },\n },\n {\n name: 'rootIndex',\n docs: [\n 'Index of root used in inclusion validity proof.',\n ],\n type: 'u16',\n },\n {\n name: 'readOnly',\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ],\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'PackedMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'merkleTreePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'nullifierQueuePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'leafIndex',\n type: 'u32',\n },\n {\n name: 'queueIndex',\n type: {\n option: {\n defined: 'QueueIndex',\n },\n },\n },\n ],\n },\n },\n {\n name: 'QueueIndex',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'queueId',\n docs: ['Id of queue in queue account.'],\n type: 'u8',\n },\n {\n name: 'index',\n docs: ['Index of compressed account hash in queue.'],\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'MerkleTreeSequenceNumber',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'pubkey',\n type: 'publicKey',\n },\n {\n name: 'seq',\n type: 'u64',\n },\n ],\n },\n },\n {\n name: 'PublicTransactionEvent',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'inputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'outputLeafIndices',\n type: {\n vec: 'u32',\n },\n },\n {\n name: 'sequenceNumbers',\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'pubkeyArray',\n type: {\n vec: 'publicKey',\n },\n },\n {\n name: 'message',\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n ],\n errors: [\n {\n code: 6000,\n name: 'SumCheckFailed',\n msg: 'Sum check failed',\n },\n {\n code: 6001,\n name: 'SignerCheckFailed',\n msg: 'Signer check failed',\n },\n {\n code: 6002,\n name: 'CpiSignerCheckFailed',\n msg: 'Cpi signer check failed',\n },\n {\n code: 6003,\n name: 'ComputeInputSumFailed',\n msg: 'Computing input sum failed.',\n },\n {\n code: 6004,\n name: 'ComputeOutputSumFailed',\n msg: 'Computing output sum failed.',\n },\n {\n code: 6005,\n name: 'ComputeRpcSumFailed',\n msg: 'Computing rpc sum failed.',\n },\n {\n code: 6006,\n name: 'InvalidAddress',\n msg: 'InvalidAddress',\n },\n {\n code: 6007,\n name: 'DeriveAddressError',\n msg: 'DeriveAddressError',\n },\n {\n code: 6008,\n name: 'CompressedSolPdaUndefinedForCompressSol',\n msg: 'CompressedSolPdaUndefinedForCompressSol',\n },\n {\n code: 6009,\n name: 'DeCompressLamportsUndefinedForCompressSol',\n msg: 'DeCompressLamportsUndefinedForCompressSol',\n },\n {\n code: 6010,\n name: 'CompressedSolPdaUndefinedForDecompressSol',\n msg: 'CompressedSolPdaUndefinedForDecompressSol',\n },\n {\n code: 6011,\n name: 'DeCompressLamportsUndefinedForDecompressSol',\n msg: 'DeCompressLamportsUndefinedForDecompressSol',\n },\n {\n code: 6012,\n name: 'DecompressRecipientUndefinedForDecompressSol',\n msg: 'DecompressRecipientUndefinedForDecompressSol',\n },\n {\n code: 6013,\n name: 'WriteAccessCheckFailed',\n msg: 'WriteAccessCheckFailed',\n },\n {\n code: 6014,\n name: 'InvokingProgramNotProvided',\n msg: 'InvokingProgramNotProvided',\n },\n {\n code: 6015,\n name: 'InvalidCapacity',\n msg: 'InvalidCapacity',\n },\n {\n code: 6016,\n name: 'InvalidMerkleTreeOwner',\n msg: 'InvalidMerkleTreeOwner',\n },\n {\n code: 6017,\n name: 'ProofIsNone',\n msg: 'ProofIsNone',\n },\n {\n code: 6018,\n name: 'ProofIsSome',\n msg: 'Proof is some but no input compressed accounts or new addresses provided.',\n },\n {\n code: 6019,\n name: 'EmptyInputs',\n msg: 'EmptyInputs',\n },\n {\n code: 6020,\n name: 'CpiContextAccountUndefined',\n msg: 'CpiContextAccountUndefined',\n },\n {\n code: 6021,\n name: 'CpiContextEmpty',\n msg: 'CpiContextEmpty',\n },\n {\n code: 6022,\n name: 'CpiContextMissing',\n msg: 'CpiContextMissing',\n },\n {\n code: 6023,\n name: 'DecompressionRecipientDefined',\n msg: 'DecompressionRecipientDefined',\n },\n {\n code: 6024,\n name: 'SolPoolPdaDefined',\n msg: 'SolPoolPdaDefined',\n },\n {\n code: 6025,\n name: 'AppendStateFailed',\n msg: 'AppendStateFailed',\n },\n {\n code: 6026,\n name: 'InstructionNotCallable',\n msg: 'The instruction is not callable',\n },\n {\n code: 6027,\n name: 'CpiContextFeePayerMismatch',\n msg: 'CpiContextFeePayerMismatch',\n },\n {\n code: 6028,\n name: 'CpiContextAssociatedMerkleTreeMismatch',\n msg: 'CpiContextAssociatedMerkleTreeMismatch',\n },\n {\n code: 6029,\n name: 'NoInputs',\n msg: 'NoInputs',\n },\n {\n code: 6030,\n name: 'InputMerkleTreeIndicesNotInOrder',\n msg: 'Input merkle tree indices are not in ascending order.',\n },\n {\n code: 6031,\n name: 'OutputMerkleTreeIndicesNotInOrder',\n msg: 'Output merkle tree indices are not in ascending order.',\n },\n {\n code: 6032,\n name: 'OutputMerkleTreeNotUnique',\n },\n {\n code: 6033,\n name: 'DataFieldUndefined',\n },\n {\n code: 6034,\n name: 'ReadOnlyAddressAlreadyExists',\n },\n {\n code: 6035,\n name: 'ReadOnlyAccountDoesNotExist',\n },\n {\n code: 6036,\n name: 'HashChainInputsLenghtInconsistent',\n },\n {\n code: 6037,\n name: 'InvalidAddressTreeHeight',\n },\n {\n code: 6038,\n name: 'InvalidStateTreeHeight',\n },\n ],\n};\n","/**\n * @param targetLamports - Target priority fee in lamports\n * @param computeUnits - Expected compute units used by the transaction\n * @returns microLamports per compute unit (use in\n * `ComputeBudgetProgram.setComputeUnitPrice`)\n */\nexport function calculateComputeUnitPrice(\n targetLamports: number,\n computeUnits: number,\n): number {\n return Math.ceil((targetLamports * 1_000_000) / computeUnits);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\n\nimport { LightSystemProgram } from '../programs';\nimport { pickRandomTreeAndQueue, Rpc } from '../rpc';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport BN from 'bn.js';\n\n/**\n * Compress lamports to a solana address\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param lamports Amount of lamports to compress\n * @param toAddress Address of the recipient compressed account\n * @param outputStateTree Optional output state tree. Defaults to a current shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n/// TODO: add multisig support\n/// TODO: add support for payer != owner\nexport async function compress(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n toAddress: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const { blockhash } = await rpc.getLatestBlockhash();\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const ix = await LightSystemProgram.compress({\n payer: payer.publicKey,\n toAddress,\n lamports,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n LightSystemProgram,\n selectMinCompressedSolAccountsForTransfer,\n} from '../programs';\nimport { pickRandomTreeAndQueue, Rpc } from '../rpc';\nimport {\n NewAddressParams,\n buildAndSignTx,\n deriveAddress,\n deriveAddressSeed,\n sendAndConfirmTx,\n} from '../utils';\nimport { defaultTestStateTreeAccounts } from '../constants';\nimport { bn } from '../state';\nimport BN from 'bn.js';\n\n/**\n * Create compressed account with address\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param seeds Seeds to derive the new account address\n * @param programId Owner of the new account\n * @param addressTree Optional address tree. Defaults to a current shared\n * address tree.\n * @param addressQueue Optional address queue. Defaults to a current shared\n * address queue.\n * @param outputStateTree Optional output state tree. Defaults to a current\n * shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\nexport async function createAccount(\n rpc: Rpc,\n payer: Signer,\n seeds: Uint8Array[],\n programId: PublicKey,\n addressTree?: PublicKey,\n addressQueue?: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const { blockhash } = await rpc.getLatestBlockhash();\n\n addressTree = addressTree ?? defaultTestStateTreeAccounts().addressTree;\n addressQueue = addressQueue ?? defaultTestStateTreeAccounts().addressQueue;\n\n const seed = deriveAddressSeed(seeds, programId);\n const address = deriveAddress(seed, addressTree);\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const proof = await rpc.getValidityProofV0(undefined, [\n {\n address: bn(address.toBytes()),\n tree: addressTree,\n queue: addressQueue,\n },\n ]);\n\n const params: NewAddressParams = {\n seed: seed,\n addressMerkleTreeRootIndex: proof.rootIndices[0],\n addressMerkleTreePubkey: proof.merkleTrees[0],\n addressQueuePubkey: proof.nullifierQueues[0],\n };\n\n const ix = await LightSystemProgram.createAccount({\n payer: payer.publicKey,\n newAddressParams: params,\n newAddress: Array.from(address.toBytes()),\n recentValidityProof: proof.compressedProof,\n programId,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n\n/**\n * Create compressed account with address and lamports\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param seeds Seeds to derive the new account address\n * @param lamports Number of compressed lamports to initialize the\n * account with\n * @param programId Owner of the new account\n * @param addressTree Optional address tree. Defaults to a current shared\n * address tree.\n * @param addressQueue Optional address queue. Defaults to a current shared\n * address queue.\n * @param outputStateTree Optional output state tree. Defaults to a current\n * shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n// TODO: add support for payer != user owner\nexport async function createAccountWithLamports(\n rpc: Rpc,\n payer: Signer,\n seeds: Uint8Array[],\n lamports: number | BN,\n programId: PublicKey,\n addressTree?: PublicKey,\n addressQueue?: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n lamports = bn(lamports);\n\n const compressedAccounts = await rpc.getCompressedAccountsByOwner(\n payer.publicKey,\n );\n\n const [inputAccounts] = selectMinCompressedSolAccountsForTransfer(\n compressedAccounts.items,\n lamports,\n );\n\n if (!outputStateTree) {\n const stateTreeInfo = await rpc.getCachedActiveStateTreeInfo();\n const { tree } = pickRandomTreeAndQueue(stateTreeInfo);\n outputStateTree = tree;\n }\n\n const { blockhash } = await rpc.getLatestBlockhash();\n\n addressTree = addressTree ?? defaultTestStateTreeAccounts().addressTree;\n addressQueue = addressQueue ?? defaultTestStateTreeAccounts().addressQueue;\n\n const seed = deriveAddressSeed(seeds, programId);\n const address = deriveAddress(seed, addressTree);\n\n const proof = await rpc.getValidityProof(\n inputAccounts.map(account => bn(account.hash)),\n [bn(address.toBytes())],\n );\n\n /// TODO(crank): Adapt before supporting addresses in rpc / cranked address trees.\n /// Currently expects address roots to be consistent with one another and\n /// static. See test-rpc.ts for more details.\n const params: NewAddressParams = {\n seed: seed,\n addressMerkleTreeRootIndex:\n proof.rootIndices[proof.rootIndices.length - 1],\n addressMerkleTreePubkey:\n proof.merkleTrees[proof.merkleTrees.length - 1],\n addressQueuePubkey:\n proof.nullifierQueues[proof.nullifierQueues.length - 1],\n };\n\n const ix = await LightSystemProgram.createAccount({\n payer: payer.publicKey,\n newAddressParams: params,\n newAddress: Array.from(address.toBytes()),\n recentValidityProof: proof.compressedProof,\n inputCompressedAccounts: inputAccounts,\n inputStateRootIndices: proof.rootIndices,\n programId,\n outputStateTree,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport { LightSystemProgram, sumUpLamports } from '../programs';\nimport { Rpc } from '../rpc';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport BN from 'bn.js';\nimport { CompressedAccountWithMerkleContext, bn } from '../state';\n\n/**\n * Decompress lamports into a solana account\n *\n * @param rpc RPC to use\n * @param payer Payer of the transaction and initialization fees\n * @param lamports Amount of lamports to compress\n * @param toAddress Address of the recipient compressed account\n * @param outputStateTree Optional output state tree. Defaults to a current shared state tree.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Transaction signature\n */\n/// TODO: add multisig support\n/// TODO: add support for payer != owner\nexport async function decompress(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n recipient: PublicKey,\n outputStateTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n /// TODO: use dynamic state tree and nullifier queue\n\n const userCompressedAccountsWithMerkleContext: CompressedAccountWithMerkleContext[] =\n (await rpc.getCompressedAccountsByOwner(payer.publicKey)).items;\n\n lamports = bn(lamports);\n\n const inputLamports = sumUpLamports(\n userCompressedAccountsWithMerkleContext,\n );\n\n if (lamports.gt(inputLamports)) {\n throw new Error(\n `Not enough compressed lamports. Expected ${lamports}, got ${inputLamports}`,\n );\n }\n\n const proof = await rpc.getValidityProof(\n userCompressedAccountsWithMerkleContext.map(x => bn(x.hash)),\n );\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const ix = await LightSystemProgram.decompress({\n payer: payer.publicKey,\n toAddress: recipient,\n outputStateTree: outputStateTree,\n inputCompressedAccounts: userCompressedAccountsWithMerkleContext,\n recentValidityProof: proof.compressedProof,\n recentInputStateRootIndices: proof.rootIndices,\n lamports,\n });\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","/** pipe function */\nexport function pipe<T, R>(\n initialFunction: (arg: T) => R,\n ...functions: ((arg: R) => R)[]\n): (initialValue: T) => R {\n return (initialValue: T): R =>\n functions.reduce(\n (currentValue, currentFunction) => currentFunction(currentValue),\n initialFunction(initialValue),\n );\n}\n\n//@ts-ignore\nif (import.meta.vitest) {\n //@ts-ignore\n const { it, expect, describe } = import.meta.vitest;\n\n describe('pipe', () => {\n it('should return the result of applying all fns to the initial value', () => {\n const addOne = (x: number) => x + 1;\n const multiplyByTwo = (x: number) => x * 2;\n const subtractThree = (x: number) => x - 3;\n const addOneMultiplyByTwoSubtractThree = pipe(\n addOne,\n multiplyByTwo,\n subtractThree,\n );\n expect(addOneMultiplyByTwoSubtractThree(5)).toBe(9);\n });\n });\n}\n","// zzz\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\n\nimport BN from 'bn.js';\nimport {\n LightSystemProgram,\n selectMinCompressedSolAccountsForTransfer,\n} from '../programs';\nimport { Rpc } from '../rpc';\n\nimport { bn, CompressedAccountWithMerkleContext } from '../state';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport { GetCompressedAccountsByOwnerConfig } from '../rpc-interface';\n\n/**\n * Transfer compressed lamports from one owner to another\n *\n * @param rpc Rpc to use\n * @param payer Payer of transaction fees\n * @param lamports Number of lamports to transfer\n * @param owner Owner of the compressed lamports\n * @param toAddress Destination address of the recipient\n * @param merkleTree State tree account that the compressed lamports should be\n * inserted into. Defaults to the default state tree account.\n * @param confirmOptions Options for confirming the transaction\n * @param config Configuration for fetching compressed accounts\n *\n *\n * @return Signature of the confirmed transaction\n */\nexport async function transfer(\n rpc: Rpc,\n payer: Signer,\n lamports: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n merkleTree?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n let accumulatedLamports = bn(0);\n const compressedAccounts: CompressedAccountWithMerkleContext[] = [];\n let cursor: string | undefined;\n const batchSize = 1000; // Maximum allowed by the API\n lamports = bn(lamports);\n\n while (accumulatedLamports.lt(lamports)) {\n const batchConfig: GetCompressedAccountsByOwnerConfig = {\n filters: undefined,\n dataSlice: undefined,\n cursor,\n limit: new BN(batchSize),\n };\n\n const batch = await rpc.getCompressedAccountsByOwner(\n owner.publicKey,\n batchConfig,\n );\n\n for (const account of batch.items) {\n if (account.lamports.gt(new BN(0))) {\n compressedAccounts.push(account);\n accumulatedLamports = accumulatedLamports.add(account.lamports);\n }\n }\n\n cursor = batch.cursor ?? undefined;\n if (batch.items.length < batchSize || accumulatedLamports.gte(lamports))\n break;\n }\n\n if (accumulatedLamports.lt(lamports)) {\n throw new Error(\n `Not enough balance for transfer. Required: ${lamports.toString()}, available: ${accumulatedLamports.toString()}`,\n );\n }\n\n const [inputAccounts] = selectMinCompressedSolAccountsForTransfer(\n compressedAccounts,\n lamports,\n );\n\n const proof = await rpc.getValidityProof(\n inputAccounts.map(account => bn(account.hash)),\n );\n\n const ix = await LightSystemProgram.transfer({\n payer: payer.publicKey,\n inputCompressedAccounts: inputAccounts,\n toAddress,\n lamports,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n outputStateTrees: merkleTree,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n );\n\n const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions);\n return txId;\n}\n"],"names":["module","exports","assert","val","msg","Error","inherits","ctor","superCtor","super_","TempCtor","prototype","constructor","BN","number","base","endian","isBN","this","negative","words","length","red","_init","Buffer","wordSize","window","require","e","parseHex4Bits","string","index","c","charCodeAt","parseHexByte","lowerBound","r","parseBase","str","start","end","mul","b","len","Math","min","i","move","dest","src","num","Array","isArray","max","left","right","cmp","_initNumber","_initArray","toString","replace","_parseHex","_parseBase","toArray","ceil","j","w","off","_strip","limbLen","limbPow","total","mod","word","imuln","_iaddn","pow","copy","_move","clone","_expand","size","_normSign","Symbol","for","inspect","zeros","groupSizes","groupBases","smallMulTo","self","out","a","lo","carry","k","ncarry","rword","maxJ","padding","groupSize","groupBase","isZero","modrn","idivn","toNumber","ret","toJSON","toBuffer","toArrayLike","ArrayType","byteLength","reqLength","res","allocUnsafe","allocate","_toArrayLikeLE","position","shift","_toArrayLikeBE","clz32","_countBits","t","_zeroBits","bitLength","hi","zeroBits","toTwos","width","abs","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","xor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","add","sub","comb10MulTo","mid","o","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","b1","bl1","bh1","b2","bl2","bh2","b3","bl3","bh3","b4","bl4","bh4","b5","bl5","bh5","b6","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","b9","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","bigMulTo","hncarry","jumboMulTo","mulTo","mulf","isNegNum","muln","sqr","isqr","toBitArray","q","iushln","bits","s","carryMask","newCarry","ishln","iushrn","hint","extended","h","mask","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","_wordDiv","mode","bhi","m","diff","qj","div","divmod","positive","divn","umod","divRound","dm","half","r2","andln","p","acc","modn","egcd","x","y","A","B","C","D","g","isEven","yp","xp","im","isOdd","jm","gcd","_invmp","x1","x2","delta","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","eq","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","name","n","tmp","_tmp","K256","call","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","split","imulK","undefined","strip","input","output","outLen","prev","next","mod3","one","nOne","lpow","z","inv","wnd","current","currentLen","mont","u","TreeType","FIELD_SIZE","HIGHEST_ADDRESS_PLUS_ONE","COMPUTE_BUDGET_PATTERN","INVOKE_DISCRIMINATOR","from","INVOKE_CPI_DISCRIMINATOR","INSERT_INTO_QUEUES_DISCRIMINATOR","noopProgram","lightProgram","accountCompressionProgram","getRegisteredProgramPda","PublicKey","getAccountCompressionAuthority","findProgramAddressSync","defaultStaticAccountsStruct","registeredProgramPda","accountCompressionAuthority","cpiSignatureAccount","defaultStateTreeLookupTables","mainnet","stateTreeLookupTable","stateTreeLookupTableMainnet","nullifyTable","nullifiedStateTreeLookupTableMainnet","devnet","stateTreeLookupTableDevnet","nullifiedStateTreeLookupTableDevnet","isLocalTest","url","includes","localTestActiveStateTreeInfo","tree","merkletreePubkey","queue","nullifierQueuePubkey","cpiContext","cpiContextPubkey","treeType","State","merkleTree2Pubkey","nullifierQueue2Pubkey","cpiContext2Pubkey","defaultTestStateTreeAccounts","nullifierQueue","merkleTree","merkleTreeHeight","DEFAULT_MERKLE_TREE_HEIGHT","addressTree","addressQueue","TRANSACTION_MERKLE_TREE_ROLLOVER_THRESHOLD","floor","STATE_MERKLE_TREE_ROLLOVER_FEE","ADDRESS_QUEUE_ROLLOVER_FEE","STATE_MERKLE_TREE_NETWORK_FEE","ADDRESS_TREE_NETWORK_FEE","basex","ALPHABET","BASE_MAP","Uint8Array","charAt","xc","TypeError","LEADER","FACTOR","log","iFACTOR","decodeUnsafe","source","psz","zeroes","b256","it3","it4","vch","encode","ArrayBuffer","isView","buffer","byteOffset","pbegin","pend","b58","it1","it2","repeat","decode","bn","createBN254","bs58","bigintNumber","enforceSize","encodeBN254toBase58","bn254Buffer","createCompressedAccount","owner","lamports","data","address","createCompressedAccountWithMerkleContext","merkleContext","Object","assign","readOnly","createMerkleContext","hash","leafIndex","Number","isSafeInteger","bytes","lengths","exists","instance","checkFinished","destroyed","finished","U32_MASK64","BigInt","_32n","fromBig","le","l","lst","Ah","Uint32Array","Al","isLE","byteSwap32","arr","toBytes","TextEncoder","utf8ToBytes","abytes","Hash","_cloneInto","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","_0n","_1n","_2n","_7n","_256n","_0x71n","round","R","push","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlBH","rotlSH","rotlL","rotlBL","rotlSL","Keccak","blockLen","suffix","outputLen","enableXOF","rounds","super","pos","posOut","state","state32","keccak","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","fill","keccakP","update","take","finish","writeInto","bufferOut","set","subarray","xofInto","xof","digestInto","destroy","digest","to","keccak_256","hashCons","hashC","create","wrapConstructor","gen","isObject","value","isObjectCustom","RegExp","Date","mapObjectSkip","_mapObject","object","mapper","options","isSeen","WeakMap","deep","target","has","get","mapArray","array","map","element","key","entries","mapResult","newKey","newValue","shouldRecurse","mapObject","UPPERCASE","LOWERCASE","LEADING_CAPITAL","IDENTIFIER","SEPARATORS","LEADING_SEPARATORS","SEPARATORS_AND_IDENTIFIER","NUMBERS_AND_IDENTIFIER","QuickLRU","Map","maxSize","maxAge","POSITIVE_INFINITY","onEviction","cache","oldCache","_size","_emitEvictions","item","_deleteIfExpired","expiry","now","delete","_getOrDeleteIfExpired","_getItemValue","_peek","_set","_moveToRecent","_entriesAscending","peek","deleted","clear","resize","newSize","items","removeCount","slice","keys","values","iterator","entriesDescending","entriesAscending","oldCacheSize","forEach","callbackFunction","thisArgument","toStringTag","JSON","stringify","QuickLru","transform","exclude","pascalCase","stopPaths","preserveConsecutiveUppercase","stopPathsSet","Set","makeMapper","parentPath","path","some","lastIndex","test","cacheKey","returnValue","trim","filter","join","toLowerCase","locale","toLocaleLowerCase","toUpperCase","toLocaleUpperCase","isLastCharLower","isLastCharUpper","isLastLastCharUpper","isLastLastCharPreserved","character","preserveCamelCase","replaceAll","match","pattern","offset","_","identifier","postProcess","camelCase","toHex","isSmallerThanBn254FieldSizeBe","toCamelCase","camelcaseKeys","hashToBn254FieldSizeBe","bumpSeed","inputWithBumpSeed","concat","hashvToBn254FieldSizeBe","hasher","getIndexOrAdd","accountsArray","findIndex","existingKey","equals","padOutputStateMerkleTrees","outputStateMerkleTrees","numberOfOutputCompressedAccounts","inputCompressedAccountsWithMerkleContext","treesArray","toAccountMetas","remainingAccounts","account","pubkey","isWritable","isSigner","packCompressedAccounts","inputCompressedAccounts","inputStateRootIndices","outputCompressedAccounts","_remainingAccounts","packedInputCompressedAccounts","packedOutputCompressedAccounts","merkleTreePubkeyIndex","nullifierQueuePubkeyIndex","compressedAccount","queueIndex","rootIndex","paddedOutputStateMerkleTrees","merkleTreeIndex","validateSufficientBalance","balance","validateSameOwner","compressedAccounts","zerothOwner","every","validateNumbersForProof","hashesLength","newAddressesLength","validateNumbers","validateNumbersForNonInclusionProof","validateNumbersForInclusionProof","allowedNumbers","type","deriveAddressSeed","seeds","programId","deriveAddress","seed","addressMerkleTreePubkey","buf","packNewAddressParams","newAddressParams","newAddressParamsPacked","addressMerkleTreeRootIndex","addressMerkleTreeAccountIndex","addressQueueAccountIndex","params","addressQueuePubkey","async","confirmTransaction","connection","signature","confirmation","latestBlockHash","getLatestBlockhash","strategy","lastValidBlockHeight","blockhash","proofFromJsonStruct","json","proofAX","deserializeHexStringToBeBytes","ar","proofAY","proofA","proofBX0","bs","proofBX1","proofBY0","proofBY1","proofB","proofCX","krs","proofCY","negateAndCompressProof","proof","proofC","aXElement","proofAIsPositive","yElementIsPositiveG1","addBitmaskToByte","bXElement","bYElement","proofBIsPositive","yElement1","yElement2","fieldMidpoint","yElementIsPositiveG2","cXElement","cYElement","proofCIsPositive","hexStr","startsWith","substring","yElement","byte","yIsPositive","buildTx","instructions","payerPublicKey","lookupTableAccounts","messageV0","TransactionMessage","payerKey","recentBlockhash","compileToV0Message","VersionedTransaction","sendAndConfirmTx","rpc","tx","confirmOptions","blockHashCtx","txId","sendTransaction","transactionConfirmationStrategy0","slot","commitment","context","confirmTransactionIndexed","confirmTx","transactionConfirmationStrategy","buildAndSignTx","payer","additionalSigners","allSigners","publicKey","sign","getLightStateTreeInfo","stateTreeLookupTableAddress","nullifyTableAddress","getAddressLookupTable","addresses","stateTreePubkeys","nullifyTablePubkeys","bundles","Layout","span","property","isInteger","makeDestinationObject","getSpan","RangeError","replicate","rv","fromArray","nameWithProperty","Layout_1","bindConstructorLayout","Class","layout","hasOwnProperty","layout_","boundConstructor_","defineProperty","writable","ExternalLayout","isCount","GreedyCount","elementSpan","rem","OffsetLayout","UInt","UIntBE","readUIntLE","writeUIntLE","readUIntBE","writeUIntBE","Int","readIntLE","writeIntLE","IntBE","readIntBE","writeIntBE","V2E32","divmodInt64","hi32","lo32","roundedInt64","NearUInt64","readUInt32LE","writeUInt32LE","NearUInt64BE","readUInt32BE","writeUInt32BE","NearInt64","readInt32LE","writeInt32LE","NearInt64BE","readInt32BE","writeInt32BE","Float","readFloatLE","writeFloatLE","FloatBE","readFloatBE","writeFloatBE","Double","readDoubleLE","writeDoubleLE","DoubleBE","readDoubleBE","writeDoubleBE","Sequence","elementLayout","count","idx","elo","reduce","v","Structure","fields","decodePrefixes","fd","fsp","firstOffset","lastOffset","lastWrote","fv","layoutFor","offsetOf","UnionDiscriminator","UnionLayoutDiscriminator","Union","discr","defaultLayout","upv","discriminator","usesPrefixDiscriminator","registry","boundGetSourceVariant","defaultGetSourceVariant","bind","getSourceVariant","configGetSourceVariant","gsv","vlo","getVariant","tag","dlo","clo","contentOffset","addVariant","variant","VariantLayout","vb","isBuffer","union","fixBitwiseResult","BitStructure","msb","_packedSetValue","_packedGetValue","addField","bf","BitField","addBoolean","Boolean","fieldFor","container","totalBits","usedBits","sum","valueMask","wordMask","wordValue","Blob","write","CString","srcb","UTF8","maxSpan","Constant","greedy","u8","u16","u24","u32","u40","u48","nu64","u16be","u24be","u32be","u40be","u48be","nu64be","s8","s16","s24","s32","s40","s48","ns64","s16be","s24be","s32be","s40be","s48be","ns64be","f32","f32be","f64","f64be","struct","seq","unionLayoutDiscriminator","blob","cstr","utf8","const","__importDefault","__esModule","default","rustEnum","vecU8","tagged","vec","bool","option","i256","u256","i128","u128","u64","i32","i16","i8","buffer_layout_1","require$$0","web3_js_1","require$$1","bn_js_1","require$$2","buffer_layout_2","enumerable","BNLayout","signed","i64","WrappedLayout","decoder","encoder","OptionLayout","decodeBool","encodeBool","wrappedLayout","receivedTag","variants","discriminant","unionLayout","MapEntryLayout","keyLayout","valueLayout","keyBytes","CompressedAccountLayout","MerkleContextLayout","NewAddressParamsLayout","InstructionDataInvokeLayout","encodeInstructionDataInvoke","alloc","dataBuffer","lengthBuffer","InstructionDataInvokeCpiLayout","decodeInstructionDataInvoke","decodeInstructionDataInvokeCpi","invokeAccountsLayout","accounts","defaultPubkey","LightSystemProgram","feePayer","authority","solPoolPda","decompressionRecipient","systemProgram","PublicTransactionEventLayout","decodePublicTransactionEvent","AppendNullifyCreateAddressInputsMetaLayout","AppendLeavesInputLayout","InsertNullifierInputLayout","InsertAddressInputLayout","MerkleTreeSequenceNumberLayout","deserializeAppendNullifyCreateAddressInputsIndexer","meta","leavesCount","readUInt8","leaves","leaf","nullifiersCount","nullifiers","nullifier","addressesCount","outputSequenceNumbersCount","output_sequence_numbers","inputSequenceNumbersCount","addressSequenceNumbersCount","outputLeafIndicesCount","output_leaf_indices","sequence_numbers","convertToPublicTransactionEvent","decoded","invokeData","convertByteArray","inputCompressedAccountHashes","account_hash","outputCompressedAccountHashes","_a","_b","_c","_d","_e","dataHash","_f","outputLeafIndices","sequenceNumbers","sn","pubkeyArray","pk","isCompress","relayFee","compressOrDecompressLamports","message","sumUpLamports","SOL_POOL_PDA_SEED","deriveCompressedSolPda","createTransferOutputState","toAddress","changeLamports","createDecompressOutputState","createNewAddressOutputState","createAccount","newAddress","recentValidityProof","outputStateTree","SystemProgram","TransactionInstruction","transfer","recentInputStateRootIndices","outputStateTrees","compress","outputCompressedAccount","decompress","selectMinCompressedSolAccountsForTransfer","transferLamports","accumulatedLamports","selectedAccounts","sort","StructError","failure","failures","cached","explanation","rest","cause","isNonArrayObject","print","toFailure","result","branch","refinement","toFailures","run","coerce","coercer","status","validator","ts","refiner","Struct","props","schema","validate","is","tuples","tuple","done","shiftIterator","define","any","Element","literal","constant","description","nullable","isNaN","Structs","S","error","coerced","first","unknown","condition","PublicKeyFromString","ArrayFromString","BN254FromString","BNFromStringOrNumber","Base64EncodedCompressedAccountDataResult","createRpcResult","pick","jsonrpc","id","code","UnknownRpcResult","jsonRpcResult","jsonRpcResultAndContext","CompressedAccountResult","slotCreated","TokenDataResult","mint","amount","delegate","CompressedTokenAccountResult","tokenData","MultipleCompressedAccountsResult","CompressedAccountsByOwnerResult","cursor","CompressedTokenAccountsByOwnerOrDelegateResult","SlotResult","HealthResult","LatestNonVotingSignaturesResult","blockTime","LatestNonVotingSignaturesResultPaginated","MerkeProofResult","rootSeq","root","NewAddressProofResult","nextIndex","lowerRangeAddress","higherRangeAddress","lowElementLeafIndex","CompressedProofResult","ValidityProofResult","compressedProof","leafIndices","rootIndices","roots","merkleTrees","MultipleMerkleProofsResult","BalanceResult","NativeBalanceResult","TokenBalanceResult","TokenBalanceListResult","tokenBalances","TokenBalanceListResultV2","CompressedMintTokenHoldersResult","AccountProofResult","SignatureListResult","SignatureListWithCursorResult","CompressedTransactionResult","compressionInfo","closedAccounts","optionalTokenData","openedAccounts","transaction","parseAccountData","getCompressedTokenAccountsByOwnerOrDelegate","ownerOrDelegate","filterByDelegate","endpoint","propertyToCheck","rpcRequest","compressionApiEndpoint","toBase58","limit","SolanaJSONRPCError","activeStateTreeInfo","getCachedActiveStateTreeInfo","_account","_tokenData","associatedQueue","getQueueForTree","parsed","indexOf","tlv","buildCompressedAccountWithMaybeTokenData","accountStructWithOptionalTokenData","compressedAccountResult","tokenDataResult","maybeTokenData","wrapBigNumbersAsStrings","text","p1","p2","p3","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","rpcEndpoint","method","convertToCamelCase","debug","body","generateCurlSnippet","escapedBody","console","stack","response","fetch","headers","ok","wrappedJsonString","parse","proverRequest","proverEndpoint","logMsg","time","circuitType","stateTreeHeight","addressTreeHeight","newAddresses","statusText","timeEnd","convertMerkleProofsWithContextToHex","merkleProofsWithContext","inputs","pathIndex","pathElements","merkleProof","hex","convertNonInclusionMerkleProofInputsToHex","nonInclusionMerkleProofInputs","indexHashedIndexedElementLeaf","merkleProofHashedIndexedElementLeaf","leafLowerRangeValue","leafHigherRangeValue","calculateTwoInputsHashChain","hashesFirst","hashesSecond","lightWasm","hashChain","poseidonHashBN","info","pickRandomTreeAndQueue","random","Rpc","Connection","config","setStateTreeInfo","getLatestActiveStateTreeInfo","getCompressedAccount","getCompressedBalance","getCompressedBalanceByOwner","getCompressedAccountProof","getMultipleCompressedAccounts","hashes","getMultipleCompressedAccountProofs","merkleProofs","getCompressedAccountsByOwner","filters","dataSlice","getCompressedTokenAccountsByOwner","getCompressedTokenAccountsByDelegate","getCompressedTokenAccountBalance","getCompressedTokenBalancesByOwner","tokenBalance","getCompressedTokenBalancesByOwnerV2","maybeFiltered","getCompressionSignaturesForAccount","getTransactionWithCompressionInfo","calculateTokenBalances","balances","preTokenBalances","postTokenBalances","getCompressionSignaturesForAddress","getCompressionSignaturesForOwner","getCompressionSignaturesForTokenOwner","getIndexerHealth","startTime","getIndexerSlot","Promise","resolve","setTimeout","getCompressedMintTokenHolders","getLatestCompressionSignatures","getLatestNonVotingSignatures","getMultipleNewAddressProofs","newAddressProofs","_proof","getValidityProofDirect","validityProof","nullifierQueues","newAddressInputs","getValidityProof","accs","trees","queues","defaultAddressTreePublicKey","defaultAddressQueuePublicKey","formattedHashes","formattedNewAddresses","getValidityProofV0","getValidityProofAndRpcContext","newAddressesWithTrees","dedupeSigner","signer","signers","UtxoErrorCode","SelectInUtxosErrorCode","CreateUtxoErrorCode","RpcErrorCode","LookupTableErrorCode","ProofErrorCode","MerkleTreeErrorCode","UtilsErrorCode","HashErrorCode","MetaError","functionName","codeMessage","IndexedElement","other","compareTo","nextValue","poseidonHash","IndexedElementBundle","newLowElement","newElement","newElementNextValue","IndexedArray","elements","currentNodeIndex","highestElementIndex","isEmpty","findElement","find","node","init","init_value","append","findLowElementIndex","findLowElement","lowElementIndex","lowElement","hashElement","nextElement","appendWithLowElementIndex","newElementBundle","newElementWithLowElementIndex","lowest","newElementIndex","MerkleTree","levels","zeroElement","capacity","_lightWasm","_zeros","_layers","poseidonHashString","_rebuild","level","insert","bulkInsert","pathIndices","comparator","el","serialize","deserialize","hashFunction","_hash","getParsedEvents","events","signatures","getConfirmedSignaturesForAddress2","txs","getParsedTransactions","maxSupportedTransactionVersion","txParsed","innerInstructions","allAccounts","accountKeys","dataVec","txRaw","getTransaction","ix","compiledInstructions","decodedData","groupedAccountVec","innerGroup","group","accountIdx","event","parseLightTransaction","transactionEvents","parseEvents","parsePublicTransactionEventWithIdl","indexerEventsTransactions","deserializeFn","transactions","err","ixInner","decodedEvent","numericData","foundSystemInstruction","appendInputsData","discriminatorStr","invokeDiscriminatorStr","invokeCpiDiscriminatorStr","getCompressedAccountByHashTest","getCompressedAccountsForTest","reverse","allOutputAccounts","allInputAccountHashes","withCtx","unspentAccounts","tokenProgramId","TokenDataLayout","parseTokenLayoutWithIdl","getCompressedTokenAccounts","eventsWithParsedTokenTlvData","all","outputHashes","outputCompressedAccountsWithParsedTokenData","parsedData","parseEventWithTokenTlvData","allOutCompressedAccounts","flatMap","allInCompressedAccountHashes","getCompressedTokenAccountsByOwnerTest","getCompressedTokenAccountsByDelegateTest","getCompressedTokenAccountByHashTest","filtered","TestRpc","connectionConfig","testRpcConfig","merkleTreeAddress","nullifierQueueAddress","depth","addressTreeAddress","addressQueueAddress","getMultipleCompressedAccountsByHashTest","_slot","then","allLeaves","allLeafIndices","bnPathElements","computedHash","hashArr","_config","getCompressedAccountsByOwnerTest","_cursor","_limit","_signature","_address","_options","_owner","indexedArray","allAddresses","higherRangeValue","_mint","ALICE","getTestKeypair","BOB","CHARLIE","DAVE","counter","Keypair","generate","fromSeed","version","constants","isMut","args","docs","isOptional","defined","kind","types","errors","recipientPublicKey","txHash","requestAirdrop","byteArray","fromSecretKey","targetLamports","computeUnits","stateTreeInfo","ComputeBudgetProgram","setComputeUnitLimit","units","preflightCommitment","inputAccounts","endpointOrWeb3JsConnection","recentSlot","createInstruction1","lookupTableAddress1","AddressLookupTableProgram","createLookupTable","recipient","userCompressedAccountsWithMerkleContext","inputLamports","deepEqual","ref","refKeys","valKeys","nullifierQueue2","merkleTree2","tableAddress","newStateTreeAddresses","newQueueAddresses","newCpiContextAddresses","lutState","extendLookupTable","lookupTable","addr","accountProofs","accountHashes","inclusionHashChain","newAddressHashes","nonInclusionHashChain","defaultAccounts","sig","fullStateTreeAddress","initialFunction","functions","initialValue","currentValue","currentFunction","ms","getTime","batchConfig","batch","signedTx"],"mappings":"2UAAA,SAAWA,EAAQC,GAIjB,SAASC,EAAQC,EAAKC,GACpB,IAAKD,EAAK,MAAM,IAAIE,MAAMD,GAAO,mBAClC,CAID,SAASE,EAAUC,EAAMC,GACvBD,EAAKE,OAASD,EACd,IAAIE,EAAW,aACfA,EAASC,UAAYH,EAAUG,UAC/BJ,EAAKI,UAAY,IAAID,EACrBH,EAAKI,UAAUC,YAAcL,CAC9B,CAID,SAASM,EAAIC,EAAQC,EAAMC,GACzB,GAAIH,EAAGI,KAAKH,GACV,OAAOA,EAGTI,KAAKC,SAAW,EAChBD,KAAKE,MAAQ,KACbF,KAAKG,OAAS,EAGdH,KAAKI,IAAM,KAEI,OAAXR,IACW,OAATC,GAA0B,OAATA,IACnBC,EAASD,EACTA,EAAO,IAGTG,KAAKK,MAAMT,GAAU,EAAGC,GAAQ,GAAIC,GAAU,MAEjD,CAUD,IAAIQ,EATkB,qBACbvB,QAAUY,EAEjBZ,EAAQY,GAAKA,EAGfA,EAAGA,GAAKA,EACRA,EAAGY,SAAW,GAGd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