@meshsdk/core 1.5.16-beta-2 → 1.5.16-beta-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.cjs CHANGED
@@ -5,4 +5,4 @@
5
5
  `+n+T.join(`,
6
6
  `+n)+`
7
7
  `+N+"}":"{"+T.join(",")+"}",n=N,P}}typeof t.stringify!="function"&&(t.stringify=function(C,E,w){var b;if(n="",a="",typeof w=="number")for(b=0;b<w;b+=1)a+=" ";else typeof w=="string"&&(a=w);if(l=E,E&&typeof E!="function"&&(typeof E!="object"||typeof E.length!="number"))throw new Error("JSON.stringify");return A("",{"":C})})})()})(Hr);var de=null;const un=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,ln=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;var dn=function(s){var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(s!=null){if(s.strict===!0&&(e.strict=!0),s.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=s.alwaysParseAsBig===!0?s.alwaysParseAsBig:!1,e.useNativeBigInt=s.useNativeBigInt===!0?s.useNativeBigInt:!1,typeof s.constructorAction<"u")if(s.constructorAction==="error"||s.constructorAction==="ignore"||s.constructorAction==="preserve")e.constructorAction=s.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${s.constructorAction}`);if(typeof s.protoAction<"u")if(s.protoAction==="error"||s.protoAction==="ignore"||s.protoAction==="preserve")e.protoAction=s.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${s.protoAction}`)}var t,r,n={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
8
- `,r:"\r",t:" "},a,c=function(k){throw{name:"SyntaxError",message:k,at:t,text:a}},l=function(k){return k&&k!==r&&c("Expected '"+k+"' instead of '"+r+"'"),r=a.charAt(t),t+=1,r},p=function(){var k,N="";for(r==="-"&&(N="-",l("-"));r>="0"&&r<="9";)N+=r,l();if(r===".")for(N+=".";l()&&r>="0"&&r<="9";)N+=r;if(r==="e"||r==="E")for(N+=r,l(),(r==="-"||r==="+")&&(N+=r,l());r>="0"&&r<="9";)N+=r,l();if(k=+N,!isFinite(k))c("Bad number");else return de==null&&(de=Le.exports),N.length>15?e.storeAsString?N:e.useNativeBigInt?BigInt(N):new de(N):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(k):new de(k):k},A=function(){var k,N,T="",Q;if(r==='"')for(var R=t;l();){if(r==='"')return t-1>R&&(T+=a.substring(R,t-1)),l(),T;if(r==="\\"){if(t-1>R&&(T+=a.substring(R,t-1)),l(),r==="u"){for(Q=0,N=0;N<4&&(k=parseInt(l(),16),!!isFinite(k));N+=1)Q=Q*16+k;T+=String.fromCharCode(Q)}else if(typeof n[r]=="string")T+=n[r];else break;R=t}}c("Bad string")},C=function(){for(;r&&r<=" ";)l()},E=function(){switch(r){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}c("Unexpected '"+r+"'")},w,b=function(){var k=[];if(r==="["){if(l("["),C(),r==="]")return l("]"),k;for(;r;){if(k.push(w()),C(),r==="]")return l("]"),k;l(","),C()}}c("Bad array")},P=function(){var k,N=Object.create(null);if(r==="{"){if(l("{"),C(),r==="}")return l("}"),N;for(;r;){if(k=A(),C(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(N,k)&&c('Duplicate key "'+k+'"'),un.test(k)===!0?e.protoAction==="error"?c("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():N[k]=w():ln.test(k)===!0?e.constructorAction==="error"?c("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():N[k]=w():N[k]=w(),C(),r==="}")return l("}"),N;l(","),C()}}c("Bad object")};return w=function(){switch(C(),r){case"{":return P();case"[":return b();case'"':return A();case"-":return p();default:return r>="0"&&r<="9"?p():E()}},function(k,N){var T;return a=k+"",t=0,r=" ",T=w(),C(),r&&c("Syntax error"),typeof N=="function"?function Q(R,X){var $,O=R[X];return O&&typeof O=="object"&&Object.keys(O).forEach(function(M){$=Q(O,M),$!==void 0?O[M]=$:delete O[M]}),N.call(R,X,O)}({"":T},""):T}},hn=dn,Fr=Hr.exports.stringify,Rr=hn;zt.exports=function(s){return{parse:Rr(s),stringify:Fr}};zt.exports.parse=Rr();zt.exports.stringify=Fr;class fn{txHex="";txBuilder=ge();txEvaluationMultiplier=1.1;_protocolParams=gt;txOutput;addingScriptInput=!1;addingPlutusMint=!1;isHydra=!1;meshTxBuilderBody;mintItem;txInQueueItem;collateralQueueItem;refScriptTxInQueueItem;reset=()=>(this.txHex="",this.txBuilder=ge(),this.txEvaluationMultiplier=1.1,this._protocolParams=gt,this.txOutput=void 0,this.addingScriptInput=!1,this.addingPlutusMint=!1,this.mintItem=void 0,this.txInQueueItem=void 0,this.collateralQueueItem=void 0,this.refScriptTxInQueueItem=void 0,this.meshTxBuilderBody=this.emptyTxBuilderBody(),this);emptyTxBuilderBody=()=>({inputs:[],outputs:[],extraInputs:[],selectionThreshold:0,collaterals:[],requiredSignatures:[],referenceInputs:[],mints:[],changeAddress:"",metadata:[],validityRange:{},certificates:[],signingKey:[]});constructor(){this.meshTxBuilderBody=this.emptyTxBuilderBody()}completeSync=e=>(e?this.meshTxBuilderBody=e:this.queueAllLastItem(),this.serializeTxBody(this.meshTxBuilderBody));completeSigning=()=>{const{signingKey:e}=this.meshTxBuilderBody;return e.length>0&&this.addAllSigningKeys(e),this.txHex};serializeTxBody=e=>{const{inputs:t,outputs:r,extraInputs:n,selectionThreshold:a,collaterals:c,referenceInputs:l,mints:p,changeAddress:A,certificates:C,validityRange:E,requiredSignatures:w,metadata:b}=e;if(this.isHydra?this.protocolParams({minFeeA:0,minFeeB:0,priceMem:0,priceStep:0,collateralPercent:0,coinsPerUTxOSize:"0"}):this.protocolParams({}),n.length>0&&this.addUtxosFrom(n,String(a)),this.removeDuplicateInputs(),this.meshTxBuilderBody.mints.sort((P,k)=>P.policyId.localeCompare(k.policyId)),this.meshTxBuilderBody.inputs.sort((P,k)=>P.txIn.txHash===k.txIn.txHash?P.txIn.txIndex-k.txIn.txIndex:P.txIn.txHash.localeCompare(k.txIn.txHash)),this.addAllInputs(t),this.addAllOutputs(r),this.addAllCollaterals(c),this.addAllReferenceInputs(l),this.addAllMints(p),this.addAllCertificates(C),this.addValidityRange(E),this.addAllRequiredSignatures(w),this.addAllMetadata(b),this.addCostModels(),A){const P=this.meshTxBuilderBody.collaterals.map(T=>{var Q,R;return((R=(Q=T.txIn.amount)==null?void 0:Q.find(X=>X.unit==="lovelace"))==null?void 0:R.quantity)||"0"}).reduce((T,Q)=>T+parseInt(Q),0),k=Math.ceil(this._protocolParams.collateralPercent*Number(Number(this.txBuilder.min_fee().checked_add(i.BigNum.from_str("10000")).to_js_value()))/100);let N=!1;if(P-k>0){const T=i.TransactionOutput.new(i.Address.from_bech32(A),i.Value.new(i.BigNum.from_str(String(k))));P-k>Number(i.min_ada_for_output(T,i.DataCost.new_coins_per_byte(i.BigNum.from_str(this._protocolParams.coinsPerUTxOSize))).to_js_value())&&(this.txBuilder.set_collateral_return(i.TransactionOutput.new(i.Address.from_bech32(A),i.Value.new(i.BigNum.from_str(String(P))))),this.txBuilder.set_total_collateral(i.BigNum.from_str(String(P))),N=!0)}this.addChange(A),N&&this.addCollateralReturn(A)}return this.buildTx(),this};txIn=(e,t,r,n)=>(this.txInQueueItem&&this.queueInput(),this.addingScriptInput?this.txInQueueItem={type:"Script",txIn:{txHash:e,txIndex:t,amount:r,address:n},scriptTxIn:{}}:this.txInQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:r,address:n}},this.addingScriptInput=!1,this);txInScript=(e,t="V2")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Datum value attempted to be called a non script input");return this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:e,version:t}},this};txInDatumValue=(e,t="Mesh")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Datum value attempted to be called a non script input");let r=e;return t==="JSON"&&(r=this.castRawDataToJsonString(e)),t==="Mesh"?(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:e}},this):(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:r}},this)};txInInlineDatumPresent=()=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Inline datum present attempted to be called a non script input");const{txHash:e,txIndex:t}=this.txInQueueItem.txIn;return e&&t.toString()&&(this.txInQueueItem.scriptTxIn.datumSource={type:"Inline",txHash:e,txIndex:t}),this};txInRedeemerValue=(e,t={...Gt},r="Mesh")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference redeemer attempted to be called a non script input");let n=e;return r==="Mesh"?(this.txInQueueItem.scriptTxIn.redeemer={data:{type:r,content:e},exUnits:t},this):(r==="JSON"&&(n=this.castRawDataToJsonString(e)),this.txInQueueItem.scriptTxIn.redeemer={data:{type:r,content:n},exUnits:t},this)};txOut=(e,t)=>(this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txOutput={address:e,amount:t},this);txOutDatumHashValue=(e,t="Mesh")=>{let r=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Hash",data:{type:t,content:r}},this;t==="JSON"&&(r=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Hash",data:{type:t,content:r}}}return this};txOutInlineDatumValue=(e,t="Mesh")=>{let r=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Inline",data:{type:t,content:r}},this;t==="JSON"&&(r=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Inline",data:{type:t,content:r}}}return this};txOutReferenceScript=(e,t="V2")=>(this.txOutput&&(this.txOutput.referenceScript={code:e,version:t}),this);spendingPlutusScriptV2=()=>(this.addingScriptInput=!0,this);spendingTxInReference=(e,t,r,n="V2")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference attempted to be called a non script input");return this.txInQueueItem.scriptTxIn.scriptSource={type:"Inline",txInInfo:{txHash:e,txIndex:t,spendingScriptHash:r,version:n}},this};spendingReferenceTxInInlineDatumPresent=()=>(this.txInInlineDatumPresent(),this);spendingReferenceTxInRedeemerValue=(e,t={...Gt})=>(this.txInRedeemerValue(e,t),this);readOnlyTxInReference=(e,t)=>(this.meshTxBuilderBody.referenceInputs.push({txHash:e,txIndex:t}),this);mintPlutusScriptV2=()=>(this.addingPlutusMint=!0,this);mint=(e,t,r)=>(this.mintItem&&this.queueMint(),this.mintItem={type:this.addingPlutusMint?"Plutus":"Native",policyId:t,assetName:r,amount:e},this.addingPlutusMint=!1,this);mintingScript=(e,t="V2")=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");return this.mintItem.scriptSource={type:"Provided",script:{code:e,version:t}},this};mintTxInReference=(e,t,r="V2")=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");return this.mintItem.scriptSource={type:"Reference Script",txHash:e,txIndex:t,version:r},this};mintReferenceTxInRedeemerValue=(e,t={...Gt},r="Mesh")=>{if(!this.mintItem)throw Error("Undefined mint");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(this.mintItem.type=="Plutus"){if(!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");let n=e;if(r==="Mesh")return this.mintItem.redeemer={data:{type:r,content:n},exUnits:t},this;r==="JSON"&&(n=this.castRawDataToJsonString(e)),this.mintItem.redeemer={data:{type:r,content:n},exUnits:t}}return this};mintRedeemerValue=(e,t={...Gt},r="Mesh")=>(this.mintReferenceTxInRedeemerValue(e,t,r),this);requiredSignerHash=e=>(this.meshTxBuilderBody.requiredSignatures.push(e),this);txInCollateral=(e,t,r,n)=>(this.collateralQueueItem&&this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:r,address:n}},this);registerPoolCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterPool",poolParams:e}),this);registerStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterStake",stakeKeyHash:e}),this);delegateStakeCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"DelegateStake",stakeKeyHash:e,poolId:t}),this);deregisterStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"DeregisterStake",stakeKeyHash:e}),this);retirePoolCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"RetirePool",poolId:e,epoch:t}),this);changeAddress=e=>(this.meshTxBuilderBody.changeAddress=e,this);invalidBefore=e=>(this.meshTxBuilderBody.validityRange.invalidBefore=e,this);invalidHereafter=e=>(this.meshTxBuilderBody.validityRange.invalidHereafter=e,this);metadataValue=(e,t)=>(this.meshTxBuilderBody.metadata.push({tag:e,metadata:t}),this);protocolParams=e=>{const t={...gt,...e};return this._protocolParams=t,this.txBuilder=ge(t),this};signingKey=e=>(this.meshTxBuilderBody.signingKey.push(e),this);selectUtxosFrom=(e,t=5e6)=>(this.meshTxBuilderBody.extraInputs=e,this.meshTxBuilderBody.selectionThreshold=t,this);addUtxosFrom=(e,t)=>{const r=this.meshTxBuilderBody.outputs.reduce((a,c)=>(c.amount.forEach(p=>{const{unit:A,quantity:C}=p,E=Number(a.get(A))||0;a.set(A,String(E+Number(C)))}),a),new Map);this.meshTxBuilderBody.inputs.reduce((a,c)=>{const l=c.txIn.amount;return l==null||l.forEach(p=>{const{unit:A,quantity:C}=p,E=Number(a.get(A))||0;a.set(A,String(E-Number(C)))}),a},r),this.meshTxBuilderBody.mints.reduce((a,c)=>{const l={unit:c.policyId+c.assetName,quantity:String(c.amount)},p=Number(a.get(l.unit))||0;return a.set(l.unit,String(p-Number(l.quantity))),a},r),on(e,r,t).forEach(a=>{this.addTxIn({type:"PubKey",txIn:{txHash:a.input.txHash,txIndex:a.input.outputIndex,amount:a.output.amount,address:a.output.address}})})};addAllSigningKeys=e=>{if(e.length>0){const t=i.Vkeywitnesses.new(),r=i.Transaction.from_hex(this.txHex),n=r.body();e.forEach(l=>{const p=l.slice(0,4)==="5820"?l.slice(4):l,A=i.PrivateKey.from_hex(p),C=i.make_vkey_witness(i.hash_transaction(n),A);t.add(C)});const a=r.witness_set();a.set_vkeys(t);const c=i.Transaction.new(n,a,r.auxiliary_data());this.txHex=c.to_hex()}};buildTx=()=>{const e=this.txBuilder.build_tx();this.txHex=e.to_hex()};queueInput=()=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="Script")if(this.txInQueueItem.scriptTxIn){if(!this.txInQueueItem.scriptTxIn.datumSource)throw Error("Script input does not contain datum information");if(!this.txInQueueItem.scriptTxIn.redeemer)throw Error("Script input does not contain redeemer information");if(!this.txInQueueItem.scriptTxIn.scriptSource)throw Error("Script input does not contain script information")}else throw Error("Script input does not contain script, datum, or redeemer information");this.meshTxBuilderBody.inputs.push(this.txInQueueItem),this.txInQueueItem=void 0};queueMint=()=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.scriptSource)throw Error("Missing mint script information");this.meshTxBuilderBody.mints.push(this.mintItem),this.mintItem=void 0};makePlutusScriptSource=e=>{const t=i.ScriptHash.from_hex(e.spendingScriptHash),r=i.TransactionInput.new(i.TransactionHash.from_hex(e.txHash),e.txIndex);return i.PlutusScriptSource.new_ref_input_with_lang_ver(t,r,vt[e.version])};removeDuplicateInputs=()=>{const e=this.meshTxBuilderBody.inputs,t=n=>`${n.txHash}#${n.txIndex}`,r=[];for(let n=0;n<e.length;n++){const a=t(e[n].txIn);r.includes(a)?(e.splice(n,1),n--):r.push(a)}};addAllInputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];switch(r.type){case"PubKey":this.addTxIn(r);break;case"Script":this.addScriptTxIn(r);break}}};addTxIn=e=>{this.txBuilder.add_input(i.Address.from_bech32(e.txIn.address),i.TransactionInput.new(i.TransactionHash.from_hex(e.txIn.txHash),e.txIn.txIndex),Qt(e.txIn.amount))};addScriptTxIn=({scriptTxIn:e,txIn:t})=>{let r;const{datumSource:n,scriptSource:a,redeemer:c}=e;if(n.type==="Provided")r=i.DatumSource.new(this.castDataToPlutusData(n.data));else{const A=i.TransactionInput.new(i.TransactionHash.from_hex(n.txHash),n.txIndex);r=i.DatumSource.new_ref_input(A)}let l;a.type=="Inline"?l=this.makePlutusScriptSource(a.txInInfo):l=i.PlutusScriptSource.new(i.PlutusScript.from_hex_with_version(a.script.code,vt[a.script.version]));const p=i.Redeemer.new(i.RedeemerTag.new_spend(),i.BigNum.from_str("0"),this.castDataToPlutusData(c.data),i.ExUnits.new(i.BigNum.from_str(String(c.exUnits.mem)),i.BigNum.from_str(String(c.exUnits.steps))));this.txBuilder.add_plutus_script_input(i.PlutusWitness.new_with_ref(l,r,p),i.TransactionInput.new(i.TransactionHash.from_hex(t.txHash),t.txIndex),Qt(t.amount))};addAllOutputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];this.addOutput(r)}};addOutput=({amount:e,address:t,datum:r,referenceScript:n})=>{const a=Qt(e),c=a.multiasset();if(a.is_zero()&&c===void 0)throw Error("Invalid output amount");let l=i.TransactionOutputBuilder.new().with_address(_t(t));r&&r.type==="Hash"&&(l=l.with_data_hash(i.hash_plutus_data(this.castDataToPlutusData(r.data)))),r&&r.type==="Inline"&&(l=l.with_plutus_data(this.castDataToPlutusData(r.data))),n&&(l=l.with_script_ref(i.ScriptRef.new_plutus_script(i.PlutusScript.from_hex_with_version(n.code,vt[n.version]))));const p=l.next();if(c){const A=a.coin().is_zero()?p.with_asset_and_min_required_coin_by_utxo_cost(c,Ne(this._protocolParams.coinsPerUTxOSize)).build():p.with_coin_and_asset(a.coin(),c).build();this.txBuilder.add_output(A)}else{const A=p.with_coin(a.coin()).build();this.txBuilder.add_output(A)}};addAllCollaterals=e=>{const t=i.TxInputsBuilder.new();for(let r=0;r<e.length;r++){const n=e[r];this.addCollateral(t,n)}this.txBuilder.set_collateral(t)};addCollateral=(e,t)=>{e.add_input(i.Address.from_bech32(t.txIn.address),i.TransactionInput.new(i.TransactionHash.from_hex(t.txIn.txHash),t.txIn.txIndex),Qt(t.txIn.amount))};addCollateralReturn=e=>{var r;const t=(r=this.txBuilder.get_fee_if_set())==null?void 0:r.to_js_value();if(t){const n=Math.ceil(this._protocolParams.collateralPercent*Number(t)/100);this.txBuilder.set_total_collateral_and_return(i.BigNum.from_str(String(n)),i.Address.from_bech32(e))}};addAllReferenceInputs=e=>{e.forEach(t=>{this.addReferenceInput(t)})};addReferenceInput=({txHash:e,txIndex:t})=>{const r=i.TransactionInput.new(i.TransactionHash.from_hex(e),t);this.txBuilder.add_reference_input(r)};addAllMints=e=>{const t=i.MintBuilder.new();let r=0;for(let n=0;n<e.length;n++){const a=e[n];if(!a.scriptSource)throw Error("Mint script is expected to be provided");if(a.type==="Plutus"){if(!a.redeemer)throw Error("Missing mint redeemer information");this.addPlutusMint(t,a,r),r++}else a.type==="Native"&&this.addNativeMint(t,a)}this.txBuilder.set_mint_builder(t)};addPlutusMint=(e,{redeemer:t,policyId:r,scriptSource:n,assetName:a,amount:c},l)=>{const p=i.Redeemer.new(i.RedeemerTag.new_mint(),i.BigNum.from_str(String(l)),this.castDataToPlutusData(t.data),i.ExUnits.new(i.BigNum.from_str(String(t.exUnits.mem)),i.BigNum.from_str(String(t.exUnits.steps)))),A=n.type==="Reference Script"?i.PlutusScriptSource.new_ref_input_with_lang_ver(i.ScriptHash.from_hex(r),i.TransactionInput.new(i.TransactionHash.from_hex(n.txHash),n.txIndex),vt[n.version]):i.PlutusScriptSource.new(i.PlutusScript.from_hex_with_version(n.script.code,vt[n.script.version]));e.add_asset(i.MintWitness.new_plutus_script(A,p),i.AssetName.new(Buffer.from(a,"hex")),i.Int.new(i.BigNum.from_str(c)))};addNativeMint=(e,{scriptSource:t,assetName:r,amount:n})=>{if(t.type==="Reference Script")throw Error("Native mint cannot have reference script");e.add_asset(i.MintWitness.new_native_script(i.NativeScript.from_hex(t.script.code)),i.AssetName.new(Buffer.from(r,"hex")),i.Int.new(i.BigNum.from_str(n)))};decimalToFraction(e){const t=10**e.toString().split(".")[1].length;return[e*t,t]}toPoolParams=e=>{const t=this.decimalToFraction(e.margin),r=i.Relays.new();e.relays.forEach(c=>{r.add(Nr(c))});const n=i.RewardAddress.from_address(i.Address.from_bech32(e.rewardAddress));if(n===void 0)throw new Error("Reward address is invalid");const a=i.Ed25519KeyHashes.new();return e.owners.forEach(c=>{a.add(i.Ed25519KeyHash.from_hex(c))}),i.PoolParams.new(i.Ed25519KeyHash.from_hex(e.operator),i.VRFKeyHash.from_hex(e.VRFKeyHash),i.BigNum.from_str(e.pledge),i.BigNum.from_str(e.cost),i.UnitInterval.new(i.BigNum.from_str(t[0].toString()),i.BigNum.from_str(t[1].toString())),n,a,r,e.metadata?i.PoolMetadata.from_json(zt.exports.stringify(e.metadata)):void 0)};addCertificate=(e,t)=>{switch(t.type){case"RegisterPool":e.add(i.Certificate.new_pool_registration(i.PoolRegistration.new(this.toPoolParams(t.poolParams))));break;case"RegisterStake":e.add(i.Certificate.new_stake_registration(i.StakeRegistration.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"DelegateStake":e.add(i.Certificate.new_stake_delegation(i.StakeDelegation.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)),t.poolId.startsWith("pool")?i.Ed25519KeyHash.from_bech32(t.poolId):i.Ed25519KeyHash.from_hex(t.poolId))));break;case"DeregisterStake":e.add(i.Certificate.new_stake_deregistration(i.StakeDeregistration.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"RetirePool":e.add(i.Certificate.new_pool_retirement(i.PoolRetirement.new(t.poolId.startsWith("pool")?i.Ed25519KeyHash.from_bech32(t.poolId):i.Ed25519KeyHash.from_hex(t.poolId),t.epoch)))}};queueAllLastItem=()=>{this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txInQueueItem&&this.queueInput(),this.collateralQueueItem&&(this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem=void 0),this.mintItem&&this.queueMint()};addAllCertificates=e=>{const t=i.Certificates.new();e.forEach(r=>{this.addCertificate(t,r)}),this.txBuilder.set_certs(t)};addCostModels=()=>{this.txBuilder.calc_script_data_hash(i.TxBuilderConstants.plutus_vasil_cost_models())};addChange=e=>{this.txBuilder.add_change_if_needed(i.Address.from_bech32(e))};addValidityRange=({invalidBefore:e,invalidHereafter:t})=>{e&&this.txBuilder.set_validity_start_interval_bignum(i.BigNum.from_str(e.toString())),t&&this.txBuilder.set_ttl_bignum(i.BigNum.from_str(t.toString()))};addAllRequiredSignatures=e=>{e.forEach(t=>{this.txBuilder.add_required_signer(i.Ed25519KeyHash.from_hex(t))})};addAllMetadata=e=>{e.forEach(({tag:t,metadata:r})=>{this.txBuilder.add_json_metadatum(i.BigNum.from_str(t),zt.exports.stringify(r))})};updateRedeemer=(e,t)=>{t.forEach(r=>{switch(r.tag){case"SPEND":{const n=e.inputs[r.index];n.type=="Script"&&n.scriptTxIn.redeemer&&(n.scriptTxIn.redeemer.exUnits.mem=Math.floor(r.budget.mem*this.txEvaluationMultiplier),n.scriptTxIn.redeemer.exUnits.steps=Math.floor(r.budget.steps*this.txEvaluationMultiplier));break}case"MINT":{const n=e.mints[r.index];n.type=="Plutus"&&n.redeemer&&(n.redeemer.exUnits.mem=Math.floor(r.budget.mem*this.txEvaluationMultiplier),n.redeemer.exUnits.steps=Math.floor(r.budget.steps*this.txEvaluationMultiplier));break}}})};castRawDataToJsonString=e=>typeof e=="object"?zt.exports.stringify(e):e;castDataToPlutusData=({type:e,content:t})=>e==="Mesh"?Ot(t):e==="CBOR"?i.PlutusData.from_hex(t):i.PlutusData.from_json(t,i.PlutusDatumSchema.DetailedSchema)}class gn extends fn{_fetcher;_submitter;_evaluator;queriedTxHashes=new Set;queriedUTxOs={};constructor({fetcher:e,submitter:t,evaluator:r,isHydra:n=!1}){super(),e&&(this._fetcher=e),t&&(this._submitter=t),r&&(this._evaluator=r),n&&(this.isHydra=!0)}complete=async e=>{e?this.meshTxBuilderBody=e:this.queueAllLastItem();const{inputs:t,collaterals:r}=this.meshTxBuilderBody,n=[...t,...r].filter(a=>!this.isInputComplete(a));if(console.log("Incomplete UTxO",n),await this.queryAllTxInfo(n),console.log("Incomplete UTxO",n),n.forEach(a=>{this.completeTxInformation(a)}),this.completeSync(e),this._evaluator){const a=await this._evaluator.evaluateTx(this.txHex);this.updateRedeemer(this.meshTxBuilderBody,a),this.completeSync(e)}return this};submitTx=async e=>{var r;return await((r=this._submitter)==null?void 0:r.submitTx(e))};getUTxOInfo=async e=>{var r;let t=[];this.queriedTxHashes.has(e)||(console.log("Query",e),this.queriedTxHashes.add(e),t=await((r=this._fetcher)==null?void 0:r.fetchUTxOs(e))||[],this.queriedUTxOs[e]=t)};queryAllTxInfo=e=>{var r;const t=[];if(e.length>0&&!this._fetcher)throw Error("Transaction information is incomplete while no fetcher instance is provided");for(let n=0;n<e.length;n++){const a=e[n];this.isInputInfoComplete(a)||t.push(this.getUTxOInfo(a.txIn.txHash)),a.type==="Script"&&((r=a.scriptTxIn.scriptSource)==null?void 0:r.type)==="Inline"&&!this.isRefScriptInfoComplete(a)&&t.push(this.getUTxOInfo(a.scriptTxIn.scriptSource.txInInfo.txHash))}return Promise.all(t)};completeTxInformation=e=>{var t;if(!this.isInputInfoComplete(e)){const r=this.queriedUTxOs[e.txIn.txHash],n=r==null?void 0:r.find(l=>l.input.outputIndex===e.txIn.txIndex),a=n==null?void 0:n.output.amount,c=n==null?void 0:n.output.address;if(!a||a.length===0)throw Error(`Couldn't find value information for ${e.txIn.txHash}#${e.txIn.txIndex}`);if(e.txIn.amount=a,e.type==="PubKey"){if(!c||c==="")throw Error(`Couldn't find address information for ${e.txIn.txHash}#${e.txIn.txIndex}`);e.txIn.address=c}}if(e.type==="Script"&&((t=e.scriptTxIn.scriptSource)==null?void 0:t.type)=="Inline"&&!this.isRefScriptInfoComplete(e)){const r=e.scriptTxIn.scriptSource.txInInfo,a=this.queriedUTxOs[r.txHash].find(c=>c.input.outputIndex===r.txIndex);if(!a)throw Error(`Couldn't find script reference utxo for ${r.txHash}#${r.txIndex}`);r.spendingScriptHash=a==null?void 0:a.output.scriptHash}};isInputComplete=e=>e.type==="PubKey"?this.isInputInfoComplete(e):e.type==="Script"?this.isInputInfoComplete(e)&&this.isRefScriptInfoComplete(e):!0;isInputInfoComplete=e=>{const{amount:t,address:r}=e.txIn;return!(e.type==="PubKey"&&(!t||!r)||e.type==="Script"&&!t)};isRefScriptInfoComplete=e=>{var r;const{scriptSource:t}=e.scriptTxIn;return!((t==null?void 0:t.type)==="Inline"&&!((r=t.txInInfo)!=null&&r.spendingScriptHash))}}class st{_networkId;_encryptedSecret;constructor(e,t){this._networkId=e,this._encryptedSecret=t}getAccount(e,t){return this.accountContext(e,t,(r,n)=>{const a=dr(this._networkId,r.to_public().hash(),n.to_public().hash()).to_address().to_bech32(),c=hr(this._networkId,r.to_public().hash()).to_address().to_bech32(),l=Pe(this._networkId,n.to_public().hash()).to_address().to_bech32();return{baseAddress:a,enterpriseAddress:c,rewardAddress:l}})}signData(e,t,r,n){try{return this.accountContext(e,t,(a,c)=>{const l={payload:n},p={address:st.resolveAddress(this._networkId,r,a,c),key:r.startsWith("stake")?c:a},{coseSign1:A,coseKey:C}=ss(l,p);return{signature:A,key:C}})}catch(a){throw new Error(`An error occurred during signData: ${a}.`)}}signTx(e,t,r,n,a){try{const c=Dr(Kr(n));return this.accountContext(e,t,(l,p)=>{const A=i.Vkeywitnesses.new();return st.resolveSigners(n,r,l.to_public().hash().to_hex()).forEach(E=>{if(E===l.to_public().hash().to_hex())A.add(i.make_vkey_witness(c,l));else if(E===p.to_public().hash().to_hex())A.add(i.make_vkey_witness(c,p));else if(a===!1)throw new Error(`Missing key witness for: ${E}`)}),A})}catch(c){throw new Error(`An error occurred during signTx: ${c}.`)}}static encryptMnemonic(e,t){const r=De.mnemonicToEntropy(e.join(" ")),n=Or(r),a=dt(n.as_bytes());return n.free(),st.encrypt(a,t)}static encryptPrivateKey(e,t){const r=i.Bip32PrivateKey.from_bech32(e),n=dt(r.as_bytes());return r.free(),st.encrypt(n,t)}static encryptSigningKeys(e,t,r){const n=st.encrypt(e.slice(4),r),a=st.encrypt(t.slice(4),r);return[n,a]}static generateMnemonic(e=256){return De.generateMnemonic(e).split(" ")}accountContext(e,t,r){const{paymentKey:n,stakeKey:a}=st.resolveKeys(e,t,this._encryptedSecret),c=r(n,a);return n.free(),a.free(),c}static decrypt(e,t){try{return i.decrypt_with_password(ct(t),e)}catch{throw new Error("The password is incorrect.")}}static encrypt(e,t){const r=mr.customAlphabet("0123456789abcdef"),n=r(64),a=r(24);return i.encrypt_with_password(ct(t),n,a,e)}static resolveAddress(e,t,r,n){const a=[dr(e,r.to_public().hash(),n.to_public().hash()),hr(e,r.to_public().hash()),Pe(e,n.to_public().hash())].find(c=>c.to_address().to_bech32()===t);if(a!==void 0)return a.to_address();throw new Error(`Address: ${t} doesn't belong to this account.`)}static resolveKeys(e,t,r){if(typeof r=="string"){const c=st.decrypt(r,t);return Qs(c,e)}const n=st.decrypt(r[0],t),a=st.decrypt(r[1],t);return{paymentKey:i.PrivateKey.from_hex(n),stakeKey:i.PrivateKey.from_hex(a)}}static resolveSigners(e,t,r){const n=l=>{const p=(T,Q=[],R=0)=>{var O,M,W,Z,D;if(T===void 0||R>=T.len())return Q;const X=T.get(R),$=new Array;switch(X.kind()){case i.CertificateKind.StakeDeregistration:{const F=(O=X.as_stake_deregistration())==null?void 0:O.stake_credential(),q=(F==null?void 0:F.kind())===i.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case i.CertificateKind.StakeDelegation:{const F=(M=X.as_stake_delegation())==null?void 0:M.stake_credential(),q=(F==null?void 0:F.kind())===i.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case i.CertificateKind.PoolRegistration:{const F=(W=X.as_pool_registration())==null?void 0:W.pool_params().pool_owners();$.push(...C(F));break}case i.CertificateKind.PoolRetirement:{const F=(Z=X.as_pool_retirement())==null?void 0:Z.pool_keyhash();F&&$.push(F.to_hex());break}case i.CertificateKind.MoveInstantaneousRewardsCert:{const F=(D=X.as_move_instantaneous_rewards_cert())==null?void 0:D.move_instantaneous_reward().as_to_stake_creds();if(F)for(let q=0;q<F.len();q+=1){const J=F.keys().get(q),nt=J.kind()===i.StakeCredKind.Key?J.to_keyhash():void 0;nt&&$.push(nt.to_hex())}break}}return p(T,[...Q,...$],R+1)},A=(T,Q=[],R=0)=>{if(T===void 0||R>=T.len())return Q;const X=T.get(R).index(),$=T.get(R).transaction_id(),O=t.find(M=>M.input.outputIndex===X&&M.input.txHash===$.to_hex())!==void 0?r:"OUR_PRINCESS_IS_IN_ANOTHER_CASTLE";return A(T,[...Q,O],R+1)},C=(T,Q=[],R=0)=>T===void 0||R>=T.len()?Q:C(T,[...Q,T.get(R).to_hex()],R+1),E=(T,Q=[],R=0)=>{if(T===void 0||R>=T.len())return Q;const X=T.keys().get(R).payment_cred(),$=X.kind()===i.StakeCredKind.Key?X.to_keyhash():void 0;return E(T,$?[...Q,$.to_hex()]:Q,R+1)},w=l.certs(),b=l.collateral(),P=l.inputs(),k=l.required_signers(),N=l.withdrawals();return[...p(w),...A(b),...A(P),...C(k),...E(N)]},a=l=>{const p=(C,E=[])=>{var w,b,P,k;if(C)for(let N=0;N<C.len();N+=1){const T=C.get(N);switch(T.kind()){case i.NativeScriptKind.ScriptPubkey:{const Q=(w=T.as_script_pubkey())==null?void 0:w.addr_keyhash().to_hex();return Q?[...E,Q]:E}case i.NativeScriptKind.ScriptAll:return p((b=T.as_script_all())==null?void 0:b.native_scripts(),E);case i.NativeScriptKind.ScriptAny:return p((P=T.as_script_any())==null?void 0:P.native_scripts(),E);case i.NativeScriptKind.ScriptNOfK:return p((k=T.as_script_n_of_k())==null?void 0:k.native_scripts(),E)}}return E},A=l.native_scripts();return[...p(A)]},c=It(e);return new Set([...n(c.body()),...a(c.witness_set())])}}const pt="MARI0TIME";class mn{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new st(e.networkId,st.encryptMnemonic(e.key.words,pt));break;case"root":this._wallet=new st(e.networkId,st.encryptPrivateKey(e.key.bech32,pt));break;case"cli":this._wallet=new st(e.networkId,st.encryptSigningKeys(e.key.payment,e.key.stake??"f0".repeat(34),pt))}}getBaseAddress(e=0){return this._wallet.getAccount(e,pt).baseAddress}getPaymentAddress(e=0){return this._wallet.getAccount(e,pt).enterpriseAddress}getRewardAddress(e=0){return this._wallet.getAccount(e,pt).rewardAddress}getUsedAddress(e=0){const t=this._wallet.getAccount(e,pt);return _t(t.enterpriseAddress)}getUsedCollateral(e=gt.maxCollateralInputs){throw new Error("getUsedCollateral not implemented.")}async getUsedUTxOs(e=0){const t=this._wallet.getAccount(e,pt);return(await this._fetcher.fetchAddressUTxOs(t.enterpriseAddress)).map(n=>wt(n))}signData(e,t,r=0){try{return this._wallet.signData(r,pt,e,t)}catch(n){throw new Error(`[AppWallet] An error occurred during signData: ${n}.`)}}async signTx(e,t=!1,r=0){try{const n=this._wallet.getAccount(r,pt),a=await this._fetcher.fetchAddressUTxOs(n.enterpriseAddress),c=this._wallet.signTx(r,pt,a,e,t),l=It(e),p=l.witness_set(),A=Oe(p,c);return p.set_vkeys(A),i.Transaction.new(l.body(),p,l.auxiliary_data()).to_hex()}catch(n){throw new Error(`[AppWallet] An error occurred during signTx: ${n}.`)}}async signTxs(e,t){return console.log("unimplemented",e,t),[]}submitTx(e){return this._submitter.submitTx(e)}static brew(e=256){return st.generateMnemonic(e)}}class Ie{_walletInstance;walletInstance;constructor(e){this._walletInstance=e,this.walletInstance={...e}}static getInstalledWallets(){return window.cardano===void 0?[]:$e.filter(e=>window.cardano[e]!==void 0).map(e=>({name:window.cardano[e].name,icon:window.cardano[e].icon,version:window.cardano[e].apiVersion}))}static async enable(e){try{const t=await Ie.resolveInstance(e);if(t!==void 0)return new Ie(t);throw new Error(`Couldn't create an instance of wallet: ${e}`)}catch(t){throw new Error(`[BrowserWallet] An error occurred during enable: ${JSON.stringify(t)}.`)}}async getBalance(){const e=await this._walletInstance.getBalance();return Ur(Os(e))}async getChangeAddress(){const e=await this._walletInstance.getChangeAddress();return Lt(e).to_bech32()}async getCollateral(e=gt.maxCollateralInputs){return(await this.getUsedCollateral(e)).map(r=>pe(r))}getNetworkId(){return this._walletInstance.getNetworkId()}async getRewardAddresses(){return(await this._walletInstance.getRewardAddresses()).map(t=>Lt(t).to_bech32())}async getUnusedAddresses(){return(await this._walletInstance.getUnusedAddresses()).map(t=>Lt(t).to_bech32())}async getUsedAddresses(){return(await this._walletInstance.getUsedAddresses()).map(t=>Lt(t).to_bech32())}async getUtxos(e=void 0){return(await this.getUsedUTxOs(e)).map(r=>pe(r))}signData(e,t){const r=_t(e).to_hex();return this._walletInstance.signData(r,ct(t))}async signTx(e,t=!1){try{const r=It(e),n=r.witness_set(),a=await this._walletInstance.signTx(e,t),c=ur(a).vkeys()??i.Vkeywitnesses.new(),l=Oe(n,c);return n.set_vkeys(l),dt(i.Transaction.new(r.body(),n,r.auxiliary_data()).to_bytes())}catch(r){throw new Error(`[BrowserWallet] An error occurred during signTx: ${JSON.stringify(r)}.`)}}async signTxs(e,t=!1){let r;if(this._walletInstance.signTxs&&(r=await this._walletInstance.signTxs(e,t)),this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(a=>({cbor:a,partialSign:t})))),!r)throw new Error("Wallet does not support signTxs");const n=[];for(let a=0;a<r.length;a++){const c=It(e[a]),l=c.witness_set(),p=ur(r[a]).vkeys()??i.Vkeywitnesses.new(),A=Oe(l,p);l.set_vkeys(A);const C=dt(i.Transaction.new(c.body(),l,c.auxiliary_data()).to_bytes());n.push(C)}return n}submitTx(e){return this._walletInstance.submitTx(e)}async getUsedAddress(){const e=await this._walletInstance.getUsedAddresses();return Lt(e[0])}async getUsedCollateral(e=gt.maxCollateralInputs){return(await this._walletInstance.experimental.getCollateral()??[]).map(r=>cr(r)).slice(0,e)}async getUsedUTxOs(e=void 0){const t=e?Qt(e).to_hex():void 0;return(await this._walletInstance.getUtxos(t)??[]).map(n=>cr(n))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,Bt),n=t.unit.slice(Bt),a=Mr(r,n);return{unit:t.unit,policyId:r,assetName:qe(n),fingerprint:a,quantity:t.quantity}})}async getLovelace(){const t=(await this.getBalance()).find(r=>r.unit==="lovelace");return t!==void 0?t.quantity:"0"}async getPolicyIdAssets(e){return(await this.getAssets()).filter(r=>r.policyId===e)}async getPolicyIds(){const e=await this.getBalance();return Array.from(new Set(e.map(t=>t.unit.slice(0,Bt)))).filter(t=>t!=="lovelace")}static resolveInstance(e){if(window.cardano===void 0)return;const t=$e.map(r=>window.cardano[r]).filter(r=>r!==void 0).find(r=>r.name.toLowerCase()===e.toLowerCase());return t==null?void 0:t.enable()}}exports.AppWallet=mn;exports.BlockfrostProvider=Xs;exports.BrowserWallet=Ie;exports.EmbeddedWallet=st;exports.ForgeScript=nn;exports.InfuraProvider=Zs;exports.KoiosProvider=tn;exports.MaestroProvider=sn;exports.MeshTxBuilder=gn;exports.OgmiosProvider=en;exports.TangoProvider=rn;exports.checkSignature=ns;exports.generateNonce=Ws;exports.isNetwork=Ar;exports.keepRelevant=pr;exports.largestFirst=Jr;exports.largestFirstMultiAsset=Ir;exports.parseAssetUnit=kt;exports.parseHttpError=S;exports.readPlutusData=js;exports.readTransaction=Js;exports.resolveDataHash=Hs;exports.resolveEpochNo=Fs;exports.resolveFingerprint=Mr;exports.resolveLanguageView=Rs;exports.resolveNativeScriptHash=qs;exports.resolvePaymentKeyHash=qt;exports.resolvePlutusScriptAddress=Vs;exports.resolvePlutusScriptHash=Ls;exports.resolvePoolId=Gs;exports.resolvePrivateKey=Ys;exports.resolveRewardAddress=ie;exports.resolveScriptRef=$s;exports.resolveSlotNo=zs;exports.resolveStakeKeyHash=Yt;exports.resolveTxFees=Ve;exports.resolveTxHash=Kr;
8
+ `,r:"\r",t:" "},a,c=function(k){throw{name:"SyntaxError",message:k,at:t,text:a}},l=function(k){return k&&k!==r&&c("Expected '"+k+"' instead of '"+r+"'"),r=a.charAt(t),t+=1,r},p=function(){var k,N="";for(r==="-"&&(N="-",l("-"));r>="0"&&r<="9";)N+=r,l();if(r===".")for(N+=".";l()&&r>="0"&&r<="9";)N+=r;if(r==="e"||r==="E")for(N+=r,l(),(r==="-"||r==="+")&&(N+=r,l());r>="0"&&r<="9";)N+=r,l();if(k=+N,!isFinite(k))c("Bad number");else return de==null&&(de=Le.exports),N.length>15?e.storeAsString?N:e.useNativeBigInt?BigInt(N):new de(N):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(k):new de(k):k},A=function(){var k,N,T="",Q;if(r==='"')for(var R=t;l();){if(r==='"')return t-1>R&&(T+=a.substring(R,t-1)),l(),T;if(r==="\\"){if(t-1>R&&(T+=a.substring(R,t-1)),l(),r==="u"){for(Q=0,N=0;N<4&&(k=parseInt(l(),16),!!isFinite(k));N+=1)Q=Q*16+k;T+=String.fromCharCode(Q)}else if(typeof n[r]=="string")T+=n[r];else break;R=t}}c("Bad string")},C=function(){for(;r&&r<=" ";)l()},E=function(){switch(r){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}c("Unexpected '"+r+"'")},w,b=function(){var k=[];if(r==="["){if(l("["),C(),r==="]")return l("]"),k;for(;r;){if(k.push(w()),C(),r==="]")return l("]"),k;l(","),C()}}c("Bad array")},P=function(){var k,N=Object.create(null);if(r==="{"){if(l("{"),C(),r==="}")return l("}"),N;for(;r;){if(k=A(),C(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(N,k)&&c('Duplicate key "'+k+'"'),un.test(k)===!0?e.protoAction==="error"?c("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():N[k]=w():ln.test(k)===!0?e.constructorAction==="error"?c("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():N[k]=w():N[k]=w(),C(),r==="}")return l("}"),N;l(","),C()}}c("Bad object")};return w=function(){switch(C(),r){case"{":return P();case"[":return b();case'"':return A();case"-":return p();default:return r>="0"&&r<="9"?p():E()}},function(k,N){var T;return a=k+"",t=0,r=" ",T=w(),C(),r&&c("Syntax error"),typeof N=="function"?function Q(R,X){var $,O=R[X];return O&&typeof O=="object"&&Object.keys(O).forEach(function(M){$=Q(O,M),$!==void 0?O[M]=$:delete O[M]}),N.call(R,X,O)}({"":T},""):T}},hn=dn,Fr=Hr.exports.stringify,Rr=hn;zt.exports=function(s){return{parse:Rr(s),stringify:Fr}};zt.exports.parse=Rr();zt.exports.stringify=Fr;class fn{txHex="";txBuilder=ge();txEvaluationMultiplier=1.1;_protocolParams=gt;txOutput;addingScriptInput=!1;addingPlutusMint=!1;isHydra=!1;meshTxBuilderBody;mintItem;txInQueueItem;collateralQueueItem;refScriptTxInQueueItem;reset=()=>(this.txHex="",this.txBuilder=ge(),this.txEvaluationMultiplier=1.1,this._protocolParams=gt,this.txOutput=void 0,this.addingScriptInput=!1,this.addingPlutusMint=!1,this.mintItem=void 0,this.txInQueueItem=void 0,this.collateralQueueItem=void 0,this.refScriptTxInQueueItem=void 0,this.meshTxBuilderBody=this.emptyTxBuilderBody(),this);emptyTxBuilderBody=()=>({inputs:[],outputs:[],extraInputs:[],selectionThreshold:0,collaterals:[],requiredSignatures:[],referenceInputs:[],mints:[],changeAddress:"",metadata:[],validityRange:{},certificates:[],signingKey:[]});constructor(){this.meshTxBuilderBody=this.emptyTxBuilderBody()}completeSync=e=>(e?this.meshTxBuilderBody=e:this.queueAllLastItem(),this.serializeTxBody(this.meshTxBuilderBody));completeSigning=()=>{const{signingKey:e}=this.meshTxBuilderBody;return e.length>0&&this.addAllSigningKeys(e),this.txHex};serializeTxBody=e=>{const{inputs:t,outputs:r,extraInputs:n,selectionThreshold:a,collaterals:c,referenceInputs:l,mints:p,changeAddress:A,certificates:C,validityRange:E,requiredSignatures:w,metadata:b}=e;if(this.isHydra?this.protocolParams({minFeeA:0,minFeeB:0,priceMem:0,priceStep:0,collateralPercent:0,coinsPerUTxOSize:"0"}):this.protocolParams({}),n.length>0&&this.addUtxosFrom(n,String(a)),this.removeDuplicateInputs(),this.meshTxBuilderBody.mints.sort((P,k)=>P.policyId.localeCompare(k.policyId)),this.meshTxBuilderBody.inputs.sort((P,k)=>P.txIn.txHash===k.txIn.txHash?P.txIn.txIndex-k.txIn.txIndex:P.txIn.txHash.localeCompare(k.txIn.txHash)),this.addAllInputs(t),this.addAllOutputs(r),this.addAllCollaterals(c),this.addAllReferenceInputs(l),this.addAllMints(p),this.addAllCertificates(C),this.addValidityRange(E),this.addAllRequiredSignatures(w),this.addAllMetadata(b),this.addCostModels(),A){const P=this.meshTxBuilderBody.collaterals.map(T=>{var Q,R;return((R=(Q=T.txIn.amount)==null?void 0:Q.find(X=>X.unit==="lovelace"))==null?void 0:R.quantity)||"0"}).reduce((T,Q)=>T+parseInt(Q),0),k=Math.ceil(this._protocolParams.collateralPercent*Number(Number(this.txBuilder.min_fee().checked_add(i.BigNum.from_str("10000")).to_js_value()))/100);let N=!1;if(P-k>0){const T=i.TransactionOutput.new(i.Address.from_bech32(A),i.Value.new(i.BigNum.from_str(String(k))));P-k>Number(i.min_ada_for_output(T,i.DataCost.new_coins_per_byte(i.BigNum.from_str(this._protocolParams.coinsPerUTxOSize))).to_js_value())&&(this.txBuilder.set_collateral_return(i.TransactionOutput.new(i.Address.from_bech32(A),i.Value.new(i.BigNum.from_str(String(P))))),this.txBuilder.set_total_collateral(i.BigNum.from_str(String(P))),N=!0)}this.addChange(A),N&&this.addCollateralReturn(A)}return this.buildTx(),this};txIn=(e,t,r,n)=>(this.txInQueueItem&&this.queueInput(),this.addingScriptInput?this.txInQueueItem={type:"Script",txIn:{txHash:e,txIndex:t,amount:r,address:n},scriptTxIn:{}}:this.txInQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:r,address:n}},this.addingScriptInput=!1,this);txInScript=(e,t="V2")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Datum value attempted to be called a non script input");return this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:e,version:t}},this};txInDatumValue=(e,t="Mesh")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Datum value attempted to be called a non script input");let r=e;return t==="JSON"&&(r=this.castRawDataToJsonString(e)),t==="Mesh"?(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:e}},this):(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:t,content:r}},this)};txInInlineDatumPresent=()=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Inline datum present attempted to be called a non script input");const{txHash:e,txIndex:t}=this.txInQueueItem.txIn;return e&&t.toString()&&(this.txInQueueItem.scriptTxIn.datumSource={type:"Inline",txHash:e,txIndex:t}),this};txInRedeemerValue=(e,t={...Gt},r="Mesh")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference redeemer attempted to be called a non script input");let n=e;return r==="Mesh"?(this.txInQueueItem.scriptTxIn.redeemer={data:{type:r,content:e},exUnits:t},this):(r==="JSON"&&(n=this.castRawDataToJsonString(e)),this.txInQueueItem.scriptTxIn.redeemer={data:{type:r,content:n},exUnits:t},this)};txOut=(e,t)=>(this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txOutput={address:e,amount:t},this);txOutDatumHashValue=(e,t="Mesh")=>{let r=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Hash",data:{type:t,content:r}},this;t==="JSON"&&(r=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Hash",data:{type:t,content:r}}}return this};txOutInlineDatumValue=(e,t="Mesh")=>{let r=e;if(this.txOutput){if(t==="Mesh")return this.txOutput.datum={type:"Inline",data:{type:t,content:r}},this;t==="JSON"&&(r=this.castRawDataToJsonString(e)),this.txOutput.datum={type:"Inline",data:{type:t,content:r}}}return this};txOutReferenceScript=(e,t="V2")=>(this.txOutput&&(this.txOutput.referenceScript={code:e,version:t}),this);spendingPlutusScriptV2=()=>(this.addingScriptInput=!0,this);spendingTxInReference=(e,t,r,n="V2")=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey")throw Error("Spending tx in reference attempted to be called a non script input");return this.txInQueueItem.scriptTxIn.scriptSource={type:"Inline",txInInfo:{txHash:e,txIndex:t,spendingScriptHash:r,version:n}},this};spendingReferenceTxInInlineDatumPresent=()=>(this.txInInlineDatumPresent(),this);spendingReferenceTxInRedeemerValue=(e,t={...Gt})=>(this.txInRedeemerValue(e,t),this);readOnlyTxInReference=(e,t)=>(this.meshTxBuilderBody.referenceInputs.push({txHash:e,txIndex:t}),this);mintPlutusScriptV2=()=>(this.addingPlutusMint=!0,this);mint=(e,t,r)=>(this.mintItem&&this.queueMint(),this.mintItem={type:this.addingPlutusMint?"Plutus":"Native",policyId:t,assetName:r,amount:e},this.addingPlutusMint=!1,this);mintingScript=(e,t="V2")=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");return this.mintItem.scriptSource={type:"Provided",script:{code:e,version:t}},this};mintTxInReference=(e,t,r="V2")=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");return this.mintItem.scriptSource={type:"Reference Script",txHash:e,txIndex:t,version:r},this};mintReferenceTxInRedeemerValue=(e,t={...Gt},r="Mesh")=>{if(!this.mintItem)throw Error("Undefined mint");if(this.mintItem.type=="Native")throw Error("Mint tx in reference can only be used on plutus script tokens");if(this.mintItem.type=="Plutus"){if(!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");let n=e;if(r==="Mesh")return this.mintItem.redeemer={data:{type:r,content:n},exUnits:t},this;r==="JSON"&&(n=this.castRawDataToJsonString(e)),this.mintItem.redeemer={data:{type:r,content:n},exUnits:t}}return this};mintRedeemerValue=(e,t={...Gt},r="Mesh")=>(this.mintReferenceTxInRedeemerValue(e,t,r),this);requiredSignerHash=e=>(this.meshTxBuilderBody.requiredSignatures.push(e),this);txInCollateral=(e,t,r,n)=>(this.collateralQueueItem&&this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem={type:"PubKey",txIn:{txHash:e,txIndex:t,amount:r,address:n}},this);registerPoolCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterPool",poolParams:e}),this);registerStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"RegisterStake",stakeKeyHash:e}),this);delegateStakeCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"DelegateStake",stakeKeyHash:e,poolId:t}),this);deregisterStakeCertificate=e=>(this.meshTxBuilderBody.certificates.push({type:"DeregisterStake",stakeKeyHash:e}),this);retirePoolCertificate=(e,t)=>(this.meshTxBuilderBody.certificates.push({type:"RetirePool",poolId:e,epoch:t}),this);changeAddress=e=>(this.meshTxBuilderBody.changeAddress=e,this);invalidBefore=e=>(this.meshTxBuilderBody.validityRange.invalidBefore=e,this);invalidHereafter=e=>(this.meshTxBuilderBody.validityRange.invalidHereafter=e,this);metadataValue=(e,t)=>(this.meshTxBuilderBody.metadata.push({tag:e,metadata:t}),this);protocolParams=e=>{const t={...gt,...e};return this._protocolParams=t,this.txBuilder=ge(t),this};signingKey=e=>(this.meshTxBuilderBody.signingKey.push(e),this);selectUtxosFrom=(e,t=5e6)=>(this.meshTxBuilderBody.extraInputs=e,this.meshTxBuilderBody.selectionThreshold=t,this);addUtxosFrom=(e,t)=>{const r=this.meshTxBuilderBody.outputs.reduce((a,c)=>(c.amount.forEach(p=>{const{unit:A,quantity:C}=p,E=Number(a.get(A))||0;a.set(A,String(E+Number(C)))}),a),new Map);this.meshTxBuilderBody.inputs.reduce((a,c)=>{const l=c.txIn.amount;return l==null||l.forEach(p=>{const{unit:A,quantity:C}=p,E=Number(a.get(A))||0;a.set(A,String(E-Number(C)))}),a},r),this.meshTxBuilderBody.mints.reduce((a,c)=>{const l={unit:c.policyId+c.assetName,quantity:String(c.amount)},p=Number(a.get(l.unit))||0;return a.set(l.unit,String(p-Number(l.quantity))),a},r),on(e,r,t).forEach(a=>{this.addTxIn({type:"PubKey",txIn:{txHash:a.input.txHash,txIndex:a.input.outputIndex,amount:a.output.amount,address:a.output.address}})})};addAllSigningKeys=e=>{if(e.length>0){const t=i.Vkeywitnesses.new(),r=i.Transaction.from_hex(this.txHex),n=r.body();e.forEach(l=>{const p=l.slice(0,4)==="5820"?l.slice(4):l,A=i.PrivateKey.from_hex(p),C=i.make_vkey_witness(i.hash_transaction(n),A);t.add(C)});const a=r.witness_set();a.set_vkeys(t);const c=i.Transaction.new(n,a,r.auxiliary_data());this.txHex=c.to_hex()}};buildTx=()=>{const e=this.txBuilder.build_tx();this.txHex=e.to_hex()};queueInput=()=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="Script")if(this.txInQueueItem.scriptTxIn){if(!this.txInQueueItem.scriptTxIn.datumSource)throw Error("Script input does not contain datum information");if(!this.txInQueueItem.scriptTxIn.redeemer)throw Error("Script input does not contain redeemer information");if(!this.txInQueueItem.scriptTxIn.scriptSource)throw Error("Script input does not contain script information")}else throw Error("Script input does not contain script, datum, or redeemer information");this.meshTxBuilderBody.inputs.push(this.txInQueueItem),this.txInQueueItem=void 0};queueMint=()=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.scriptSource)throw Error("Missing mint script information");this.meshTxBuilderBody.mints.push(this.mintItem),this.mintItem=void 0};makePlutusScriptSource=e=>{const t=i.ScriptHash.from_hex(e.spendingScriptHash),r=i.TransactionInput.new(i.TransactionHash.from_hex(e.txHash),e.txIndex);return i.PlutusScriptSource.new_ref_input_with_lang_ver(t,r,vt[e.version])};removeDuplicateInputs=()=>{const e=this.meshTxBuilderBody.inputs,t=n=>`${n.txHash}#${n.txIndex}`,r=[];for(let n=0;n<e.length;n++){const a=t(e[n].txIn);r.includes(a)?(e.splice(n,1),n--):r.push(a)}};addAllInputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];switch(r.type){case"PubKey":this.addTxIn(r);break;case"Script":this.addScriptTxIn(r);break}}};addTxIn=e=>{this.txBuilder.add_input(i.Address.from_bech32(e.txIn.address),i.TransactionInput.new(i.TransactionHash.from_hex(e.txIn.txHash),e.txIn.txIndex),Qt(e.txIn.amount))};addScriptTxIn=({scriptTxIn:e,txIn:t})=>{let r;const{datumSource:n,scriptSource:a,redeemer:c}=e;if(n.type==="Provided")r=i.DatumSource.new(this.castDataToPlutusData(n.data));else{const A=i.TransactionInput.new(i.TransactionHash.from_hex(n.txHash),n.txIndex);r=i.DatumSource.new_ref_input(A)}let l;a.type=="Inline"?l=this.makePlutusScriptSource(a.txInInfo):l=i.PlutusScriptSource.new(i.PlutusScript.from_hex_with_version(a.script.code,vt[a.script.version]));const p=i.Redeemer.new(i.RedeemerTag.new_spend(),i.BigNum.from_str("0"),this.castDataToPlutusData(c.data),i.ExUnits.new(i.BigNum.from_str(String(c.exUnits.mem)),i.BigNum.from_str(String(c.exUnits.steps))));this.txBuilder.add_plutus_script_input(i.PlutusWitness.new_with_ref(l,r,p),i.TransactionInput.new(i.TransactionHash.from_hex(t.txHash),t.txIndex),Qt(t.amount))};addAllOutputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];this.addOutput(r)}};addOutput=({amount:e,address:t,datum:r,referenceScript:n})=>{const a=Qt(e),c=a.multiasset();if(a.is_zero()&&c===void 0)throw Error("Invalid output amount");let l=i.TransactionOutputBuilder.new().with_address(_t(t));r&&r.type==="Hash"&&(l=l.with_data_hash(i.hash_plutus_data(this.castDataToPlutusData(r.data)))),r&&r.type==="Inline"&&(l=l.with_plutus_data(this.castDataToPlutusData(r.data))),n&&(l=l.with_script_ref(i.ScriptRef.new_plutus_script(i.PlutusScript.from_hex_with_version(n.code,vt[n.version]))));const p=l.next();if(c){const A=a.coin().is_zero()?p.with_asset_and_min_required_coin_by_utxo_cost(c,Ne(this._protocolParams.coinsPerUTxOSize)).build():p.with_coin_and_asset(a.coin(),c).build();this.txBuilder.add_output(A)}else{const A=p.with_coin(a.coin()).build();this.txBuilder.add_output(A)}};addAllCollaterals=e=>{const t=i.TxInputsBuilder.new();for(let r=0;r<e.length;r++){const n=e[r];this.addCollateral(t,n)}this.txBuilder.set_collateral(t)};addCollateral=(e,t)=>{e.add_input(i.Address.from_bech32(t.txIn.address),i.TransactionInput.new(i.TransactionHash.from_hex(t.txIn.txHash),t.txIn.txIndex),Qt(t.txIn.amount))};addCollateralReturn=e=>{var r;const t=(r=this.txBuilder.get_fee_if_set())==null?void 0:r.to_js_value();if(t){const n=Math.ceil(this._protocolParams.collateralPercent*Number(t)/100);this.txBuilder.set_total_collateral_and_return(i.BigNum.from_str(String(n)),i.Address.from_bech32(e))}};addAllReferenceInputs=e=>{e.forEach(t=>{this.addReferenceInput(t)})};addReferenceInput=({txHash:e,txIndex:t})=>{const r=i.TransactionInput.new(i.TransactionHash.from_hex(e),t);this.txBuilder.add_reference_input(r)};addAllMints=e=>{const t=i.MintBuilder.new();let r=0;for(let n=0;n<e.length;n++){const a=e[n];if(!a.scriptSource)throw Error("Mint script is expected to be provided");if(a.type==="Plutus"){if(!a.redeemer)throw Error("Missing mint redeemer information");this.addPlutusMint(t,a,r),r++}else a.type==="Native"&&this.addNativeMint(t,a)}this.txBuilder.set_mint_builder(t)};addPlutusMint=(e,{redeemer:t,policyId:r,scriptSource:n,assetName:a,amount:c},l)=>{const p=i.Redeemer.new(i.RedeemerTag.new_mint(),i.BigNum.from_str(String(l)),this.castDataToPlutusData(t.data),i.ExUnits.new(i.BigNum.from_str(String(t.exUnits.mem)),i.BigNum.from_str(String(t.exUnits.steps)))),A=n.type==="Reference Script"?i.PlutusScriptSource.new_ref_input_with_lang_ver(i.ScriptHash.from_hex(r),i.TransactionInput.new(i.TransactionHash.from_hex(n.txHash),n.txIndex),vt[n.version]):i.PlutusScriptSource.new(i.PlutusScript.from_hex_with_version(n.script.code,vt[n.script.version]));e.add_asset(i.MintWitness.new_plutus_script(A,p),i.AssetName.new(Buffer.from(a,"hex")),i.Int.new(i.BigNum.from_str(c)))};addNativeMint=(e,{scriptSource:t,assetName:r,amount:n})=>{if(t.type==="Reference Script")throw Error("Native mint cannot have reference script");e.add_asset(i.MintWitness.new_native_script(i.NativeScript.from_hex(t.script.code)),i.AssetName.new(Buffer.from(r,"hex")),i.Int.new(i.BigNum.from_str(n)))};decimalToFraction(e){const t=10**e.toString().split(".")[1].length;return[e*t,t]}toPoolParams=e=>{const t=this.decimalToFraction(e.margin),r=i.Relays.new();e.relays.forEach(c=>{r.add(Nr(c))});const n=i.RewardAddress.from_address(i.Address.from_bech32(e.rewardAddress));if(n===void 0)throw new Error("Reward address is invalid");const a=i.Ed25519KeyHashes.new();return e.owners.forEach(c=>{a.add(i.Ed25519KeyHash.from_hex(c))}),i.PoolParams.new(i.Ed25519KeyHash.from_hex(e.operator),i.VRFKeyHash.from_hex(e.VRFKeyHash),i.BigNum.from_str(e.pledge),i.BigNum.from_str(e.cost),i.UnitInterval.new(i.BigNum.from_str(t[0].toString()),i.BigNum.from_str(t[1].toString())),n,a,r,e.metadata?i.PoolMetadata.from_json(zt.exports.stringify(e.metadata)):void 0)};addCertificate=(e,t)=>{switch(t.type){case"RegisterPool":e.add(i.Certificate.new_pool_registration(i.PoolRegistration.new(this.toPoolParams(t.poolParams))));break;case"RegisterStake":e.add(i.Certificate.new_stake_registration(i.StakeRegistration.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"DelegateStake":e.add(i.Certificate.new_stake_delegation(i.StakeDelegation.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)),t.poolId.startsWith("pool")?i.Ed25519KeyHash.from_bech32(t.poolId):i.Ed25519KeyHash.from_hex(t.poolId))));break;case"DeregisterStake":e.add(i.Certificate.new_stake_deregistration(i.StakeDeregistration.new(i.StakeCredential.from_keyhash(i.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"RetirePool":e.add(i.Certificate.new_pool_retirement(i.PoolRetirement.new(t.poolId.startsWith("pool")?i.Ed25519KeyHash.from_bech32(t.poolId):i.Ed25519KeyHash.from_hex(t.poolId),t.epoch)))}};queueAllLastItem=()=>{this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txInQueueItem&&this.queueInput(),this.collateralQueueItem&&(this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem=void 0),this.mintItem&&this.queueMint()};addAllCertificates=e=>{const t=i.Certificates.new();e.forEach(r=>{this.addCertificate(t,r)}),this.txBuilder.set_certs(t)};addCostModels=()=>{this.txBuilder.calc_script_data_hash(i.TxBuilderConstants.plutus_vasil_cost_models())};addChange=e=>{this.txBuilder.add_change_if_needed(i.Address.from_bech32(e))};addValidityRange=({invalidBefore:e,invalidHereafter:t})=>{e&&this.txBuilder.set_validity_start_interval_bignum(i.BigNum.from_str(e.toString())),t&&this.txBuilder.set_ttl_bignum(i.BigNum.from_str(t.toString()))};addAllRequiredSignatures=e=>{e.forEach(t=>{this.txBuilder.add_required_signer(i.Ed25519KeyHash.from_hex(t))})};addAllMetadata=e=>{e.forEach(({tag:t,metadata:r})=>{this.txBuilder.add_json_metadatum(i.BigNum.from_str(t),zt.exports.stringify(r))})};updateRedeemer=(e,t)=>{t.forEach(r=>{switch(r.tag){case"SPEND":{const n=e.inputs[r.index];n.type=="Script"&&n.scriptTxIn.redeemer&&(n.scriptTxIn.redeemer.exUnits.mem=Math.floor(r.budget.mem*this.txEvaluationMultiplier),n.scriptTxIn.redeemer.exUnits.steps=Math.floor(r.budget.steps*this.txEvaluationMultiplier));break}case"MINT":{const n=e.mints[r.index];n.type=="Plutus"&&n.redeemer&&(n.redeemer.exUnits.mem=Math.floor(r.budget.mem*this.txEvaluationMultiplier),n.redeemer.exUnits.steps=Math.floor(r.budget.steps*this.txEvaluationMultiplier));break}}})};castRawDataToJsonString=e=>typeof e=="object"?zt.exports.stringify(e):e;castDataToPlutusData=({type:e,content:t})=>e==="Mesh"?Ot(t):e==="CBOR"?i.PlutusData.from_hex(t):i.PlutusData.from_json(t,i.PlutusDatumSchema.DetailedSchema)}class gn extends fn{_fetcher;_submitter;_evaluator;queriedTxHashes=new Set;queriedUTxOs={};constructor({fetcher:e,submitter:t,evaluator:r,isHydra:n=!1}){super(),e&&(this._fetcher=e),t&&(this._submitter=t),r&&(this._evaluator=r),n&&(this.isHydra=!0)}complete=async e=>{e?this.meshTxBuilderBody=e:this.queueAllLastItem();const{inputs:t,collaterals:r}=this.meshTxBuilderBody,n=[...t,...r].filter(a=>!this.isInputComplete(a));if(console.log("Incomplete UTxO",n),await this.queryAllTxInfo(n),console.log("Incomplete UTxO",n),n.forEach(a=>{this.completeTxInformation(a)}),this.completeSync(e),this._evaluator){const a=await this._evaluator.evaluateTx(this.txHex);this.updateRedeemer(this.meshTxBuilderBody,a),this.completeSync(e)}return this};submitTx=async e=>{var r;return await((r=this._submitter)==null?void 0:r.submitTx(e))};getUTxOInfo=async e=>{var r;let t=[];this.queriedTxHashes.has(e)||(console.log("Query",e),this.queriedTxHashes.add(e),t=await((r=this._fetcher)==null?void 0:r.fetchUTxOs(e))||[],this.queriedUTxOs[e]=t)};queryAllTxInfo=e=>{var r;const t=[];if(e.length>0&&!this._fetcher)throw Error("Transaction information is incomplete while no fetcher instance is provided");for(let n=0;n<e.length;n++){const a=e[n];this.isInputInfoComplete(a)||t.push(this.getUTxOInfo(a.txIn.txHash)),a.type==="Script"&&((r=a.scriptTxIn.scriptSource)==null?void 0:r.type)==="Inline"&&!this.isRefScriptInfoComplete(a)&&t.push(this.getUTxOInfo(a.scriptTxIn.scriptSource.txInInfo.txHash))}return Promise.all(t)};completeTxInformation=e=>{var t;if(!this.isInputInfoComplete(e)){const r=this.queriedUTxOs[e.txIn.txHash],n=r==null?void 0:r.find(l=>l.input.outputIndex===e.txIn.txIndex),a=n==null?void 0:n.output.amount,c=n==null?void 0:n.output.address;if(!a||a.length===0)throw Error(`Couldn't find value information for ${e.txIn.txHash}#${e.txIn.txIndex}`);if(e.txIn.amount=a,e.type==="PubKey"){if(!c||c==="")throw Error(`Couldn't find address information for ${e.txIn.txHash}#${e.txIn.txIndex}`);e.txIn.address=c}}if(e.type==="Script"&&((t=e.scriptTxIn.scriptSource)==null?void 0:t.type)=="Inline"&&!this.isRefScriptInfoComplete(e)){const r=e.scriptTxIn.scriptSource.txInInfo,a=this.queriedUTxOs[r.txHash].find(c=>c.input.outputIndex===r.txIndex);if(!a)throw Error(`Couldn't find script reference utxo for ${r.txHash}#${r.txIndex}`);r.spendingScriptHash=a==null?void 0:a.output.scriptHash}};isInputComplete=e=>e.type==="PubKey"?this.isInputInfoComplete(e):e.type==="Script"?this.isInputInfoComplete(e)&&this.isRefScriptInfoComplete(e):!0;isInputInfoComplete=e=>{const{amount:t,address:r}=e.txIn;return!(e.type==="PubKey"&&(!t||!r)||e.type==="Script"&&!t)};isRefScriptInfoComplete=e=>{var r;const{scriptSource:t}=e.scriptTxIn;return!((t==null?void 0:t.type)==="Inline"&&!((r=t.txInInfo)!=null&&r.spendingScriptHash))}}class st{_networkId;_encryptedSecret;constructor(e,t){this._networkId=e,this._encryptedSecret=t}getAccount(e,t){return this.accountContext(e,t,(r,n)=>{const a=dr(this._networkId,r.to_public().hash(),n.to_public().hash()).to_address().to_bech32(),c=hr(this._networkId,r.to_public().hash()).to_address().to_bech32(),l=Pe(this._networkId,n.to_public().hash()).to_address().to_bech32();return{baseAddress:a,enterpriseAddress:c,rewardAddress:l}})}signData(e,t,r,n){try{return this.accountContext(e,t,(a,c)=>{const l={payload:n},p={address:st.resolveAddress(this._networkId,r,a,c),key:r.startsWith("stake")?c:a},{coseSign1:A,coseKey:C}=ss(l,p);return{signature:A,key:C}})}catch(a){throw new Error(`An error occurred during signData: ${a}.`)}}signTx(e,t,r,n,a){try{const c=Dr(Kr(n));return this.accountContext(e,t,(l,p)=>{const A=i.Vkeywitnesses.new();return st.resolveSigners(n,r,l.to_public().hash().to_hex()).forEach(E=>{if(E===l.to_public().hash().to_hex())A.add(i.make_vkey_witness(c,l));else if(E===p.to_public().hash().to_hex())A.add(i.make_vkey_witness(c,p));else if(a===!1)throw new Error(`Missing key witness for: ${E}`)}),A})}catch(c){throw new Error(`An error occurred during signTx: ${c}.`)}}static encryptMnemonic(e,t){const r=De.mnemonicToEntropy(e.join(" ")),n=Or(r),a=dt(n.as_bytes());return n.free(),st.encrypt(a,t)}static encryptPrivateKey(e,t){const r=i.Bip32PrivateKey.from_bech32(e),n=dt(r.as_bytes());return r.free(),st.encrypt(n,t)}static encryptSigningKeys(e,t,r){const n=st.encrypt(e.slice(4),r),a=st.encrypt(t.slice(4),r);return[n,a]}static generateMnemonic(e=256){return De.generateMnemonic(e).split(" ")}accountContext(e,t,r){const{paymentKey:n,stakeKey:a}=st.resolveKeys(e,t,this._encryptedSecret),c=r(n,a);return n.free(),a.free(),c}static decrypt(e,t){try{return i.decrypt_with_password(ct(t),e)}catch{throw new Error("The password is incorrect.")}}static encrypt(e,t){const r=mr.customAlphabet("0123456789abcdef"),n=r(64),a=r(24);return i.encrypt_with_password(ct(t),n,a,e)}static resolveAddress(e,t,r,n){const a=[dr(e,r.to_public().hash(),n.to_public().hash()),hr(e,r.to_public().hash()),Pe(e,n.to_public().hash())].find(c=>c.to_address().to_bech32()===t);if(a!==void 0)return a.to_address();throw new Error(`Address: ${t} doesn't belong to this account.`)}static resolveKeys(e,t,r){if(typeof r=="string"){const c=st.decrypt(r,t);return Qs(c,e)}const n=st.decrypt(r[0],t),a=st.decrypt(r[1],t);return{paymentKey:i.PrivateKey.from_hex(n),stakeKey:i.PrivateKey.from_hex(a)}}static resolveSigners(e,t,r){const n=l=>{const p=(T,Q=[],R=0)=>{var O,M,W,Z,D;if(T===void 0||R>=T.len())return Q;const X=T.get(R),$=new Array;switch(X.kind()){case i.CertificateKind.StakeDeregistration:{const F=(O=X.as_stake_deregistration())==null?void 0:O.stake_credential(),q=(F==null?void 0:F.kind())===i.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case i.CertificateKind.StakeDelegation:{const F=(M=X.as_stake_delegation())==null?void 0:M.stake_credential(),q=(F==null?void 0:F.kind())===i.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case i.CertificateKind.PoolRegistration:{const F=(W=X.as_pool_registration())==null?void 0:W.pool_params().pool_owners();$.push(...C(F));break}case i.CertificateKind.PoolRetirement:{const F=(Z=X.as_pool_retirement())==null?void 0:Z.pool_keyhash();F&&$.push(F.to_hex());break}case i.CertificateKind.MoveInstantaneousRewardsCert:{const F=(D=X.as_move_instantaneous_rewards_cert())==null?void 0:D.move_instantaneous_reward().as_to_stake_creds();if(F)for(let q=0;q<F.len();q+=1){const J=F.keys().get(q),nt=J.kind()===i.StakeCredKind.Key?J.to_keyhash():void 0;nt&&$.push(nt.to_hex())}break}}return p(T,[...Q,...$],R+1)},A=(T,Q=[],R=0)=>{if(T===void 0||R>=T.len())return Q;const X=T.get(R).index(),$=T.get(R).transaction_id(),O=t.find(M=>M.input.outputIndex===X&&M.input.txHash===$.to_hex())!==void 0?r:"OUR_PRINCESS_IS_IN_ANOTHER_CASTLE";return A(T,[...Q,O],R+1)},C=(T,Q=[],R=0)=>T===void 0||R>=T.len()?Q:C(T,[...Q,T.get(R).to_hex()],R+1),E=(T,Q=[],R=0)=>{if(T===void 0||R>=T.len())return Q;const X=T.keys().get(R).payment_cred(),$=X.kind()===i.StakeCredKind.Key?X.to_keyhash():void 0;return E(T,$?[...Q,$.to_hex()]:Q,R+1)},w=l.certs(),b=l.collateral(),P=l.inputs(),k=l.required_signers(),N=l.withdrawals();return[...p(w),...A(b),...A(P),...C(k),...E(N)]},a=l=>{const p=(C,E=[])=>{var w,b,P,k;if(C)for(let N=0;N<C.len();N+=1){const T=C.get(N);switch(T.kind()){case i.NativeScriptKind.ScriptPubkey:{const Q=(w=T.as_script_pubkey())==null?void 0:w.addr_keyhash().to_hex();return Q?[...E,Q]:E}case i.NativeScriptKind.ScriptAll:return p((b=T.as_script_all())==null?void 0:b.native_scripts(),E);case i.NativeScriptKind.ScriptAny:return p((P=T.as_script_any())==null?void 0:P.native_scripts(),E);case i.NativeScriptKind.ScriptNOfK:return p((k=T.as_script_n_of_k())==null?void 0:k.native_scripts(),E)}}return E},A=l.native_scripts();return[...p(A)]},c=It(e);return new Set([...n(c.body()),...a(c.witness_set())])}}const pt="MARI0TIME";class mn{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new st(e.networkId,st.encryptMnemonic(e.key.words,pt));break;case"root":this._wallet=new st(e.networkId,st.encryptPrivateKey(e.key.bech32,pt));break;case"cli":this._wallet=new st(e.networkId,st.encryptSigningKeys(e.key.payment,e.key.stake??"f0".repeat(34),pt))}}getBaseAddress(e=0){return this._wallet.getAccount(e,pt).baseAddress}getPaymentAddress(e=0){return this._wallet.getAccount(e,pt).enterpriseAddress}getRewardAddress(e=0){return this._wallet.getAccount(e,pt).rewardAddress}getUsedAddress(e=0){const t=this._wallet.getAccount(e,pt);return _t(t.enterpriseAddress)}getUsedCollateral(e=gt.maxCollateralInputs){throw new Error("getUsedCollateral not implemented.")}async getUsedUTxOs(e=0){const t=this._wallet.getAccount(e,pt);return(await this._fetcher.fetchAddressUTxOs(t.enterpriseAddress)).map(n=>wt(n))}signData(e,t,r=0){try{return this._wallet.signData(r,pt,e,t)}catch(n){throw new Error(`[AppWallet] An error occurred during signData: ${n}.`)}}async signTx(e,t=!1,r=0){try{const n=this._wallet.getAccount(r,pt),a=await this._fetcher.fetchAddressUTxOs(n.enterpriseAddress),c=this._wallet.signTx(r,pt,a,e,t),l=It(e),p=l.witness_set(),A=Oe(p,c);return p.set_vkeys(A),i.Transaction.new(l.body(),p,l.auxiliary_data()).to_hex()}catch(n){throw new Error(`[AppWallet] An error occurred during signTx: ${n}.`)}}async signTxs(e,t){return console.log("unimplemented",e,t),[]}submitTx(e){return this._submitter.submitTx(e)}static brew(e=256){return st.generateMnemonic(e)}}class Ie{_walletInstance;walletInstance;constructor(e){this._walletInstance=e,this.walletInstance={...e}}static getInstalledWallets(){return window.cardano===void 0?[]:$e.filter(e=>window.cardano[e]!==void 0).map(e=>({name:window.cardano[e].name,icon:window.cardano[e].icon,version:window.cardano[e].apiVersion}))}static async enable(e){try{const t=await Ie.resolveInstance(e);if(t!==void 0)return new Ie(t);throw new Error(`Couldn't create an instance of wallet: ${e}`)}catch(t){throw new Error(`[BrowserWallet] An error occurred during enable: ${JSON.stringify(t)}.`)}}async getBalance(){const e=await this._walletInstance.getBalance();return Ur(Os(e))}async getChangeAddress(){const e=await this._walletInstance.getChangeAddress();return Lt(e).to_bech32()}async getCollateral(e=gt.maxCollateralInputs){return(await this.getUsedCollateral(e)).map(r=>pe(r))}getNetworkId(){return this._walletInstance.getNetworkId()}async getRewardAddresses(){return(await this._walletInstance.getRewardAddresses()).map(t=>Lt(t).to_bech32())}async getUnusedAddresses(){return(await this._walletInstance.getUnusedAddresses()).map(t=>Lt(t).to_bech32())}async getUsedAddresses(){return(await this._walletInstance.getUsedAddresses()).map(t=>Lt(t).to_bech32())}async getUtxos(e=void 0){return(await this.getUsedUTxOs(e)).map(r=>pe(r))}signData(e,t){const r=_t(e).to_hex();return this._walletInstance.signData(r,ct(t))}async signTx(e,t=!1){try{const r=It(e),n=r.witness_set(),a=await this._walletInstance.signTx(e,t),c=ur(a).vkeys()??i.Vkeywitnesses.new(),l=Oe(n,c);return n.set_vkeys(l),dt(i.Transaction.new(r.body(),n,r.auxiliary_data()).to_bytes())}catch(r){throw new Error(`[BrowserWallet] An error occurred during signTx: ${JSON.stringify(r)}.`)}}async signTxs(e,t=!1){let r;if(this._walletInstance.signTxs&&(r=await this._walletInstance.signTxs(e,t)),!r&&this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(a=>({cbor:a,partialSign:t})))),!r)throw new Error("Wallet does not support signTxs");const n=[];for(let a=0;a<r.length;a++){const c=It(e[a]),l=c.witness_set(),p=ur(r[a]).vkeys()??i.Vkeywitnesses.new(),A=Oe(l,p);l.set_vkeys(A);const C=dt(i.Transaction.new(c.body(),l,c.auxiliary_data()).to_bytes());n.push(C)}return n}submitTx(e){return this._walletInstance.submitTx(e)}async getUsedAddress(){const e=await this._walletInstance.getUsedAddresses();return Lt(e[0])}async getUsedCollateral(e=gt.maxCollateralInputs){return(await this._walletInstance.experimental.getCollateral()??[]).map(r=>cr(r)).slice(0,e)}async getUsedUTxOs(e=void 0){const t=e?Qt(e).to_hex():void 0;return(await this._walletInstance.getUtxos(t)??[]).map(n=>cr(n))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,Bt),n=t.unit.slice(Bt),a=Mr(r,n);return{unit:t.unit,policyId:r,assetName:qe(n),fingerprint:a,quantity:t.quantity}})}async getLovelace(){const t=(await this.getBalance()).find(r=>r.unit==="lovelace");return t!==void 0?t.quantity:"0"}async getPolicyIdAssets(e){return(await this.getAssets()).filter(r=>r.policyId===e)}async getPolicyIds(){const e=await this.getBalance();return Array.from(new Set(e.map(t=>t.unit.slice(0,Bt)))).filter(t=>t!=="lovelace")}static resolveInstance(e){if(window.cardano===void 0)return;const t=$e.map(r=>window.cardano[r]).filter(r=>r!==void 0).find(r=>r.name.toLowerCase()===e.toLowerCase());return t==null?void 0:t.enable()}}exports.AppWallet=mn;exports.BlockfrostProvider=Xs;exports.BrowserWallet=Ie;exports.EmbeddedWallet=st;exports.ForgeScript=nn;exports.InfuraProvider=Zs;exports.KoiosProvider=tn;exports.MaestroProvider=sn;exports.MeshTxBuilder=gn;exports.OgmiosProvider=en;exports.TangoProvider=rn;exports.checkSignature=ns;exports.generateNonce=Ws;exports.isNetwork=Ar;exports.keepRelevant=pr;exports.largestFirst=Jr;exports.largestFirstMultiAsset=Ir;exports.parseAssetUnit=kt;exports.parseHttpError=S;exports.readPlutusData=js;exports.readTransaction=Js;exports.resolveDataHash=Hs;exports.resolveEpochNo=Fs;exports.resolveFingerprint=Mr;exports.resolveLanguageView=Rs;exports.resolveNativeScriptHash=qs;exports.resolvePaymentKeyHash=qt;exports.resolvePlutusScriptAddress=Vs;exports.resolvePlutusScriptHash=Ls;exports.resolvePoolId=Gs;exports.resolvePrivateKey=Ys;exports.resolveRewardAddress=ie;exports.resolveScriptRef=$s;exports.resolveSlotNo=zs;exports.resolveStakeKeyHash=Yt;exports.resolveTxFees=Ve;exports.resolveTxHash=Kr;
package/dist/core.js CHANGED
@@ -5011,7 +5011,7 @@ class He {
5011
5011
  }
5012
5012
  async signTxs(e, t = !1) {
5013
5013
  let r;
5014
- if (this._walletInstance.signTxs && (r = await this._walletInstance.signTxs(e, t)), this._walletInstance.experimental.signTxs && (r = await this._walletInstance.experimental.signTxs(e.map((a) => ({
5014
+ if (this._walletInstance.signTxs && (r = await this._walletInstance.signTxs(e, t)), !r && this._walletInstance.experimental.signTxs && (r = await this._walletInstance.experimental.signTxs(e.map((a) => ({
5015
5015
  cbor: a,
5016
5016
  partialSign: t
5017
5017
  })))), !r)
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Rapidly build Web3 apps on the Cardano Blockchain.",
4
4
  "homepage": "https://meshjs.dev",
5
5
  "author": "MeshJS",
6
- "version": "1.5.16-beta-2",
6
+ "version": "1.5.16-beta-4",
7
7
  "license": "Apache-2.0",
8
8
  "type": "module",
9
9
  "repository": {