@taquito/sapling 14.0.0-beta-RC.0

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.
Files changed (56) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +93 -0
  3. package/dist/lib/constants.js +8 -0
  4. package/dist/lib/constants.js.map +1 -0
  5. package/dist/lib/error.js +72 -0
  6. package/dist/lib/error.js.map +1 -0
  7. package/dist/lib/sapling-forger/sapling-forger.js +101 -0
  8. package/dist/lib/sapling-forger/sapling-forger.js.map +1 -0
  9. package/dist/lib/sapling-keys/helpers.js +30 -0
  10. package/dist/lib/sapling-keys/helpers.js.map +1 -0
  11. package/dist/lib/sapling-keys/in-memory-proving-key.js +84 -0
  12. package/dist/lib/sapling-keys/in-memory-proving-key.js.map +1 -0
  13. package/dist/lib/sapling-keys/in-memory-spending-key.js +146 -0
  14. package/dist/lib/sapling-keys/in-memory-spending-key.js.map +1 -0
  15. package/dist/lib/sapling-keys/in-memory-viewing-key.js +101 -0
  16. package/dist/lib/sapling-keys/in-memory-viewing-key.js.map +1 -0
  17. package/dist/lib/sapling-module-wrapper.js +83 -0
  18. package/dist/lib/sapling-module-wrapper.js.map +1 -0
  19. package/dist/lib/sapling-state/sapling-state.js +171 -0
  20. package/dist/lib/sapling-state/sapling-state.js.map +1 -0
  21. package/dist/lib/sapling-state/utils.js +60 -0
  22. package/dist/lib/sapling-state/utils.js.map +1 -0
  23. package/dist/lib/sapling-tx-builder/sapling-transactions-builder.js +288 -0
  24. package/dist/lib/sapling-tx-builder/sapling-transactions-builder.js.map +1 -0
  25. package/dist/lib/sapling-tx-viewer/helpers.js +31 -0
  26. package/dist/lib/sapling-tx-viewer/helpers.js.map +1 -0
  27. package/dist/lib/sapling-tx-viewer/sapling-transaction-viewer.js +230 -0
  28. package/dist/lib/sapling-tx-viewer/sapling-transaction-viewer.js.map +1 -0
  29. package/dist/lib/taquito-sapling.js +293 -0
  30. package/dist/lib/taquito-sapling.js.map +1 -0
  31. package/dist/lib/types.js +3 -0
  32. package/dist/lib/types.js.map +1 -0
  33. package/dist/lib/version.js +9 -0
  34. package/dist/lib/version.js.map +1 -0
  35. package/dist/taquito-sapling.es6.js +1456 -0
  36. package/dist/taquito-sapling.es6.js.map +1 -0
  37. package/dist/taquito-sapling.umd.js +1485 -0
  38. package/dist/taquito-sapling.umd.js.map +1 -0
  39. package/dist/types/constants.d.ts +5 -0
  40. package/dist/types/error.d.ts +50 -0
  41. package/dist/types/sapling-forger/sapling-forger.d.ts +30 -0
  42. package/dist/types/sapling-keys/helpers.d.ts +2 -0
  43. package/dist/types/sapling-keys/in-memory-proving-key.d.ts +35 -0
  44. package/dist/types/sapling-keys/in-memory-spending-key.d.ts +53 -0
  45. package/dist/types/sapling-keys/in-memory-viewing-key.d.ts +48 -0
  46. package/dist/types/sapling-module-wrapper.d.ts +19 -0
  47. package/dist/types/sapling-state/sapling-state.d.ts +55 -0
  48. package/dist/types/sapling-state/utils.d.ts +22 -0
  49. package/dist/types/sapling-tx-builder/sapling-transactions-builder.d.ts +32 -0
  50. package/dist/types/sapling-tx-viewer/helpers.d.ts +11 -0
  51. package/dist/types/sapling-tx-viewer/sapling-transaction-viewer.d.ts +50 -0
  52. package/dist/types/taquito-sapling.d.ts +81 -0
  53. package/dist/types/types.d.ts +147 -0
  54. package/dist/types/version.d.ts +4 -0
  55. package/fetch-sapling-params.js +41 -0
  56. package/package.json +112 -0
