@lightprotocol/stateless.js 0.17.2-alpha.0 → 0.17.2-alpha.2
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/constants.d.ts +2 -0
- package/dist/cjs/browser/idl.d.ts +1015 -0
- package/dist/cjs/browser/index.cjs +1 -1
- package/dist/cjs/browser/index.cjs.map +1 -1
- package/dist/cjs/browser/index.d.ts +1 -0
- package/dist/cjs/browser/rpc-interface.d.ts +110 -117
- package/dist/cjs/browser/rpc.d.ts +2 -57
- package/dist/cjs/browser/state/types.d.ts +5 -0
- package/dist/cjs/browser/test-helpers/test-rpc/test-rpc.d.ts +2 -3
- package/dist/cjs/browser/utils/test-utils.d.ts +8 -0
- package/dist/cjs/node/constants.d.ts +2 -0
- package/dist/cjs/node/idl.d.ts +1015 -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 +1 -0
- package/dist/cjs/node/rpc-interface.d.ts +110 -117
- package/dist/cjs/node/rpc.d.ts +2 -57
- package/dist/cjs/node/state/types.d.ts +5 -0
- package/dist/cjs/node/test-helpers/test-rpc/test-rpc.d.ts +2 -3
- package/dist/cjs/node/utils/test-utils.d.ts +8 -0
- package/dist/types/index.d.ts +1036 -193
- package/package.json +9 -8
- package/dist/cjs/browser/connection-interface.d.ts +0 -125
- package/dist/cjs/node/connection-interface.d.ts +0 -125
- package/dist/es/browser/actions/common.d.ts +0 -3
- package/dist/es/browser/actions/compress.d.ts +0 -16
- package/dist/es/browser/actions/create-account.d.ts +0 -41
- package/dist/es/browser/actions/decompress.d.ts +0 -16
- package/dist/es/browser/actions/index.d.ts +0 -5
- package/dist/es/browser/actions/transfer.d.ts +0 -20
- package/dist/es/browser/connection-interface.d.ts +0 -125
- package/dist/es/browser/constants.d.ts +0 -63
- package/dist/es/browser/errors.d.ts +0 -74
- package/dist/es/browser/index.d.ts +0 -10
- package/dist/es/browser/index.js +0 -2
- package/dist/es/browser/index.js.map +0 -1
- package/dist/es/browser/instruction/index.d.ts +0 -1
- package/dist/es/browser/instruction/pack-compressed-accounts.d.ts +0 -35
- package/dist/es/browser/programs/index.d.ts +0 -2
- package/dist/es/browser/programs/layout.d.ts +0 -25
- package/dist/es/browser/programs/system.d.ts +0 -199
- package/dist/es/browser/rpc-interface.d.ts +0 -1179
- package/dist/es/browser/rpc.d.ts +0 -330
- package/dist/es/browser/state/BN254.d.ts +0 -14
- package/dist/es/browser/state/compressed-account.d.ts +0 -31
- package/dist/es/browser/state/index.d.ts +0 -3
- package/dist/es/browser/state/types.d.ts +0 -91
- package/dist/es/browser/test-helpers/index.d.ts +0 -2
- package/dist/es/browser/test-helpers/merkle-tree/index.d.ts +0 -2
- package/dist/es/browser/test-helpers/merkle-tree/indexed-array.d.ts +0 -85
- package/dist/es/browser/test-helpers/merkle-tree/merkle-tree.d.ts +0 -92
- package/dist/es/browser/test-helpers/test-rpc/get-compressed-accounts.d.ts +0 -7
- package/dist/es/browser/test-helpers/test-rpc/get-compressed-token-accounts.d.ts +0 -40
- package/dist/es/browser/test-helpers/test-rpc/get-parsed-events.d.ts +0 -13
- package/dist/es/browser/test-helpers/test-rpc/index.d.ts +0 -3
- package/dist/es/browser/test-helpers/test-rpc/test-rpc.d.ts +0 -250
- package/dist/es/browser/utils/address.d.ts +0 -63
- package/dist/es/browser/utils/airdrop.d.ts +0 -7
- package/dist/es/browser/utils/calculate-compute-unit-price.d.ts +0 -7
- package/dist/es/browser/utils/conversion.d.ts +0 -31
- package/dist/es/browser/utils/index.d.ts +0 -10
- package/dist/es/browser/utils/parse-validity-proof.d.ts +0 -20
- package/dist/es/browser/utils/pipe.d.ts +0 -2
- package/dist/es/browser/utils/send-and-confirm.d.ts +0 -52
- package/dist/es/browser/utils/sleep.d.ts +0 -1
- package/dist/es/browser/utils/test-utils.d.ts +0 -23
- package/dist/es/browser/utils/validation.d.ts +0 -4
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../../node_modules/.pnpm/bn.js@5.2.1/node_modules/bn.js/lib/bn.js","../../../../../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/pipe.ts","../../../../../src/utils/send-and-confirm.ts","../../../../../src/utils/sleep.ts","../../../../../src/utils/test-utils.ts","../../../../../src/utils/calculate-compute-unit-price.ts","../../../../../node_modules/.pnpm/@coral-xyz+borsh@0.30.1_@solana+web3.js@1.95.5_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","../../../../../src/actions/compress.ts","../../../../../src/actions/create-account.ts","../../../../../src/actions/decompress.ts","../../../../../src/actions/common.ts","../../../../../src/actions/transfer.ts","../../../../../src/errors.ts","../../../../../src/rpc-interface.ts","../../../../../src/rpc.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"],"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 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 { Buffer } from 'buffer';\nimport { ConfirmOptions, PublicKey } from '@solana/web3.js';\n\nexport const FIELD_SIZE = new BN(\n '21888242871839275222246405745257275088548364400416034343698204186575808495617',\n);\nexport const HIGHEST_ADDRESS_PLUS_ONE = new BN(\n '452312848583266388373324160190187140051835877600158453279131187530910662655',\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 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\nexport const nullifierQueuePubkey =\n 'nfq1NvQDJ2GEgnS8zt9prAe8rjjpAW1zFkrvZoBR148';\n\nexport const merkletreePubkey = 'smt1NamzXdq4AMqS2fS2F1i5KTYPZRhoHgWx38d8WsT';\nexport const addressTree = 'amt1Ayt45jfbdw5YSo7iz6WZxUmnZsQTYXy82hVwyC2';\nexport const addressQueue = 'aq1S9z4reTSQAdgWHGD2zDaS39sjGrAxbR31vxJ2F4F';\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 && obj.constructor === Object) {\n return Object.keys(obj).reduce((result, key) => {\n const camelCaseKey = key.replace(/([-_][a-z])/gi, $1 => {\n return $1.toUpperCase().replace('-', '').replace('_', '');\n });\n result[camelCaseKey] = toCamelCase(obj[key]);\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';\nimport { defaultTestStateTreeAccounts } from '../constants';\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/** @internal */\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 return new Array(numberOfOutputCompressedAccounts).fill(\n defaultTestStateTreeAccounts().merkleTree,\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// TODO: include owner and lamports in packing.\n/**\n * Packs Compressed Accounts.\n *\n * Replaces PublicKey with index pointer to remaining accounts.\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 /// 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","/** 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","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","// zzz\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import { Connection, Keypair, Signer } from '@solana/web3.js';\nimport { confirmTx } from '../utils/send-and-confirm';\nimport { Rpc } from '../rpc';\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 * 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","/**\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","\"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 { InstructionDataInvoke, PublicTransactionEvent } from '../state';\nimport { LightSystemProgram } from './system';\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\n// Use the defined structs in the main layout with field names\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\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n\n return Buffer.concat([\n Buffer.from([26, 16, 169, 7, 21, 202, 242, 25]),\n lengthBuffer,\n dataBuffer,\n ]);\n}\n\nexport function decodeInstructionDataInvoke(\n buffer: Buffer,\n): InstructionDataInvoke {\n return InstructionDataInvokeLayout.decode(buffer);\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 return buffer.slice(0, len);\n}\n\nexport function decodePublicTransactionEvent(\n buffer: Buffer,\n): PublicTransactionEvent {\n return PublicTransactionEventLayout.decode(buffer);\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 /// 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 /// Pack accounts\n const {\n packedInputCompressedAccounts,\n packedOutputCompressedAccounts,\n remainingAccounts,\n } = packCompressedAccounts(\n inputCompressedAccounts,\n recentInputStateRootIndices,\n outputCompressedAccounts,\n outputStateTrees,\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 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 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: this.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: this.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","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\n\nimport { LightSystemProgram } from '../programs';\nimport { Rpc } from '../rpc';\nimport { buildAndSignTx, sendAndConfirmTx } from '../utils';\nimport BN from 'bn.js';\nimport { defaultTestStateTreeAccounts } from '../constants';\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 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 { 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 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 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","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","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 /// TODO: allow multiple\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 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 const txId = await sendAndConfirmTx(rpc, signedTx, confirmOptions);\n return txId;\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 {\n PublicKey,\n MemcmpFilter,\n DataSlice,\n RpcResponseAndContext,\n Commitment,\n SignatureResult,\n} 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 class BaseRpc {\n private async getCancellationPromise() {\n throw new Error(\n 'getCancellationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n );\n }\n private async getTransactionConfirmationPromise() {\n throw new Error(\n 'getTransactionConfirmationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n );\n }\n private async confirmTransactionUsingBlockHeightExceedanceStrategy() {\n throw new Error(\n 'confirmTransactionUsingBlockHeightExceedanceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n );\n }\n private async confirmTransactionUsingDurableNonceStrategy() {\n throw new Error(\n 'confirmTransactionUsingDurableNonceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n );\n }\n private async confirmTransactionUsingLegacyTimeoutStrategy({\n commitment,\n signature,\n }: {\n commitment?: Commitment;\n signature: string;\n }): Promise<RpcResponseAndContext<SignatureResult>> {\n throw new Error(\n 'confirmTransactionUsingLegacyTimeoutStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n );\n }\n}\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\nconst BNFromInt = coerce(instance(BN), number(), value => {\n // Check if the number is safe\n if (Number.isSafeInteger(value)) {\n return bn(value);\n } else {\n // Convert to string if the number is unsafe\n return bn(value.toString(), 10);\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: BNFromInt,\n }),\n ),\n lamports: BNFromInt,\n owner: PublicKeyFromString,\n leafIndex: number(),\n tree: PublicKeyFromString,\n seq: nullable(BNFromInt),\n slotCreated: BNFromInt,\n});\n\nexport const TokenDataResult = pick({\n mint: PublicKeyFromString,\n owner: PublicKeyFromString,\n amount: BNFromInt,\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: BNFromInt,\n});\n\nexport const NativeBalanceResult = BNFromInt;\n\nexport const TokenBalanceResult = pick({\n balance: BNFromInt,\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: BNFromInt,\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 Commitment,\n PublicKey,\n Transaction,\n VersionedTransaction,\n SendOptions,\n BlockhashWithExpiryBlockHeight,\n RpcResponseAndContext,\n GetBalanceConfig,\n GetSupplyConfig,\n Supply,\n GetTokenAccountsByOwnerConfig,\n GetProgramAccountsResponse,\n TokenAccountsFilter,\n AccountInfo,\n GetMultipleAccountsConfig,\n StakeActivationData,\n GetStakeActivationConfig,\n TransactionConfirmationStrategy,\n SignatureResult,\n ContactInfo,\n VoteAccountStatus,\n GetSlotConfig,\n GetSlotLeaderConfig,\n SignatureStatusConfig,\n SignatureStatus,\n GetTransactionCountConfig,\n InflationGovernor,\n GetInflationRewardConfig,\n InflationReward,\n InflationRate,\n EpochInfo,\n GetEpochInfoConfig,\n EpochSchedule,\n LeaderSchedule,\n FeeCalculator,\n GetRecentPrioritizationFeesConfig,\n RecentPrioritizationFees,\n GetLatestBlockhashConfig,\n Version,\n TransactionResponse,\n VersionedTransactionResponse,\n ParsedTransactionWithMeta,\n ParsedConfirmedTransaction,\n SimulateTransactionConfig,\n SimulatedTransactionResponse,\n Message,\n Signer,\n AccountChangeCallback,\n AccountSubscriptionConfig,\n ProgramAccountChangeCallback,\n ProgramAccountSubscriptionConfig,\n LogsFilter,\n LogsCallback,\n SlotChangeCallback,\n SlotUpdateCallback,\n SignatureResultCallback,\n SignatureSubscriptionCallback,\n SignatureSubscriptionOptions,\n RootChangeCallback,\n ConfirmOptions,\n GetMultipleAccountsConfig as OriginalGetMultipleAccountsConfig,\n GetAccountInfoConfig,\n GetLargestAccountsConfig,\n TokenAccountBalancePair,\n AccountBalancePair,\n ParsedAccountData,\n SimulateTransactionConfig as OriginalSimulateTransactionConfig,\n SimulatedTransactionResponse as OriginalSimulatedTransactionResponse,\n SignatureSubscriptionOptions as OriginalSignatureSubscriptionOptions,\n Finality,\n GetTransactionConfig,\n GetVersionedTransactionConfig,\n ConfirmedBlock,\n BlockProduction,\n TransactionSignature,\n BlockSignatures,\n ConfirmedSignatureInfo,\n AddressLookupTableAccount,\n GetBlockHeightConfig,\n GetBlockProductionConfig,\n ParsedNoneModeBlockResponse,\n SolanaJSONRPCError,\n TokenAmount,\n GetStakeMinimumDelegationConfig,\n GetNonceAndContextConfig,\n NonceAccount,\n GetNonceConfig,\n GetProgramAccountsConfig,\n GetParsedProgramAccountsConfig,\n Blockhash,\n PerfSample,\n VersionedMessage,\n IsBlockhashValidConfig,\n GetVersionedBlockConfig,\n VersionedAccountsModeBlockResponse,\n VersionedBlockResponse,\n VersionedNoneModeBlockResponse,\n ParsedAccountsModeBlockResponse,\n ConfirmedTransaction,\n ConfirmedSignaturesForAddress2Options,\n SignaturesForAddressOptions,\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 BaseRpc,\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 { defaultTestStateTreeAccounts } from './constants';\nimport BN from 'bn.js';\nimport { toCamelCase, toHex } from './utils/conversion';\n\ntype ClientSubscriptionId = number;\n\n// // Define an interface that includes the methods you need from Connection\n// interface ConnectionInterface {\n// sendTransaction(transaction: any, options?: any): Promise<any>;\n// getLatestBlockhash(): Promise<BlockhashWithExpiryBlockHeight>;\n// confirmTransaction(signature: string, commitment?: string): Promise<any>;\n// commitment: string;\n// // Add other methods and properties as needed\n// }\n\nimport {\n proofFromJsonStruct,\n negateAndCompressProof,\n} from './utils/parse-validity-proof';\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 res.result.value.items.map(item => {\n const _account = item.account;\n const _tokenData = item.tokenData;\n\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n _account.tree!,\n mockNullifierQueue,\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): {\n account: CompressedAccountWithMerkleContext;\n maybeTokenData: TokenData | null;\n} {\n const compressedAccountResult = accountStructWithOptionalTokenData.account;\n const tokenDataResult =\n accountStructWithOptionalTokenData.optionalTokenData;\n\n const compressedAccount: CompressedAccountWithMerkleContext =\n createCompressedAccountWithMerkleContext(\n createMerkleContext(\n compressedAccountResult.merkleTree,\n mockNullifierQueue,\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 = '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 config?: ConnectionConfig,\n): Rpc {\n const endpoint =\n typeof endpointOrWeb3JsConnection === 'string'\n ? endpointOrWeb3JsConnection\n : endpointOrWeb3JsConnection.rpcEndpoint;\n return new Rpc(endpoint, compressionApiEndpoint, proverEndpoint, config);\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 if (convertToCamelCase) {\n const res = await response.json();\n return toCamelCase(res);\n }\n return await response.json();\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}\nimport { LightWasm } from './test-helpers';\nimport { ConnectionInterface } from './connection-interface';\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/// TODO: replace with dynamic nullifierQueue\nconst mockNullifierQueue = defaultTestStateTreeAccounts().nullifierQueue;\nconst mockAddressQueue = defaultTestStateTreeAccounts().addressQueue;\n\n/**\n *\n */\nexport class Rpc\n extends Connection\n implements ConnectionInterface, CompressionApiInterface\n{\n connection: Connection;\n compressionApiEndpoint: string;\n proverEndpoint: string;\n\n /**\n * Establish a Compression-compatible JSON RPC connection\n *\n * @param endpoint Endpoint to the solana cluster\n * @param compressionApiEndpoint Endpoint to the compression server\n * @param proverEndpoint Endpoint to the prover server.\n * @param connectionConfig Optional connection config\n */\n constructor(\n endpoint: string,\n compressionApiEndpoint: string,\n proverEndpoint: string,\n config?: ConnectionConfig,\n ) {\n super(endpoint, config || 'confirmed');\n // super();\n this.connection = new Connection(endpoint, config || 'confirmed');\n this.compressionApiEndpoint = compressionApiEndpoint;\n this.proverEndpoint = proverEndpoint;\n }\n\n get commitment(): Commitment | undefined {\n return this.connection.commitment;\n }\n\n get rpcEndpoint(): string {\n return this.connection.rpcEndpoint;\n }\n\n // === Connection Methods Delegated ===\n\n async getBalanceAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise<RpcResponseAndContext<number>> {\n return this.connection.getBalanceAndContext(\n publicKey,\n commitmentOrConfig,\n );\n }\n\n async getBalance(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetBalanceConfig,\n ): Promise<number> {\n return this.connection.getBalance(publicKey, commitmentOrConfig);\n }\n\n async getBlockTime(slot: number): Promise<number | null> {\n return this.connection.getBlockTime(slot);\n }\n\n async getMinimumLedgerSlot(): Promise<number> {\n return this.connection.getMinimumLedgerSlot();\n }\n\n async getFirstAvailableBlock(): Promise<number> {\n return this.connection.getFirstAvailableBlock();\n }\n\n async getSupply(\n config?: GetSupplyConfig | Commitment,\n ): Promise<RpcResponseAndContext<Supply>> {\n return this.connection.getSupply(config);\n }\n\n async getTokenSupply(\n tokenMintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise<RpcResponseAndContext<TokenAmount>> {\n return this.connection.getTokenSupply(tokenMintAddress, commitment);\n }\n\n async getTokenAccountBalance(\n tokenAddress: PublicKey,\n commitment?: Commitment,\n ): Promise<RpcResponseAndContext<TokenAmount>> {\n return this.connection.getTokenAccountBalance(tokenAddress, commitment);\n }\n\n async getTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitmentOrConfig?: Commitment | GetTokenAccountsByOwnerConfig,\n ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>> {\n return this.connection.getTokenAccountsByOwner(\n ownerAddress,\n filter,\n commitmentOrConfig,\n );\n }\n\n async getParsedTokenAccountsByOwner(\n ownerAddress: PublicKey,\n filter: TokenAccountsFilter,\n commitment?: Commitment,\n ): Promise<\n RpcResponseAndContext<\n Array<{\n pubkey: PublicKey;\n account: AccountInfo<ParsedAccountData>;\n }>\n >\n > {\n return this.connection.getParsedTokenAccountsByOwner(\n ownerAddress,\n filter,\n commitment,\n );\n }\n\n async getLargestAccounts(\n config?: GetLargestAccountsConfig,\n ): Promise<RpcResponseAndContext<Array<AccountBalancePair>>> {\n return this.connection.getLargestAccounts(config);\n }\n\n async getTokenLargestAccounts(\n mintAddress: PublicKey,\n commitment?: Commitment,\n ): Promise<RpcResponseAndContext<Array<TokenAccountBalancePair>>> {\n return this.connection.getTokenLargestAccounts(mintAddress, commitment);\n }\n\n async getAccountInfoAndContext(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise<RpcResponseAndContext<AccountInfo<Buffer> | null>> {\n return this.connection.getAccountInfoAndContext(\n publicKey,\n commitmentOrConfig,\n );\n }\n\n async getParsedAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise<\n RpcResponseAndContext<AccountInfo<Buffer | ParsedAccountData> | null>\n > {\n return this.connection.getParsedAccountInfo(\n publicKey,\n commitmentOrConfig,\n );\n }\n\n async getAccountInfo(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n ): Promise<AccountInfo<Buffer> | null> {\n return this.connection.getAccountInfo(publicKey, commitmentOrConfig);\n }\n\n async getMultipleParsedAccounts(\n publicKeys: PublicKey[],\n rawConfig?: GetMultipleAccountsConfig,\n ): Promise<\n RpcResponseAndContext<\n (AccountInfo<Buffer | ParsedAccountData> | null)[]\n >\n > {\n return this.connection.getMultipleParsedAccounts(publicKeys, rawConfig);\n }\n\n async getMultipleAccountsInfoAndContext(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise<RpcResponseAndContext<(AccountInfo<Buffer> | null)[]>> {\n return this.connection.getMultipleAccountsInfoAndContext(\n publicKeys,\n commitmentOrConfig,\n );\n }\n\n async getMultipleAccountsInfo(\n publicKeys: PublicKey[],\n commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n ): Promise<(AccountInfo<Buffer> | null)[]> {\n return this.connection.getMultipleAccountsInfo(\n publicKeys,\n commitmentOrConfig,\n );\n }\n\n async getStakeActivation(\n publicKey: PublicKey,\n commitmentOrConfig?: Commitment | GetStakeActivationConfig,\n epoch?: number,\n ): Promise<StakeActivationData> {\n return this.connection.getStakeActivation(\n publicKey,\n commitmentOrConfig,\n epoch,\n );\n }\n\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise<GetProgramAccountsResponse>;\n\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment: GetProgramAccountsConfig & { withContext: true },\n ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>>;\n\n async getProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetProgramAccountsConfig | Commitment,\n ): Promise<\n | GetProgramAccountsResponse\n | RpcResponseAndContext<GetProgramAccountsResponse>\n > {\n return this.connection.getProgramAccounts(\n programId,\n configOrCommitment,\n );\n }\n\n async getParsedProgramAccounts(\n programId: PublicKey,\n configOrCommitment?: GetParsedProgramAccountsConfig | Commitment,\n ): Promise<\n Array<{\n pubkey: PublicKey;\n account: AccountInfo<Buffer | ParsedAccountData>;\n }>\n > {\n return this.connection.getParsedProgramAccounts(\n programId,\n configOrCommitment,\n );\n }\n\n // === Subscription Methods ===\n\n // onAccountChange(\n // publicKey: PublicKey,\n // callback: AccountChangeCallback,\n // config?: AccountSubscriptionConfig,\n // ): ClientSubscriptionId {\n // return this.connection.onAccountChange(publicKey, callback, config);\n // }\n\n // async removeAccountChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeAccountChangeListener(\n // clientSubscriptionId,\n // );\n // }\n\n // onProgramAccountChange(\n // programId: PublicKey,\n // callback: ProgramAccountChangeCallback,\n // config?: ProgramAccountSubscriptionConfig,\n // ): ClientSubscriptionId {\n // return this.connection.onProgramAccountChange(\n // programId,\n // callback,\n // config,\n // );\n // }\n\n // async removeProgramAccountChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeProgramAccountChangeListener(\n // clientSubscriptionId,\n // );\n // }\n\n // onLogs(\n // filter: LogsFilter,\n // callback: LogsCallback,\n // commitment?: Commitment,\n // ): ClientSubscriptionId {\n // return this.connection.onLogs(filter, callback, commitment);\n // }\n\n // async removeOnLogsListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeOnLogsListener(clientSubscriptionId);\n // }\n\n // onSlotChange(callback: SlotChangeCallback): ClientSubscriptionId {\n // return this.connection.onSlotChange(callback);\n // }\n\n // async removeSlotChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSlotChangeListener(clientSubscriptionId);\n // }\n\n // onSlotUpdate(callback: SlotUpdateCallback): ClientSubscriptionId {\n // return this.connection.onSlotUpdate(callback);\n // }\n\n // async removeSlotUpdateListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSlotUpdateListener(clientSubscriptionId);\n // }\n\n // onSignature(\n // signature: TransactionSignature,\n // callback: SignatureResultCallback,\n // commitment?: Commitment,\n // ): ClientSubscriptionId {\n // return this.connection.onSignature(signature, callback, commitment);\n // }\n\n // onSignatureWithOptions(\n // signature: TransactionSignature,\n // callback: SignatureSubscriptionCallback,\n // options?: SignatureSubscriptionOptions,\n // ): ClientSubscriptionId {\n // return this.connection.onSignatureWithOptions(\n // signature,\n // callback,\n // options,\n // );\n // }\n\n // async removeSignatureListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSignatureListener(clientSubscriptionId);\n // }\n\n // onRootChange(callback: RootChangeCallback): ClientSubscriptionId {\n // return this.connection.onRootChange(callback);\n // }\n\n // async removeRootChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeRootChangeListener(clientSubscriptionId);\n // }\n\n // // === Transaction Methods ===\n\n // async sendTransaction(\n // transaction: VersionedTransaction,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendTransaction(transaction, options);\n // }\n\n // async sendRawTransaction(\n // rawTransaction: Buffer | Uint8Array | Array<number>,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendRawTransaction(rawTransaction, options);\n // }\n\n // async sendEncodedTransaction(\n // encodedTransaction: string,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendEncodedTransaction(\n // encodedTransaction,\n // options,\n // );\n // }\n\n // async simulateTransaction(\n // transaction: VersionedTransaction,\n // config?: SimulateTransactionConfig,\n // ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {\n // return this.connection.simulateTransaction(transaction, config);\n // }\n\n // async requestAirdrop(\n // to: PublicKey,\n // lamports: number,\n // ): Promise<TransactionSignature> {\n // return this.connection.requestAirdrop(to, lamports);\n // }\n\n // async getStakeMinimumDelegation(\n // config?: GetStakeMinimumDelegationConfig,\n // ): Promise<RpcResponseAndContext<number>> {\n // return this.connection.getStakeMinimumDelegation(config);\n // }\n\n // async getTransactions(\n // signatures: TransactionSignature[],\n // commitmentOrConfig?: GetTransactionConfig | Finality,\n // ): Promise<(VersionedTransactionResponse | null)[]> {\n // return this.connection.getTransactions(signatures, commitmentOrConfig);\n // }\n\n // async getTransaction(\n // signature: string,\n // rawConfig?: GetTransactionConfig,\n // ): Promise<VersionedTransactionResponse | null> {\n // return this.connection.getTransaction(signature, rawConfig);\n // }\n\n // async getParsedTransaction(\n // signature: TransactionSignature,\n // commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n // ): Promise<ParsedTransactionWithMeta | null> {\n // return this.connection.getParsedTransaction(\n // signature,\n // commitmentOrConfig,\n // );\n // }\n\n // async getParsedTransactions(\n // signatures: TransactionSignature[],\n // commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n // ): Promise<(ParsedTransactionWithMeta | null)[]> {\n // return this.connection.getParsedTransactions(\n // signatures,\n // commitmentOrConfig,\n // );\n // }\n\n // async getConfirmedBlock(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<ConfirmedBlock> {\n // return this.connection.getConfirmedBlock(slot, commitment);\n // }\n\n // async getBlocks(\n // startSlot: number,\n // endSlot?: number,\n // commitment?: Finality,\n // ): Promise<Array<number>> {\n // return this.connection.getBlocks(startSlot, endSlot, commitment);\n // }\n\n // async getBlockSignatures(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<BlockSignatures> {\n // return this.connection.getBlockSignatures(slot, commitment);\n // }\n\n // async getConfirmedBlockSignatures(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<BlockSignatures> {\n // return this.connection.getConfirmedBlockSignatures(slot, commitment);\n // }\n\n // confirmTransaction(\n // strategy: TransactionConfirmationStrategy,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n // /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // // eslint-disable-next-line no-dupe-class-members\n // confirmTransaction(\n // strategy: TransactionSignature,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n // async confirmTransaction(\n // strategy: TransactionConfirmationStrategy | TransactionSignature,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>> {\n // // @ts-ignore\n // return this.connection.confirmTransaction(strategy, commitment);\n // }\n\n // // private async getCancellationPromise() {\n // // throw new Error(\n // // 'getCancellationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // // );\n // // }\n // // private async getTransactionConfirmationPromise() {\n // // throw new Error(\n // // 'getTransactionConfirmationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // // );\n // // }\n // // private async confirmTransactionUsingBlockHeightExceedanceStrategy() {\n // // throw new Error(\n // // 'confirmTransactionUsingBlockHeightExceedanceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // // );\n // // }\n // // async confirmTransactionUsingDurableNonceStrategy() {\n // // throw new Error(\n // // 'confirmTransactionUsingDurableNonceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // // );\n // // }\n // // private async confirmTransactionUsingLegacyTimeoutStrategy({\n // // commitment,\n // // signature,\n // // }: {\n // // commitment?: Commitment;\n // // signature: string;\n // // }): Promise<RpcResponseAndContext<SignatureResult>> {\n // // throw new Error(\n // // 'confirmTransactionUsingLegacyTimeoutStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // // );\n // // }\n // // _buildArgs(\n // // args: Array<any>,\n // // override?: Commitment,\n // // encoding?: 'jsonParsed' | 'base64',\n // // extra?: any,\n // // ): Array<any> {\n // // const commitment = override || this.connection.commitment;\n // // if (commitment || encoding || extra) {\n // // let options: any = {};\n // // if (encoding) {\n // // options.encoding = encoding;\n // // }\n // // if (commitment) {\n // // options.commitment = commitment;\n // // }\n // // if (extra) {\n // // options = Object.assign(options, extra);\n // // }\n // // args.push(options);\n // // }\n // // return args;\n // // }\n\n // async getClusterNodes(): Promise<Array<ContactInfo>> {\n // return this.connection.getClusterNodes();\n // }\n\n // async getVoteAccounts(commitment?: Commitment): Promise<VoteAccountStatus> {\n // return this.connection.getVoteAccounts(commitment);\n // }\n\n // async getSlot(\n // commitmentOrConfig?: Commitment | GetSlotConfig,\n // ): Promise<number> {\n // return this.connection.getSlot(commitmentOrConfig);\n // }\n\n // async getSlotLeader(\n // commitmentOrConfig?: Commitment | GetSlotLeaderConfig,\n // ): Promise<string> {\n // return this.connection.getSlotLeader(commitmentOrConfig);\n // }\n\n // async getSlotLeaders(\n // startSlot: number,\n // limit: number,\n // ): Promise<Array<PublicKey>> {\n // return this.connection.getSlotLeaders(startSlot, limit);\n // }\n\n // async getSignatureStatus(\n // signature: TransactionSignature,\n // config?: SignatureStatusConfig,\n // ): Promise<RpcResponseAndContext<SignatureStatus | null>> {\n // return this.connection.getSignatureStatus(signature, config);\n // }\n\n // async getSignatureStatuses(\n // signatures: Array<TransactionSignature>,\n // config?: SignatureStatusConfig,\n // ): Promise<RpcResponseAndContext<Array<SignatureStatus | null>>> {\n // return this.connection.getSignatureStatuses(signatures, config);\n // }\n\n // async getTotalSupply(commitment?: Commitment): Promise<number> {\n // return this.connection.getTotalSupply(commitment);\n // }\n\n // async getBlockHeight(config?: GetBlockHeightConfig): Promise<number> {\n // return this.connection.getBlockHeight(config);\n // }\n\n // async getBlockProduction(\n // configOrCommitment?: GetBlockProductionConfig | Commitment,\n // ): Promise<RpcResponseAndContext<BlockProduction>> {\n // return this.connection.getBlockProduction(configOrCommitment);\n // }\n\n // async getTransactionCount(\n // config?: GetTransactionCountConfig,\n // ): Promise<number> {\n // return this.connection.getTransactionCount(config);\n // }\n\n // async getInflationGovernor(): Promise<InflationGovernor> {\n // return this.connection.getInflationGovernor();\n // }\n\n // async getInflationReward(\n // addresses: PublicKey[],\n // epochs?: number,\n // config?: GetInflationRewardConfig,\n // ): Promise<Array<InflationReward | null>> {\n // return this.connection.getInflationReward(addresses, epochs, config);\n // }\n\n // async getInflationRate(): Promise<InflationRate> {\n // return this.connection.getInflationRate();\n // }\n\n // async getEpochInfo(config?: GetEpochInfoConfig): Promise<EpochInfo> {\n // return this.connection.getEpochInfo(config);\n // }\n\n // async getEpochSchedule(): Promise<EpochSchedule> {\n // return this.connection.getEpochSchedule();\n // }\n\n // async getLeaderSchedule(): Promise<LeaderSchedule> {\n // return this.connection.getLeaderSchedule();\n // }\n\n // async getRecentBlockhashAndContext(commitment?: Commitment): Promise<\n // RpcResponseAndContext<{\n // blockhash: Blockhash;\n // feeCalculator: FeeCalculator;\n // }>\n // > {\n // return this.connection.getRecentBlockhashAndContext(commitment);\n // }\n\n // async getRecentPerformanceSamples(\n // limit?: number,\n // ): Promise<Array<PerfSample>> {\n // return this.connection.getRecentPerformanceSamples(limit);\n // }\n\n // async getFeeCalculatorForBlockhash(\n // blockhash: Blockhash,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<FeeCalculator | null>> {\n // return this.connection.getFeeCalculatorForBlockhash(\n // blockhash,\n // commitment,\n // );\n // }\n\n // async getFeeForMessage(\n // message: VersionedMessage,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<number | null>> {\n // return this.connection.getFeeForMessage(message, commitment);\n // }\n\n // async getMinimumBalanceForRentExemption(\n // dataLength: number,\n // commitment?: Commitment,\n // ): Promise<number> {\n // return this.connection.getMinimumBalanceForRentExemption(\n // dataLength,\n // commitment,\n // );\n // }\n\n // async getRecentBlockhash(\n // commitment?: Commitment,\n // ): Promise<{ blockhash: Blockhash; feeCalculator: FeeCalculator }> {\n // return this.connection.getRecentBlockhash(commitment);\n // }\n\n // async getGenesisHash(): Promise<string> {\n // return this.connection.getGenesisHash();\n // }\n // async getBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<VersionedBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'accounts' },\n // ): Promise<VersionedAccountsModeBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'none' },\n // ): Promise<VersionedNoneModeBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<\n // | VersionedBlockResponse\n // | VersionedAccountsModeBlockResponse\n // | VersionedNoneModeBlockResponse\n // | null\n // > {\n // return this.connection.getBlock(slot, rawConfig);\n // }\n\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<ParsedAccountsModeBlockResponse>;\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & { transactionDetails: 'accounts' },\n ): Promise<ParsedAccountsModeBlockResponse>;\n async getParsedBlock(\n slot: number,\n rawConfig: GetVersionedBlockConfig & { transactionDetails: 'none' },\n ): Promise<ParsedNoneModeBlockResponse>;\n async getParsedBlock(\n slot: number,\n rawConfig?: GetVersionedBlockConfig,\n ): Promise<\n ParsedAccountsModeBlockResponse | ParsedNoneModeBlockResponse | null\n > {\n return this.connection.getParsedBlock(slot, rawConfig);\n }\n\n async getConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise<ConfirmedTransaction | null> {\n return this.connection.getConfirmedTransaction(signature, commitment);\n }\n\n async getParsedConfirmedTransaction(\n signature: TransactionSignature,\n commitment?: Finality,\n ): Promise<ParsedConfirmedTransaction | null> {\n return this.connection.getParsedConfirmedTransaction(\n signature,\n commitment,\n );\n }\n\n async getParsedConfirmedTransactions(\n signatures: TransactionSignature[],\n commitment?: Finality,\n ): Promise<(ParsedConfirmedTransaction | null)[]> {\n return this.connection.getParsedConfirmedTransactions(\n signatures,\n commitment,\n );\n }\n\n async getConfirmedSignaturesForAddress(\n address: PublicKey,\n startSlot: number,\n endSlot: number,\n ): Promise<Array<TransactionSignature>> {\n return this.connection.getConfirmedSignaturesForAddress(\n address,\n startSlot,\n endSlot,\n );\n }\n\n async getConfirmedSignaturesForAddress2(\n address: PublicKey,\n options?: ConfirmedSignaturesForAddress2Options,\n commitment?: Finality,\n ): Promise<Array<ConfirmedSignatureInfo>> {\n return this.connection.getConfirmedSignaturesForAddress2(\n address,\n options,\n commitment,\n );\n }\n\n async getSignaturesForAddress(\n address: PublicKey,\n options?: SignaturesForAddressOptions,\n commitment?: Finality,\n ): Promise<Array<ConfirmedSignatureInfo>> {\n return this.connection.getSignaturesForAddress(\n address,\n options,\n commitment,\n );\n }\n\n async getRecentPrioritizationFees(\n config?: GetRecentPrioritizationFeesConfig,\n ): Promise<RecentPrioritizationFees[]> {\n return this.connection.getRecentPrioritizationFees(config);\n }\n\n async getLatestBlockhash(\n config?: GetLatestBlockhashConfig,\n ): Promise<BlockhashWithExpiryBlockHeight> {\n return this.connection.getLatestBlockhash(config);\n }\n async getLatestBlockhashAndContext(\n commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n ): Promise<RpcResponseAndContext<BlockhashWithExpiryBlockHeight>> {\n return this.connection.getLatestBlockhashAndContext(commitmentOrConfig);\n }\n\n async isBlockhashValid(\n blockhash: Blockhash,\n config?: IsBlockhashValidConfig,\n ): Promise<RpcResponseAndContext<boolean>> {\n return this.connection.isBlockhashValid(blockhash, config);\n }\n\n async getVersion(): Promise<Version> {\n return this.connection.getVersion();\n }\n\n async getAddressLookupTable(\n accountKey: PublicKey,\n config?: GetAccountInfoConfig,\n ): Promise<RpcResponseAndContext<AddressLookupTableAccount | null>> {\n return this.connection.getAddressLookupTable(accountKey, config);\n }\n\n async getNonceAndContext(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceAndContextConfig,\n ): Promise<RpcResponseAndContext<NonceAccount | null>> {\n return this.connection.getNonceAndContext(\n nonceAccount,\n commitmentOrConfig,\n );\n }\n\n async getNonce(\n nonceAccount: PublicKey,\n commitmentOrConfig?: Commitment | GetNonceConfig,\n ): Promise<NonceAccount | null> {\n return this.connection.getNonce(nonceAccount, commitmentOrConfig);\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 const item = res.result.value;\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n mockNullifierQueue,\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\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: mockNullifierQueue, // 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 accounts: CompressedAccountWithMerkleContext[] = [];\n res.result.value.items.map(item => {\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n mockNullifierQueue,\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 for (const proof of res.result.value) {\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: mockAddressQueue, // TODO(photon): support nullifierQueue in response.\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\n res.result.value.items.map(item => {\n const account = createCompressedAccountWithMerkleContext(\n createMerkleContext(\n item.tree!,\n mockNullifierQueue,\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 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 res.result.compressionInfo.closedAccounts.map(item => {\n closedAccounts.push(buildCompressedAccountWithMaybeTokenData(item));\n });\n res.result.compressionInfo.openedAccounts.map(item => {\n openedAccounts.push(buildCompressedAccountWithMaybeTokenData(item));\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: mockAddressQueue,\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 * 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 defaultAddressTreePublicKey =\n defaultTestStateTreeAccounts().addressTree;\n const defaultAddressQueuePublicKey =\n defaultTestStateTreeAccounts().addressQueue;\n const defaultStateTreePublicKey =\n defaultTestStateTreeAccounts().merkleTree;\n const defaultStateQueuePublicKey =\n defaultTestStateTreeAccounts().nullifierQueue;\n const formattedHashes = hashes.map(item => {\n return {\n hash: item,\n tree: defaultStateTreePublicKey,\n queue: defaultStateQueuePublicKey,\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 { 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 ParsedMessageAccount,\n ParsedTransactionWithMeta,\n} from '@solana/web3.js';\nimport bs58 from 'bs58';\nimport { defaultStaticAccountsStruct } from '../../constants';\nimport { LightSystemProgram } from '../../programs';\nimport { Rpc } from '../../rpc';\nimport { PublicTransactionEvent } from '../../state';\nimport { decodePublicTransactionEvent } from '../../programs/layout';\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 { noopProgram, accountCompressionProgram } =\n defaultStaticAccountsStruct();\n\n /// Get raw transactions\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 /// 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 /// Parse events\n const parsedEvents = parseEvents(\n transactionEvents,\n parsePublicTransactionEventWithIdl,\n );\n\n return parsedEvents;\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","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\n const compressedTokenAccounts = await getCompressedTokenAccounts(events);\n\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 {\n Connection,\n ConnectionConfig,\n Commitment,\n PublicKey,\n Transaction,\n VersionedTransaction,\n SendOptions,\n BlockhashWithExpiryBlockHeight,\n RpcResponseAndContext,\n GetBalanceConfig,\n GetSupplyConfig,\n Supply,\n GetTokenAccountsByOwnerConfig,\n GetProgramAccountsResponse,\n TokenAccountsFilter,\n AccountInfo,\n GetMultipleAccountsConfig,\n StakeActivationData,\n GetStakeActivationConfig,\n TransactionConfirmationStrategy,\n SignatureResult,\n ContactInfo,\n VoteAccountStatus,\n GetSlotConfig,\n GetSlotLeaderConfig,\n SignatureStatusConfig,\n SignatureStatus,\n GetTransactionCountConfig,\n InflationGovernor,\n GetInflationRewardConfig,\n InflationReward,\n InflationRate,\n EpochInfo,\n GetEpochInfoConfig,\n EpochSchedule,\n LeaderSchedule,\n FeeCalculator,\n GetRecentPrioritizationFeesConfig,\n RecentPrioritizationFees,\n GetLatestBlockhashConfig,\n Version,\n TransactionResponse,\n VersionedTransactionResponse,\n ParsedTransactionWithMeta,\n ParsedConfirmedTransaction,\n SimulateTransactionConfig,\n SimulatedTransactionResponse,\n Message,\n Signer,\n AccountChangeCallback,\n AccountSubscriptionConfig,\n ProgramAccountChangeCallback,\n ProgramAccountSubscriptionConfig,\n LogsFilter,\n LogsCallback,\n SlotChangeCallback,\n SlotUpdateCallback,\n SignatureResultCallback,\n SignatureSubscriptionCallback,\n SignatureSubscriptionOptions,\n RootChangeCallback,\n ConfirmOptions,\n GetMultipleAccountsConfig as OriginalGetMultipleAccountsConfig,\n GetAccountInfoConfig,\n GetLargestAccountsConfig,\n TokenAccountBalancePair,\n AccountBalancePair,\n ParsedAccountData,\n SimulateTransactionConfig as OriginalSimulateTransactionConfig,\n SimulatedTransactionResponse as OriginalSimulatedTransactionResponse,\n SignatureSubscriptionOptions as OriginalSignatureSubscriptionOptions,\n Finality,\n GetTransactionConfig,\n GetVersionedTransactionConfig,\n ConfirmedBlock,\n BlockProduction,\n TransactionSignature,\n BlockSignatures,\n ConfirmedSignatureInfo,\n AddressLookupTableAccount,\n GetBlockHeightConfig,\n GetBlockProductionConfig,\n ParsedNoneModeBlockResponse,\n SolanaJSONRPCError,\n TokenAmount,\n GetStakeMinimumDelegationConfig,\n GetNonceAndContextConfig,\n NonceAccount,\n GetNonceConfig,\n IsBlockhashValidConfig,\n Blockhash,\n GetProgramAccountsConfig,\n GetParsedProgramAccountsConfig,\n VersionedMessage,\n VersionedNoneModeBlockResponse,\n VersionedBlockResponse,\n GetVersionedBlockConfig,\n VersionedAccountsModeBlockResponse,\n ParsedAccountsModeBlockResponse,\n SignaturesForAddressOptions,\n ConfirmedSignaturesForAddress2Options,\n ConfirmedTransaction,\n PerfSample,\n} 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 { defaultTestStateTreeAccounts } 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 BaseRpc,\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 Rpc,\n convertMerkleProofsWithContextToHex,\n convertNonInclusionMerkleProofInputsToHex,\n proverRequest,\n} from '../../rpc';\nimport { ConnectionInterface } from '../../connection-interface';\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 ) as unknown as Rpc;\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 connection: Connection;\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\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.connection = new Connection(\n endpoint,\n 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 // get commitment(): Commitment | undefined {\n // return this.connection.commitment;\n // }\n\n // get rpcEndpoint(): string {\n // return this.connection.rpcEndpoint;\n // }\n\n // // === Connection Methods Delegated ===\n\n // async getBalanceAndContext(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetBalanceConfig,\n // ): Promise<RpcResponseAndContext<number>> {\n // return this.connection.getBalanceAndContext(\n // publicKey,\n // commitmentOrConfig,\n // );\n // }\n\n // async getBalance(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetBalanceConfig,\n // ): Promise<number> {\n // return this.connection.getBalance(publicKey, commitmentOrConfig);\n // }\n\n // async getBlockTime(slot: number): Promise<number | null> {\n // return this.connection.getBlockTime(slot);\n // }\n\n // async getMinimumLedgerSlot(): Promise<number> {\n // return this.connection.getMinimumLedgerSlot();\n // }\n\n // async getFirstAvailableBlock(): Promise<number> {\n // return this.connection.getFirstAvailableBlock();\n // }\n\n // async getSupply(\n // config?: GetSupplyConfig | Commitment,\n // ): Promise<RpcResponseAndContext<Supply>> {\n // return this.connection.getSupply(config);\n // }\n\n // async getTokenSupply(\n // tokenMintAddress: PublicKey,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<TokenAmount>> {\n // return this.connection.getTokenSupply(tokenMintAddress, commitment);\n // }\n\n // async getTokenAccountBalance(\n // tokenAddress: PublicKey,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<TokenAmount>> {\n // return this.connection.getTokenAccountBalance(tokenAddress, commitment);\n // }\n\n // async getTokenAccountsByOwner(\n // ownerAddress: PublicKey,\n // filter: TokenAccountsFilter,\n // commitmentOrConfig?: Commitment | GetTokenAccountsByOwnerConfig,\n // ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>> {\n // return this.connection.getTokenAccountsByOwner(\n // ownerAddress,\n // filter,\n // commitmentOrConfig,\n // );\n // }\n\n // async getParsedTokenAccountsByOwner(\n // ownerAddress: PublicKey,\n // filter: TokenAccountsFilter,\n // commitment?: Commitment,\n // ): Promise<\n // RpcResponseAndContext<\n // Array<{\n // pubkey: PublicKey;\n // account: AccountInfo<ParsedAccountData>;\n // }>\n // >\n // > {\n // return this.connection.getParsedTokenAccountsByOwner(\n // ownerAddress,\n // filter,\n // commitment,\n // );\n // }\n\n // async getLargestAccounts(\n // config?: GetLargestAccountsConfig,\n // ): Promise<RpcResponseAndContext<Array<AccountBalancePair>>> {\n // return this.connection.getLargestAccounts(config);\n // }\n\n // async getTokenLargestAccounts(\n // mintAddress: PublicKey,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<Array<TokenAccountBalancePair>>> {\n // return this.connection.getTokenLargestAccounts(mintAddress, commitment);\n // }\n\n // async getAccountInfoAndContext(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n // ): Promise<RpcResponseAndContext<AccountInfo<Buffer> | null>> {\n // return this.connection.getAccountInfoAndContext(\n // publicKey,\n // commitmentOrConfig,\n // );\n // }\n\n // async getParsedAccountInfo(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n // ): Promise<\n // RpcResponseAndContext<AccountInfo<Buffer | ParsedAccountData> | null>\n // > {\n // return this.connection.getParsedAccountInfo(\n // publicKey,\n // commitmentOrConfig,\n // );\n // }\n\n // async getAccountInfo(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetAccountInfoConfig,\n // ): Promise<AccountInfo<Buffer> | null> {\n // return this.connection.getAccountInfo(publicKey, commitmentOrConfig);\n // }\n\n // async getMultipleParsedAccounts(\n // publicKeys: PublicKey[],\n // rawConfig?: GetMultipleAccountsConfig,\n // ): Promise<\n // RpcResponseAndContext<\n // (AccountInfo<Buffer | ParsedAccountData> | null)[]\n // >\n // > {\n // return this.connection.getMultipleParsedAccounts(publicKeys, rawConfig);\n // }\n\n // async getMultipleAccountsInfoAndContext(\n // publicKeys: PublicKey[],\n // commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n // ): Promise<RpcResponseAndContext<(AccountInfo<Buffer> | null)[]>> {\n // return this.connection.getMultipleAccountsInfoAndContext(\n // publicKeys,\n // commitmentOrConfig,\n // );\n // }\n\n // async getMultipleAccountsInfo(\n // publicKeys: PublicKey[],\n // commitmentOrConfig?: Commitment | GetMultipleAccountsConfig,\n // ): Promise<(AccountInfo<Buffer> | null)[]> {\n // return this.connection.getMultipleAccountsInfo(\n // publicKeys,\n // commitmentOrConfig,\n // );\n // }\n\n // async getStakeActivation(\n // publicKey: PublicKey,\n // commitmentOrConfig?: Commitment | GetStakeActivationConfig,\n // epoch?: number,\n // ): Promise<StakeActivationData> {\n // return this.connection.getStakeActivation(\n // publicKey,\n // commitmentOrConfig,\n // epoch,\n // );\n // }\n\n // async getProgramAccounts(\n // programId: PublicKey,\n // configOrCommitment?: GetProgramAccountsConfig | Commitment,\n // ): Promise<GetProgramAccountsResponse>;\n\n // async getProgramAccounts(\n // programId: PublicKey,\n // configOrCommitment: GetProgramAccountsConfig & { withContext: true },\n // ): Promise<RpcResponseAndContext<GetProgramAccountsResponse>>;\n\n // async getProgramAccounts(\n // programId: PublicKey,\n // configOrCommitment?: GetProgramAccountsConfig | Commitment,\n // ): Promise<\n // | GetProgramAccountsResponse\n // | RpcResponseAndContext<GetProgramAccountsResponse>\n // > {\n // return this.connection.getProgramAccounts(\n // programId,\n // configOrCommitment,\n // );\n // }\n\n // async getParsedProgramAccounts(\n // programId: PublicKey,\n // configOrCommitment?: GetParsedProgramAccountsConfig | Commitment,\n // ): Promise<\n // Array<{\n // pubkey: PublicKey;\n // account: AccountInfo<Buffer | ParsedAccountData>;\n // }>\n // > {\n // return this.connection.getParsedProgramAccounts(\n // programId,\n // configOrCommitment,\n // );\n // }\n\n // // === Subscription Methods ===\n\n // onAccountChange(\n // publicKey: PublicKey,\n // callback: AccountChangeCallback,\n // config?: AccountSubscriptionConfig,\n // ): ClientSubscriptionId {\n // return this.connection.onAccountChange(publicKey, callback, config);\n // }\n\n // async removeAccountChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeAccountChangeListener(\n // clientSubscriptionId,\n // );\n // }\n\n // onProgramAccountChange(\n // programId: PublicKey,\n // callback: ProgramAccountChangeCallback,\n // config?: ProgramAccountSubscriptionConfig,\n // ): ClientSubscriptionId {\n // return this.connection.onProgramAccountChange(\n // programId,\n // callback,\n // config,\n // );\n // }\n\n // async removeProgramAccountChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeProgramAccountChangeListener(\n // clientSubscriptionId,\n // );\n // }\n\n // onLogs(\n // filter: LogsFilter,\n // callback: LogsCallback,\n // commitment?: Commitment,\n // ): ClientSubscriptionId {\n // return this.connection.onLogs(filter, callback, commitment);\n // }\n\n // async removeOnLogsListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeOnLogsListener(clientSubscriptionId);\n // }\n\n // onSlotChange(callback: SlotChangeCallback): ClientSubscriptionId {\n // return this.connection.onSlotChange(callback);\n // }\n\n // async removeSlotChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSlotChangeListener(clientSubscriptionId);\n // }\n\n // onSlotUpdate(callback: SlotUpdateCallback): ClientSubscriptionId {\n // return this.connection.onSlotUpdate(callback);\n // }\n\n // async removeSlotUpdateListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSlotUpdateListener(clientSubscriptionId);\n // }\n\n // onSignature(\n // signature: TransactionSignature,\n // callback: SignatureResultCallback,\n // commitment?: Commitment,\n // ): ClientSubscriptionId {\n // return this.connection.onSignature(signature, callback, commitment);\n // }\n\n // onSignatureWithOptions(\n // signature: TransactionSignature,\n // callback: SignatureSubscriptionCallback,\n // options?: SignatureSubscriptionOptions,\n // ): ClientSubscriptionId {\n // return this.connection.onSignatureWithOptions(\n // signature,\n // callback,\n // options,\n // );\n // }\n\n // async removeSignatureListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeSignatureListener(clientSubscriptionId);\n // }\n\n // onRootChange(callback: RootChangeCallback): ClientSubscriptionId {\n // return this.connection.onRootChange(callback);\n // }\n\n // async removeRootChangeListener(\n // clientSubscriptionId: ClientSubscriptionId,\n // ): Promise<void> {\n // return this.connection.removeRootChangeListener(clientSubscriptionId);\n // }\n\n // // === Transaction Methods ===\n\n // async sendTransaction(\n // transaction: VersionedTransaction,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendTransaction(transaction, options);\n // }\n\n // async sendRawTransaction(\n // rawTransaction: Buffer | Uint8Array | Array<number>,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendRawTransaction(rawTransaction, options);\n // }\n\n // async sendEncodedTransaction(\n // encodedTransaction: string,\n // options?: SendOptions,\n // ): Promise<TransactionSignature> {\n // return this.connection.sendEncodedTransaction(\n // encodedTransaction,\n // options,\n // );\n // }\n\n // async simulateTransaction(\n // transaction: VersionedTransaction,\n // config?: SimulateTransactionConfig,\n // ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> {\n // return this.connection.simulateTransaction(transaction, config);\n // }\n\n // async requestAirdrop(\n // to: PublicKey,\n // lamports: number,\n // ): Promise<TransactionSignature> {\n // return this.connection.requestAirdrop(to, lamports);\n // }\n\n // async getStakeMinimumDelegation(\n // config?: GetStakeMinimumDelegationConfig,\n // ): Promise<RpcResponseAndContext<number>> {\n // return this.connection.getStakeMinimumDelegation(config);\n // }\n\n // async getTransactions(\n // signatures: TransactionSignature[],\n // commitmentOrConfig?: GetTransactionConfig | Finality,\n // ): Promise<(VersionedTransactionResponse | null)[]> {\n // return this.connection.getTransactions(signatures, commitmentOrConfig);\n // }\n\n // async getTransaction(\n // signature: string,\n // rawConfig?: GetTransactionConfig,\n // ): Promise<VersionedTransactionResponse | null> {\n // return this.connection.getTransaction(signature, rawConfig);\n // }\n\n // async getParsedTransaction(\n // signature: TransactionSignature,\n // commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n // ): Promise<ParsedTransactionWithMeta | null> {\n // return this.connection.getParsedTransaction(\n // signature,\n // commitmentOrConfig,\n // );\n // }\n\n // async getParsedTransactions(\n // signatures: TransactionSignature[],\n // commitmentOrConfig?: GetVersionedTransactionConfig | Finality,\n // ): Promise<(ParsedTransactionWithMeta | null)[]> {\n // return this.connection.getParsedTransactions(\n // signatures,\n // commitmentOrConfig,\n // );\n // }\n\n // async getConfirmedBlock(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<ConfirmedBlock> {\n // return this.connection.getConfirmedBlock(slot, commitment);\n // }\n\n // async getBlocks(\n // startSlot: number,\n // endSlot?: number,\n // commitment?: Finality,\n // ): Promise<Array<number>> {\n // return this.connection.getBlocks(startSlot, endSlot, commitment);\n // }\n\n // async getBlockSignatures(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<BlockSignatures> {\n // return this.connection.getBlockSignatures(slot, commitment);\n // }\n\n // async getConfirmedBlockSignatures(\n // slot: number,\n // commitment?: Finality,\n // ): Promise<BlockSignatures> {\n // return this.connection.getConfirmedBlockSignatures(slot, commitment);\n // }\n\n // confirmTransaction(\n // strategy: TransactionConfirmationStrategy,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n // /** @deprecated Instead, call `confirmTransaction` and pass in {@link TransactionConfirmationStrategy} */\n // // eslint-disable-next-line no-dupe-class-members\n // confirmTransaction(\n // strategy: TransactionSignature,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>>;\n\n // async confirmTransaction(\n // strategy: TransactionConfirmationStrategy | TransactionSignature,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<SignatureResult>> {\n // // @ts-ignore\n // return this.connection.confirmTransaction(strategy, commitment);\n // }\n\n // async getClusterNodes(): Promise<Array<ContactInfo>> {\n // return this.connection.getClusterNodes();\n // }\n\n // async getVoteAccounts(commitment?: Commitment): Promise<VoteAccountStatus> {\n // return this.connection.getVoteAccounts(commitment);\n // }\n\n // async getSlot(\n // commitmentOrConfig?: Commitment | GetSlotConfig,\n // ): Promise<number> {\n // return this.connection.getSlot(commitmentOrConfig);\n // }\n\n // async getSlotLeader(\n // commitmentOrConfig?: Commitment | GetSlotLeaderConfig,\n // ): Promise<string> {\n // return this.connection.getSlotLeader(commitmentOrConfig);\n // }\n\n // async getSlotLeaders(\n // startSlot: number,\n // limit: number,\n // ): Promise<Array<PublicKey>> {\n // return this.connection.getSlotLeaders(startSlot, limit);\n // }\n\n // async getSignatureStatus(\n // signature: TransactionSignature,\n // config?: SignatureStatusConfig,\n // ): Promise<RpcResponseAndContext<SignatureStatus | null>> {\n // return this.connection.getSignatureStatus(signature, config);\n // }\n\n // async getSignatureStatuses(\n // signatures: Array<TransactionSignature>,\n // config?: SignatureStatusConfig,\n // ): Promise<RpcResponseAndContext<Array<SignatureStatus | null>>> {\n // return this.connection.getSignatureStatuses(signatures, config);\n // }\n\n // async getTotalSupply(commitment?: Commitment): Promise<number> {\n // return this.connection.getTotalSupply(commitment);\n // }\n\n // async getBlockHeight(config?: GetBlockHeightConfig): Promise<number> {\n // return this.connection.getBlockHeight(config);\n // }\n\n // async getBlockProduction(\n // configOrCommitment?: GetBlockProductionConfig | Commitment,\n // ): Promise<RpcResponseAndContext<BlockProduction>> {\n // return this.connection.getBlockProduction(configOrCommitment);\n // }\n\n // async getTransactionCount(\n // config?: GetTransactionCountConfig,\n // ): Promise<number> {\n // return this.connection.getTransactionCount(config);\n // }\n\n // async getInflationGovernor(): Promise<InflationGovernor> {\n // return this.connection.getInflationGovernor();\n // }\n\n // async getInflationReward(\n // addresses: PublicKey[],\n // epochs?: number,\n // config?: GetInflationRewardConfig,\n // ): Promise<Array<InflationReward | null>> {\n // return this.connection.getInflationReward(addresses, epochs, config);\n // }\n\n // async getInflationRate(): Promise<InflationRate> {\n // return this.connection.getInflationRate();\n // }\n\n // async getEpochInfo(config?: GetEpochInfoConfig): Promise<EpochInfo> {\n // return this.connection.getEpochInfo(config);\n // }\n\n // async getEpochSchedule(): Promise<EpochSchedule> {\n // return this.connection.getEpochSchedule();\n // }\n\n // async getLeaderSchedule(): Promise<LeaderSchedule> {\n // return this.connection.getLeaderSchedule();\n // }\n\n // async getRecentBlockhashAndContext(commitment?: Commitment): Promise<\n // RpcResponseAndContext<{\n // blockhash: Blockhash;\n // feeCalculator: FeeCalculator;\n // }>\n // > {\n // return this.connection.getRecentBlockhashAndContext(commitment);\n // }\n\n // async getRecentPerformanceSamples(\n // limit?: number,\n // ): Promise<Array<PerfSample>> {\n // return this.connection.getRecentPerformanceSamples(limit);\n // }\n\n // async getFeeCalculatorForBlockhash(\n // blockhash: Blockhash,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<FeeCalculator | null>> {\n // return this.connection.getFeeCalculatorForBlockhash(\n // blockhash,\n // commitment,\n // );\n // }\n\n // async getFeeForMessage(\n // message: VersionedMessage,\n // commitment?: Commitment,\n // ): Promise<RpcResponseAndContext<number | null>> {\n // return this.connection.getFeeForMessage(message, commitment);\n // }\n\n // async getMinimumBalanceForRentExemption(\n // dataLength: number,\n // commitment?: Commitment,\n // ): Promise<number> {\n // return this.connection.getMinimumBalanceForRentExemption(\n // dataLength,\n // commitment,\n // );\n // }\n\n // async getRecentBlockhash(\n // commitment?: Commitment,\n // ): Promise<{ blockhash: Blockhash; feeCalculator: FeeCalculator }> {\n // return this.connection.getRecentBlockhash(commitment);\n // }\n\n // async getGenesisHash(): Promise<string> {\n // return this.connection.getGenesisHash();\n // }\n // async getBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<VersionedBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'accounts' },\n // ): Promise<VersionedAccountsModeBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'none' },\n // ): Promise<VersionedNoneModeBlockResponse | null>;\n // async getBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<\n // | VersionedBlockResponse\n // | VersionedAccountsModeBlockResponse\n // | VersionedNoneModeBlockResponse\n // | null\n // > {\n // return this.connection.getBlock(slot, rawConfig);\n // }\n\n // async getParsedBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<ParsedAccountsModeBlockResponse>;\n // async getParsedBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'accounts' },\n // ): Promise<ParsedAccountsModeBlockResponse>;\n // async getParsedBlock(\n // slot: number,\n // rawConfig: GetVersionedBlockConfig & { transactionDetails: 'none' },\n // ): Promise<ParsedNoneModeBlockResponse>;\n // async getParsedBlock(\n // slot: number,\n // rawConfig?: GetVersionedBlockConfig,\n // ): Promise<\n // ParsedAccountsModeBlockResponse | ParsedNoneModeBlockResponse | null\n // > {\n // return this.connection.getParsedBlock(slot, rawConfig);\n // }\n\n // async getConfirmedTransaction(\n // signature: TransactionSignature,\n // commitment?: Finality,\n // ): Promise<ConfirmedTransaction | null> {\n // return this.connection.getConfirmedTransaction(signature, commitment);\n // }\n\n // async getParsedConfirmedTransaction(\n // signature: TransactionSignature,\n // commitment?: Finality,\n // ): Promise<ParsedConfirmedTransaction | null> {\n // return this.connection.getParsedConfirmedTransaction(\n // signature,\n // commitment,\n // );\n // }\n\n // async getParsedConfirmedTransactions(\n // signatures: TransactionSignature[],\n // commitment?: Finality,\n // ): Promise<(ParsedConfirmedTransaction | null)[]> {\n // return this.connection.getParsedConfirmedTransactions(\n // signatures,\n // commitment,\n // );\n // }\n\n // async getConfirmedSignaturesForAddress(\n // address: PublicKey,\n // startSlot: number,\n // endSlot: number,\n // ): Promise<Array<TransactionSignature>> {\n // return this.connection.getConfirmedSignaturesForAddress(\n // address,\n // startSlot,\n // endSlot,\n // );\n // }\n\n // async getConfirmedSignaturesForAddress2(\n // address: PublicKey,\n // options?: ConfirmedSignaturesForAddress2Options,\n // commitment?: Finality,\n // ): Promise<Array<ConfirmedSignatureInfo>> {\n // return this.connection.getConfirmedSignaturesForAddress2(\n // address,\n // options,\n // commitment,\n // );\n // }\n\n // async getSignaturesForAddress(\n // address: PublicKey,\n // options?: SignaturesForAddressOptions,\n // commitment?: Finality,\n // ): Promise<Array<ConfirmedSignatureInfo>> {\n // return this.connection.getSignaturesForAddress(\n // address,\n // options,\n // commitment,\n // );\n // }\n\n // async getRecentPrioritizationFees(\n // config?: GetRecentPrioritizationFeesConfig,\n // ): Promise<RecentPrioritizationFees[]> {\n // return this.connection.getRecentPrioritizationFees(config);\n // }\n\n // async getLatestBlockhash(\n // config?: GetLatestBlockhashConfig,\n // ): Promise<BlockhashWithExpiryBlockHeight> {\n // return this.connection.getLatestBlockhash(config);\n // }\n // async getLatestBlockhashAndContext(\n // commitmentOrConfig?: Commitment | GetLatestBlockhashConfig,\n // ): Promise<RpcResponseAndContext<BlockhashWithExpiryBlockHeight>> {\n // return this.connection.getLatestBlockhashAndContext(commitmentOrConfig);\n // }\n\n // async isBlockhashValid(\n // blockhash: Blockhash,\n // config?: IsBlockhashValidConfig,\n // ): Promise<RpcResponseAndContext<boolean>> {\n // return this.connection.isBlockhashValid(blockhash, config);\n // }\n\n // async getVersion(): Promise<Version> {\n // return this.connection.getVersion();\n // }\n\n // async getAddressLookupTable(\n // accountKey: PublicKey,\n // config?: GetAccountInfoConfig,\n // ): Promise<RpcResponseAndContext<AddressLookupTableAccount | null>> {\n // return this.connection.getAddressLookupTable(accountKey, config);\n // }\n\n // async getNonceAndContext(\n // nonceAccount: PublicKey,\n // commitmentOrConfig?: Commitment | GetNonceAndContextConfig,\n // ): Promise<RpcResponseAndContext<NonceAccount | null>> {\n // return this.connection.getNonceAndContext(\n // nonceAccount,\n // commitmentOrConfig,\n // );\n // }\n\n // async getNonce(\n // nonceAccount: PublicKey,\n // commitmentOrConfig?: Commitment | GetNonceConfig,\n // ): Promise<NonceAccount | null> {\n // return this.connection.getNonce(nonceAccount, commitmentOrConfig);\n // }\n\n // _buildArgs(\n // args: Array<any>,\n // override?: Commitment,\n // encoding?: 'jsonParsed' | 'base64',\n // extra?: any,\n // ): Array<any> {\n // const commitment = override || this.connection.commitment;\n // if (commitment || encoding || extra) {\n // let options: any = {};\n // if (encoding) {\n // options.encoding = encoding;\n // }\n // if (commitment) {\n // options.commitment = commitment;\n // }\n // if (extra) {\n // options = Object.assign(options, extra);\n // }\n // args.push(options);\n // }\n // return args;\n // }\n\n // private async getCancellationPromise() {\n // throw new Error(\n // 'getCancellationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // );\n // }\n // private async getTransactionConfirmationPromise() {\n // throw new Error(\n // 'getTransactionConfirmationPromise not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // );\n // }\n // private async confirmTransactionUsingBlockHeightExceedanceStrategy() {\n // throw new Error(\n // 'confirmTransactionUsingBlockHeightExceedanceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // );\n // }\n // async confirmTransactionUsingDurableNonceStrategy() {\n // throw new Error(\n // 'confirmTransactionUsingDurableNonceStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // );\n // }\n // private async confirmTransactionUsingLegacyTimeoutStrategy({\n // commitment,\n // signature,\n // }: {\n // commitment?: Commitment;\n // signature: string;\n // }): Promise<RpcResponseAndContext<SignatureResult>> {\n // throw new Error(\n // 'confirmTransactionUsingLegacyTimeoutStrategy not supported in rpc. it is a stub that is marked as private in web3.js Connection',\n // );\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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 // @ts-ignore\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"],"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","FIELD_SIZE","HIGHEST_ADDRESS_PLUS_ONE","noopProgram","lightProgram","accountCompressionProgram","getRegisteredProgramPda","PublicKey","getAccountCompressionAuthority","findProgramAddressSync","from","defaultStaticAccounts","defaultStaticAccountsStruct","registeredProgramPda","accountCompressionAuthority","cpiSignatureAccount","defaultTestStateTreeAccounts","nullifierQueue","nullifierQueuePubkey","merkleTree","merkletreePubkey","merkleTreeHeight","DEFAULT_MERKLE_TREE_HEIGHT","addressTree","addressQueue","confirmConfig","commitment","preflightCommitment","DEFAULT_MERKLE_TREE_ROOTS","UTXO_MERGE_THRESHOLD","UTXO_MERGE_MAXIMUM","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","readOnly","createMerkleContext","hash","leafIndex","Number","isSafeInteger","bytes","lengths","includes","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","byteArrayToKeypair","byteArray","Keypair","fromSecretKey","toHex","value","bufToDecStr","buf","isSmallerThanBn254FieldSizeBe","hashToBn254FieldSizeBe","bumpSeed","inputWithBumpSeed","concat","hashvToBn254FieldSizeBe","hasher","pushUniqueItems","items","map","forEach","item","toCamelCase","obj","v","Object","keys","reduce","result","key","$1","toUpperCase","vitest","it","expect","describe","toEqual","toBe","reverse","refResult","async","not","toBeNull","toBeInstanceOf","toBeLessThanOrEqual","test_key","testKey","anotherTestKey","array_key","arrayKey","anotherArrayKey","getIndexOrAdd","accountsArray","findIndex","existingKey","equals","padOutputStateMerkleTrees","outputStateMerkleTrees","numberOfOutputCompressedAccounts","inputCompressedAccountsWithMerkleContext","treesArray","slice","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","deriveAddressSeed","seeds","programId","deriveAddress","seed","addressMerkleTreePubkey","packNewAddressParams","newAddressParams","newAddressParamsPacked","addressMerkleTreeRootIndex","addressMerkleTreeAccountIndex","addressQueueAccountIndex","params","addressQueuePubkey","toStrictEqual","derivedAddress","packedParams","airdropSol","connection","recipientPublicKey","txHash","requestAirdrop","confirmTransaction","signature","confirmation","latestBlockHash","getLatestBlockhash","strategy","lastValidBlockHeight","blockhash","placeholderValidityProof","_","checkValidityProofShape","proof","proofFromJsonStruct","json","proofAX","deserializeHexStringToBeBytes","ar","proofAY","proofA","proofBX0","bs","proofBX1","proofBY0","proofBY1","proofB","proofCX","krs","proofCY","negateAndCompressProof","proofC","aXElement","proofAIsPositive","yElementIsPositiveG1","addBitmaskToByte","bXElement","bYElement","proofBIsPositive","yElement1","yElement2","fieldMidpoint","yElementIsPositiveG2","cXElement","cYElement","proofCIsPositive","hexStr","startsWith","substring","yElement","byte","yIsPositive","TEST_JSON","COMPRESSED_PROOF_A","COMPRESSED_PROOF_B","COMPRESSED_PROOF_C","compressedProof","validityProof","validProof","toThrow","invalidProof","pipe","initialFunction","functions","initialValue","currentValue","currentFunction","addOneMultiplyByTwoSubtractThree","buildTx","instructions","payerPublicKey","lookupTableAccounts","messageV0","TransactionMessage","payerKey","recentBlockhash","compileToV0Message","VersionedTransaction","sendAndConfirmTx","rpc","tx","confirmOptions","blockHashCtx","txId","sendTransaction","transactionConfirmationStrategy0","slot","context","confirmTransactionIndexed","confirmTx","transactionConfirmationStrategy","buildAndSignTx","payer","additionalSigners","allSigners","publicKey","sign","sleep","ms","Promise","resolve","setTimeout","ALICE","getTestKeypair","BOB","CHARLIE","DAVE","newAccountWithLamports","counter","sig","getConnection","Connection","generate","fromSeed","keypair","keypair2","toBeDefined","secretKey","testFn","kp1","kp2","initialKeypair","nextKeypair","nextNextKeypair","nextNextNextKeypair","calculateComputeUnitPrice","targetLamports","computeUnits","__importDefault","__esModule","default","defineProperty","array","rustEnum","vecU8","tagged","vec","bool","option","i256","u256","i128","u128","u64","struct","f64","f32","i32","u32","i16","u16","i8","u8","buffer_layout_1","require$$0","web3_js_1","require$$1","bn_js_1","require$$2","buffer_layout_2","enumerable","get","s8","s16","s32","BNLayout","Layout","span","signed","property","blob","offset","i64","WrappedLayout","layout","decoder","encoder","getSpan","OptionLayout","discriminator","decodeBool","encodeBool","elementLayout","seq","values","tag","wrappedLayout","replicate","receivedTag","variants","discriminant","unionLayout","union","variant","addVariant","MapEntryLayout","keyLayout","valueLayout","keyBytes","Map","entries","CompressedAccountLayout","MerkleContextLayout","NewAddressParamsLayout","InstructionDataInvokeLayout","encodeInstructionDataInvoke","alloc","dataBuffer","lengthBuffer","writeUInt32LE","decodeInstructionDataInvoke","invokeAccountsLayout","accounts","defaultPubkey","LightSystemProgram","feePayer","authority","solPoolPda","decompressionRecipient","systemProgram","PublicTransactionEventLayout","encodePublicTransactionEvent","decodePublicTransactionEvent","sumUpLamports","SOL_POOL_PDA_SEED","static","deriveCompressedSolPda","createTransferOutputState","toAddress","changeLamports","createDecompressOutputState","createNewAddressOutputState","createAccount","newAddress","recentValidityProof","outputStateTree","relayFee","compressOrDecompressLamports","isCompress","SystemProgram","TransactionInstruction","transfer","recentInputStateRootIndices","outputStateTrees","compress","outputCompressedAccount","decompress","selectMinCompressedSolAccountsForTransfer","transferLamports","accumulatedLamports","selectedAccounts","sort","ix","ComputeBudgetProgram","setComputeUnitLimit","units","getValidityProofV0","tree","queue","rootIndices","merkleTrees","nullifierQueues","createAccountWithLamports","getCompressedAccountsByOwner","inputAccounts","getValidityProof","recipient","userCompressedAccountsWithMerkleContext","inputLamports","dedupeSigner","signer","signers","filter","cursor","batchConfig","filters","dataSlice","limit","batch","signedTx","UtxoErrorCode","SelectInUtxosErrorCode","CreateUtxoErrorCode","RpcErrorCode","LookupTableErrorCode","HashErrorCode","ProofErrorCode","MerkleTreeErrorCode","UtilsErrorCode","MetaError","code","functionName","codeMessage","UtxoError","SelectInUtxosError","CreateUtxoError","RpcError","LookupTableError","HashError","ProofError","MerkleTreeError","UtilsError","BaseRpc","getCancellationPromise","getTransactionConfirmationPromise","confirmTransactionUsingBlockHeightExceedanceStrategy","confirmTransactionUsingDurableNonceStrategy","confirmTransactionUsingLegacyTimeoutStrategy","PublicKeyFromString","coerce","ArrayFromString","BN254FromString","BNFromInt","Base64EncodedCompressedAccountDataResult","createRpcResult","pick","jsonrpc","literal","id","error","unknown","message","nullable","any","UnknownRpcResult","jsonRpcResult","schema","jsonRpcResultAndContext","CompressedAccountResult","dataHash","slotCreated","TokenDataResult","mint","amount","delegate","CompressedTokenAccountResult","tokenData","MultipleCompressedAccountsResult","CompressedAccountsByOwnerResult","CompressedTokenAccountsByOwnerOrDelegateResult","SlotResult","HealthResult","LatestNonVotingSignaturesResult","blockTime","LatestNonVotingSignaturesResultPaginated","MerkeProofResult","rootSeq","root","NewAddressProofResult","nextIndex","lowerRangeAddress","higherRangeAddress","lowElementLeafIndex","CompressedProofResult","ValidityProofResult","leafIndices","leaves","roots","MultipleMerkleProofsResult","BalanceResult","NativeBalanceResult","TokenBalanceResult","TokenBalanceListResult","tokenBalances","TokenBalanceListResultV2","CompressedMintTokenHoldersResult","AccountProofResult","toUnixTimestamp","Date","getTime","SignatureListResult","SignatureListWithCursorResult","CompressedTransactionResult","compressionInfo","closedAccounts","optionalTokenData","openedAccounts","transaction","parseAccountData","getCompressedTokenAccountsByOwnerOrDelegate","ownerOrDelegate","options","filterByDelegate","endpoint","propertyToCheck","unsafeRes","rpcRequest","compressionApiEndpoint","toBase58","SolanaJSONRPCError","_account","_tokenData","mockNullifierQueue","parsed","indexOf","tlv","buildCompressedAccountWithMaybeTokenData","accountStructWithOptionalTokenData","compressedAccountResult","tokenDataResult","maybeTokenData","createRpc","endpointOrWeb3JsConnection","proverEndpoint","config","rpcEndpoint","Rpc","method","convertToCamelCase","body","JSON","stringify","response","fetch","headers","ok","status","proverRequest","circuitType","stateTreeHeight","addressTreeHeight","newAddresses","statusText","convertMerkleProofsWithContextToHex","merkleProofsWithContext","inputs","pathIndex","pathElements","merkleProof","hex","leaf","convertNonInclusionMerkleProofInputsToHex","nonInclusionMerkleProofInputs","indexHashedIndexedElementLeaf","merkleProofHashedIndexedElementLeaf","leafLowerRangeValue","leafHigherRangeValue","calculateTwoInputsHashChain","hashesFirst","hashesSecond","lightWasm","hashChain","poseidonHashBN","getPublicInputHash","accountProofs","accountHashes","newAddressProofs","inclusionHashChain","newAddressHashes","nonInclusionHashChain","mockAddressQueue","getBalanceAndContext","commitmentOrConfig","getBalance","getBlockTime","getMinimumLedgerSlot","getFirstAvailableBlock","getSupply","getTokenSupply","tokenMintAddress","getTokenAccountBalance","tokenAddress","getTokenAccountsByOwner","ownerAddress","getParsedTokenAccountsByOwner","getLargestAccounts","getTokenLargestAccounts","mintAddress","getAccountInfoAndContext","getParsedAccountInfo","getAccountInfo","getMultipleParsedAccounts","publicKeys","rawConfig","getMultipleAccountsInfoAndContext","getMultipleAccountsInfo","getStakeActivation","epoch","getProgramAccounts","configOrCommitment","getParsedProgramAccounts","getParsedBlock","getConfirmedTransaction","getParsedConfirmedTransaction","getParsedConfirmedTransactions","signatures","getConfirmedSignaturesForAddress","startSlot","endSlot","getConfirmedSignaturesForAddress2","getSignaturesForAddress","getRecentPrioritizationFees","getLatestBlockhashAndContext","isBlockhashValid","getVersion","getAddressLookupTable","accountKey","getNonceAndContext","nonceAccount","getNonce","getCompressedAccount","getCompressedBalance","getCompressedBalanceByOwner","getCompressedAccountProof","getMultipleCompressedAccounts","hashes","join","getMultipleCompressedAccountProofs","merkleProofs","getCompressedTokenAccountsByOwner","getCompressedTokenAccountsByDelegate","getCompressedTokenAccountBalance","getCompressedTokenBalancesByOwner","tokenBalance","getCompressedTokenBalancesByOwnerV2","maybeFiltered","getCompressionSignaturesForAccount","getTransactionWithCompressionInfo","calculateTokenBalances","balances","preTokenBalances","postTokenBalances","getCompressionSignaturesForAddress","getCompressionSignaturesForOwner","getCompressionSignaturesForTokenOwner","getIndexerHealth","startTime","now","getIndexerSlot","getCompressedMintTokenHolders","getLatestCompressionSignatures","getLatestNonVotingSignatures","getMultipleNewAddressProofs","addresses","_proof","getValidityProofDirect","newAddressInputs","defaultAddressTreePublicKey","defaultAddressQueuePublicKey","defaultStateTreePublicKey","defaultStateQueuePublicKey","formattedHashes","formattedNewAddresses","getValidityProofAndRpcContext","newAddressesWithTrees","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","DEFAULT_ZERO","MerkleTree","levels","capacity","zeroElement","_zeros","_layers","_lightWasm","poseidonHashString","_rebuild","level","insert","bulkInsert","isNaN","path","pathIndices","comparator","el","serialize","deserialize","hashFunction","assign","_hash","getParsedEvents","transactionEvents","getParsedTransactions","maxSupportedTransactionVersion","accountKeys","some","parseEvents","parsePublicTransactionEventWithIdl","indexerEventsTransactions","deserializeFn","transactions","meta","err","innerInstructions","ixInner","decodedEvent","numericData","getCompressedAccountByHashTest","getCompressedAccountsForTest","events","allOutputAccounts","allInputAccountHashes","event","outputCompressedAccountHashes","outputLeafIndices","withCtx","inputCompressedAccountHashes","unspentAccounts","tokenProgramId","TokenDataLayout","parseTokenLayoutWithIdl","getCompressedTokenAccounts","eventsWithParsedTokenTlvData","all","pubkeyArray","outputHashes","outputCompressedAccountsWithParsedTokenData","parsedData","parseEventWithTokenTlvData","allOutCompressedAccounts","flatMap","allInCompressedAccountHashes","getCompressedTokenAccountsByOwnerTest","getCompressedTokenAccountsByDelegateTest","getCompressedTokenAccountByHashTest","filtered","getTestRpc","merkleTreeAddress","nullifierQueueAddress","depth","defaultAccounts","TestRpc","addressTreeAddress","addressQueueAddress","connectionConfig","testRpcConfig","getMultipleCompressedAccountsByHashTest","_slot","then","allLeaves","allLeafIndices","bnPathElements","computedHash","hashArr","_config","getCompressedAccountsByOwnerTest","_cursor","_limit","_signature","_address","_options","_owner","indexedArray","allAddresses","higherRangeValue","_mint"],"mappings":"itBAAA,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,CAU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