@meshsdk/core 1.5.24-alpha.2 → 1.5.24-alpha.3
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 +1 -1
- package/dist/core.js +9 -6
- package/package.json +1 -1
package/dist/core.cjs
CHANGED
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
`+n+k.join(`,
|
|
6
6
|
`+n)+`
|
|
7
7
|
`+N+"}":"{"+k.join(",")+"}",n=N,P}}typeof t.stringify!="function"&&(t.stringify=function(B,v,w){var b;if(n="",i="",typeof w=="number")for(b=0;b<w;b+=1)i+=" ";else typeof w=="string"&&(i=w);if(l=v,v&&typeof v!="function"&&(typeof v!="object"||typeof v.length!="number"))throw new Error("JSON.stringify");return y("",{"":B})})})()})(Rr);var fe=null;const fn=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,gn=/(?: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 mn=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:" "},i,c=function(T){throw{name:"SyntaxError",message:T,at:t,text:i}},l=function(T){return T&&T!==r&&c("Expected '"+T+"' instead of '"+r+"'"),r=i.charAt(t),t+=1,r},p=function(){var T,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(T=+N,!isFinite(T))c("Bad number");else return fe==null&&(fe=ze.exports),N.length>15?e.storeAsString?N:e.useNativeBigInt?BigInt(N):new fe(N):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(T):new fe(T):T},y=function(){var T,N,k="",Q;if(r==='"')for(var R=t;l();){if(r==='"')return t-1>R&&(k+=i.substring(R,t-1)),l(),k;if(r==="\\"){if(t-1>R&&(k+=i.substring(R,t-1)),l(),r==="u"){for(Q=0,N=0;N<4&&(T=parseInt(l(),16),!!isFinite(T));N+=1)Q=Q*16+T;k+=String.fromCharCode(Q)}else if(typeof n[r]=="string")k+=n[r];else break;R=t}}c("Bad string")},B=function(){for(;r&&r<=" ";)l()},v=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 T=[];if(r==="["){if(l("["),B(),r==="]")return l("]"),T;for(;r;){if(T.push(w()),B(),r==="]")return l("]"),T;l(","),B()}}c("Bad array")},P=function(){var T,N=Object.create(null);if(r==="{"){if(l("{"),B(),r==="}")return l("}"),N;for(;r;){if(T=y(),B(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(N,T)&&c('Duplicate key "'+T+'"'),fn.test(T)===!0?e.protoAction==="error"?c("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():N[T]=w():gn.test(T)===!0?e.constructorAction==="error"?c("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():N[T]=w():N[T]=w(),B(),r==="}")return l("}"),N;l(","),B()}}c("Bad object")};return w=function(){switch(B(),r){case"{":return P();case"[":return b();case'"':return y();case"-":return p();default:return r>="0"&&r<="9"?p():v()}},function(T,N){var k;return i=T+"",t=0,r=" ",k=w(),B(),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)}({"":k},""):k}},pn=mn,qr=Rr.exports.stringify,Vr=pn;Wt.exports=function(s){return{parse:Vr(s),stringify:qr}};Wt.exports.parse=Vr();Wt.exports.stringify=qr;class An{txHex="";txBuilder=pe();txEvaluationMultiplier=1.1;_protocolParams=It;txOutput;addingScriptInput=!1;addingPlutusMint=!1;isHydra=!1;meshTxBuilderBody;mintItem;txInQueueItem;collateralQueueItem;refScriptTxInQueueItem;reset=()=>(this.txHex="",this.txBuilder=pe(),this.txEvaluationMultiplier=1.1,this._protocolParams=It,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:i,collaterals:c,referenceInputs:l,mints:p,changeAddress:y,certificates:B,validityRange:v,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(i)),this.removeDuplicateInputs(),this.meshTxBuilderBody.mints.sort((P,T)=>P.policyId.localeCompare(T.policyId)),this.meshTxBuilderBody.inputs.sort((P,T)=>P.txIn.txHash===T.txIn.txHash?P.txIn.txIndex-T.txIn.txIndex:P.txIn.txHash.localeCompare(T.txIn.txHash)),this.addAllInputs(t),this.addAllOutputs(r),this.addAllCollaterals(c),this.addAllReferenceInputs(l),this.addAllMints(p),this.addAllCertificates(B),this.addValidityRange(v),this.addAllRequiredSignatures(w),this.addAllMetadata(b),this.addCostModels(),y){const P=this.meshTxBuilderBody.collaterals.map(k=>{var Q,R;return((R=(Q=k.txIn.amount)==null?void 0:Q.find(X=>X.unit==="lovelace"))==null?void 0:R.quantity)||"0"}).reduce((k,Q)=>k+parseInt(Q),0),T=Math.ceil(this._protocolParams.collateralPercent*Number(Number(this.txBuilder.min_fee().checked_add(a.BigNum.from_str("10000")).to_js_value()))/100);let N=!1;if(P-T>0){const k=a.TransactionOutput.new(a.Address.from_bech32(y),a.Value.new(a.BigNum.from_str(String(T))));P-T>Number(a.min_ada_for_output(k,a.DataCost.new_coins_per_byte(a.BigNum.from_str(this._protocolParams.coinsPerUTxOSize))).to_js_value())&&(this.txBuilder.set_collateral_return(a.TransactionOutput.new(a.Address.from_bech32(y),a.Value.new(a.BigNum.from_str(String(P))))),this.txBuilder.set_total_collateral(a.BigNum.from_str(String(P))),N=!0)}this.addChange(y),N&&this.addCollateralReturn(y)}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)=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey"&&(this.txInQueueItem={type:"SimpleScript",txIn:this.txInQueueItem.txIn,simpleScriptTxIn:{scriptSource:{type:"Provided",script:e}}}),this.txInQueueItem.type==="Script"){const r=t||"V2";this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:e,version:r}}}return 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Datum value attempted to be called on a simple 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Inline datum present attempted to be called on a simple 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={...Yt},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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference redeemer attempted to be called on a simple 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference attempted to be called on a simple 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={...Yt},r="Mesh")=>(this.txInRedeemerValue(e,t,r),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={...Yt},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={...Yt},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={...It,...e};return this._protocolParams=t,this.txBuilder=pe(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((i,c)=>(c.amount.forEach(p=>{const{unit:y,quantity:B}=p,v=Number(i.get(y))||0;i.set(y,String(v+Number(B)))}),i),new Map);this.meshTxBuilderBody.inputs.reduce((i,c)=>{const l=c.txIn.amount;return l==null||l.forEach(p=>{const{unit:y,quantity:B}=p,v=Number(i.get(y))||0;i.set(y,String(v-Number(B)))}),i},r),this.meshTxBuilderBody.mints.reduce((i,c)=>{const l={unit:c.policyId+c.assetName,quantity:String(c.amount)},p=Number(i.get(l.unit))||0;return i.set(l.unit,String(p-Number(l.quantity))),i},r),hn(e,r,t).forEach(i=>{const c={type:"PubKey",txIn:{txHash:i.input.txHash,txIndex:i.input.outputIndex,amount:i.output.amount,address:i.output.address}};this.meshTxBuilderBody.inputs.push(c),this.addTxIn(c)})};addAllSigningKeys=e=>{if(e.length>0){const t=a.Vkeywitnesses.new(),r=a.Transaction.from_hex(this.txHex),n=r.body();e.forEach(l=>{const p=l.slice(0,4)==="5820"?l.slice(4):l,y=a.PrivateKey.from_hex(p),B=a.make_vkey_witness(a.hash_transaction(n),y);t.add(B)});const i=r.witness_set();i.set_vkeys(t);const c=a.Transaction.new(n,i,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=a.ScriptHash.from_hex(e.spendingScriptHash),r=a.TransactionInput.new(a.TransactionHash.from_hex(e.txHash),e.txIndex);return a.PlutusScriptSource.new_ref_input_with_lang_ver(t,r,bt[e.version])};removeDuplicateInputs=()=>{const e=this.meshTxBuilderBody.inputs,t=n=>`${n.txHash}#${n.txIndex}`,r=[];for(let n=0;n<e.length;n++){const i=t(e[n].txIn);r.includes(i)?(e.splice(n,1),n--):r.push(i)}};addAllInputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];switch(r.type){case"PubKey":this.addTxIn(r);break;case"SimpleScript":this.addNativeScriptTxIn(r);break;case"Script":this.addScriptTxIn(r);break}}};addTxIn=e=>{this.txBuilder.add_input(a.Address.from_bech32(e.txIn.address),a.TransactionInput.new(a.TransactionHash.from_hex(e.txIn.txHash),e.txIn.txIndex),St(e.txIn.amount))};addNativeScriptTxIn=({txIn:e,simpleScriptTxIn:t})=>{t.scriptSource.type==="Provided"&&this.txBuilder.add_native_script_input(a.NativeScript.from_hex(t.scriptSource.script),a.TransactionInput.new(a.TransactionHash.from_hex(e.txHash),e.txIndex),St(e.amount))};addScriptTxIn=({scriptTxIn:e,txIn:t})=>{let r;const{datumSource:n,scriptSource:i,redeemer:c}=e;if(n.type==="Provided")r=a.DatumSource.new(this.castDataToPlutusData(n.data));else{const y=a.TransactionInput.new(a.TransactionHash.from_hex(n.txHash),n.txIndex);r=a.DatumSource.new_ref_input(y)}let l;i.type=="Inline"?l=this.makePlutusScriptSource(i.txInInfo):l=a.PlutusScriptSource.new(a.PlutusScript.from_hex_with_version(i.script.code,bt[i.script.version]));const p=a.Redeemer.new(a.RedeemerTag.new_spend(),a.BigNum.from_str("0"),this.castDataToPlutusData(c.data),a.ExUnits.new(a.BigNum.from_str(String(c.exUnits.mem)),a.BigNum.from_str(String(c.exUnits.steps))));this.txBuilder.add_plutus_script_input(a.PlutusWitness.new_with_ref(l,r,p),a.TransactionInput.new(a.TransactionHash.from_hex(t.txHash),t.txIndex),St(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 i=St(e),c=i.multiasset();if(i.is_zero()&&c===void 0)throw Error("Invalid output amount");let l=a.TransactionOutputBuilder.new().with_address(xt(t));r&&r.type==="Hash"&&(l=l.with_data_hash(a.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(a.ScriptRef.new_plutus_script(a.PlutusScript.from_hex_with_version(n.code,bt[n.version]))));const p=l.next();if(c){const y=i.coin().is_zero()?p.with_asset_and_min_required_coin_by_utxo_cost(c,Pe(this._protocolParams.coinsPerUTxOSize)).build():p.with_coin_and_asset(i.coin(),c).build();this.txBuilder.add_output(y)}else{const y=p.with_coin(i.coin()).build();this.txBuilder.add_output(y)}};addAllCollaterals=e=>{const t=a.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(a.Address.from_bech32(t.txIn.address),a.TransactionInput.new(a.TransactionHash.from_hex(t.txIn.txHash),t.txIn.txIndex),St(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(a.BigNum.from_str(String(n)),a.Address.from_bech32(e))}};addAllReferenceInputs=e=>{e.forEach(t=>{this.addReferenceInput(t)})};addReferenceInput=({txHash:e,txIndex:t})=>{const r=a.TransactionInput.new(a.TransactionHash.from_hex(e),t);this.txBuilder.add_reference_input(r)};addAllMints=e=>{const t=a.MintBuilder.new();let r=0;for(let n=0;n<e.length;n++){const i=e[n];if(!i.scriptSource)throw Error("Mint script is expected to be provided");if(i.type==="Plutus"){if(!i.redeemer)throw Error("Missing mint redeemer information");this.addPlutusMint(t,i,r),r++}else i.type==="Native"&&this.addNativeMint(t,i)}this.txBuilder.set_mint_builder(t)};addPlutusMint=(e,{redeemer:t,policyId:r,scriptSource:n,assetName:i,amount:c},l)=>{const p=a.Redeemer.new(a.RedeemerTag.new_mint(),a.BigNum.from_str(String(l)),this.castDataToPlutusData(t.data),a.ExUnits.new(a.BigNum.from_str(String(t.exUnits.mem)),a.BigNum.from_str(String(t.exUnits.steps)))),y=n.type==="Reference Script"?a.PlutusScriptSource.new_ref_input_with_lang_ver(a.ScriptHash.from_hex(r),a.TransactionInput.new(a.TransactionHash.from_hex(n.txHash),n.txIndex),bt[n.version]):a.PlutusScriptSource.new(a.PlutusScript.from_hex_with_version(n.script.code,bt[n.script.version]));e.add_asset(a.MintWitness.new_plutus_script(y,p),a.AssetName.new(Buffer.from(i,"hex")),a.Int.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(a.MintWitness.new_native_script(a.NativeScript.from_hex(t.script.code)),a.AssetName.new(Buffer.from(r,"hex")),a.Int.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=a.Relays.new();e.relays.forEach(c=>{r.add(Or(c))});const n=a.RewardAddress.from_address(a.Address.from_bech32(e.rewardAddress));if(n===void 0)throw new Error("Reward address is invalid");const i=a.Ed25519KeyHashes.new();return e.owners.forEach(c=>{i.add(a.Ed25519KeyHash.from_hex(c))}),a.PoolParams.new(a.Ed25519KeyHash.from_hex(e.operator),a.VRFKeyHash.from_hex(e.VRFKeyHash),a.BigNum.from_str(e.pledge),a.BigNum.from_str(e.cost),a.UnitInterval.new(a.BigNum.from_str(t[0].toString()),a.BigNum.from_str(t[1].toString())),n,i,r,e.metadata?a.PoolMetadata.from_json(Wt.exports.stringify(e.metadata)):void 0)};addCertificate=(e,t)=>{switch(t.type){case"RegisterPool":e.add(a.Certificate.new_pool_registration(a.PoolRegistration.new(this.toPoolParams(t.poolParams))));break;case"RegisterStake":e.add(a.Certificate.new_stake_registration(a.StakeRegistration.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"DelegateStake":e.add(a.Certificate.new_stake_delegation(a.StakeDelegation.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)),t.poolId.startsWith("pool")?a.Ed25519KeyHash.from_bech32(t.poolId):a.Ed25519KeyHash.from_hex(t.poolId))));break;case"DeregisterStake":e.add(a.Certificate.new_stake_deregistration(a.StakeDeregistration.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"RetirePool":e.add(a.Certificate.new_pool_retirement(a.PoolRetirement.new(t.poolId.startsWith("pool")?a.Ed25519KeyHash.from_bech32(t.poolId):a.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=a.Certificates.new();e.forEach(r=>{this.addCertificate(t,r)}),this.txBuilder.set_certs(t)};addCostModels=()=>{this.txBuilder.calc_script_data_hash(a.TxBuilderConstants.plutus_vasil_cost_models())};addChange=e=>{this.txBuilder.add_change_if_needed(a.Address.from_bech32(e))};addValidityRange=({invalidBefore:e,invalidHereafter:t})=>{e&&this.txBuilder.set_validity_start_interval_bignum(a.BigNum.from_str(e.toString())),t&&this.txBuilder.set_ttl_bignum(a.BigNum.from_str(t.toString()))};addAllRequiredSignatures=e=>{e.forEach(t=>{this.txBuilder.add_required_signer(a.Ed25519KeyHash.from_hex(t))})};addAllMetadata=e=>{e.forEach(({tag:t,metadata:r})=>{this.txBuilder.add_json_metadatum(a.BigNum.from_str(t),Wt.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"?Wt.exports.stringify(e):e;castDataToPlutusData=({type:e,content:t})=>e==="Mesh"?Ot(t):e==="CBOR"?a.PlutusData.from_hex(t):a.PlutusData.from_json(t,a.PlutusDatumSchema.DetailedSchema)}class In extends An{_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(i=>!this.isInputComplete(i));if(await this.queryAllTxInfo(n),n.forEach(i=>{this.completeTxInformation(i)}),this.completeSync(e),this._evaluator){const i=await this._evaluator.evaluateTx(this.txHex);this.updateRedeemer(this.meshTxBuilderBody,i),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)||(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 i=e[n];this.isInputInfoComplete(i)||t.push(this.getUTxOInfo(i.txIn.txHash)),i.type==="Script"&&((r=i.scriptTxIn.scriptSource)==null?void 0:r.type)==="Inline"&&!this.isRefScriptInfoComplete(i)&&t.push(this.getUTxOInfo(i.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),i=n==null?void 0:n.output.amount,c=n==null?void 0:n.output.address;if(!i||i.length===0)throw Error(`Couldn't find value information for ${e.txIn.txHash}#${e.txIn.txIndex}`);if(e.txIn.amount=i,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,i=this.queriedUTxOs[r.txHash].find(c=>c.input.outputIndex===r.txIndex);if(!i)throw Error(`Couldn't find script reference utxo for ${r.txHash}#${r.txIndex}`);r.spendingScriptHash=i==null?void 0:i.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 rt{_networkId;_encryptedSecret;constructor(e,t){this._networkId=e,this._encryptedSecret=t}getAccount(e,t,r=0){return this.accountContext(e,r,t,(n,i)=>{const c=mr(this._networkId,n.to_public().hash(),i.to_public().hash()).to_address().to_bech32(),l=pr(this._networkId,n.to_public().hash()).to_address().to_bech32(),p=Ue(this._networkId,i.to_public().hash()).to_address().to_bech32();return{baseAddress:c,enterpriseAddress:l,rewardAddress:p}})}signData(e,t,r,n,i=0){try{return this.accountContext(e,i,t,(c,l)=>{const p={payload:n},y={address:rt.resolveAddress(this._networkId,r,c,l),key:r.startsWith("stake")?l:c},{coseSign1:B,coseKey:v}=as(p,y);return{signature:B,key:v}})}catch(c){throw new Error(`An error occurred during signData: ${c}.`)}}signTx(e,t,r,n,i,c=0){try{const l=ke(Me(n));return this.accountContext(e,c,t,(p,y)=>{const B=a.Vkeywitnesses.new();return rt.resolveSigners(n,r,p.to_public().hash().to_hex()).forEach(w=>{if(w===p.to_public().hash().to_hex())B.add(a.make_vkey_witness(l,p));else if(w===y.to_public().hash().to_hex())B.add(a.make_vkey_witness(l,y));else if(i===!1)throw new Error(`Missing key witness for: ${w}`)}),B})}catch(l){throw new Error(`An error occurred during signTx: ${l}.`)}}addPaymentKey(e,t,r,n,i=0){const c=ke(Me(r));return this.accountContext(e,i,t,(l,p)=>{n.add(a.make_vkey_witness(c,l))}),n}static encryptMnemonic(e,t){const r=De.mnemonicToEntropy(e.join(" ")),n=Hr(r),i=ht(n.as_bytes());return n.free(),rt.encrypt(i,t)}static encryptPrivateKey(e,t){const r=a.Bip32PrivateKey.from_bech32(e),n=ht(r.as_bytes());return r.free(),rt.encrypt(n,t)}static encryptSigningKeys(e,t,r){const n=rt.encrypt(e.slice(4),r),i=rt.encrypt(t.slice(4),r);return[n,i]}static generateMnemonic(e=256){return De.generateMnemonic(e).split(" ")}accountContext(e,t,r,n){const{paymentKey:i,stakeKey:c}=rt.resolveKeys(e,t,r,this._encryptedSecret),l=n(i,c);return i.free(),c.free(),l}static decrypt(e,t){try{return a.decrypt_with_password(ft(t),e)}catch{throw new Error("The password is incorrect.")}}static encrypt(e,t){const r=_r.customAlphabet("0123456789abcdef"),n=r(64),i=r(24);return a.encrypt_with_password(ft(t),n,i,e)}static resolveAddress(e,t,r,n){const i=[mr(e,r.to_public().hash(),n.to_public().hash()),pr(e,r.to_public().hash()),Ue(e,n.to_public().hash())].find(c=>c.to_address().to_bech32()===t);if(i!==void 0)return i.to_address();throw new Error(`Address: ${t} doesn't belong to this account.`)}static resolveKeys(e,t,r,n){if(typeof n=="string"){const l=rt.decrypt(n,r);return ks(l,e,t)}const i=rt.decrypt(n[0],r),c=rt.decrypt(n[1],r);return{paymentKey:a.PrivateKey.from_hex(i),stakeKey:a.PrivateKey.from_hex(c)}}static resolveSigners(e,t,r){const n=l=>{const p=(k,Q=[],R=0)=>{var O,M,W,Z,D;if(k===void 0||R>=k.len())return Q;const X=k.get(R),$=new Array;switch(X.kind()){case a.CertificateKind.StakeDeregistration:{const F=(O=X.as_stake_deregistration())==null?void 0:O.stake_credential(),q=(F==null?void 0:F.kind())===a.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case a.CertificateKind.StakeDelegation:{const F=(M=X.as_stake_delegation())==null?void 0:M.stake_credential(),q=(F==null?void 0:F.kind())===a.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case a.CertificateKind.PoolRegistration:{const F=(W=X.as_pool_registration())==null?void 0:W.pool_params().pool_owners();$.push(...B(F));break}case a.CertificateKind.PoolRetirement:{const F=(Z=X.as_pool_retirement())==null?void 0:Z.pool_keyhash();F&&$.push(F.to_hex());break}case a.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()===a.StakeCredKind.Key?j.to_keyhash():void 0;nt&&$.push(nt.to_hex())}break}}return p(k,[...Q,...$],R+1)},y=(k,Q=[],R=0)=>{if(k===void 0||R>=k.len())return Q;const X=k.get(R).index(),$=k.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 y(k,[...Q,O],R+1)},B=(k,Q=[],R=0)=>k===void 0||R>=k.len()?Q:B(k,[...Q,k.get(R).to_hex()],R+1),v=(k,Q=[],R=0)=>{if(k===void 0||R>=k.len())return Q;const X=k.keys().get(R).payment_cred(),$=X.kind()===a.StakeCredKind.Key?X.to_keyhash():void 0;return v(k,$?[...Q,$.to_hex()]:Q,R+1)},w=l.certs(),b=l.collateral(),P=l.inputs(),T=l.required_signers(),N=l.withdrawals();return[...p(w),...y(b),...y(P),...B(T),...v(N)]},i=l=>{const p=(B,v=[])=>{var w,b,P,T;if(B)for(let N=0;N<B.len();N+=1){const k=B.get(N);switch(k.kind()){case a.NativeScriptKind.ScriptPubkey:{const Q=(w=k.as_script_pubkey())==null?void 0:w.addr_keyhash().to_hex();return Q?[...v,Q]:v}case a.NativeScriptKind.ScriptAll:return p((b=k.as_script_all())==null?void 0:b.native_scripts(),v);case a.NativeScriptKind.ScriptAny:return p((P=k.as_script_any())==null?void 0:P.native_scripts(),v);case a.NativeScriptKind.ScriptNOfK:return p((T=k.as_script_n_of_k())==null?void 0:T.native_scripts(),v)}}return v},y=l.native_scripts();return[...p(y)]},c=At(e);return new Set([...n(c.body()),...i(c.witness_set())])}}const lt="MARI0TIME";class Ae{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new rt(e.networkId,rt.encryptMnemonic(e.key.words,lt));break;case"root":this._wallet=new rt(e.networkId,rt.encryptPrivateKey(e.key.bech32,lt));break;case"cli":this._wallet=new rt(e.networkId,rt.encryptSigningKeys(e.key.payment,e.key.stake??"f0".repeat(34),lt))}}getBaseAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).baseAddress}getPaymentAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).enterpriseAddress}getRewardAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).rewardAddress}getUsedAddress(e=0,t=0){const r=this._wallet.getAccount(e,lt,t);return xt(r.enterpriseAddress)}getUsedCollateral(e=It.maxCollateralInputs){throw new Error("getUsedCollateral not implemented.")}async getUsedUTxOs(e=0){if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");const t=this._wallet.getAccount(e,lt);return(await this._fetcher.fetchAddressUTxOs(t.enterpriseAddress)).map(n=>pt(n))}signData(e,t,r=0,n=0){try{return this._wallet.signData(r,lt,e,t,n)}catch(i){throw new Error(`[AppWallet] An error occurred during signData: ${i}.`)}}async signTx(e,t=!1,r=0,n=0){try{if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");const i=this._wallet.getAccount(r,lt),c=await this._fetcher.fetchAddressUTxOs(i.enterpriseAddress),l=this._wallet.signTx(r,lt,c,e,t,n),p=At(e),y=p.witness_set(),B=ye(y,l);return y.set_vkeys(B),a.Transaction.new(p.body(),y,p.auxiliary_data()).to_hex()}catch(i){throw new Error(`[AppWallet] An error occurred during signTx: ${i}.`)}}signTxSync(e,t=!1,r=0,n=0){try{const i=this._wallet.signTx(r,lt,[],e,t,n);this._wallet.addPaymentKey(r,lt,e,i,n);const c=At(e),l=c.witness_set(),p=ye(l,i);return l.set_vkeys(p),a.Transaction.new(c.body(),l,c.auxiliary_data()).to_hex()}catch(i){throw new Error(`[AppWallet] An error occurred during signTx: ${i}.`)}}async signTxs(e,t){return console.log("unimplemented",e,t),[]}submitTx(e){if(!this._submitter)throw new Error("[AppWallet] Submitter is required to submit transactions. Please provide a submitter.");return this._submitter.submitTx(e)}static brew(e=256){return rt.generateMnemonic(e)}async getUtxos(){return await this.getUsedUTxOs()}async getCollateral(){return(await this.getUsedUTxOs())[0]}async getUsedAddresses(){return console.log(1,await this.getPaymentAddress()),[await this.getPaymentAddress()]}}class xe{_walletInstance;_walletName;walletInstance;constructor(e,t){this._walletInstance=e,this._walletName=t,this.walletInstance={...e}}static getInstalledWallets(){return window.cardano===void 0?[]:je.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 xe.resolveInstance(e);if(t!==void 0)return new xe(t,e);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 Kr(Hs(e))}async getChangeAddress(){const e=await this._walletInstance.getChangeAddress();return Gt(e).to_bech32()}async getCollateral(e=It.maxCollateralInputs){return(await this.getUsedCollateral(e)).map(r=>ae(r))}getNetworkId(){return this._walletInstance.getNetworkId()}async getRewardAddresses(){return(await this._walletInstance.getRewardAddresses()).map(t=>Gt(t).to_bech32())}async getUnusedAddresses(){return(await this._walletInstance.getUnusedAddresses()).map(t=>Gt(t).to_bech32())}async getUsedAddresses(){return(await this._walletInstance.getUsedAddresses()).map(t=>Gt(t).to_bech32())}async getUtxos(e=void 0){return(await this.getUsedUTxOs(e)).map(r=>ae(r))}signData(e,t){const r=xt(e).to_hex();return this._walletInstance.signData(r,ft(t))}async signTx(e,t=!1){try{const r=At(e),n=r.witness_set(),i=await this._walletInstance.signTx(e,t),c=fr(i).vkeys()??a.Vkeywitnesses.new(),l=ye(n,c);return n.set_vkeys(l),ht(a.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;switch(this._walletName){case"Typhon Wallet":this._walletInstance.signTxs&&(r=await this._walletInstance.signTxs(e,t));break;default:this._walletInstance.signTxs?r=await this._walletInstance.signTxs(e.map(i=>({cbor:i,partialSign:t}))):this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(i=>({cbor:i,partialSign:t}))));break}if(!r)throw new Error("Wallet does not support signTxs");const n=[];for(let i=0;i<r.length;i++){const c=At(e[i]),l=c.witness_set(),p=fr(r[i]).vkeys()??a.Vkeywitnesses.new(),y=ye(l,p);l.set_vkeys(y);const B=ht(a.Transaction.new(c.body(),l,c.auxiliary_data()).to_bytes());n.push(B)}return n}submitTx(e){return this._walletInstance.submitTx(e)}async getUsedAddress(){const e=await this._walletInstance.getUsedAddresses();return Gt(e[0])}async getUsedCollateral(e=It.maxCollateralInputs){return(await this._walletInstance.experimental.getCollateral()??[]).map(r=>dr(r)).slice(0,e)}async getUsedUTxOs(e=void 0){const t=e?St(e).to_hex():void 0;return(await this._walletInstance.getUtxos(t)??[]).map(n=>dr(n))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,dt),n=t.unit.slice(dt),i=Ye(r,n);return{unit:t.unit,policyId:r,assetName:Ge(n),fingerprint:i,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,dt)))).filter(t=>t!=="lovelace")}static resolveInstance(e){if(window.cardano===void 0)return;const t=je.map(r=>window.cardano[r]).filter(r=>r!==void 0).find(r=>r.name.toLowerCase()===e.toLowerCase());return t==null?void 0:t.enable()}}class _n{_wallet;_network;constructor(e){switch(this._network=e.networkId,e.key.type){case"root":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"root",bech32:e.key.bech32}});break;case"cli":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"cli",payment:e.key.payment}});break;case"mnemonic":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"mnemonic",words:e.key.words}});break}}async getBalance(){const e=await this.getUtxos(),t=new Map;return e.map(n=>{n.output.amount.map(i=>{const c=i.unit,l=Number(i.quantity);if(t.has(c)){const p=t.get(c);t.set(c,p+l)}else t.set(c,l)})}),Array.from(t,([n,i])=>({unit:n,quantity:i.toString()}))}getChangeAddress(){return this._wallet.getPaymentAddress()}async getCollateral(){const t=(await this.getUtxos()).filter(r=>r.output.amount.length===1&&r.output.amount[0].unit==="lovelace");t.sort((r,n)=>Number(r.output.amount[0].quantity)-Number(n.output.amount[0].quantity));for(const r of t)if(Number(r.output.amount[0].quantity)>=5e6)return[r];return[]}getNetworkId(){return this._network}async getRewardAddresses(){return[await this._wallet.getRewardAddress()]}getUnusedAddresses(){return[this.getChangeAddress()]}async getUsedAddresses(){return[this.getChangeAddress()]}async getUtxos(){return(await this.getUsedUTxOs()).map(t=>ae(t))}signData(e){return this._wallet.signData(this.getChangeAddress(),e)}async signTx(e,t=!1){return await this._wallet.signTx(e,t)}async signTxs(e,t=!1){const r=[];for(const n of e){const i=await this.signTx(n,t);r.push(i)}return r}async submitTx(e){return await this._wallet.submitTx(e)}getUsedAddress(){return this._wallet.getUsedAddress()}async getUsedCollateral(){return(await this.getCollateral()).map(r=>pt(r))}async getUsedUTxOs(){return await this._wallet.getUtxos()}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,dt),n=t.unit.slice(dt),i=Ye(r,n);return{unit:t.unit,policyId:r,assetName:Ge(n),fingerprint:i,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,dt)))).filter(t=>t!=="lovelace")}async createCollateral(){const t=await new exports.Transaction({initiator:this._wallet}).sendLovelace(this.getChangeAddress(),"5000000").build(),r=await this.signTx(t);return await this.submitTx(r)}static brew(e=!1,t=256){const r=rt.generateMnemonic(t);return e?Fr(r):r}}exports.AppWallet=Ae;exports.BlockfrostProvider=rn;exports.BrowserWallet=xe;exports.EmbeddedWallet=rt;exports.ForgeScript=un;exports.InfuraProvider=sn;exports.KoiosProvider=nn;exports.MaestroProvider=on;exports.MeshTxBuilder=In;exports.MeshWallet=_n;exports.OgmiosProvider=an;exports.YaciProvider=cn;exports.checkSignature=os;exports.generateNonce=Zs;exports.isNetwork=yr;exports.keepRelevant=xr;exports.largestFirst=ts;exports.largestFirstMultiAsset=wr;exports.mergeAssets=zr;exports.parseAssetUnit=Tt;exports.parseHttpError=S;exports.readPlutusData=tn;exports.readTransaction=en;exports.resolveDataHash=qs;exports.resolveEpochNo=Vs;exports.resolveFingerprint=Ye;exports.resolveLanguageView=Ls;exports.resolveNativeScriptAddress=Gs;exports.resolveNativeScriptHash=Ys;exports.resolveNativeScriptHex=$s;exports.resolvePaymentKeyHash=qt;exports.resolvePlutusScriptAddress=zs;exports.resolvePlutusScriptHash=Ws;exports.resolvePoolId=Js;exports.resolvePrivateKey=Fr;exports.resolveRewardAddress=oe;exports.resolveScriptRef=js;exports.resolveSlotNo=Xs;exports.resolveStakeKeyHash=$t;exports.resolveTxFees=$e;exports.resolveTxHash=Me;
|
|
8
|
+
`,r:"\r",t:" "},i,c=function(T){throw{name:"SyntaxError",message:T,at:t,text:i}},l=function(T){return T&&T!==r&&c("Expected '"+T+"' instead of '"+r+"'"),r=i.charAt(t),t+=1,r},p=function(){var T,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(T=+N,!isFinite(T))c("Bad number");else return fe==null&&(fe=ze.exports),N.length>15?e.storeAsString?N:e.useNativeBigInt?BigInt(N):new fe(N):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(T):new fe(T):T},y=function(){var T,N,k="",Q;if(r==='"')for(var R=t;l();){if(r==='"')return t-1>R&&(k+=i.substring(R,t-1)),l(),k;if(r==="\\"){if(t-1>R&&(k+=i.substring(R,t-1)),l(),r==="u"){for(Q=0,N=0;N<4&&(T=parseInt(l(),16),!!isFinite(T));N+=1)Q=Q*16+T;k+=String.fromCharCode(Q)}else if(typeof n[r]=="string")k+=n[r];else break;R=t}}c("Bad string")},B=function(){for(;r&&r<=" ";)l()},v=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 T=[];if(r==="["){if(l("["),B(),r==="]")return l("]"),T;for(;r;){if(T.push(w()),B(),r==="]")return l("]"),T;l(","),B()}}c("Bad array")},P=function(){var T,N=Object.create(null);if(r==="{"){if(l("{"),B(),r==="}")return l("}"),N;for(;r;){if(T=y(),B(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(N,T)&&c('Duplicate key "'+T+'"'),fn.test(T)===!0?e.protoAction==="error"?c("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():N[T]=w():gn.test(T)===!0?e.constructorAction==="error"?c("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():N[T]=w():N[T]=w(),B(),r==="}")return l("}"),N;l(","),B()}}c("Bad object")};return w=function(){switch(B(),r){case"{":return P();case"[":return b();case'"':return y();case"-":return p();default:return r>="0"&&r<="9"?p():v()}},function(T,N){var k;return i=T+"",t=0,r=" ",k=w(),B(),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)}({"":k},""):k}},pn=mn,qr=Rr.exports.stringify,Vr=pn;Wt.exports=function(s){return{parse:Vr(s),stringify:qr}};Wt.exports.parse=Vr();Wt.exports.stringify=qr;class An{txHex="";txBuilder=pe();txEvaluationMultiplier=1.1;_protocolParams=It;txOutput;addingScriptInput=!1;addingPlutusMint=!1;isHydra=!1;meshTxBuilderBody;mintItem;txInQueueItem;collateralQueueItem;refScriptTxInQueueItem;reset=()=>(this.txHex="",this.txBuilder=pe(),this.txEvaluationMultiplier=1.1,this._protocolParams=It,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:i,collaterals:c,referenceInputs:l,mints:p,changeAddress:y,certificates:B,validityRange:v,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(i)),this.removeDuplicateInputs(),this.meshTxBuilderBody.mints.sort((P,T)=>P.policyId.localeCompare(T.policyId)),this.meshTxBuilderBody.inputs.sort((P,T)=>P.txIn.txHash===T.txIn.txHash?P.txIn.txIndex-T.txIn.txIndex:P.txIn.txHash.localeCompare(T.txIn.txHash)),this.addAllInputs(t),this.addAllOutputs(r),this.addAllCollaterals(c),this.addAllReferenceInputs(l),this.addAllMints(p),this.addAllCertificates(B),this.addValidityRange(v),this.addAllRequiredSignatures(w),this.addAllMetadata(b),this.addCostModels(),y){const P=this.meshTxBuilderBody.collaterals.map(k=>{var Q,R;return((R=(Q=k.txIn.amount)==null?void 0:Q.find(X=>X.unit==="lovelace"))==null?void 0:R.quantity)||"0"}).reduce((k,Q)=>k+parseInt(Q),0),T=Math.ceil(this._protocolParams.collateralPercent*Number(Number(this.txBuilder.min_fee().checked_add(a.BigNum.from_str("10000")).to_js_value()))/100);let N=!1;if(P-T>0){const k=a.TransactionOutput.new(a.Address.from_bech32(y),a.Value.new(a.BigNum.from_str(String(T))));P-T>Number(a.min_ada_for_output(k,a.DataCost.new_coins_per_byte(a.BigNum.from_str(this._protocolParams.coinsPerUTxOSize))).to_js_value())&&(this.txBuilder.set_collateral_return(a.TransactionOutput.new(a.Address.from_bech32(y),a.Value.new(a.BigNum.from_str(String(P))))),this.txBuilder.set_total_collateral(a.BigNum.from_str(String(P))),N=!0)}this.addChange(y),N&&this.addCollateralReturn(y)}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)=>{if(!this.txInQueueItem)throw Error("Undefined input");if(this.txInQueueItem.type==="PubKey"&&(this.txInQueueItem={type:"SimpleScript",txIn:this.txInQueueItem.txIn,simpleScriptTxIn:{scriptSource:{type:"Provided",script:e}}}),this.txInQueueItem.type==="Script"){const r=t||"V2";this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:e,version:r}}}return 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Datum value attempted to be called on a simple 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Inline datum present attempted to be called on a simple 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={...Yt},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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference redeemer attempted to be called on a simple 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");if(this.txInQueueItem.type==="SimpleScript")throw Error("Spending tx in reference attempted to be called on a simple 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={...Yt},r="Mesh")=>(this.txInRedeemerValue(e,t,r),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={...Yt},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={...Yt},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={...It,...e};return this._protocolParams=t,this.txBuilder=pe(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((i,c)=>(c.amount.forEach(p=>{const{unit:y,quantity:B}=p,v=Number(i.get(y))||0;i.set(y,String(v+Number(B)))}),i),new Map);this.meshTxBuilderBody.inputs.reduce((i,c)=>{const l=c.txIn.amount;return l==null||l.forEach(p=>{const{unit:y,quantity:B}=p,v=Number(i.get(y))||0;i.set(y,String(v-Number(B)))}),i},r),this.meshTxBuilderBody.mints.reduce((i,c)=>{const l={unit:c.policyId+c.assetName,quantity:String(c.amount)},p=Number(i.get(l.unit))||0;return i.set(l.unit,String(p-Number(l.quantity))),i},r),hn(e,r,t).forEach(i=>{const c={type:"PubKey",txIn:{txHash:i.input.txHash,txIndex:i.input.outputIndex,amount:i.output.amount,address:i.output.address}};this.meshTxBuilderBody.inputs.push(c),this.addTxIn(c)})};addAllSigningKeys=e=>{if(e.length>0){const t=a.Vkeywitnesses.new(),r=a.Transaction.from_hex(this.txHex),n=r.body();e.forEach(l=>{const p=l.slice(0,4)==="5820"?l.slice(4):l,y=a.PrivateKey.from_hex(p),B=a.make_vkey_witness(a.hash_transaction(n),y);t.add(B)});const i=r.witness_set();i.set_vkeys(t);const c=a.Transaction.new(n,i,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=a.ScriptHash.from_hex(e.spendingScriptHash),r=a.TransactionInput.new(a.TransactionHash.from_hex(e.txHash),e.txIndex);return a.PlutusScriptSource.new_ref_input_with_lang_ver(t,r,bt[e.version])};removeDuplicateInputs=()=>{const e=this.meshTxBuilderBody.inputs,t=n=>`${n.txHash}#${n.txIndex}`,r=[];for(let n=0;n<e.length;n++){const i=t(e[n].txIn);r.includes(i)?(e.splice(n,1),n--):r.push(i)}};addAllInputs=e=>{for(let t=0;t<e.length;t++){const r=e[t];switch(r.type){case"PubKey":this.addTxIn(r);break;case"SimpleScript":this.addNativeScriptTxIn(r);break;case"Script":this.addScriptTxIn(r);break}}};addTxIn=e=>{this.txBuilder.add_input(a.Address.from_bech32(e.txIn.address),a.TransactionInput.new(a.TransactionHash.from_hex(e.txIn.txHash),e.txIn.txIndex),St(e.txIn.amount))};addNativeScriptTxIn=({txIn:e,simpleScriptTxIn:t})=>{t.scriptSource.type==="Provided"&&this.txBuilder.add_native_script_input(a.NativeScript.from_hex(t.scriptSource.script),a.TransactionInput.new(a.TransactionHash.from_hex(e.txHash),e.txIndex),St(e.amount))};addScriptTxIn=({scriptTxIn:e,txIn:t})=>{let r;const{datumSource:n,scriptSource:i,redeemer:c}=e;if(n.type==="Provided")r=a.DatumSource.new(this.castDataToPlutusData(n.data));else{const y=a.TransactionInput.new(a.TransactionHash.from_hex(n.txHash),n.txIndex);r=a.DatumSource.new_ref_input(y)}let l;i.type=="Inline"?l=this.makePlutusScriptSource(i.txInInfo):l=a.PlutusScriptSource.new(a.PlutusScript.from_hex_with_version(i.script.code,bt[i.script.version]));const p=a.Redeemer.new(a.RedeemerTag.new_spend(),a.BigNum.from_str("0"),this.castDataToPlutusData(c.data),a.ExUnits.new(a.BigNum.from_str(String(c.exUnits.mem)),a.BigNum.from_str(String(c.exUnits.steps))));this.txBuilder.add_plutus_script_input(a.PlutusWitness.new_with_ref(l,r,p),a.TransactionInput.new(a.TransactionHash.from_hex(t.txHash),t.txIndex),St(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 i=St(e),c=i.multiasset();if(i.is_zero()&&c===void 0)throw Error("Invalid output amount");let l=a.TransactionOutputBuilder.new().with_address(xt(t));r&&r.type==="Hash"&&(l=l.with_data_hash(a.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(a.ScriptRef.new_plutus_script(a.PlutusScript.from_hex_with_version(n.code,bt[n.version]))));const p=l.next();if(c){const y=i.coin().is_zero()?p.with_asset_and_min_required_coin_by_utxo_cost(c,Pe(this._protocolParams.coinsPerUTxOSize)).build():p.with_coin_and_asset(i.coin(),c).build();this.txBuilder.add_output(y)}else{const y=p.with_coin(i.coin()).build();this.txBuilder.add_output(y)}};addAllCollaterals=e=>{const t=a.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(a.Address.from_bech32(t.txIn.address),a.TransactionInput.new(a.TransactionHash.from_hex(t.txIn.txHash),t.txIn.txIndex),St(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(a.BigNum.from_str(String(n)),a.Address.from_bech32(e))}};addAllReferenceInputs=e=>{e.forEach(t=>{this.addReferenceInput(t)})};addReferenceInput=({txHash:e,txIndex:t})=>{const r=a.TransactionInput.new(a.TransactionHash.from_hex(e),t);this.txBuilder.add_reference_input(r)};addAllMints=e=>{const t=a.MintBuilder.new();let r=0;for(let n=0;n<e.length;n++){const i=e[n];if(!i.scriptSource)throw Error("Mint script is expected to be provided");if(i.type==="Plutus"){if(!i.redeemer)throw Error("Missing mint redeemer information");this.addPlutusMint(t,i,r),r++}else i.type==="Native"&&this.addNativeMint(t,i)}this.txBuilder.set_mint_builder(t)};addPlutusMint=(e,{redeemer:t,policyId:r,scriptSource:n,assetName:i,amount:c},l)=>{const p=a.Redeemer.new(a.RedeemerTag.new_mint(),a.BigNum.from_str(String(l)),this.castDataToPlutusData(t.data),a.ExUnits.new(a.BigNum.from_str(String(t.exUnits.mem)),a.BigNum.from_str(String(t.exUnits.steps)))),y=n.type==="Reference Script"?a.PlutusScriptSource.new_ref_input_with_lang_ver(a.ScriptHash.from_hex(r),a.TransactionInput.new(a.TransactionHash.from_hex(n.txHash),n.txIndex),bt[n.version]):a.PlutusScriptSource.new(a.PlutusScript.from_hex_with_version(n.script.code,bt[n.script.version]));e.add_asset(a.MintWitness.new_plutus_script(y,p),a.AssetName.new(Buffer.from(i,"hex")),a.Int.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(a.MintWitness.new_native_script(a.NativeScript.from_hex(t.script.code)),a.AssetName.new(Buffer.from(r,"hex")),a.Int.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=a.Relays.new();e.relays.forEach(c=>{r.add(Or(c))});const n=a.RewardAddress.from_address(a.Address.from_bech32(e.rewardAddress));if(n===void 0)throw new Error("Reward address is invalid");const i=a.Ed25519KeyHashes.new();return e.owners.forEach(c=>{i.add(a.Ed25519KeyHash.from_hex(c))}),a.PoolParams.new(a.Ed25519KeyHash.from_hex(e.operator),a.VRFKeyHash.from_hex(e.VRFKeyHash),a.BigNum.from_str(e.pledge),a.BigNum.from_str(e.cost),a.UnitInterval.new(a.BigNum.from_str(t[0].toString()),a.BigNum.from_str(t[1].toString())),n,i,r,e.metadata?a.PoolMetadata.from_json(Wt.exports.stringify(e.metadata)):void 0)};addCertificate=(e,t)=>{switch(t.type){case"RegisterPool":e.add(a.Certificate.new_pool_registration(a.PoolRegistration.new(this.toPoolParams(t.poolParams))));break;case"RegisterStake":e.add(a.Certificate.new_stake_registration(a.StakeRegistration.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"DelegateStake":e.add(a.Certificate.new_stake_delegation(a.StakeDelegation.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)),t.poolId.startsWith("pool")?a.Ed25519KeyHash.from_bech32(t.poolId):a.Ed25519KeyHash.from_hex(t.poolId))));break;case"DeregisterStake":e.add(a.Certificate.new_stake_deregistration(a.StakeDeregistration.new(a.StakeCredential.from_keyhash(a.Ed25519KeyHash.from_hex(t.stakeKeyHash)))));break;case"RetirePool":e.add(a.Certificate.new_pool_retirement(a.PoolRetirement.new(t.poolId.startsWith("pool")?a.Ed25519KeyHash.from_bech32(t.poolId):a.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=a.Certificates.new();e.forEach(r=>{this.addCertificate(t,r)}),this.txBuilder.set_certs(t)};addCostModels=()=>{this.txBuilder.calc_script_data_hash(a.TxBuilderConstants.plutus_vasil_cost_models())};addChange=e=>{this.txBuilder.add_change_if_needed(a.Address.from_bech32(e))};addValidityRange=({invalidBefore:e,invalidHereafter:t})=>{e&&this.txBuilder.set_validity_start_interval_bignum(a.BigNum.from_str(e.toString())),t&&this.txBuilder.set_ttl_bignum(a.BigNum.from_str(t.toString()))};addAllRequiredSignatures=e=>{e.forEach(t=>{this.txBuilder.add_required_signer(a.Ed25519KeyHash.from_hex(t))})};addAllMetadata=e=>{e.forEach(({tag:t,metadata:r})=>{this.txBuilder.add_json_metadatum(a.BigNum.from_str(t),Wt.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"?Wt.exports.stringify(e):e;castDataToPlutusData=({type:e,content:t})=>e==="Mesh"?Ot(t):e==="CBOR"?a.PlutusData.from_hex(t):a.PlutusData.from_json(t,a.PlutusDatumSchema.DetailedSchema)}class In extends An{_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(i=>!this.isInputComplete(i));if(await this.queryAllTxInfo(n),n.forEach(i=>{this.completeTxInformation(i)}),this.completeSync(e),this._evaluator){const i=await this._evaluator.evaluateTx(this.txHex);this.updateRedeemer(this.meshTxBuilderBody,i),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)||(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 i=e[n];this.isInputInfoComplete(i)||t.push(this.getUTxOInfo(i.txIn.txHash)),i.type==="Script"&&((r=i.scriptTxIn.scriptSource)==null?void 0:r.type)==="Inline"&&!this.isRefScriptInfoComplete(i)&&t.push(this.getUTxOInfo(i.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),i=n==null?void 0:n.output.amount,c=n==null?void 0:n.output.address;if(!i||i.length===0)throw Error(`Couldn't find value information for ${e.txIn.txHash}#${e.txIn.txIndex}`);if(e.txIn.amount=i,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,i=this.queriedUTxOs[r.txHash].find(c=>c.input.outputIndex===r.txIndex);if(!i)throw Error(`Couldn't find script reference utxo for ${r.txHash}#${r.txIndex}`);r.spendingScriptHash=i==null?void 0:i.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 rt{_networkId;_encryptedSecret;constructor(e,t){this._networkId=e,this._encryptedSecret=t}getAccount(e,t,r=0){return this.accountContext(e,r,t,(n,i)=>{const c=mr(this._networkId,n.to_public().hash(),i.to_public().hash()).to_address().to_bech32(),l=pr(this._networkId,n.to_public().hash()).to_address().to_bech32(),p=Ue(this._networkId,i.to_public().hash()).to_address().to_bech32();return{baseAddress:c,enterpriseAddress:l,rewardAddress:p}})}signData(e,t,r,n,i=0){try{return this.accountContext(e,i,t,(c,l)=>{const p={payload:n},y={address:rt.resolveAddress(this._networkId,r,c,l),key:r.startsWith("stake")?l:c},{coseSign1:B,coseKey:v}=as(p,y);return{signature:B,key:v}})}catch(c){throw new Error(`An error occurred during signData: ${c}.`)}}signTx(e,t,r,n,i,c=0){try{const l=ke(Me(n));return this.accountContext(e,c,t,(p,y)=>{const B=a.Vkeywitnesses.new();return rt.resolveSigners(n,r,p.to_public().hash().to_hex()).forEach(w=>{if(w===p.to_public().hash().to_hex())B.add(a.make_vkey_witness(l,p));else if(w===y.to_public().hash().to_hex())B.add(a.make_vkey_witness(l,y));else if(i===!1)throw new Error(`Missing key witness for: ${w}`)}),B})}catch(l){throw new Error(`An error occurred during signTx: ${l}.`)}}addPaymentKey(e,t,r,n,i=0){const c=ke(Me(r));return this.accountContext(e,i,t,(l,p)=>{n.add(a.make_vkey_witness(c,l))}),n}static encryptMnemonic(e,t){const r=De.mnemonicToEntropy(e.join(" ")),n=Hr(r),i=ht(n.as_bytes());return n.free(),rt.encrypt(i,t)}static encryptPrivateKey(e,t){const r=a.Bip32PrivateKey.from_bech32(e),n=ht(r.as_bytes());return r.free(),rt.encrypt(n,t)}static encryptSigningKeys(e,t,r){const n=rt.encrypt(e.slice(4),r),i=rt.encrypt(t.slice(4),r);return[n,i]}static generateMnemonic(e=256){return De.generateMnemonic(e).split(" ")}accountContext(e,t,r,n){const{paymentKey:i,stakeKey:c}=rt.resolveKeys(e,t,r,this._encryptedSecret),l=n(i,c);return i.free(),c.free(),l}static decrypt(e,t){try{return a.decrypt_with_password(ft(t),e)}catch{throw new Error("The password is incorrect.")}}static encrypt(e,t){const r=_r.customAlphabet("0123456789abcdef"),n=r(64),i=r(24);return a.encrypt_with_password(ft(t),n,i,e)}static resolveAddress(e,t,r,n){const i=[mr(e,r.to_public().hash(),n.to_public().hash()),pr(e,r.to_public().hash()),Ue(e,n.to_public().hash())].find(c=>c.to_address().to_bech32()===t);if(i!==void 0)return i.to_address();throw new Error(`Address: ${t} doesn't belong to this account.`)}static resolveKeys(e,t,r,n){if(typeof n=="string"){const l=rt.decrypt(n,r);return ks(l,e,t)}const i=rt.decrypt(n[0],r),c=rt.decrypt(n[1],r);return{paymentKey:a.PrivateKey.from_hex(i),stakeKey:a.PrivateKey.from_hex(c)}}static resolveSigners(e,t,r){const n=l=>{const p=(k,Q=[],R=0)=>{var O,M,W,Z,D;if(k===void 0||R>=k.len())return Q;const X=k.get(R),$=new Array;switch(X.kind()){case a.CertificateKind.StakeDeregistration:{const F=(O=X.as_stake_deregistration())==null?void 0:O.stake_credential(),q=(F==null?void 0:F.kind())===a.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case a.CertificateKind.StakeDelegation:{const F=(M=X.as_stake_delegation())==null?void 0:M.stake_credential(),q=(F==null?void 0:F.kind())===a.StakeCredKind.Key?F.to_keyhash():void 0;q&&$.push(q.to_hex());break}case a.CertificateKind.PoolRegistration:{const F=(W=X.as_pool_registration())==null?void 0:W.pool_params().pool_owners();$.push(...B(F));break}case a.CertificateKind.PoolRetirement:{const F=(Z=X.as_pool_retirement())==null?void 0:Z.pool_keyhash();F&&$.push(F.to_hex());break}case a.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()===a.StakeCredKind.Key?j.to_keyhash():void 0;nt&&$.push(nt.to_hex())}break}}return p(k,[...Q,...$],R+1)},y=(k,Q=[],R=0)=>{if(k===void 0||R>=k.len())return Q;const X=k.get(R).index(),$=k.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 y(k,[...Q,O],R+1)},B=(k,Q=[],R=0)=>k===void 0||R>=k.len()?Q:B(k,[...Q,k.get(R).to_hex()],R+1),v=(k,Q=[],R=0)=>{if(k===void 0||R>=k.len())return Q;const X=k.keys().get(R).payment_cred(),$=X.kind()===a.StakeCredKind.Key?X.to_keyhash():void 0;return v(k,$?[...Q,$.to_hex()]:Q,R+1)},w=l.certs(),b=l.collateral(),P=l.inputs(),T=l.required_signers(),N=l.withdrawals();return[...p(w),...y(b),...y(P),...B(T),...v(N)]},i=l=>{const p=(B,v=[])=>{var w,b,P,T;if(B)for(let N=0;N<B.len();N+=1){const k=B.get(N);switch(k.kind()){case a.NativeScriptKind.ScriptPubkey:{const Q=(w=k.as_script_pubkey())==null?void 0:w.addr_keyhash().to_hex();return Q?[...v,Q]:v}case a.NativeScriptKind.ScriptAll:return p((b=k.as_script_all())==null?void 0:b.native_scripts(),v);case a.NativeScriptKind.ScriptAny:return p((P=k.as_script_any())==null?void 0:P.native_scripts(),v);case a.NativeScriptKind.ScriptNOfK:return p((T=k.as_script_n_of_k())==null?void 0:T.native_scripts(),v)}}return v},y=l.native_scripts();return[...p(y)]},c=At(e);return new Set([...n(c.body()),...i(c.witness_set())])}}const lt="MARI0TIME";class Ae{_fetcher;_submitter;_wallet;constructor(e){switch(this._fetcher=e.fetcher,this._submitter=e.submitter,e.key.type){case"mnemonic":this._wallet=new rt(e.networkId,rt.encryptMnemonic(e.key.words,lt));break;case"root":this._wallet=new rt(e.networkId,rt.encryptPrivateKey(e.key.bech32,lt));break;case"cli":this._wallet=new rt(e.networkId,rt.encryptSigningKeys(e.key.payment,e.key.stake??"f0".repeat(34),lt))}}getBaseAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).baseAddress}getPaymentAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).enterpriseAddress}getRewardAddress(e=0,t=0){return this._wallet.getAccount(e,lt,t).rewardAddress}getUsedAddress(e=0,t=0){const r=this._wallet.getAccount(e,lt,t);return xt(r.enterpriseAddress)}getUsedCollateral(e=It.maxCollateralInputs){throw new Error("getUsedCollateral not implemented.")}async getUsedUTxOs(e=0){if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");const t=this._wallet.getAccount(e,lt);return(await this._fetcher.fetchAddressUTxOs(t.enterpriseAddress)).map(n=>pt(n))}signData(e,t,r=0,n=0){try{return this._wallet.signData(r,lt,e,t,n)}catch(i){throw new Error(`[AppWallet] An error occurred during signData: ${i}.`)}}async signTx(e,t=!1,r=0,n=0){try{if(!this._fetcher)throw new Error("[AppWallet] Fetcher is required to fetch UTxOs. Please provide a fetcher.");const i=this._wallet.getAccount(r,lt),c=await this._fetcher.fetchAddressUTxOs(i.enterpriseAddress),l=this._wallet.signTx(r,lt,c,e,t,n),p=At(e),y=p.witness_set(),B=ye(y,l);return y.set_vkeys(B),a.Transaction.new(p.body(),y,p.auxiliary_data()).to_hex()}catch(i){throw new Error(`[AppWallet] An error occurred during signTx: ${i}.`)}}signTxSync(e,t=!1,r=0,n=0){try{const i=this._wallet.signTx(r,lt,[],e,t,n);this._wallet.addPaymentKey(r,lt,e,i,n);const c=At(e),l=c.witness_set(),p=ye(l,i);return l.set_vkeys(p),a.Transaction.new(c.body(),l,c.auxiliary_data()).to_hex()}catch(i){throw new Error(`[AppWallet] An error occurred during signTx: ${i}.`)}}async signTxs(e,t){return console.log("unimplemented",e,t),[]}submitTx(e){if(!this._submitter)throw new Error("[AppWallet] Submitter is required to submit transactions. Please provide a submitter.");return this._submitter.submitTx(e)}static brew(e=256){return rt.generateMnemonic(e)}async getUtxos(){return await this.getUsedUTxOs()}async getCollateral(){return(await this.getUsedUTxOs())[0]}async getUsedAddresses(){return console.log(1,await this.getPaymentAddress()),[await this.getPaymentAddress()]}}class xe{_walletInstance;_walletName;walletInstance;constructor(e,t){this._walletInstance=e,this._walletName=t,this.walletInstance={...e}}static getInstalledWallets(){return window.cardano===void 0?[]:je.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 xe.resolveInstance(e);if(t!==void 0)return new xe(t,e);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 Kr(Hs(e))}async getChangeAddress(){const e=await this._walletInstance.getChangeAddress();return Gt(e).to_bech32()}async getCollateral(e=It.maxCollateralInputs){return(await this.getUsedCollateral(e)).map(r=>ae(r))}getNetworkId(){return this._walletInstance.getNetworkId()}async getRewardAddresses(){return(await this._walletInstance.getRewardAddresses()).map(t=>Gt(t).to_bech32())}async getUnusedAddresses(){return(await this._walletInstance.getUnusedAddresses()).map(t=>Gt(t).to_bech32())}async getUsedAddresses(){return(await this._walletInstance.getUsedAddresses()).map(t=>Gt(t).to_bech32())}async getUtxos(e=void 0){return(await this.getUsedUTxOs(e)).map(r=>ae(r))}signData(e,t){const r=xt(e).to_hex();return this._walletInstance.signData(r,ft(t))}async signTx(e,t=!1){try{const r=At(e),n=r.witness_set(),i=await this._walletInstance.signTx(e,t),c=fr(i).vkeys()??a.Vkeywitnesses.new(),l=ye(n,c);return n.set_vkeys(l),ht(a.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;switch(this._walletName){case"Typhon Wallet":this._walletInstance.signTxs&&(r=await this._walletInstance.signTxs(e,t));break;default:this._walletInstance.signTxs?r=await this._walletInstance.signTxs(e.map(i=>({cbor:i,partialSign:t}))):this._walletInstance.experimental.signTxs&&(r=await this._walletInstance.experimental.signTxs(e.map(i=>({cbor:i,partialSign:t}))));break}if(!r)throw new Error("Wallet does not support signTxs");const n=[];for(let i=0;i<r.length;i++)if(!r[i])n.push(e[i]);else{const c=At(e[i]),l=c.witness_set(),p=fr(r[i]).vkeys()??a.Vkeywitnesses.new(),y=ye(l,p);l.set_vkeys(y);const B=ht(a.Transaction.new(c.body(),l,c.auxiliary_data()).to_bytes());n.push(B)}return n}submitTx(e){return this._walletInstance.submitTx(e)}async getUsedAddress(){const e=await this._walletInstance.getUsedAddresses();return Gt(e[0])}async getUsedCollateral(e=It.maxCollateralInputs){return(await this._walletInstance.experimental.getCollateral()??[]).map(r=>dr(r)).slice(0,e)}async getUsedUTxOs(e=void 0){const t=e?St(e).to_hex():void 0;return(await this._walletInstance.getUtxos(t)??[]).map(n=>dr(n))}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,dt),n=t.unit.slice(dt),i=Ye(r,n);return{unit:t.unit,policyId:r,assetName:Ge(n),fingerprint:i,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,dt)))).filter(t=>t!=="lovelace")}static resolveInstance(e){if(window.cardano===void 0)return;const t=je.map(r=>window.cardano[r]).filter(r=>r!==void 0).find(r=>r.name.toLowerCase()===e.toLowerCase());return t==null?void 0:t.enable()}}class _n{_wallet;_network;constructor(e){switch(this._network=e.networkId,e.key.type){case"root":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"root",bech32:e.key.bech32}});break;case"cli":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"cli",payment:e.key.payment}});break;case"mnemonic":this._wallet=new Ae({networkId:e.networkId,fetcher:e.fetcher,submitter:e.submitter,key:{type:"mnemonic",words:e.key.words}});break}}async getBalance(){const e=await this.getUtxos(),t=new Map;return e.map(n=>{n.output.amount.map(i=>{const c=i.unit,l=Number(i.quantity);if(t.has(c)){const p=t.get(c);t.set(c,p+l)}else t.set(c,l)})}),Array.from(t,([n,i])=>({unit:n,quantity:i.toString()}))}getChangeAddress(){return this._wallet.getPaymentAddress()}async getCollateral(){const t=(await this.getUtxos()).filter(r=>r.output.amount.length===1&&r.output.amount[0].unit==="lovelace");t.sort((r,n)=>Number(r.output.amount[0].quantity)-Number(n.output.amount[0].quantity));for(const r of t)if(Number(r.output.amount[0].quantity)>=5e6)return[r];return[]}getNetworkId(){return this._network}async getRewardAddresses(){return[await this._wallet.getRewardAddress()]}getUnusedAddresses(){return[this.getChangeAddress()]}async getUsedAddresses(){return[this.getChangeAddress()]}async getUtxos(){return(await this.getUsedUTxOs()).map(t=>ae(t))}signData(e){return this._wallet.signData(this.getChangeAddress(),e)}async signTx(e,t=!1){return await this._wallet.signTx(e,t)}async signTxs(e,t=!1){const r=[];for(const n of e){const i=await this.signTx(n,t);r.push(i)}return r}async submitTx(e){return await this._wallet.submitTx(e)}getUsedAddress(){return this._wallet.getUsedAddress()}async getUsedCollateral(){return(await this.getCollateral()).map(r=>pt(r))}async getUsedUTxOs(){return await this._wallet.getUtxos()}async getAssets(){return(await this.getBalance()).filter(t=>t.unit!=="lovelace").map(t=>{const r=t.unit.slice(0,dt),n=t.unit.slice(dt),i=Ye(r,n);return{unit:t.unit,policyId:r,assetName:Ge(n),fingerprint:i,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,dt)))).filter(t=>t!=="lovelace")}async createCollateral(){const t=await new exports.Transaction({initiator:this._wallet}).sendLovelace(this.getChangeAddress(),"5000000").build(),r=await this.signTx(t);return await this.submitTx(r)}static brew(e=!1,t=256){const r=rt.generateMnemonic(t);return e?Fr(r):r}}exports.AppWallet=Ae;exports.BlockfrostProvider=rn;exports.BrowserWallet=xe;exports.EmbeddedWallet=rt;exports.ForgeScript=un;exports.InfuraProvider=sn;exports.KoiosProvider=nn;exports.MaestroProvider=on;exports.MeshTxBuilder=In;exports.MeshWallet=_n;exports.OgmiosProvider=an;exports.YaciProvider=cn;exports.checkSignature=os;exports.generateNonce=Zs;exports.isNetwork=yr;exports.keepRelevant=xr;exports.largestFirst=ts;exports.largestFirstMultiAsset=wr;exports.mergeAssets=zr;exports.parseAssetUnit=Tt;exports.parseHttpError=S;exports.readPlutusData=tn;exports.readTransaction=en;exports.resolveDataHash=qs;exports.resolveEpochNo=Vs;exports.resolveFingerprint=Ye;exports.resolveLanguageView=Ls;exports.resolveNativeScriptAddress=Gs;exports.resolveNativeScriptHash=Ys;exports.resolveNativeScriptHex=$s;exports.resolvePaymentKeyHash=qt;exports.resolvePlutusScriptAddress=zs;exports.resolvePlutusScriptHash=Ws;exports.resolvePoolId=Js;exports.resolvePrivateKey=Fr;exports.resolveRewardAddress=oe;exports.resolveScriptRef=js;exports.resolveSlotNo=Xs;exports.resolveStakeKeyHash=$t;exports.resolveTxFees=$e;exports.resolveTxHash=Me;
|
package/dist/core.js
CHANGED
|
@@ -5092,12 +5092,15 @@ class He {
|
|
|
5092
5092
|
if (!r)
|
|
5093
5093
|
throw new Error("Wallet does not support signTxs");
|
|
5094
5094
|
const n = [];
|
|
5095
|
-
for (let i = 0; i < r.length; i++)
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5095
|
+
for (let i = 0; i < r.length; i++)
|
|
5096
|
+
if (!r[i])
|
|
5097
|
+
n.push(e[i]);
|
|
5098
|
+
else {
|
|
5099
|
+
const c = pt(e[i]), l = c.witness_set(), p = gr(r[i]).vkeys() ?? a.Vkeywitnesses.new(), y = ye(l, p);
|
|
5100
|
+
l.set_vkeys(y);
|
|
5101
|
+
const B = lt(a.Transaction.new(c.body(), l, c.auxiliary_data()).to_bytes());
|
|
5102
|
+
n.push(B);
|
|
5103
|
+
}
|
|
5101
5104
|
return n;
|
|
5102
5105
|
}
|
|
5103
5106
|
submitTx(e) {
|
package/package.json
CHANGED