@@ -0,0 +1,1456 @@
1
+ import BigNumber from 'bignumber.js';
2
+ import { MichelCodecPacker } from '@taquito/taquito';
3
+ import { b58cencode, prefix, Prefix, bytes2Char, toHexBuf, char2Bytes, hex2buf, mergebuf, hex2Bytes, num2PaddedHex, b58cdecode, ValidationResult, format, validateKeyHash, InvalidAddressError, InvalidKeyError } from '@taquito/utils';
4
+ import * as sapling from '@airgap/sapling-wasm';
5
+ import { merkleHash } from '@airgap/sapling-wasm';
6
+ import blake from 'blakejs';
7
+ import { openSecretBox, secretBox } from '@stablelib/nacl';
8
+ import { randomBytes } from '@stablelib/random';
9
+ import * as bip39 from 'bip39';
10
+ import toBuffer from 'typedarray-to-buffer';
11
+ import pbkdf2 from 'pbkdf2';
12
+
13
+ /******************************************************************************
14
+ Copyright (c) Microsoft Corporation.
15
+
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
+ PERFORMANCE OF THIS SOFTWARE.
26
+ ***************************************************************************** */
27
+
28
+ function __rest(s, e) {
29
+ var t = {};
30
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
31
+ t[p] = s[p];
32
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
33
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
34
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
35
+ t[p[i]] = s[p[i]];
36
+ }
37
+ return t;
38
+ }
39
+
40
+ function __awaiter(thisArg, _arguments, P, generator) {
41
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
42
+ return new (P || (P = Promise))(function (resolve, reject) {
43
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
44
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
45
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
46
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
47
+ });
48
+ }
49
+
50
+ function __classPrivateFieldGet(receiver, state, kind, f) {
51
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
52
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
53
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
54
+ }
55
+
56
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
57
+ if (kind === "m") throw new TypeError("Private method is not writable");
58
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
59
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
60
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
61
+ }
62
+
63
+ /**
64
+ * @category Error
65
+ * @description Error indicating that the spending key is invalid
66
+ */
67
+ class InvalidSpendingKey extends Error {
68
+ constructor(sk, reason = 'The spending key is invalid') {
69
+ super(`${reason}: ${sk}`);
70
+ this.name = 'InvalidSpendingKey';
71
+ }
72
+ }
73
+ /**
74
+ * @category Error
75
+ * @description Error that indicates an invalid Merkle root being passed
76
+ */
77
+ class InvalidMerkleRootError extends Error {
78
+ constructor(root) {
79
+ super(`The following Merkle tree is invalid: ${JSON.stringify(root)}`);
80
+ this.root = root;
81
+ this.name = 'InvalidMerkleRootError';
82
+ }
83
+ }
84
+ /**
85
+ * @category Error
86
+ * @description Error that indicates a failure when trying to construct the Merkle tree
87
+ */
88
+ class TreeConstructionFailure extends Error {
89
+ constructor(message) {
90
+ super(message);
91
+ this.message = message;
92
+ this.name = 'TreeConstructionFailure';
93
+ }
94
+ }
95
+ /**
96
+ * @category Error
97
+ * @description Error indicating that the memo is invalid
98
+ */
99
+ class InvalidMemo extends Error {
100
+ constructor(memo, errorDetail) {
101
+ super(`The memo '${memo}' is invalid. ${errorDetail}`);
102
+ this.name = 'InvalidMemo';
103
+ }
104
+ }
105
+ /**
106
+ * @category Error
107
+ * @description Error indicating that there is not enough balance to prepare the sapling transaction
108
+ */
109
+ class InsufficientBalance extends Error {
110
+ constructor(realBalance, amountToSpend) {
111
+ super(`Unable to spend ${amountToSpend} mutez while the balance is only ${realBalance} mutez.`);
112
+ this.name = 'InsufficientBalance';
113
+ }
114
+ }
115
+ /**
116
+ * @category Error
117
+ * @description Error indicating that a parameter is invalid
118
+ */
119
+ class InvalidParameter extends Error {
120
+ constructor(message) {
121
+ super(message);
122
+ this.name = 'InvalidParameter';
123
+ }
124
+ }
125
+
126
+ function memoHexToUtf8(memo) {
127
+ const memoNoPadding = removeZeroPaddedBytesRight(memo);
128
+ return memoNoPadding === '' ? memoNoPadding : bytes2Char(memoNoPadding);
129
+ }
130
+ function removeZeroPaddedBytesRight(memo) {
131
+ const matchZeroRight = memo.match(/^(.*?)(00)+$/);
132
+ return matchZeroRight ? matchZeroRight[1] : memo;
133
+ }
134
+ function readableFormat(saplingTransactionProperties) {
135
+ return {
136
+ value: convertValueToBigNumber(saplingTransactionProperties.value),
137
+ memo: memoHexToUtf8(Buffer.from(saplingTransactionProperties.memo).toString('hex')),
138
+ paymentAddress: b58cencode(saplingTransactionProperties.paymentAddress, prefix[Prefix.ZET1]),
139
+ };
140
+ }
141
+ function convertValueToBigNumber(value) {
142
+ return new BigNumber(Buffer.from(value).toString('hex'), 16);
143
+ }
144
+ function bufToUint8Array(buffer) {
145
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT);
146
+ }
147
+
148
+ class SaplingForger {
149
+ /**
150
+ * @description Forge sapling transactions
151
+ * @param spendDescriptions the list of spend descriptions
152
+ * @param outputDescriptions the list of output descriptions
153
+ * @param signature signature hash
154
+ * @param balance balance of the Sapling contract (input/output difference)
155
+ * @param root root of the merkle tree
156
+ * @returns Forged sapling transaction of type Buffer
157
+ */
158
+ forgeSaplingTransaction(tx) {
159
+ const spendBuf = this.forgeSpendDescriptions(tx.inputs);
160
+ const spend = Buffer.concat([toHexBuf(spendBuf.length, 32), spendBuf]);
161
+ const outputBuf = this.forgeOutputDescriptions(tx.outputs);
162
+ const output = Buffer.concat([toHexBuf(outputBuf.length, 32), outputBuf]);
163
+ const root = Buffer.from(tx.root, 'hex');
164
+ return Buffer.concat([
165
+ spend,
166
+ output,
167
+ tx.signature,
168
+ toHexBuf(tx.balance, 64),
169
+ root,
170
+ toHexBuf(tx.boundData.length, 32),
171
+ tx.boundData,
172
+ ]);
173
+ }
174
+ /**
175
+ * @description Forge list of spend descriptions
176
+ * @param spendDescriptions list of spend descriptions
177
+ * @returns concatenated forged bytes of type Buffer
178
+ */
179
+ forgeSpendDescriptions(spendDescriptions) {
180
+ const descriptions = [];
181
+ for (const i of spendDescriptions) {
182
+ const buff = this.forgeSpendDescription(i);
183
+ descriptions.push(buff);
184
+ }
185
+ return Buffer.concat(descriptions);
186
+ }
187
+ forgeSpendDescription(desc) {
188
+ return Buffer.concat([
189
+ desc.commitmentValue,
190
+ desc.nullifier,
191
+ desc.publicKeyReRandomization,
192
+ desc.proof,
193
+ desc.signature,
194
+ ]);
195
+ }
196
+ /**
197
+ * @description Forge list of output descriptions
198
+ * @param outputDescriptions list of output descriptions
199
+ * @returns concatenated forged bytes of type Buffer
200
+ */
201
+ forgeOutputDescriptions(outputDescriptions) {
202
+ const descriptions = [];
203
+ for (const i of outputDescriptions) {
204
+ const buff = this.forgeOutputDescription(i);
205
+ descriptions.push(buff);
206
+ }
207
+ return Buffer.concat(descriptions);
208
+ }
209
+ forgeOutputDescription(desc) {
210
+ const ct = desc.ciphertext;
211
+ return Buffer.concat([
212
+ desc.commitment,
213
+ desc.proof,
214
+ ct.commitmentValue,
215
+ ct.ephemeralPublicKey,
216
+ toHexBuf(ct.payloadEnc.length, 32),
217
+ ct.payloadEnc,
218
+ ct.nonceEnc,
219
+ ct.payloadOut,
220
+ ct.nonceOut,
221
+ ]);
222
+ }
223
+ forgeUnsignedTxInput(unsignedSpendDescription) {
224
+ return Buffer.concat([
225
+ unsignedSpendDescription.commitmentValue,
226
+ unsignedSpendDescription.nullifier,
227
+ unsignedSpendDescription.publicKeyReRandomization,
228
+ unsignedSpendDescription.proof,
229
+ ]);
230
+ }
231
+ forgeTransactionPlaintext(txPlainText) {
232
+ const encodedMemo = Buffer.from(char2Bytes(txPlainText.memo).padEnd(txPlainText.memoSize, '0'), 'hex');
233
+ return Buffer.concat([
234
+ txPlainText.diversifier,
235
+ toHexBuf(new BigNumber(txPlainText.amount), 64),
236
+ txPlainText.randomCommitmentTrapdoor,
237
+ toHexBuf(txPlainText.memoSize, 32),
238
+ encodedMemo,
239
+ ]);
240
+ }
241
+ }
242
+
243
+ const KDF_KEY = 'KDFSaplingForTezosV1';
244
+ const OCK_KEY = 'OCK_keystringderivation_TEZOS';
245
+ const DEFAULT_MEMO = '';
246
+ const DEFAULT_BOUND_DATA = Buffer.from('', 'hex');
247
+
248
+ var _viewingKeyProvider, _readProvider$2, _saplingContractId;
249
+ /**
250
+ * @description Allows to retrieve and decrypt sapling transactions using on a viewing key
251
+ *
252
+ * @param inMemoryViewingKey Holds the sapling viewing key
253
+ * @param saplingContractId Address of the sapling contract or sapling id if the smart contract contains multiple sapling states
254
+ * @param readProvider Allows to read data from the blockchain
255
+ */
256
+ class SaplingTransactionViewer {
257
+ constructor(inMemoryViewingKey, saplingContractId, readProvider) {
258
+ _viewingKeyProvider.set(this, void 0);
259
+ _readProvider$2.set(this, void 0);
260
+ _saplingContractId.set(this, void 0);
261
+ __classPrivateFieldSet(this, _viewingKeyProvider, inMemoryViewingKey);
262
+ __classPrivateFieldSet(this, _saplingContractId, saplingContractId);
263
+ __classPrivateFieldSet(this, _readProvider$2, readProvider);
264
+ }
265
+ /**
266
+ * @description Retrieve the unspent balance associated with the configured viewing key and sapling state
267
+ *
268
+ * @returns the balance in mutez represented as a BigNumber
269
+ *
270
+ */
271
+ getBalance() {
272
+ return __awaiter(this, void 0, void 0, function* () {
273
+ let balance = new BigNumber(0);
274
+ const { commitments_and_ciphertexts, nullifiers } = yield this.getSaplingDiff();
275
+ for (let i = 0; i < commitments_and_ciphertexts.length; i++) {
276
+ const decrypted = yield this.decryptCiphertextAsReceiver(commitments_and_ciphertexts[i]);
277
+ if (decrypted) {
278
+ const valueBigNumber = convertValueToBigNumber(decrypted.value);
279
+ const isSpent = yield this.isSpent(decrypted.paymentAddress, valueBigNumber.toString(), decrypted.randomCommitmentTrapdoor, i, nullifiers);
280
+ if (!isSpent) {
281
+ balance = balance.plus(valueBigNumber);
282
+ }
283
+ }
284
+ }
285
+ return balance;
286
+ });
287
+ }
288
+ /**
289
+ * @description Retrieve all the incoming and outgoing transactions associated with the configured viewing key.
290
+ * The response properties are in Uint8Array format; use the getIncomingAndOutgoingTransactions method for readable properties
291
+ *
292
+ */
293
+ getIncomingAndOutgoingTransactionsRaw() {
294
+ return __awaiter(this, void 0, void 0, function* () {
295
+ const incoming = [];
296
+ const outgoing = [];
297
+ const { commitments_and_ciphertexts, nullifiers } = yield this.getSaplingDiff();
298
+ for (let i = 0; i < commitments_and_ciphertexts.length; i++) {
299
+ const decryptedAsReceiver = yield this.decryptCiphertextAsReceiver(commitments_and_ciphertexts[i]);
300
+ const decryptedAsSender = yield this.decryptCiphertextAsSender(commitments_and_ciphertexts[i]);
301
+ if (decryptedAsReceiver) {
302
+ const balance = convertValueToBigNumber(decryptedAsReceiver.value);
303
+ const isSpent = yield this.isSpent(decryptedAsReceiver.paymentAddress, balance.toString(), decryptedAsReceiver.randomCommitmentTrapdoor, i, nullifiers);
304
+ incoming.push(Object.assign(Object.assign({}, decryptedAsReceiver), { isSpent, position: i }));
305
+ }
306
+ if (decryptedAsSender) {
307
+ outgoing.push(decryptedAsSender);
308
+ }
309
+ }
310
+ return {
311
+ incoming,
312
+ outgoing,
313
+ };
314
+ });
315
+ }
316
+ /**
317
+ * @description Retrieve all the incoming and outgoing decoded transactions associated with the configured viewing key
318
+ *
319
+ */
320
+ getIncomingAndOutgoingTransactions() {
321
+ return __awaiter(this, void 0, void 0, function* () {
322
+ const tx = yield this.getIncomingAndOutgoingTransactionsRaw();
323
+ const incoming = tx.incoming.map((_a) => {
324
+ var { isSpent } = _a, rest = __rest(_a, ["isSpent"]);
325
+ return Object.assign(Object.assign({}, readableFormat(rest)), { isSpent });
326
+ });
327
+ const outgoing = tx.outgoing.map((outgoingTx) => {
328
+ return readableFormat(outgoingTx);
329
+ });
330
+ return { incoming, outgoing };
331
+ });
332
+ }
333
+ getSaplingDiff() {
334
+ return __awaiter(this, void 0, void 0, function* () {
335
+ let saplingDiffResponse;
336
+ if (__classPrivateFieldGet(this, _saplingContractId).saplingId) {
337
+ saplingDiffResponse = yield __classPrivateFieldGet(this, _readProvider$2).getSaplingDiffById({ id: __classPrivateFieldGet(this, _saplingContractId).saplingId }, 'head');
338
+ }
339
+ else if (__classPrivateFieldGet(this, _saplingContractId).contractAddress) {
340
+ saplingDiffResponse = yield __classPrivateFieldGet(this, _readProvider$2).getSaplingDiffByContract(__classPrivateFieldGet(this, _saplingContractId).contractAddress, 'head');
341
+ }
342
+ else {
343
+ throw new InvalidParameter('A contract address or a sapling id was expected in the SaplingTransactionViewer constructor.');
344
+ }
345
+ return saplingDiffResponse;
346
+ });
347
+ }
348
+ decryptCiphertextAsReceiver(commitmentsAndCiphertexts) {
349
+ return __awaiter(this, void 0, void 0, function* () {
350
+ const commitment = commitmentsAndCiphertexts[0];
351
+ const { epk, payload_enc, nonce_enc } = commitmentsAndCiphertexts[1];
352
+ const incomingViewingKey = yield __classPrivateFieldGet(this, _viewingKeyProvider).getIncomingViewingKey();
353
+ const keyAgreement = yield sapling.keyAgreement(epk, incomingViewingKey);
354
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
355
+ const decrypted = yield this.decryptCiphertext(keyAgreementHash, hex2buf(nonce_enc), hex2buf(payload_enc));
356
+ if (decrypted) {
357
+ const { diversifier, value, randomCommitmentTrapdoor: rcm, memo, } = this.extractTransactionProperties(decrypted);
358
+ const paymentAddress = bufToUint8Array(yield sapling.getRawPaymentAddressFromIncomingViewingKey(incomingViewingKey, diversifier));
359
+ try {
360
+ const valid = yield sapling.verifyCommitment(commitment, paymentAddress, convertValueToBigNumber(value).toString(), rcm);
361
+ if (valid) {
362
+ return { value, memo, paymentAddress, randomCommitmentTrapdoor: rcm };
363
+ }
364
+ }
365
+ catch (ex) {
366
+ if (!/invalid value/.test(ex)) {
367
+ throw ex;
368
+ }
369
+ }
370
+ }
371
+ });
372
+ }
373
+ decryptCiphertextAsSender(commitmentsAndCiphertexts) {
374
+ return __awaiter(this, void 0, void 0, function* () {
375
+ const commitment = commitmentsAndCiphertexts[0];
376
+ const { epk, payload_enc, nonce_enc, payload_out, nonce_out, cv } = commitmentsAndCiphertexts[1];
377
+ const outgoingViewingKey = yield __classPrivateFieldGet(this, _viewingKeyProvider).getOutgoingViewingKey();
378
+ const concat = cv.concat(commitment, epk, outgoingViewingKey.toString('hex'));
379
+ const outgoingCipherKey = blake.blake2b(Buffer.from(concat, 'hex'), Buffer.from(OCK_KEY), 32);
380
+ const decryptedOut = yield this.decryptCiphertext(outgoingCipherKey, hex2buf(nonce_out), hex2buf(payload_out));
381
+ if (decryptedOut) {
382
+ const { recipientDiversifiedTransmissionKey: pkd, ephemeralPrivateKey: esk } = this.extractPkdAndEsk(decryptedOut);
383
+ const keyAgreement = yield sapling.keyAgreement(pkd, esk);
384
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
385
+ const decryptedEnc = yield this.decryptCiphertext(keyAgreementHash, hex2buf(nonce_enc), hex2buf(payload_enc));
386
+ if (decryptedEnc) {
387
+ const { diversifier, value, randomCommitmentTrapdoor: rcm, memo, } = this.extractTransactionProperties(decryptedEnc);
388
+ const paymentAddress = mergebuf(diversifier, pkd);
389
+ try {
390
+ const isValid = yield sapling.verifyCommitment(commitment, paymentAddress, convertValueToBigNumber(value).toString(), rcm);
391
+ if (isValid) {
392
+ return { value, memo, paymentAddress, randomCommitmentTrapdoor: rcm };
393
+ }
394
+ }
395
+ catch (ex) {
396
+ if (!/invalid value/.test(ex)) {
397
+ throw ex;
398
+ }
399
+ }
400
+ }
401
+ }
402
+ });
403
+ }
404
+ decryptCiphertext(keyAgreementHash, nonce, payload) {
405
+ return __awaiter(this, void 0, void 0, function* () {
406
+ return openSecretBox(keyAgreementHash, nonce, payload);
407
+ });
408
+ }
409
+ extractTransactionProperties(decrypted) {
410
+ return {
411
+ diversifier: decrypted.slice(0, 11),
412
+ value: decrypted.slice(11, 19),
413
+ randomCommitmentTrapdoor: decrypted.slice(19, 51),
414
+ memoSize: decrypted.slice(51, 55),
415
+ memo: decrypted.slice(55),
416
+ };
417
+ }
418
+ extractPkdAndEsk(decrypted) {
419
+ return {
420
+ recipientDiversifiedTransmissionKey: decrypted.slice(0, 32),
421
+ ephemeralPrivateKey: decrypted.slice(32),
422
+ };
423
+ }
424
+ isSpent(address, value, randomCommitmentTrapdoor, position, nullifiers) {
425
+ return __awaiter(this, void 0, void 0, function* () {
426
+ const computedNullifier = yield sapling.computeNullifier(__classPrivateFieldGet(this, _viewingKeyProvider).getFullViewingKey(), address, value, randomCommitmentTrapdoor, position);
427
+ return nullifiers.includes(computedNullifier.toString('hex'));
428
+ });
429
+ }
430
+ }
431
+ _viewingKeyProvider = new WeakMap(), _readProvider$2 = new WeakMap(), _saplingContractId = new WeakMap();
432
+
433
+ /**
434
+ *
435
+ * @param leaves nodes in the tree that we would like to make pairs from
436
+ * @returns a paired/chunked array: [a, b, c, d] => [[a, b], [c, d]]
437
+ */
438
+ function pairNodes(leaves) {
439
+ const pairs = new Array(Math.ceil(leaves.length / 2));
440
+ for (let i = 0; i < leaves.length / 2; i++) {
441
+ pairs[i] = leaves.slice(i * 2, i * 2 + 2);
442
+ }
443
+ return pairs;
444
+ }
445
+ /**
446
+ * @description helper function to assist in Lazy initializing an object
447
+ */
448
+ class Lazy {
449
+ constructor(init) {
450
+ this.init = init;
451
+ this.isInitialized = false;
452
+ this.value = undefined;
453
+ }
454
+ // initializes the lazily initiated object
455
+ get() {
456
+ return __awaiter(this, void 0, void 0, function* () {
457
+ if (!this.isInitialized) {
458
+ this.value = yield this.init();
459
+ this.isInitialized = true;
460
+ }
461
+ return this.value;
462
+ });
463
+ }
464
+ }
465
+ /**
466
+ *
467
+ * @param hex hexadecimal string we would like to swap
468
+ * @returns a hexadecimal string with swapped endians
469
+ */
470
+ const changeEndianness = (hex) => {
471
+ if (hex.length % 2 != 0) {
472
+ hex = '0' + hex;
473
+ }
474
+ const bytes = hex.match(/.{2}/g) || [];
475
+ return bytes.reverse().join('');
476
+ };
477
+
478
+ /**
479
+ * Some code in this file was originally written or inspired by Airgap-it
480
+ * https://github.com/airgap-it/airgap-coin-lib/blob/master/LICENSE.md
481
+ *
482
+ */
483
+ /**
484
+ * @description The SaplingState class's main purpose is to provide a Merkle path for the forger and the transaction builder, so that it may verify that the Sapling transaction is valid
485
+ *
486
+ */
487
+ class SaplingState {
488
+ constructor(height) {
489
+ this.height = height;
490
+ this.uncommittedMerkleHash = '0100000000000000000000000000000000000000000000000000000000000000';
491
+ this.uncommittedMerkleHashes = new Lazy(() => this.createUncommittedMerkleHashes());
492
+ }
493
+ getStateTree(stateDiff, constructTree = true) {
494
+ return __awaiter(this, void 0, void 0, function* () {
495
+ if (this.stateTree !== undefined && this.stateTree.root === stateDiff.root) {
496
+ return this.stateTree;
497
+ }
498
+ const commitments = stateDiff.commitments_and_ciphertexts.map(([commitment, _]) => commitment);
499
+ let merkleTree;
500
+ if (constructTree) {
501
+ merkleTree = yield this.constructMerkleTree(commitments, 0);
502
+ yield this.validateMerkleTree(merkleTree, stateDiff.root);
503
+ }
504
+ this.stateTree = {
505
+ height: this.height,
506
+ size: commitments.length,
507
+ root: stateDiff.root,
508
+ tree: merkleTree,
509
+ };
510
+ return this.stateTree;
511
+ });
512
+ }
513
+ /**
514
+ *
515
+ * @param stateTree stateTree parameter that holds information details on our Merkle tree
516
+ * @param position position of the hash in the Merkle tree
517
+ * @returns a promise of a string that serves as the Merkle path that can be passed on to the Sapling forger or the transaction builder
518
+ */
519
+ getWitness(stateTree, position) {
520
+ return __awaiter(this, void 0, void 0, function* () {
521
+ const heightBuffer = hex2Bytes(changeEndianness(num2PaddedHex(stateTree.height)));
522
+ const posBuffer = hex2Bytes(changeEndianness(num2PaddedHex(position, 64)));
523
+ const neighbouringHashes = yield this.getNeighbouringHashes([], stateTree.height, position, stateTree.tree);
524
+ const witness = neighbouringHashes
525
+ .map((hash) => Buffer.concat([hex2Bytes(changeEndianness(num2PaddedHex(hash.length))), hash]))
526
+ .reverse()
527
+ .reduce((acc, next) => Buffer.concat([acc, next]));
528
+ return Buffer.concat([heightBuffer, witness, posBuffer]).toString('hex');
529
+ });
530
+ }
531
+ /**
532
+ *
533
+ * @param leaves array of leaves or nodes that we want to construct the Merkle tree from
534
+ * @param height height of the desired Merkle tree
535
+ * @returns a promise of MerkleTree type object
536
+ */
537
+ constructMerkleTree(leaves, height) {
538
+ return __awaiter(this, void 0, void 0, function* () {
539
+ if (height === this.height && leaves.length === 1) {
540
+ return leaves[0];
541
+ }
542
+ if (height === this.height || leaves.length > Math.pow(2, this.height - 1 - height)) {
543
+ throw new TreeConstructionFailure('Children length exceeds maximum number of nodes in a merkle tree');
544
+ }
545
+ const pairedLeaves = pairNodes(leaves);
546
+ const updatedLeaves = yield Promise.all(pairedLeaves.map((chunk) => __awaiter(this, void 0, void 0, function* () {
547
+ const left = yield this.getMerkleHash(chunk[0], height);
548
+ const right = yield this.getMerkleHash(chunk[1], height);
549
+ const parentHash = yield merkleHash(height, left, right);
550
+ return [parentHash.toString('hex'), chunk[0], chunk[1]];
551
+ })));
552
+ return this.constructMerkleTree(updatedLeaves, height + 1);
553
+ });
554
+ }
555
+ getMerkleHash(tree, height) {
556
+ return __awaiter(this, void 0, void 0, function* () {
557
+ if (tree === undefined) {
558
+ return (yield this.uncommittedMerkleHashes.get())[height];
559
+ }
560
+ else if (typeof tree === 'string') {
561
+ return Buffer.from(tree, 'hex');
562
+ }
563
+ else {
564
+ return Buffer.from(tree[0], 'hex');
565
+ }
566
+ });
567
+ }
568
+ /**
569
+ *
570
+ * @returns hashes of empty or null values to fill in the Merkle tree
571
+ */
572
+ createUncommittedMerkleHashes() {
573
+ return __awaiter(this, void 0, void 0, function* () {
574
+ const res = new Array(this.height);
575
+ res[0] = Buffer.from(this.uncommittedMerkleHash, 'hex');
576
+ for (let i = 0; i < this.height; i++) {
577
+ const hash = res[i];
578
+ res[i + 1] = yield merkleHash(i, hash, hash);
579
+ }
580
+ return res;
581
+ });
582
+ }
583
+ /**
584
+ *
585
+ * @param tree Merkle tree to validate
586
+ * @param expectedRoot the expected merkle root to validate against
587
+ */
588
+ validateMerkleTree(tree, expectedRoot) {
589
+ return __awaiter(this, void 0, void 0, function* () {
590
+ const root = yield this.getMerkleHash(tree, this.height - 1);
591
+ if (root.toString('hex') !== expectedRoot) {
592
+ throw new InvalidMerkleRootError(root.toString('hex'));
593
+ }
594
+ });
595
+ }
596
+ /**
597
+ *
598
+ * @param acc accumulator variable for the recursive function
599
+ * @param height height of the tree
600
+ * @param position position of the hash we would like find the neighbours of
601
+ * @param tree the Merkle tree that we want to traverse
602
+ * @returns the accumulated Buffer array of neighbouring hashes
603
+ */
604
+ getNeighbouringHashes(acc, height, position, tree) {
605
+ return __awaiter(this, void 0, void 0, function* () {
606
+ if (typeof tree === 'undefined') {
607
+ throw new Error();
608
+ }
609
+ else if (typeof tree === 'string') {
610
+ return acc;
611
+ }
612
+ else {
613
+ let nextPos, nextTree, otherTree;
614
+ const fullTree = new BigNumber(2).pow(height - 1);
615
+ if (position.lt(fullTree)) {
616
+ nextPos = position;
617
+ nextTree = tree[1];
618
+ otherTree = tree[2];
619
+ }
620
+ else {
621
+ nextPos = position.minus(fullTree);
622
+ nextTree = tree[2];
623
+ otherTree = tree[1];
624
+ }
625
+ return this.getNeighbouringHashes([yield this.getMerkleHash(otherTree, height - 1), ...acc], height - 1, nextPos, nextTree);
626
+ }
627
+ });
628
+ }
629
+ }
630
+
631
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
632
+ const saplingOutputParams = require('../saplingOutputParams');
633
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
634
+ const saplingSpendParams = require('../saplingSpendParams');
635
+ class SaplingWrapper {
636
+ withProvingContext(action) {
637
+ return __awaiter(this, void 0, void 0, function* () {
638
+ yield this.initSaplingParameters();
639
+ return sapling.withProvingContext(action);
640
+ });
641
+ }
642
+ getRandomBytes(length) {
643
+ return randomBytes(length);
644
+ }
645
+ randR() {
646
+ return __awaiter(this, void 0, void 0, function* () {
647
+ return sapling.randR();
648
+ });
649
+ }
650
+ getOutgoingViewingKey(vk) {
651
+ return __awaiter(this, void 0, void 0, function* () {
652
+ return sapling.getOutgoingViewingKey(vk);
653
+ });
654
+ }
655
+ preparePartialOutputDescription(parametersOutputProof) {
656
+ return __awaiter(this, void 0, void 0, function* () {
657
+ const partialOutputDesc = yield sapling.preparePartialOutputDescription(parametersOutputProof.saplingContext, parametersOutputProof.address, parametersOutputProof.randomCommitmentTrapdoor, parametersOutputProof.ephemeralPrivateKey, parametersOutputProof.amount);
658
+ return {
659
+ commitmentValue: partialOutputDesc.cv,
660
+ commitment: partialOutputDesc.cm,
661
+ proof: partialOutputDesc.proof,
662
+ };
663
+ });
664
+ }
665
+ getDiversifiedFromRawPaymentAddress(decodedDestination) {
666
+ return __awaiter(this, void 0, void 0, function* () {
667
+ return sapling.getDiversifiedFromRawPaymentAddress(decodedDestination);
668
+ });
669
+ }
670
+ deriveEphemeralPublicKey(diversifier, esk) {
671
+ return __awaiter(this, void 0, void 0, function* () {
672
+ return sapling.deriveEphemeralPublicKey(diversifier, esk);
673
+ });
674
+ }
675
+ getPkdFromRawPaymentAddress(destination) {
676
+ return __awaiter(this, void 0, void 0, function* () {
677
+ return sapling.getPkdFromRawPaymentAddress(destination);
678
+ });
679
+ }
680
+ keyAgreement(p, sk) {
681
+ return __awaiter(this, void 0, void 0, function* () {
682
+ return sapling.keyAgreement(p, sk);
683
+ });
684
+ }
685
+ createBindingSignature(saplingContext, balance, transactionSigHash) {
686
+ return __awaiter(this, void 0, void 0, function* () {
687
+ return sapling.createBindingSignature(saplingContext, balance, transactionSigHash);
688
+ });
689
+ }
690
+ initSaplingParameters() {
691
+ return __awaiter(this, void 0, void 0, function* () {
692
+ const spendParams = Buffer.from(saplingSpendParams.saplingSpendParams, 'base64');
693
+ const outputParams = Buffer.from(saplingOutputParams.saplingOutputParams, 'base64');
694
+ return sapling.initParameters(spendParams, outputParams);
695
+ });
696
+ }
697
+ }
698
+
699
+ var _inMemorySpendingKey$1, _inMemoryProvingKey, _saplingForger$1, _contractAddress$1, _saplingId$1, _memoSize$1, _readProvider$1, _saplingWrapper, _chainId, _saplingState;
700
+ class SaplingTransactionBuilder {
701
+ constructor(keys, saplingForger, saplingContractDetails, readProvider, saplingWrapper = new SaplingWrapper()) {
702
+ _inMemorySpendingKey$1.set(this, void 0);
703
+ _inMemoryProvingKey.set(this, void 0);
704
+ _saplingForger$1.set(this, void 0);
705
+ _contractAddress$1.set(this, void 0);
706
+ _saplingId$1.set(this, void 0);
707
+ _memoSize$1.set(this, void 0);
708
+ _readProvider$1.set(this, void 0);
709
+ _saplingWrapper.set(this, void 0);
710
+ _chainId.set(this, void 0);
711
+ _saplingState.set(this, void 0);
712
+ __classPrivateFieldSet(this, _saplingForger$1, saplingForger);
713
+ __classPrivateFieldSet(this, _contractAddress$1, saplingContractDetails.contractAddress);
714
+ __classPrivateFieldSet(this, _memoSize$1, saplingContractDetails.memoSize);
715
+ __classPrivateFieldSet(this, _inMemorySpendingKey$1, keys.saplingSigner);
716
+ __classPrivateFieldSet(this, _inMemoryProvingKey, keys.saplingProver);
717
+ __classPrivateFieldSet(this, _saplingState, new SaplingState(32));
718
+ __classPrivateFieldSet(this, _saplingId$1, saplingContractDetails.saplingId);
719
+ __classPrivateFieldSet(this, _saplingWrapper, saplingWrapper);
720
+ __classPrivateFieldSet(this, _readProvider$1, readProvider);
721
+ }
722
+ createShieldedTx(saplingTransactionParams, txTotalAmount, boundData) {
723
+ return __awaiter(this, void 0, void 0, function* () {
724
+ const rcm = yield __classPrivateFieldGet(this, _saplingWrapper).randR();
725
+ const balance = this.calculateTransactionBalance('0', txTotalAmount.toString());
726
+ const { signature, inputs, outputs } = yield __classPrivateFieldGet(this, _saplingWrapper).withProvingContext((saplingContext) => __awaiter(this, void 0, void 0, function* () {
727
+ const outputs = [];
728
+ const inputs = [];
729
+ for (const i in saplingTransactionParams) {
730
+ outputs.push(yield this.prepareSaplingOutputDescription({
731
+ saplingContext,
732
+ address: b58cdecode(saplingTransactionParams[i].to, prefix[Prefix.ZET1]),
733
+ amount: saplingTransactionParams[i].amount,
734
+ memo: saplingTransactionParams[i].memo,
735
+ randomCommitmentTrapdoor: rcm,
736
+ }));
737
+ }
738
+ const signature = yield this.createBindingSignature({
739
+ saplingContext,
740
+ inputs,
741
+ outputs,
742
+ balance,
743
+ boundData,
744
+ });
745
+ return { signature, inputs, outputs };
746
+ }));
747
+ return {
748
+ inputs,
749
+ outputs,
750
+ signature,
751
+ balance,
752
+ };
753
+ });
754
+ }
755
+ createSaplingTx(saplingTransactionParams, txTotalAmount, boundData, chosenInputs) {
756
+ return __awaiter(this, void 0, void 0, function* () {
757
+ const randomCommitmentTrapdoor = yield __classPrivateFieldGet(this, _saplingWrapper).randR();
758
+ const saplingViewer = yield __classPrivateFieldGet(this, _inMemorySpendingKey$1).getSaplingViewingKeyProvider();
759
+ const outgoingViewingKey = yield saplingViewer.getOutgoingViewingKey();
760
+ const { signature, balance, inputs, outputs } = yield __classPrivateFieldGet(this, _saplingWrapper).withProvingContext((saplingContext) => __awaiter(this, void 0, void 0, function* () {
761
+ const outputs = [];
762
+ const inputs = [];
763
+ inputs.push(...(yield this.prepareSaplingSpendDescription(saplingContext, chosenInputs.inputsToSpend)));
764
+ let sumAmountOutput = new BigNumber(0);
765
+ for (const i in saplingTransactionParams) {
766
+ sumAmountOutput = sumAmountOutput.plus(new BigNumber(saplingTransactionParams[i].amount));
767
+ outputs.push(yield this.prepareSaplingOutputDescription({
768
+ saplingContext,
769
+ address: b58cdecode(saplingTransactionParams[i].to, prefix[Prefix.ZET1]),
770
+ amount: saplingTransactionParams[i].amount,
771
+ memo: saplingTransactionParams[i].memo,
772
+ randomCommitmentTrapdoor,
773
+ outgoingViewingKey,
774
+ }));
775
+ }
776
+ if (chosenInputs.sumSelectedInputs.isGreaterThan(sumAmountOutput)) {
777
+ const payBackAddress = (yield saplingViewer.getAddress()).address;
778
+ const { payBackOutput, payBackAmount } = yield this.createPaybackOutput({
779
+ saplingContext,
780
+ address: b58cdecode(payBackAddress, prefix[Prefix.ZET1]),
781
+ amount: txTotalAmount.toString(),
782
+ memo: DEFAULT_MEMO,
783
+ randomCommitmentTrapdoor: randomCommitmentTrapdoor,
784
+ outgoingViewingKey: outgoingViewingKey,
785
+ }, chosenInputs.sumSelectedInputs);
786
+ sumAmountOutput = sumAmountOutput.plus(new BigNumber(payBackAmount));
787
+ outputs.push(payBackOutput);
788
+ }
789
+ const balance = this.calculateTransactionBalance(chosenInputs.sumSelectedInputs.toString(), sumAmountOutput.toString());
790
+ const signature = yield this.createBindingSignature({
791
+ saplingContext,
792
+ inputs,
793
+ outputs,
794
+ balance,
795
+ boundData,
796
+ });
797
+ return { signature, balance, inputs, outputs };
798
+ }));
799
+ return {
800
+ inputs,
801
+ outputs,
802
+ signature,
803
+ balance,
804
+ };
805
+ });
806
+ }
807
+ // sum of values of inputs minus sums of values of output equals balance
808
+ calculateTransactionBalance(inputTotal, outputTotal) {
809
+ return new BigNumber(inputTotal).minus(new BigNumber(outputTotal));
810
+ }
811
+ prepareSaplingOutputDescription(parametersOutputDescription) {
812
+ return __awaiter(this, void 0, void 0, function* () {
813
+ const ephemeralPrivateKey = yield __classPrivateFieldGet(this, _saplingWrapper).randR();
814
+ const { commitmentValue, commitment, proof } = yield __classPrivateFieldGet(this, _saplingWrapper).preparePartialOutputDescription({
815
+ saplingContext: parametersOutputDescription.saplingContext,
816
+ address: parametersOutputDescription.address,
817
+ randomCommitmentTrapdoor: parametersOutputDescription.randomCommitmentTrapdoor,
818
+ ephemeralPrivateKey,
819
+ amount: parametersOutputDescription.amount,
820
+ });
821
+ const diversifier = yield __classPrivateFieldGet(this, _saplingWrapper).getDiversifiedFromRawPaymentAddress(parametersOutputDescription.address);
822
+ const ephemeralPublicKey = yield __classPrivateFieldGet(this, _saplingWrapper).deriveEphemeralPublicKey(diversifier, ephemeralPrivateKey);
823
+ const outgoingCipherKey = parametersOutputDescription.outgoingViewingKey
824
+ ? blake.blake2b(Buffer.concat([
825
+ commitmentValue,
826
+ commitment,
827
+ ephemeralPublicKey,
828
+ parametersOutputDescription.outgoingViewingKey,
829
+ ]), Buffer.from(OCK_KEY), 32)
830
+ : __classPrivateFieldGet(this, _saplingWrapper).getRandomBytes(32);
831
+ const ciphertext = yield this.encryptCiphertext({
832
+ address: parametersOutputDescription.address,
833
+ ephemeralPrivateKey,
834
+ diversifier,
835
+ outgoingCipherKey,
836
+ amount: parametersOutputDescription.amount,
837
+ randomCommitmentTrapdoor: parametersOutputDescription.randomCommitmentTrapdoor,
838
+ memo: parametersOutputDescription.memo,
839
+ });
840
+ return {
841
+ commitment,
842
+ proof,
843
+ ciphertext: Object.assign(Object.assign({}, ciphertext), { commitmentValue,
844
+ ephemeralPublicKey }),
845
+ };
846
+ });
847
+ }
848
+ prepareSaplingSpendDescription(saplingContext, inputsToSpend) {
849
+ return __awaiter(this, void 0, void 0, function* () {
850
+ const publicKeyReRandomization = yield __classPrivateFieldGet(this, _saplingWrapper).randR();
851
+ let stateDiff;
852
+ if (__classPrivateFieldGet(this, _saplingId$1)) {
853
+ stateDiff = yield __classPrivateFieldGet(this, _readProvider$1).getSaplingDiffById({ id: __classPrivateFieldGet(this, _saplingId$1) }, 'head');
854
+ }
855
+ else {
856
+ stateDiff = yield __classPrivateFieldGet(this, _readProvider$1).getSaplingDiffByContract(__classPrivateFieldGet(this, _contractAddress$1), 'head');
857
+ }
858
+ const stateTree = yield __classPrivateFieldGet(this, _saplingState).getStateTree(stateDiff, true);
859
+ const saplingSpendDescriptions = [];
860
+ for (let i = 0; i < inputsToSpend.length; i++) {
861
+ const amount = convertValueToBigNumber(inputsToSpend[i].value).toString();
862
+ const witness = yield __classPrivateFieldGet(this, _saplingState).getWitness(stateTree, new BigNumber(inputsToSpend[i].position));
863
+ const unsignedSpendDescription = __classPrivateFieldGet(this, _inMemoryProvingKey) ? yield __classPrivateFieldGet(this, _inMemoryProvingKey).prepareSpendDescription({
864
+ saplingContext,
865
+ address: inputsToSpend[i].paymentAddress,
866
+ randomCommitmentTrapdoor: inputsToSpend[i].randomCommitmentTrapdoor,
867
+ publicKeyReRandomization,
868
+ amount,
869
+ root: stateDiff.root,
870
+ witness,
871
+ })
872
+ : yield __classPrivateFieldGet(this, _inMemorySpendingKey$1).prepareSpendDescription({
873
+ saplingContext,
874
+ address: inputsToSpend[i].paymentAddress,
875
+ randomCommitmentTrapdoor: inputsToSpend[i].randomCommitmentTrapdoor,
876
+ publicKeyReRandomization,
877
+ amount,
878
+ root: stateDiff.root,
879
+ witness,
880
+ });
881
+ const unsignedSpendDescriptionBytes = __classPrivateFieldGet(this, _saplingForger$1).forgeUnsignedTxInput(unsignedSpendDescription);
882
+ const hash = blake.blake2b(unsignedSpendDescriptionBytes, yield this.getAntiReplay(), 32);
883
+ const spendDescription = yield __classPrivateFieldGet(this, _inMemorySpendingKey$1).signSpendDescription({
884
+ publicKeyReRandomization,
885
+ unsignedSpendDescription,
886
+ hash,
887
+ });
888
+ if (spendDescription.signature === undefined) {
889
+ throw new Error('Spend signing failed');
890
+ }
891
+ saplingSpendDescriptions.push(spendDescription);
892
+ }
893
+ return saplingSpendDescriptions;
894
+ });
895
+ }
896
+ encryptCiphertext(parametersCiphertext) {
897
+ return __awaiter(this, void 0, void 0, function* () {
898
+ const recipientDiversifiedTransmissionKey = yield __classPrivateFieldGet(this, _saplingWrapper).getPkdFromRawPaymentAddress(parametersCiphertext.address);
899
+ const keyAgreement = yield __classPrivateFieldGet(this, _saplingWrapper).keyAgreement(recipientDiversifiedTransmissionKey, parametersCiphertext.ephemeralPrivateKey);
900
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
901
+ const nonceEnc = Buffer.from(__classPrivateFieldGet(this, _saplingWrapper).getRandomBytes(24));
902
+ const transactionPlaintext = __classPrivateFieldGet(this, _saplingForger$1).forgeTransactionPlaintext({
903
+ diversifier: parametersCiphertext.diversifier,
904
+ amount: parametersCiphertext.amount,
905
+ randomCommitmentTrapdoor: parametersCiphertext.randomCommitmentTrapdoor,
906
+ memoSize: __classPrivateFieldGet(this, _memoSize$1) * 2,
907
+ memo: parametersCiphertext.memo,
908
+ });
909
+ const nonceOut = Buffer.from(__classPrivateFieldGet(this, _saplingWrapper).getRandomBytes(24));
910
+ const payloadEnc = Buffer.from(secretBox(keyAgreementHash, nonceEnc, transactionPlaintext));
911
+ const payloadOut = Buffer.from(secretBox(parametersCiphertext.outgoingCipherKey, nonceOut, Buffer.concat([
912
+ recipientDiversifiedTransmissionKey,
913
+ parametersCiphertext.ephemeralPrivateKey,
914
+ ])));
915
+ return { payloadEnc, nonceEnc, payloadOut, nonceOut };
916
+ });
917
+ }
918
+ createPaybackOutput(params, sumSelectedInputs) {
919
+ return __awaiter(this, void 0, void 0, function* () {
920
+ const payBackAmount = sumSelectedInputs.minus(params.amount).toString();
921
+ const payBackOutput = yield this.prepareSaplingOutputDescription({
922
+ saplingContext: params.saplingContext,
923
+ address: params.address,
924
+ amount: payBackAmount,
925
+ memo: params.memo,
926
+ randomCommitmentTrapdoor: params.randomCommitmentTrapdoor,
927
+ outgoingViewingKey: params.outgoingViewingKey,
928
+ });
929
+ return { payBackOutput, payBackAmount };
930
+ });
931
+ }
932
+ createBindingSignature(parametersBindingSig) {
933
+ return __awaiter(this, void 0, void 0, function* () {
934
+ const outputs = __classPrivateFieldGet(this, _saplingForger$1).forgeOutputDescriptions(parametersBindingSig.outputs);
935
+ const inputs = __classPrivateFieldGet(this, _saplingForger$1).forgeSpendDescriptions(parametersBindingSig.inputs);
936
+ const transactionSigHash = blake.blake2b(Buffer.concat([inputs, outputs, parametersBindingSig.boundData]), yield this.getAntiReplay(), 32);
937
+ return __classPrivateFieldGet(this, _saplingWrapper).createBindingSignature(parametersBindingSig.saplingContext, parametersBindingSig.balance.toFixed(), transactionSigHash);
938
+ });
939
+ }
940
+ getAntiReplay() {
941
+ return __awaiter(this, void 0, void 0, function* () {
942
+ let chainId = __classPrivateFieldGet(this, _chainId);
943
+ if (!chainId) {
944
+ chainId = yield __classPrivateFieldGet(this, _readProvider$1).getChainId();
945
+ __classPrivateFieldSet(this, _chainId, chainId);
946
+ }
947
+ return Buffer.from(`${__classPrivateFieldGet(this, _contractAddress$1)}${chainId}`);
948
+ });
949
+ }
950
+ }
951
+ _inMemorySpendingKey$1 = new WeakMap(), _inMemoryProvingKey = new WeakMap(), _saplingForger$1 = new WeakMap(), _contractAddress$1 = new WeakMap(), _saplingId$1 = new WeakMap(), _memoSize$1 = new WeakMap(), _readProvider$1 = new WeakMap(), _saplingWrapper = new WeakMap(), _chainId = new WeakMap(), _saplingState = new WeakMap();
952
+
953
+ function decryptKey(spendingKey, password) {
954
+ const keyArr = b58cdecode(spendingKey, prefix[Prefix.SASK]);
955
+ // exit first if no password and key is encrypted
956
+ if (!password && spendingKey.slice(0, 4) !== 'sask') {
957
+ throw new InvalidSpendingKey(spendingKey, 'no password Provided to decrypt');
958
+ }
959
+ if (password && spendingKey.slice(0, 4) !== 'sask') {
960
+ const salt = toBuffer(keyArr.slice(0, 8));
961
+ const encryptedSk = toBuffer(keyArr.slice(8));
962
+ const encryptionKey = pbkdf2.pbkdf2Sync(password, salt, 32768, 32, 'sha512');
963
+ const decrypted = openSecretBox(new Uint8Array(encryptionKey), new Uint8Array(24), new Uint8Array(encryptedSk));
964
+ if (!decrypted) {
965
+ throw new InvalidSpendingKey(spendingKey, 'Encrypted Spending Key or Password Incorrect');
966
+ }
967
+ return toBuffer(decrypted);
968
+ }
969
+ else {
970
+ return toBuffer(keyArr);
971
+ }
972
+ }
973
+
974
+ var _spendingKeyBuf, _saplingViewingKey;
975
+ /**
976
+ * @description holds the spending key, create proof and signature for spend descriptions
977
+ * can instantiate from mnemonic word list or decrypt a encrypted spending key
978
+ * with access to instantiate a InMemoryViewingKey
979
+ */
980
+ class InMemorySpendingKey {
981
+ /**
982
+ *
983
+ * @param spendingKey unencrypted sask... or encrypted MMXj...
984
+ * @param password required for MMXj encrypted keys
985
+ */
986
+ constructor(spendingKey, password) {
987
+ _spendingKeyBuf.set(this, void 0);
988
+ _saplingViewingKey.set(this, void 0);
989
+ __classPrivateFieldSet(this, _spendingKeyBuf, decryptKey(spendingKey, password));
990
+ }
991
+ /**
992
+ *
993
+ * @param mnemonic string of words
994
+ * @param derivationPath tezos current standard 'm/'
995
+ * @returns InMemorySpendingKey class instantiated
996
+ */
997
+ static fromMnemonic(mnemonic, derivationPath = 'm/') {
998
+ return __awaiter(this, void 0, void 0, function* () {
999
+ // no password passed here. password provided only changes from sask -> MMXj
1000
+ const fullSeed = yield bip39.mnemonicToSeed(mnemonic);
1001
+ const first32 = fullSeed.slice(0, 32);
1002
+ const second32 = fullSeed.slice(32);
1003
+ // reduce seed bytes must be 32 bytes reflecting both halves
1004
+ const seed = Buffer.from(first32.map((byte, index) => byte ^ second32[index]));
1005
+ const spendingKeyArr = new Uint8Array(yield sapling.getExtendedSpendingKey(seed, derivationPath));
1006
+ const spendingKey = b58cencode(spendingKeyArr, prefix[Prefix.SASK]);
1007
+ if (ValidationResult.VALID !== 3) {
1008
+ throw new InvalidSpendingKey(spendingKey);
1009
+ }
1010
+ return new InMemorySpendingKey(spendingKey);
1011
+ });
1012
+ }
1013
+ /**
1014
+ *
1015
+ * @returns InMemoryViewingKey instantiated class
1016
+ */
1017
+ getSaplingViewingKeyProvider() {
1018
+ return __awaiter(this, void 0, void 0, function* () {
1019
+ let viewingKey;
1020
+ if (!__classPrivateFieldGet(this, _saplingViewingKey)) {
1021
+ viewingKey = yield sapling.getExtendedFullViewingKeyFromSpendingKey(__classPrivateFieldGet(this, _spendingKeyBuf));
1022
+ __classPrivateFieldSet(this, _saplingViewingKey, new InMemoryViewingKey(viewingKey.toString('hex')));
1023
+ }
1024
+ return __classPrivateFieldGet(this, _saplingViewingKey);
1025
+ });
1026
+ }
1027
+ /**
1028
+ * @description Prepare an unsigned sapling spend description using the spending key
1029
+ * @param parametersSpendProof.saplingContext The sapling proving context
1030
+ * @param parametersSpendProof.address The address of the input
1031
+ * @param parametersSpendProof.randomCommitmentTrapdoor The randomness of the commitment
1032
+ * @param parametersSpendProof.publicKeyReRandomization The re-randomization of the public key
1033
+ * @param parametersSpendProof.amount The value of the input
1034
+ * @param parametersSpendProof.root The root of the merkle tree
1035
+ * @param parametersSpendProof.witness The path of the commitment in the tree
1036
+ * @param derivationPath tezos current standard 'm/'
1037
+ * @returns The unsigned spend description
1038
+ */
1039
+ prepareSpendDescription(parametersSpendProof) {
1040
+ return __awaiter(this, void 0, void 0, function* () {
1041
+ const spendDescription = yield sapling.prepareSpendDescriptionWithSpendingKey(parametersSpendProof.saplingContext, __classPrivateFieldGet(this, _spendingKeyBuf), parametersSpendProof.address, parametersSpendProof.randomCommitmentTrapdoor, parametersSpendProof.publicKeyReRandomization, parametersSpendProof.amount, parametersSpendProof.root, parametersSpendProof.witness);
1042
+ return {
1043
+ commitmentValue: spendDescription.cv,
1044
+ nullifier: spendDescription.nf,
1045
+ publicKeyReRandomization: spendDescription.rk,
1046
+ rtAnchor: spendDescription.rt,
1047
+ proof: spendDescription.proof,
1048
+ };
1049
+ });
1050
+ }
1051
+ /**
1052
+ * @description Sign a sapling spend description
1053
+ * @param parametersSpendSig.publicKeyReRandomization The re-randomization of the public key
1054
+ * @param parametersSpendSig.unsignedSpendDescription The unsigned Spend description
1055
+ * @param parametersSpendSig.hash The data to be signed
1056
+ * @returns The signed spend description
1057
+ */
1058
+ signSpendDescription(parametersSpendSig) {
1059
+ return __awaiter(this, void 0, void 0, function* () {
1060
+ const signedSpendDescription = yield sapling.signSpendDescription({
1061
+ cv: parametersSpendSig.unsignedSpendDescription.commitmentValue,
1062
+ rt: parametersSpendSig.unsignedSpendDescription.rtAnchor,
1063
+ nf: parametersSpendSig.unsignedSpendDescription.nullifier,
1064
+ rk: parametersSpendSig.unsignedSpendDescription.publicKeyReRandomization,
1065
+ proof: parametersSpendSig.unsignedSpendDescription.proof,
1066
+ }, __classPrivateFieldGet(this, _spendingKeyBuf), parametersSpendSig.publicKeyReRandomization, parametersSpendSig.hash);
1067
+ return {
1068
+ commitmentValue: signedSpendDescription.cv,
1069
+ nullifier: signedSpendDescription.nf,
1070
+ publicKeyReRandomization: signedSpendDescription.rk,
1071
+ proof: signedSpendDescription.proof,
1072
+ signature: signedSpendDescription.spendAuthSig,
1073
+ };
1074
+ });
1075
+ }
1076
+ /**
1077
+ * @description Return a proof authorizing key from the configured spending key
1078
+ */
1079
+ getProvingKey() {
1080
+ return __awaiter(this, void 0, void 0, function* () {
1081
+ const provingKey = yield sapling.getProofAuthorizingKey(__classPrivateFieldGet(this, _spendingKeyBuf));
1082
+ return provingKey.toString('hex');
1083
+ });
1084
+ }
1085
+ }
1086
+ _spendingKeyBuf = new WeakMap(), _saplingViewingKey = new WeakMap();
1087
+
1088
+ var _fullViewingKey;
1089
+ /**
1090
+ * @description Holds the viewing key
1091
+ */
1092
+ class InMemoryViewingKey {
1093
+ constructor(fullViewingKey) {
1094
+ _fullViewingKey.set(this, void 0);
1095
+ __classPrivateFieldSet(this, _fullViewingKey, Buffer.from(fullViewingKey, 'hex'));
1096
+ }
1097
+ /**
1098
+ * @description Allows to instantiate the InMemoryViewingKey from an encrypted/unencrypted spending key
1099
+ *
1100
+ * @param spendingKey Base58Check-encoded spending key
1101
+ * @param password Optional password to decrypt the spending key
1102
+ * @example
1103
+ * ```
1104
+ * await InMemoryViewingKey.fromSpendingKey('sask27SLmU9herddHz4qFJBLMjWYMbJF8RtS579w9ej9mfCYK7VUdyCJPHK8AzW9zMsopGZEkYeNjAY7Zz1bkM7CGu8eKLzrjBLTMC5wWJDhxiK91ahA29rhDRsHdJDV2u2jFwb2MNUix8JW7sAkAqYVaJpCehTBPgRQ1KqKwqqUaNmuD8kazd4Q8MCWmgbWs21Yuomdqyi9FLigjRp7oY4m5adaVU19Nj1AHvsMY2tePeU2L')
1105
+ * ```
1106
+ *
1107
+ */
1108
+ static fromSpendingKey(spendingKey, password) {
1109
+ return __awaiter(this, void 0, void 0, function* () {
1110
+ const inMemorySpendingkey = new InMemorySpendingKey(spendingKey, password);
1111
+ return inMemorySpendingkey.getSaplingViewingKeyProvider();
1112
+ });
1113
+ }
1114
+ /**
1115
+ * @description Retrieve the full viewing key
1116
+ * @returns Buffer representing the full viewing key
1117
+ *
1118
+ */
1119
+ getFullViewingKey() {
1120
+ return __classPrivateFieldGet(this, _fullViewingKey);
1121
+ }
1122
+ /**
1123
+ * @description Retrieve the outgoing viewing key
1124
+ * @returns Buffer representing the outgoing viewing key
1125
+ *
1126
+ */
1127
+ getOutgoingViewingKey() {
1128
+ return __awaiter(this, void 0, void 0, function* () {
1129
+ return sapling.getOutgoingViewingKey(__classPrivateFieldGet(this, _fullViewingKey));
1130
+ });
1131
+ }
1132
+ /**
1133
+ * @description Retrieve the incoming viewing key
1134
+ * @returns Buffer representing the incoming viewing key
1135
+ *
1136
+ */
1137
+ getIncomingViewingKey() {
1138
+ return __awaiter(this, void 0, void 0, function* () {
1139
+ return sapling.getIncomingViewingKey(__classPrivateFieldGet(this, _fullViewingKey));
1140
+ });
1141
+ }
1142
+ /**
1143
+ * @description Retrieve a payment address
1144
+ * @param addressIndex used to determine which diversifier should be used to derive the address, default is 0
1145
+ * @returns Base58Check-encoded address and its index
1146
+ *
1147
+ */
1148
+ getAddress(addressIndex) {
1149
+ return __awaiter(this, void 0, void 0, function* () {
1150
+ const { index, raw } = yield sapling.getPaymentAddressFromViewingKey(__classPrivateFieldGet(this, _fullViewingKey), addressIndex);
1151
+ return {
1152
+ address: b58cencode(raw, prefix[Prefix.ZET1]),
1153
+ addressIndex: index.readInt32LE(),
1154
+ };
1155
+ });
1156
+ }
1157
+ }
1158
+ _fullViewingKey = new WeakMap();
1159
+
1160
+ var _provingKey;
1161
+ /**
1162
+ * @description holds the proving key, create proof for spend descriptions
1163
+ * The class can be instantiated from a proving key or a spending key
1164
+ */
1165
+ class InMemoryProvingKey {
1166
+ constructor(provingKey) {
1167
+ _provingKey.set(this, void 0);
1168
+ __classPrivateFieldSet(this, _provingKey, Buffer.from(provingKey, 'hex'));
1169
+ }
1170
+ /**
1171
+ * @description Allows to instantiate the InMemoryProvingKey from an encrypted/unencrypted spending key
1172
+ *
1173
+ * @param spendingKey Base58Check-encoded spending key
1174
+ * @param password Optional password to decrypt the spending key
1175
+ * @example
1176
+ * ```
1177
+ * await InMemoryProvingKey.fromSpendingKey('sask27SLmU9herddHz4qFJBLMjWYMbJF8RtS579w9ej9mfCYK7VUdyCJPHK8AzW9zMsopGZEkYeNjAY7Zz1bkM7CGu8eKLzrjBLTMC5wWJDhxiK91ahA29rhDRsHdJDV2u2jFwb2MNUix8JW7sAkAqYVaJpCehTBPgRQ1KqKwqqUaNmuD8kazd4Q8MCWmgbWs21Yuomdqyi9FLigjRp7oY4m5adaVU19Nj1AHvsMY2tePeU2L')
1178
+ * ```
1179
+ *
1180
+ */
1181
+ static fromSpendingKey(spendingKey, password) {
1182
+ return __awaiter(this, void 0, void 0, function* () {
1183
+ const decodedSpendingKey = decryptKey(spendingKey, password);
1184
+ const provingKey = yield sapling.getProofAuthorizingKey(decodedSpendingKey);
1185
+ return new InMemoryProvingKey(provingKey.toString('hex'));
1186
+ });
1187
+ }
1188
+ /**
1189
+ * @description Prepare an unsigned sapling spend description using the proving key
1190
+ *
1191
+ * @param parametersSpendProof.saplingContext The sapling proving context
1192
+ * @param parametersSpendProof.address The address of the input
1193
+ * @param parametersSpendProof.randomCommitmentTrapdoor The randomness of the commitment
1194
+ * @param parametersSpendProof.publicKeyReRandomization The re-randomization of the public key
1195
+ * @param parametersSpendProof.amount The value of the input
1196
+ * @param parametersSpendProof.root The root of the merkle tree
1197
+ * @param parametersSpendProof.witness The path of the commitment in the tree
1198
+ * @param derivationPath tezos current standard 'm/'
1199
+ * @returns The unsinged spend description
1200
+ */
1201
+ prepareSpendDescription(parametersSpendProof) {
1202
+ return __awaiter(this, void 0, void 0, function* () {
1203
+ const spendDescription = yield sapling.prepareSpendDescriptionWithAuthorizingKey(parametersSpendProof.saplingContext, __classPrivateFieldGet(this, _provingKey), parametersSpendProof.address, parametersSpendProof.randomCommitmentTrapdoor, parametersSpendProof.publicKeyReRandomization, parametersSpendProof.amount, parametersSpendProof.root, parametersSpendProof.witness);
1204
+ return {
1205
+ commitmentValue: spendDescription.cv,
1206
+ nullifier: spendDescription.nf,
1207
+ publicKeyReRandomization: spendDescription.rk,
1208
+ rtAnchor: spendDescription.rt,
1209
+ proof: spendDescription.proof,
1210
+ };
1211
+ });
1212
+ }
1213
+ }
1214
+ _provingKey = new WeakMap();
1215
+
1216
+ /**
1217
+ * @packageDocumentation
1218
+ * @module @taquito/sapling
1219
+ */
1220
+ var _inMemorySpendingKey, _saplingId, _contractAddress, _memoSize, _readProvider, _packer, _saplingForger, _saplingTxBuilder, _saplingTransactionViewer;
1221
+ /**
1222
+ * @description Class that surfaces all of the sapling capability allowing to read from a sapling state and prepare transactions
1223
+ *
1224
+ * @param keys.saplingSigner Holds the sapling spending key
1225
+ * @param keys.saplingProver (Optional) Allows to generate the proofs with the proving key rather than the spending key
1226
+ * @param saplingContractDetails Contains the address of the sapling contract, the memo size, and an optional sapling id that must be defined if the sapling contract contains more than one sapling state
1227
+ * @param readProvider Allows to read data from the blockchain
1228
+ * @param packer (Optional) Allows packing data. Use the `MichelCodecPacker` by default.
1229
+ * @param saplingForger (Optional) Allows serializing the sapling transactions. Use the `SaplingForger` by default.
1230
+ * @param saplingTxBuilder (Optional) Allows to prepare the sapling transactions. Use the `SaplingTransactionBuilder` by default.
1231
+ * @example
1232
+ * ```
1233
+ * const inMemorySpendingKey = await InMemorySpendingKey.fromMnemonic('YOUR_MNEMONIC');
1234
+ * const readProvider = new RpcReadAdapter(new RpcClient('https://YOUR_PREFERRED_RPC_URL'))
1235
+ *
1236
+ * const saplingToolkit = new SaplingToolkit(
1237
+ * { saplingSigner: inMemorySpendingKey },
1238
+ * { contractAddress: SAPLING_CONTRACT_ADDRESS, memoSize: 8 },
1239
+ * readProvider
1240
+ * )
1241
+ * ```
1242
+ */
1243
+ class SaplingToolkit {
1244
+ constructor(keys, saplingContractDetails, readProvider, packer = new MichelCodecPacker(), saplingForger = new SaplingForger(), saplingTxBuilder = new SaplingTransactionBuilder(keys, saplingForger, saplingContractDetails, readProvider)) {
1245
+ _inMemorySpendingKey.set(this, void 0);
1246
+ _saplingId.set(this, void 0);
1247
+ _contractAddress.set(this, void 0);
1248
+ _memoSize.set(this, void 0);
1249
+ _readProvider.set(this, void 0);
1250
+ _packer.set(this, void 0);
1251
+ _saplingForger.set(this, void 0);
1252
+ _saplingTxBuilder.set(this, void 0);
1253
+ _saplingTransactionViewer.set(this, void 0);
1254
+ __classPrivateFieldSet(this, _inMemorySpendingKey, keys.saplingSigner);
1255
+ __classPrivateFieldSet(this, _saplingId, saplingContractDetails.saplingId);
1256
+ __classPrivateFieldSet(this, _contractAddress, saplingContractDetails.contractAddress);
1257
+ __classPrivateFieldSet(this, _memoSize, saplingContractDetails.memoSize);
1258
+ __classPrivateFieldSet(this, _readProvider, readProvider);
1259
+ __classPrivateFieldSet(this, _packer, packer);
1260
+ __classPrivateFieldSet(this, _saplingForger, saplingForger);
1261
+ __classPrivateFieldSet(this, _saplingTxBuilder, saplingTxBuilder);
1262
+ }
1263
+ /**
1264
+ * @description Get an instance of `SaplingTransactionViewer` which allows to retrieve and decrypt sapling transactions and calculate the unspent balance.
1265
+ */
1266
+ getSaplingTransactionViewer() {
1267
+ return __awaiter(this, void 0, void 0, function* () {
1268
+ let saplingTransactionViewer;
1269
+ if (!__classPrivateFieldGet(this, _saplingTransactionViewer)) {
1270
+ const saplingViewingKey = yield __classPrivateFieldGet(this, _inMemorySpendingKey).getSaplingViewingKeyProvider();
1271
+ saplingTransactionViewer = new SaplingTransactionViewer(saplingViewingKey, this.getSaplingContractId(), __classPrivateFieldGet(this, _readProvider));
1272
+ __classPrivateFieldSet(this, _saplingTransactionViewer, saplingTransactionViewer);
1273
+ }
1274
+ return __classPrivateFieldGet(this, _saplingTransactionViewer);
1275
+ });
1276
+ }
1277
+ /**
1278
+ * @description Prepare a shielded transaction
1279
+ * @param shieldedTxParams `to` is the payment address that will receive the shielded tokens (zet).
1280
+ * `amount` is the amount of shielded tokens in tez by default.
1281
+ * `mutez` needs to be set to true if the amount of shielded tokens is in mutez.
1282
+ * `memo` is an empty string by default.
1283
+ * @returns a string representing the sapling transaction
1284
+ */
1285
+ prepareShieldedTransaction(shieldedTxParams) {
1286
+ return __awaiter(this, void 0, void 0, function* () {
1287
+ const { formatedParams, totalAmount } = this.formatTransactionParams(shieldedTxParams, this.validateDestinationSaplingAddress);
1288
+ const root = yield this.getRoot();
1289
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _saplingTxBuilder).createShieldedTx(formatedParams, totalAmount, DEFAULT_BOUND_DATA);
1290
+ const forgedSaplingTx = __classPrivateFieldGet(this, _saplingForger).forgeSaplingTransaction({
1291
+ inputs,
1292
+ outputs,
1293
+ balance,
1294
+ root,
1295
+ boundData: DEFAULT_BOUND_DATA,
1296
+ signature,
1297
+ });
1298
+ return forgedSaplingTx.toString('hex');
1299
+ });
1300
+ }
1301
+ /**
1302
+ * @description Prepare an unshielded transaction
1303
+ * @param unshieldedTxParams `to` is the Tezos address that will receive the unshielded tokens (tz1, tz2 or tz3).
1304
+ * `amount` is the amount of unshielded tokens in tez by default.
1305
+ * `mutez` needs to be set to true if the amount of unshielded tokens is in mutez.
1306
+ * @returns a string representing the sapling transaction.
1307
+ */
1308
+ prepareUnshieldedTransaction(unshieldedTxParams) {
1309
+ return __awaiter(this, void 0, void 0, function* () {
1310
+ const { formatedParams, totalAmount } = this.formatTransactionParams([unshieldedTxParams], this.validateDestinationImplicitAddress);
1311
+ const boundData = yield this.createBoundData(formatedParams[0].to);
1312
+ const root = yield this.getRoot();
1313
+ const chosenInputs = yield this.selectInputsToSpend(new BigNumber(formatedParams[0].amount));
1314
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _saplingTxBuilder).createSaplingTx([], totalAmount, boundData, chosenInputs);
1315
+ const forgedSaplingTx = __classPrivateFieldGet(this, _saplingForger).forgeSaplingTransaction({
1316
+ inputs,
1317
+ outputs,
1318
+ balance,
1319
+ root,
1320
+ boundData,
1321
+ signature,
1322
+ });
1323
+ return forgedSaplingTx.toString('hex');
1324
+ });
1325
+ }
1326
+ /**
1327
+ * @description Prepare a sapling transaction (zet to zet)
1328
+ * @param saplingTxParams `to` is the payment address that will receive the shielded tokens (zet).
1329
+ * `amount` is the amount of unshielded tokens in tez by default.
1330
+ * `mutez` needs to be set to true if the amount of unshielded tokens is in mutez.
1331
+ * `memo` is an empty string by default.
1332
+ * @returns a string representing the sapling transaction.
1333
+ */
1334
+ prepareSaplingTransaction(saplingTxParams) {
1335
+ return __awaiter(this, void 0, void 0, function* () {
1336
+ const { formatedParams, totalAmount } = this.formatTransactionParams(saplingTxParams, this.validateDestinationSaplingAddress);
1337
+ const root = yield this.getRoot();
1338
+ const chosenInputs = yield this.selectInputsToSpend(totalAmount);
1339
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _saplingTxBuilder).createSaplingTx(formatedParams, totalAmount, DEFAULT_BOUND_DATA, chosenInputs);
1340
+ const forgedSaplingTx = __classPrivateFieldGet(this, _saplingForger).forgeSaplingTransaction({
1341
+ inputs,
1342
+ outputs,
1343
+ balance,
1344
+ root,
1345
+ boundData: DEFAULT_BOUND_DATA,
1346
+ signature,
1347
+ });
1348
+ return forgedSaplingTx.toString('hex');
1349
+ });
1350
+ }
1351
+ formatTransactionParams(txParams, validateDestination) {
1352
+ const formatedParams = [];
1353
+ let totalAmount = new BigNumber(0);
1354
+ txParams.forEach((param) => {
1355
+ var _a;
1356
+ validateDestination(param.to);
1357
+ const amountMutez = param.mutez
1358
+ ? param.amount.toString()
1359
+ : format('tz', 'mutez', param.amount).toString();
1360
+ totalAmount = totalAmount.plus(new BigNumber(amountMutez));
1361
+ const memo = (_a = param.memo) !== null && _a !== void 0 ? _a : DEFAULT_MEMO;
1362
+ if (memo.length > __classPrivateFieldGet(this, _memoSize)) {
1363
+ throw new InvalidMemo(memo, 'The memo is too long.');
1364
+ }
1365
+ formatedParams.push({ to: param.to, amount: amountMutez, memo });
1366
+ });
1367
+ return { formatedParams, totalAmount };
1368
+ }
1369
+ getRoot() {
1370
+ return __awaiter(this, void 0, void 0, function* () {
1371
+ if (__classPrivateFieldGet(this, _saplingId)) {
1372
+ const { root } = yield __classPrivateFieldGet(this, _readProvider).getSaplingDiffById({ id: __classPrivateFieldGet(this, _saplingId) }, 'head');
1373
+ return root;
1374
+ }
1375
+ else {
1376
+ const { root } = yield __classPrivateFieldGet(this, _readProvider).getSaplingDiffByContract(__classPrivateFieldGet(this, _contractAddress), 'head');
1377
+ return root;
1378
+ }
1379
+ });
1380
+ }
1381
+ createBoundData(destination) {
1382
+ return __awaiter(this, void 0, void 0, function* () {
1383
+ const pref = destination.substr(0, 3);
1384
+ let pad;
1385
+ switch (pref) {
1386
+ case 'tz1': {
1387
+ pad = Buffer.from('00', 'hex');
1388
+ break;
1389
+ }
1390
+ case 'tz2': {
1391
+ pad = Buffer.from('01', 'hex');
1392
+ break;
1393
+ }
1394
+ case 'tz3': {
1395
+ pad = Buffer.from('02', 'hex');
1396
+ break;
1397
+ }
1398
+ default: {
1399
+ throw new InvalidKeyError(destination, "The 'to' parameter contains an invalid prefix.");
1400
+ }
1401
+ }
1402
+ const decodedDestination = b58cdecode(destination, prefix[pref]);
1403
+ const padDestination = Buffer.concat([pad, Buffer.from(decodedDestination)]);
1404
+ const packedDestination = yield __classPrivateFieldGet(this, _packer).packData({
1405
+ data: { bytes: padDestination.toString('hex') },
1406
+ type: { prim: 'bytes' },
1407
+ });
1408
+ return Buffer.from(packedDestination.packed, 'hex');
1409
+ });
1410
+ }
1411
+ validateDestinationImplicitAddress(to) {
1412
+ if (validateKeyHash(to) !== ValidationResult.VALID) {
1413
+ throw new InvalidAddressError(to, "The 'to' parameter must be a Tezos public key hash (tz1, tz2, tz3).");
1414
+ }
1415
+ }
1416
+ validateDestinationSaplingAddress(to) {
1417
+ if (!to.startsWith(Prefix.ZET1)) {
1418
+ throw new InvalidAddressError(to, "The 'to' parameter must be a sapling address (zet1).");
1419
+ }
1420
+ }
1421
+ getSaplingContractId() {
1422
+ let saplingContractId;
1423
+ if (__classPrivateFieldGet(this, _saplingId)) {
1424
+ saplingContractId = { saplingId: __classPrivateFieldGet(this, _saplingId) };
1425
+ }
1426
+ else {
1427
+ saplingContractId = { contractAddress: __classPrivateFieldGet(this, _contractAddress) };
1428
+ }
1429
+ return saplingContractId;
1430
+ }
1431
+ selectInputsToSpend(amountMutez) {
1432
+ return __awaiter(this, void 0, void 0, function* () {
1433
+ const saplingTxViewer = yield this.getSaplingTransactionViewer();
1434
+ const { incoming } = yield saplingTxViewer.getIncomingAndOutgoingTransactionsRaw();
1435
+ const inputsToSpend = [];
1436
+ let sumSelectedInputs = new BigNumber(0);
1437
+ incoming.forEach((input) => {
1438
+ if (!input.isSpent && sumSelectedInputs.isLessThan(amountMutez)) {
1439
+ const txAmount = convertValueToBigNumber(input.value);
1440
+ sumSelectedInputs = sumSelectedInputs.plus(txAmount);
1441
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1442
+ const rest = __rest(input, ["isSpent"]);
1443
+ inputsToSpend.push(rest);
1444
+ }
1445
+ });
1446
+ if (sumSelectedInputs.isLessThan(new BigNumber(amountMutez))) {
1447
+ throw new InsufficientBalance(sumSelectedInputs.toString(), amountMutez.toString());
1448
+ }
1449
+ return { inputsToSpend, sumSelectedInputs };
1450
+ });
1451
+ }
1452
+ }
1453
+ _inMemorySpendingKey = new WeakMap(), _saplingId = new WeakMap(), _contractAddress = new WeakMap(), _memoSize = new WeakMap(), _readProvider = new WeakMap(), _packer = new WeakMap(), _saplingForger = new WeakMap(), _saplingTxBuilder = new WeakMap(), _saplingTransactionViewer = new WeakMap();
1454
+
1455
+ export { InMemoryProvingKey, InMemorySpendingKey, InMemoryViewingKey, SaplingToolkit, SaplingTransactionViewer };
1456
+ //# sourceMappingURL=taquito-sapling.es6.js.map