{"version":3,"sources":["jsdelivr-header.js","/npm/@taquito/sapling@24.2.0/dist/taquito-sapling.umd.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,ACNA;AACA;AACA","file":"/npm/@taquito/sapling@24.2.0/dist/taquito-sapling.umd.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@taquito/sapling@24.2.0/dist/taquito-sapling.umd.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?t(exports,require(\"bignumber.js\"),require(\"@taquito/taquito\"),require(\"@taquito/utils\"),require(\"@taquito/core\"),require(\"@airgap/sapling-wasm\"),require(\"blakejs\"),require(\"@stablelib/nacl\"),require(\"@stablelib/random\"),require(\"typedarray-to-buffer\"),require(\"pbkdf2\"),require(\"bip39\")):\"function\"==typeof define&&define.amd?define([\"exports\",\"bignumber.js\",\"@taquito/taquito\",\"@taquito/utils\",\"@taquito/core\",\"@airgap/sapling-wasm\",\"blakejs\",\"@stablelib/nacl\",\"@stablelib/random\",\"typedarray-to-buffer\",\"pbkdf2\",\"bip39\"],t):t((e=\"undefined\"!=typeof globalThis?globalThis:e||self).taquitoSapling={},e.BigNumber,e.taquito,e.utils,e.core,e.sapling,e.blake,e.nacl,e.random,e.toBuffer,e.pbkdf2,e.bip39)}(this,(function(e,t,i,n,r,o,s,a,d,u,c,p){\"use strict\";function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if(\"default\"!==i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var h=l(o),f=l(p);function m(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&\"function\"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}function g(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{d(n.next(e))}catch(e){o(e)}}function a(e){try{d(n.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}d((n=n.apply(e,t||[])).next())}))}function y(e,t,i,n){if(\"a\"===i&&!n)throw new TypeError(\"Private accessor was defined without a getter\");if(\"function\"==typeof t?e!==t||!n:!t.has(e))throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");return\"m\"===i?n:\"a\"===i?n.call(e):n?n.value:t.get(e)}function v(e,t,i,n,r){if(\"m\"===n)throw new TypeError(\"Private method is not writable\");if(\"a\"===n&&!r)throw new TypeError(\"Private accessor was defined without a setter\");if(\"function\"==typeof t?e!==t||!r:!t.has(e))throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");return\"a\"===n?r.call(e,i):r?r.value=i:t.set(e,i),i}\"function\"==typeof SuppressedError&&SuppressedError;class S extends r.ParameterValidationError{constructor(e,t){super(),this.sk=e,this.errorDetail=t,this.name=\"InvalidSpendingKey\",this.message=`Invalid spending key \"${e}\" ${t}.`}}class w extends r.ParameterValidationError{constructor(e){super(),this.root=e,this.name=\"InvalidMerkleTreeError\",this.message=`Invalid merkle tree has root \"${JSON.stringify(e)}\" different from expected root.`}}class b extends r.TaquitoError{constructor(e){super(),this.message=e,this.name=\"TreeConstructionFailure\"}}class x extends r.ParameterValidationError{constructor(e,t){super(),this.memo=e,this.errorDetails=t,this.name=\"InvalidMemo\",this.message=`Invalid memo \"${e}\" with length ${e.length} ${t}`}}class T extends r.TaquitoError{constructor(e,t){super(),this.realBalance=e,this.amountToSpend=t,this.name=\"InsufficientBalance\",this.message=`Unable to spend \"${t}\" mutez while the balance is only ${e} mutez.`}}class k extends r.TaquitoError{constructor(e){super(),this.message=e,this.name=\"SaplingTransactionViewerError\"}}function P(e){const t=function(e){const t=e.match(/^(.*?)(00)+$/);return t?t[1]:e}(e);return\"\"===t?t:n.bytesToString(t)}function B(e){return{value:A(e.value),memo:P(Buffer.from(e.memo).toString(\"hex\")),paymentAddress:n.b58Encode(e.paymentAddress,n.PrefixV2.SaplingAddress)}}function A(e){return new t(Buffer.from(e).toString(\"hex\"),16)}class C{forgeSaplingTransaction(e){const t=this.forgeSpendDescriptions(e.inputs),i=Buffer.concat([n.toHexBuf(t.length,32),t]),r=this.forgeOutputDescriptions(e.outputs),o=Buffer.concat([n.toHexBuf(r.length,32),r]),s=Buffer.from(e.root,\"hex\");return Buffer.concat([i,o,e.signature,n.toHexBuf(e.balance,64),s,n.toHexBuf(e.boundData.length,32),e.boundData])}forgeSpendDescriptions(e){const t=[];for(const i of e){const e=this.forgeSpendDescription(i);t.push(e)}return Buffer.concat(t)}forgeSpendDescription(e){return Buffer.concat([e.commitmentValue,e.nullifier,e.publicKeyReRandomization,e.proof,e.signature])}forgeOutputDescriptions(e){const t=[];for(const i of e){const e=this.forgeOutputDescription(i);t.push(e)}return Buffer.concat(t)}forgeOutputDescription(e){const t=e.ciphertext;return Buffer.concat([e.commitment,e.proof,t.commitmentValue,t.ephemeralPublicKey,n.toHexBuf(t.payloadEnc.length,32),t.payloadEnc,t.nonceEnc,t.payloadOut,t.nonceOut])}forgeUnsignedTxInput(e){return Buffer.concat([e.commitmentValue,e.nullifier,e.publicKeyReRandomization,e.proof])}forgeTransactionPlaintext(e){const i=Buffer.from(n.stringToBytes(e.memo).padEnd(e.memoSize,\"0\"),\"hex\");return Buffer.concat([e.diversifier,n.toHexBuf(new t(e.amount),64),e.randomCommitmentTrapdoor,n.toHexBuf(e.memoSize,32),i])}}const D=\"KDFSaplingForTezosV1\",K=\"OCK_keystringderivation_TEZOS\",V=Buffer.from(\"\",\"hex\");var O,R,M;class E{constructor(e,t,i){O.set(this,void 0),R.set(this,void 0),M.set(this,void 0),v(this,O,e,\"f\"),v(this,M,t,\"f\"),v(this,R,i,\"f\")}getBalance(){return g(this,void 0,void 0,(function*(){let e=new t(0);const{commitments_and_ciphertexts:i,nullifiers:n}=yield this.getSaplingDiff();for(let t=0;t<i.length;t++){const r=yield this.decryptCiphertextAsReceiver(i[t]);if(r){const i=A(r.value);(yield this.isSpent(r.paymentAddress,i.toString(),r.randomCommitmentTrapdoor,t,n))||(e=e.plus(i))}}return e}))}getIncomingAndOutgoingTransactionsRaw(){return g(this,void 0,void 0,(function*(){const e=[],t=[],{commitments_and_ciphertexts:i,nullifiers:n}=yield this.getSaplingDiff();for(let r=0;r<i.length;r++){const o=yield this.decryptCiphertextAsReceiver(i[r]),s=yield this.decryptCiphertextAsSender(i[r]);if(o){const t=A(o.value),i=yield this.isSpent(o.paymentAddress,t.toString(),o.randomCommitmentTrapdoor,r,n);e.push(Object.assign(Object.assign({},o),{isSpent:i,position:r}))}s&&t.push(s)}return{incoming:e,outgoing:t}}))}getIncomingAndOutgoingTransactions(){return g(this,void 0,void 0,(function*(){const e=yield this.getIncomingAndOutgoingTransactionsRaw();return{incoming:e.incoming.map((e=>{var{isSpent:t}=e,i=m(e,[\"isSpent\"]);return Object.assign(Object.assign({},B(i)),{isSpent:t})})),outgoing:e.outgoing.map((e=>B(e)))}}))}getSaplingDiff(){return g(this,void 0,void 0,(function*(){let e;if(y(this,M,\"f\").saplingId)e=yield y(this,R,\"f\").getSaplingDiffById({id:y(this,M,\"f\").saplingId},\"head\");else{if(!y(this,M,\"f\").contractAddress)throw new k(\"A contract address or a sapling id was expected in the SaplingTransactionViewer constructor.\");e=yield y(this,R,\"f\").getSaplingDiffByContract(y(this,M,\"f\").contractAddress,\"head\")}return e}))}decryptCiphertextAsReceiver(e){return g(this,void 0,void 0,(function*(){const t=e[0],{epk:i,payload_enc:r,nonce_enc:o}=e[1],a=yield y(this,O,\"f\").getIncomingViewingKey(),d=yield h.keyAgreement(i,a),u=s.blake2b(d,Buffer.from(D),32),c=yield this.decryptCiphertext(u,n.hex2buf(o),n.hex2buf(r));if(c){const{diversifier:e,value:i,randomCommitmentTrapdoor:n,memo:r}=this.extractTransactionProperties(c),o=(p=yield h.getRawPaymentAddressFromIncomingViewingKey(a,e),new Uint8Array(p.buffer,p.byteOffset,p.byteLength/Uint8Array.BYTES_PER_ELEMENT));try{if(yield h.verifyCommitment(t,o,A(i).toString(),n))return{value:i,memo:r,paymentAddress:o,randomCommitmentTrapdoor:n}}catch(e){if(!/invalid value/.test(e))throw e}}var p}))}decryptCiphertextAsSender(e){return g(this,void 0,void 0,(function*(){const t=e[0],{epk:i,payload_enc:r,nonce_enc:o,payload_out:a,nonce_out:d,cv:u}=e[1],c=yield y(this,O,\"f\").getOutgoingViewingKey(),p=u.concat(t,i,c.toString(\"hex\")),l=s.blake2b(Buffer.from(p,\"hex\"),Buffer.from(K),32),f=yield this.decryptCiphertext(l,n.hex2buf(d),n.hex2buf(a));if(f){const{recipientDiversifiedTransmissionKey:e,ephemeralPrivateKey:i}=this.extractPkdAndEsk(f),a=yield h.keyAgreement(e,i),d=s.blake2b(a,Buffer.from(D),32),u=yield this.decryptCiphertext(d,n.hex2buf(o),n.hex2buf(r));if(u){const{diversifier:i,value:r,randomCommitmentTrapdoor:o,memo:s}=this.extractTransactionProperties(u),a=n.mergebuf(i,e);try{if(yield h.verifyCommitment(t,a,A(r).toString(),o))return{value:r,memo:s,paymentAddress:a,randomCommitmentTrapdoor:o}}catch(e){if(!/invalid value/.test(e))throw e}}}}))}decryptCiphertext(e,t,i){return g(this,void 0,void 0,(function*(){return a.openSecretBox(e,t,i)}))}extractTransactionProperties(e){return{diversifier:e.slice(0,11),value:e.slice(11,19),randomCommitmentTrapdoor:e.slice(19,51),memoSize:e.slice(51,55),memo:e.slice(55)}}extractPkdAndEsk(e){return{recipientDiversifiedTransmissionKey:e.slice(0,32),ephemeralPrivateKey:e.slice(32)}}isSpent(e,t,i,n,r){return g(this,void 0,void 0,(function*(){const o=yield h.computeNullifier(y(this,O,\"f\").getFullViewingKey(),e,t,i,n);return r.includes(o.toString(\"hex\"))}))}}O=new WeakMap,R=new WeakMap,M=new WeakMap;class I{constructor(e){this.init=e,this.isInitialized=!1,this.value=void 0}get(){return g(this,void 0,void 0,(function*(){return this.isInitialized||(this.value=yield this.init(),this.isInitialized=!0),this.value}))}}const z=e=>{e.length%2!=0&&(e=\"0\"+e);return(e.match(/.{2}/g)||[]).reverse().join(\"\")};class W{constructor(e){this.height=e,this.uncommittedMerkleHash=\"0100000000000000000000000000000000000000000000000000000000000000\",this.uncommittedMerkleHashes=new I((()=>this.createUncommittedMerkleHashes()))}getStateTree(e){return g(this,arguments,void 0,(function*(e,t=!0){if(void 0!==this.stateTree&&this.stateTree.root===e.root)return this.stateTree;const i=e.commitments_and_ciphertexts.map((([e,t])=>e));let n;return t&&(n=yield this.constructMerkleTree(i,0),yield this.validateMerkleTree(n,e.root)),this.stateTree={height:this.height,size:i.length,root:e.root,tree:n},this.stateTree}))}getWitness(e,t){return g(this,void 0,void 0,(function*(){const i=n.hex2Bytes(z(n.num2PaddedHex(e.height))),r=n.hex2Bytes(z(n.num2PaddedHex(t,64))),o=(yield this.getNeighbouringHashes([],e.height,t,e.tree)).map((e=>Buffer.concat([n.hex2Bytes(z(n.num2PaddedHex(e.length))),e]))).reverse().reduce(((e,t)=>Buffer.concat([e,t])));return Buffer.concat([i,o,r]).toString(\"hex\")}))}constructMerkleTree(e,t){return g(this,void 0,void 0,(function*(){if(t===this.height&&1===e.length)return e[0];if(t===this.height||e.length>Math.pow(2,this.height-1-t))throw new b(\"Children length exceeds maximum number of nodes in a merkle tree\");const i=function(e){const t=new Array(Math.ceil(e.length/2));for(let i=0;i<e.length/2;i++)t[i]=e.slice(2*i,2*i+2);return t}(e),n=yield Promise.all(i.map((e=>g(this,void 0,void 0,(function*(){const i=yield this.getMerkleHash(e[0],t),n=yield this.getMerkleHash(e[1],t);return[(yield o.merkleHash(t,i,n)).toString(\"hex\"),e[0],e[1]]})))));return this.constructMerkleTree(n,t+1)}))}getMerkleHash(e,t){return g(this,void 0,void 0,(function*(){return void 0===e?(yield this.uncommittedMerkleHashes.get())[t]:\"string\"==typeof e?Buffer.from(e,\"hex\"):Buffer.from(e[0],\"hex\")}))}createUncommittedMerkleHashes(){return g(this,void 0,void 0,(function*(){const e=new Array(this.height);e[0]=Buffer.from(this.uncommittedMerkleHash,\"hex\");for(let t=0;t<this.height;t++){const i=e[t];e[t+1]=yield o.merkleHash(t,i,i)}return e}))}validateMerkleTree(e,t){return g(this,void 0,void 0,(function*(){const i=yield this.getMerkleHash(e,this.height-1);if(i.toString(\"hex\")!==t)throw new w(i.toString(\"hex\"))}))}getNeighbouringHashes(e,i,n,r){return g(this,void 0,void 0,(function*(){if(void 0===r)throw new Error;if(\"string\"==typeof r)return e;{let o,s,a;const d=new t(2).pow(i-1);return n.lt(d)?(o=n,s=r[1],a=r[2]):(o=n.minus(d),s=r[2],a=r[1]),this.getNeighbouringHashes([yield this.getMerkleHash(a,i-1),...e],i-1,o,s)}}))}}const H=require(\"../saplingOutputParams\"),q=require(\"../saplingSpendParams\");class j{withProvingContext(e){return g(this,void 0,void 0,(function*(){return yield this.initSaplingParameters(),h.withProvingContext(e)}))}getRandomBytes(e){return d.randomBytes(e)}randR(){return g(this,void 0,void 0,(function*(){return h.randR()}))}getOutgoingViewingKey(e){return g(this,void 0,void 0,(function*(){return h.getOutgoingViewingKey(e)}))}preparePartialOutputDescription(e){return g(this,void 0,void 0,(function*(){const t=yield h.preparePartialOutputDescription(e.saplingContext,e.address,e.randomCommitmentTrapdoor,e.ephemeralPrivateKey,e.amount);return{commitmentValue:t.cv,commitment:t.cm,proof:t.proof}}))}getDiversifiedFromRawPaymentAddress(e){return g(this,void 0,void 0,(function*(){return h.getDiversifiedFromRawPaymentAddress(e)}))}deriveEphemeralPublicKey(e,t){return g(this,void 0,void 0,(function*(){return h.deriveEphemeralPublicKey(e,t)}))}getPkdFromRawPaymentAddress(e){return g(this,void 0,void 0,(function*(){return h.getPkdFromRawPaymentAddress(e)}))}keyAgreement(e,t){return g(this,void 0,void 0,(function*(){return h.keyAgreement(e,t)}))}createBindingSignature(e,t,i){return g(this,void 0,void 0,(function*(){return h.createBindingSignature(e,t,i)}))}initSaplingParameters(){return g(this,void 0,void 0,(function*(){const e=Buffer.from(q.saplingSpendParams,\"base64\"),t=Buffer.from(H.saplingOutputParams,\"base64\");return h.initParameters(e,t)}))}}var F,_,$,U,N,L,G,J,Y,Z,Q,X,ee,te,ie,ne,re,oe,se,ae,de,ue,ce;class pe{constructor(e,t,i,n,r=new j){F.set(this,void 0),_.set(this,void 0),$.set(this,void 0),U.set(this,void 0),N.set(this,void 0),L.set(this,void 0),G.set(this,void 0),J.set(this,void 0),Y.set(this,void 0),Z.set(this,void 0),v(this,$,t,\"f\"),v(this,U,i.contractAddress,\"f\"),v(this,L,i.memoSize,\"f\"),v(this,F,e.saplingSigner,\"f\"),v(this,_,e.saplingProver,\"f\"),v(this,Z,new W(32),\"f\"),v(this,N,i.saplingId,\"f\"),v(this,J,r,\"f\"),v(this,G,n,\"f\")}createShieldedTx(e,t,i){return g(this,void 0,void 0,(function*(){const r=yield y(this,J,\"f\").randR(),o=this.calculateTransactionBalance(\"0\",t.toString()),{signature:s,inputs:a,outputs:d}=yield y(this,J,\"f\").withProvingContext((t=>g(this,void 0,void 0,(function*(){const s=[],a=[];for(const i in e){const[o]=n.b58DecodeAndCheckPrefix(e[i].to,[n.PrefixV2.SaplingAddress]);s.push(yield this.prepareSaplingOutputDescription({saplingContext:t,address:o,amount:e[i].amount,memo:e[i].memo,randomCommitmentTrapdoor:r}))}return{signature:yield this.createBindingSignature({saplingContext:t,inputs:a,outputs:s,balance:o,boundData:i}),inputs:a,outputs:s}}))));return{inputs:a,outputs:d,signature:s,balance:o}}))}createSaplingTx(e,i,r,o){return g(this,void 0,void 0,(function*(){const s=yield y(this,J,\"f\").randR(),a=yield y(this,F,\"f\").getSaplingViewingKeyProvider(),d=yield a.getOutgoingViewingKey(),{signature:u,balance:c,inputs:p,outputs:l}=yield y(this,J,\"f\").withProvingContext((u=>g(this,void 0,void 0,(function*(){const c=[],p=[];p.push(...yield this.prepareSaplingSpendDescription(u,o.inputsToSpend));let l=new t(0);for(const i in e){l=l.plus(new t(e[i].amount));const[r]=n.b58DecodeAndCheckPrefix(e[i].to,[n.PrefixV2.SaplingAddress]);c.push(yield this.prepareSaplingOutputDescription({saplingContext:u,address:r,amount:e[i].amount,memo:e[i].memo,randomCommitmentTrapdoor:s,outgoingViewingKey:d}))}if(o.sumSelectedInputs.isGreaterThan(l)){const e=(yield a.getAddress()).address,[r]=n.b58DecodeAndCheckPrefix(e,[n.PrefixV2.SaplingAddress]),{payBackOutput:p,payBackAmount:h}=yield this.createPaybackOutput({saplingContext:u,address:r,amount:i.toString(),memo:\"\",randomCommitmentTrapdoor:s,outgoingViewingKey:d},o.sumSelectedInputs);l=l.plus(new t(h)),c.push(p)}const h=this.calculateTransactionBalance(o.sumSelectedInputs.toString(),l.toString());return{signature:yield this.createBindingSignature({saplingContext:u,inputs:p,outputs:c,balance:h,boundData:r}),balance:h,inputs:p,outputs:c}}))));return{inputs:p,outputs:l,signature:u,balance:c}}))}calculateTransactionBalance(e,i){return new t(e).minus(new t(i))}prepareSaplingOutputDescription(e){return g(this,void 0,void 0,(function*(){const t=yield y(this,J,\"f\").randR(),{commitmentValue:i,commitment:n,proof:r}=yield y(this,J,\"f\").preparePartialOutputDescription({saplingContext:e.saplingContext,address:e.address,randomCommitmentTrapdoor:e.randomCommitmentTrapdoor,ephemeralPrivateKey:t,amount:e.amount}),o=yield y(this,J,\"f\").getDiversifiedFromRawPaymentAddress(e.address),a=yield y(this,J,\"f\").deriveEphemeralPublicKey(o,t),d=e.outgoingViewingKey?s.blake2b(Buffer.concat([i,n,a,e.outgoingViewingKey]),Buffer.from(K),32):y(this,J,\"f\").getRandomBytes(32),u=yield this.encryptCiphertext({address:e.address,ephemeralPrivateKey:t,diversifier:o,outgoingCipherKey:d,amount:e.amount,randomCommitmentTrapdoor:e.randomCommitmentTrapdoor,memo:e.memo});return{commitment:n,proof:r,ciphertext:Object.assign(Object.assign({},u),{commitmentValue:i,ephemeralPublicKey:a})}}))}prepareSaplingSpendDescription(e,i){return g(this,void 0,void 0,(function*(){const n=yield y(this,J,\"f\").randR();let r;r=y(this,N,\"f\")?yield y(this,G,\"f\").getSaplingDiffById({id:y(this,N,\"f\")},\"head\"):yield y(this,G,\"f\").getSaplingDiffByContract(y(this,U,\"f\"),\"head\");const o=yield y(this,Z,\"f\").getStateTree(r,!0),a=[];for(let d=0;d<i.length;d++){const u=A(i[d].value).toString(),c=yield y(this,Z,\"f\").getWitness(o,new t(i[d].position)),p=y(this,_,\"f\")?yield y(this,_,\"f\").prepareSpendDescription({saplingContext:e,address:i[d].paymentAddress,randomCommitmentTrapdoor:i[d].randomCommitmentTrapdoor,publicKeyReRandomization:n,amount:u,root:r.root,witness:c}):yield y(this,F,\"f\").prepareSpendDescription({saplingContext:e,address:i[d].paymentAddress,randomCommitmentTrapdoor:i[d].randomCommitmentTrapdoor,publicKeyReRandomization:n,amount:u,root:r.root,witness:c}),l=y(this,$,\"f\").forgeUnsignedTxInput(p),h=s.blake2b(l,yield this.getAntiReplay(),32),f=yield y(this,F,\"f\").signSpendDescription({publicKeyReRandomization:n,unsignedSpendDescription:p,hash:h});if(void 0===f.signature)throw new Error(\"Spend signing failed\");a.push(f)}return a}))}encryptCiphertext(e){return g(this,void 0,void 0,(function*(){const t=yield y(this,J,\"f\").getPkdFromRawPaymentAddress(e.address),i=yield y(this,J,\"f\").keyAgreement(t,e.ephemeralPrivateKey),n=s.blake2b(i,Buffer.from(D),32),r=Buffer.from(y(this,J,\"f\").getRandomBytes(24)),o=y(this,$,\"f\").forgeTransactionPlaintext({diversifier:e.diversifier,amount:e.amount,randomCommitmentTrapdoor:e.randomCommitmentTrapdoor,memoSize:2*y(this,L,\"f\"),memo:e.memo}),d=Buffer.from(y(this,J,\"f\").getRandomBytes(24));return{payloadEnc:Buffer.from(a.secretBox(n,r,o)),nonceEnc:r,payloadOut:Buffer.from(a.secretBox(e.outgoingCipherKey,d,Buffer.concat([t,e.ephemeralPrivateKey]))),nonceOut:d}}))}createPaybackOutput(e,t){return g(this,void 0,void 0,(function*(){const i=t.minus(e.amount).toString();return{payBackOutput:yield this.prepareSaplingOutputDescription({saplingContext:e.saplingContext,address:e.address,amount:i,memo:e.memo,randomCommitmentTrapdoor:e.randomCommitmentTrapdoor,outgoingViewingKey:e.outgoingViewingKey}),payBackAmount:i}}))}createBindingSignature(e){return g(this,void 0,void 0,(function*(){const t=y(this,$,\"f\").forgeOutputDescriptions(e.outputs),i=y(this,$,\"f\").forgeSpendDescriptions(e.inputs),n=s.blake2b(Buffer.concat([i,t,e.boundData]),yield this.getAntiReplay(),32);return y(this,J,\"f\").createBindingSignature(e.saplingContext,e.balance.toFixed(),n)}))}getAntiReplay(){return g(this,void 0,void 0,(function*(){let e=y(this,Y,\"f\");return e||(e=yield y(this,G,\"f\").getChainId(),v(this,Y,e,\"f\")),Buffer.from(`${y(this,U,\"f\")}${e}`)}))}}function le(e,t){const[i,o]=(()=>{try{return n.b58DecodeAndCheckPrefix(e,[n.PrefixV2.SaplingSpendingKey,n.PrefixV2.EncryptedSaplingSpendingKey])}catch(t){throw t instanceof r.ParameterValidationError?new S(e,\"invalid spending key\"):t}})();if(o===n.PrefixV2.EncryptedSaplingSpendingKey){if(!t)throw new S(e,\"no password provided to decrypt\");const n=u(i.slice(0,8)),r=u(i.slice(8)),o=c.pbkdf2Sync(t,n,32768,32,\"sha512\"),s=a.openSecretBox(new Uint8Array(o),new Uint8Array(24),new Uint8Array(r));if(!s)throw new S(e,\"incorrect password or unable to decrypt\");return u(s)}return u(i)}F=new WeakMap,_=new WeakMap,$=new WeakMap,U=new WeakMap,N=new WeakMap,L=new WeakMap,G=new WeakMap,J=new WeakMap,Y=new WeakMap,Z=new WeakMap;class he{constructor(e){Q.set(this,void 0),v(this,Q,Buffer.from(e,\"hex\"),\"f\")}static fromSpendingKey(e,t){return g(this,void 0,void 0,(function*(){const i=le(e,t),n=yield h.getExtendedFullViewingKeyFromSpendingKey(i);return new he(n.toString(\"hex\"))}))}getFullViewingKey(){return y(this,Q,\"f\")}getOutgoingViewingKey(){return g(this,void 0,void 0,(function*(){return h.getOutgoingViewingKey(y(this,Q,\"f\"))}))}getIncomingViewingKey(){return g(this,void 0,void 0,(function*(){return h.getIncomingViewingKey(y(this,Q,\"f\"))}))}getAddress(e){return g(this,void 0,void 0,(function*(){const{index:t,raw:i}=yield h.getPaymentAddressFromViewingKey(y(this,Q,\"f\"),e);return{address:n.b58Encode(i,n.PrefixV2.SaplingAddress),addressIndex:t.readInt32LE()}}))}}Q=new WeakMap;class fe{constructor(e,t){X.set(this,void 0),ee.set(this,void 0),v(this,X,le(e,t),\"f\")}static fromMnemonic(e){return g(this,arguments,void 0,(function*(e,t=\"m/\"){const i=yield f.mnemonicToSeed(e),r=i.slice(0,32),o=i.slice(32),s=Buffer.from(r.map(((e,t)=>e^o[t]))),a=new Uint8Array(yield h.getExtendedSpendingKey(s,t)),d=n.b58Encode(a,n.PrefixV2.SaplingSpendingKey);return new fe(d)}))}getSaplingViewingKeyProvider(){return g(this,void 0,void 0,(function*(){let e;return y(this,ee,\"f\")||(e=yield h.getExtendedFullViewingKeyFromSpendingKey(y(this,X,\"f\")),v(this,ee,new he(e.toString(\"hex\")),\"f\")),y(this,ee,\"f\")}))}prepareSpendDescription(e){return g(this,void 0,void 0,(function*(){const t=yield h.prepareSpendDescriptionWithSpendingKey(e.saplingContext,y(this,X,\"f\"),e.address,e.randomCommitmentTrapdoor,e.publicKeyReRandomization,e.amount,e.root,e.witness);return{commitmentValue:t.cv,nullifier:t.nf,publicKeyReRandomization:t.rk,rtAnchor:t.rt,proof:t.proof}}))}signSpendDescription(e){return g(this,void 0,void 0,(function*(){const t=yield h.signSpendDescription({cv:e.unsignedSpendDescription.commitmentValue,rt:e.unsignedSpendDescription.rtAnchor,nf:e.unsignedSpendDescription.nullifier,rk:e.unsignedSpendDescription.publicKeyReRandomization,proof:e.unsignedSpendDescription.proof},y(this,X,\"f\"),e.publicKeyReRandomization,e.hash);return{commitmentValue:t.cv,nullifier:t.nf,publicKeyReRandomization:t.rk,proof:t.proof,signature:t.spendAuthSig}}))}getProvingKey(){return g(this,void 0,void 0,(function*(){return(yield h.getProofAuthorizingKey(y(this,X,\"f\"))).toString(\"hex\")}))}}X=new WeakMap,ee=new WeakMap;class me{constructor(e){te.set(this,void 0),v(this,te,Buffer.from(e,\"hex\"),\"f\")}static fromSpendingKey(e,t){return g(this,void 0,void 0,(function*(){const i=le(e,t),n=yield h.getProofAuthorizingKey(i);return new me(n.toString(\"hex\"))}))}prepareSpendDescription(e){return g(this,void 0,void 0,(function*(){const t=yield h.prepareSpendDescriptionWithAuthorizingKey(e.saplingContext,y(this,te,\"f\"),e.address,e.randomCommitmentTrapdoor,e.publicKeyReRandomization,e.amount,e.root,e.witness);return{commitmentValue:t.cv,nullifier:t.nf,publicKeyReRandomization:t.rk,rtAnchor:t.rt,proof:t.proof}}))}}te=new WeakMap;ie=new WeakMap,ne=new WeakMap,re=new WeakMap,oe=new WeakMap,se=new WeakMap,ae=new WeakMap,de=new WeakMap,ue=new WeakMap,ce=new WeakMap,e.InMemoryProvingKey=me,e.InMemorySpendingKey=fe,e.InMemoryViewingKey=he,e.SaplingToolkit=class{constructor(e,t,n,r=new i.MichelCodecPacker,o=new C,s=new pe(e,o,t,n)){ie.set(this,void 0),ne.set(this,void 0),re.set(this,void 0),oe.set(this,void 0),se.set(this,void 0),ae.set(this,void 0),de.set(this,void 0),ue.set(this,void 0),ce.set(this,void 0),v(this,ie,e.saplingSigner,\"f\"),v(this,ne,t.saplingId,\"f\"),v(this,re,t.contractAddress,\"f\"),v(this,oe,t.memoSize,\"f\"),v(this,se,n,\"f\"),v(this,ae,r,\"f\"),v(this,de,o,\"f\"),v(this,ue,s,\"f\")}getSaplingTransactionViewer(){return g(this,void 0,void 0,(function*(){let e;if(!y(this,ce,\"f\")){const t=yield y(this,ie,\"f\").getSaplingViewingKeyProvider();e=new E(t,this.getSaplingContractId(),y(this,se,\"f\")),v(this,ce,e,\"f\")}return y(this,ce,\"f\")}))}prepareShieldedTransaction(e){return g(this,void 0,void 0,(function*(){const{formatedParams:t,totalAmount:i}=this.formatTransactionParams(e,this.validateDestinationSaplingAddress),n=yield this.getRoot(),{inputs:r,outputs:o,signature:s,balance:a}=yield y(this,ue,\"f\").createShieldedTx(t,i,V);return y(this,de,\"f\").forgeSaplingTransaction({inputs:r,outputs:o,balance:a,root:n,boundData:V,signature:s}).toString(\"hex\")}))}prepareUnshieldedTransaction(e){return g(this,void 0,void 0,(function*(){const{formatedParams:i,totalAmount:n}=this.formatTransactionParams([e],this.validateDestinationImplicitAddress),r=yield this.createBoundData(i[0].to),o=yield this.getRoot(),s=yield this.selectInputsToSpend(new t(i[0].amount)),{inputs:a,outputs:d,signature:u,balance:c}=yield y(this,ue,\"f\").createSaplingTx([],n,r,s);return y(this,de,\"f\").forgeSaplingTransaction({inputs:a,outputs:d,balance:c,root:o,boundData:r,signature:u}).toString(\"hex\")}))}prepareSaplingTransaction(e){return g(this,void 0,void 0,(function*(){const{formatedParams:t,totalAmount:i}=this.formatTransactionParams(e,this.validateDestinationSaplingAddress),n=yield this.getRoot(),r=yield this.selectInputsToSpend(i),{inputs:o,outputs:s,signature:a,balance:d}=yield y(this,ue,\"f\").createSaplingTx(t,i,V,r);return y(this,de,\"f\").forgeSaplingTransaction({inputs:o,outputs:s,balance:d,root:n,boundData:V,signature:a}).toString(\"hex\")}))}formatTransactionParams(e,i){const r=[];let o=new t(0);return e.forEach((e=>{var s;i(e.to);const a=e.mutez?e.amount.toString():n.format(\"tz\",\"mutez\",e.amount).toString();o=o.plus(new t(a));const d=null!==(s=e.memo)&&void 0!==s?s:\"\";if(d.length>y(this,oe,\"f\"))throw new x(d,`expecting length to be less than ${y(this,oe,\"f\")}`);r.push({to:e.to,amount:a,memo:d})})),{formatedParams:r,totalAmount:o}}getRoot(){return g(this,void 0,void 0,(function*(){if(y(this,ne,\"f\")){const{root:e}=yield y(this,se,\"f\").getSaplingDiffById({id:y(this,ne,\"f\")},\"head\");return e}{const{root:e}=yield y(this,se,\"f\").getSaplingDiffByContract(y(this,re,\"f\"),\"head\");return e}}))}createBoundData(e){return g(this,void 0,void 0,(function*(){const t=n.b58DecodePublicKeyHash(e,\"hex\"),i=yield y(this,ae,\"f\").packData({data:{bytes:t},type:{prim:\"bytes\"}});return Buffer.from(i.packed,\"hex\")}))}validateDestinationImplicitAddress(e){const t=n.validateKeyHash(e);if(t!==n.ValidationResult.VALID)throw new r.InvalidKeyHashError(e,t)}validateDestinationSaplingAddress(e){try{n.b58DecodeAndCheckPrefix(e,[n.PrefixV2.SaplingAddress])}catch(t){throw new r.InvalidAddressError(e,`expecting prefix ${n.PrefixV2.SaplingAddress}.`)}}getSaplingContractId(){let e;return e=y(this,ne,\"f\")?{saplingId:y(this,ne,\"f\")}:{contractAddress:y(this,re,\"f\")},e}selectInputsToSpend(e){return g(this,void 0,void 0,(function*(){const i=yield this.getSaplingTransactionViewer(),{incoming:n}=yield i.getIncomingAndOutgoingTransactionsRaw(),r=[];let o=new t(0);if(n.forEach((t=>{if(!t.isSpent&&o.isLessThan(e)){const e=A(t.value);o=o.plus(e);const{isSpent:i}=t,n=m(t,[\"isSpent\"]);r.push(n)}})),o.isLessThan(new t(e)))throw new T(o.toString(),e.toString());return{inputsToSpend:r,sumSelectedInputs:o}}))}},e.SaplingTransactionViewer=E}));\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sInNvdXJjZXMiOltdLCJtYXBwaW5ncyI6IiIsImlnbm9yZUxpc3QiOltdfQ=="]}