@meshsdk/transaction 1.6.2 → 1.6.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/index.cjs CHANGED
@@ -1 +1,1991 @@
1
- "use strict";var P=Object.create;var x=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var M=(a,t)=>{for(var e in t)x(a,e,{get:t[e],enumerable:!0})},y=(a,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of v(t))!E.call(a,r)&&r!==e&&x(a,r,{get:()=>t[r],enumerable:!(i=b(t,r))||i.enumerable});return a};var R=(a,t,e)=>(e=a!=null?P(V(a)):{},y(t||!a||!a.__esModule?x(e,"default",{value:a,enumerable:!0}):e,a)),O=a=>y(x({},"__esModule",{value:!0}),a);var A={};M(A,{ForgeScript:()=>S,MeshTxBuilder:()=>m,Transaction:()=>w});module.exports=O(A);var B=require("@meshsdk/core-csl");var T=R(require("json-bigint"),1),o=require("@meshsdk/common"),I=class{txEvaluationMultiplier=1.1;txOutput;addingPlutusScriptInput=!1;plutusSpendingScriptVersion;addingPlutusMint=!1;plutusMintingScriptVersion;addingPlutusWithdrawal=!1;plutusWithdrawalScriptVersion;_protocolParams=o.DEFAULT_PROTOCOL_PARAMETERS;mintItem;txInQueueItem;withdrawalItem;collateralQueueItem;refScriptTxInQueueItem;meshTxBuilderBody;constructor(){this.meshTxBuilderBody=(0,o.emptyTxBuilderBody)()}txIn=(t,e,i,r)=>(this.txInQueueItem&&this.queueInput(),this.addingPlutusScriptInput?this.txInQueueItem={type:"Script",txIn:{txHash:t,txIndex:e,amount:i,address:r},scriptTxIn:{}}:this.txInQueueItem={type:"PubKey",txIn:{txHash:t,txIndex:e,amount:i,address:r}},this.addingPlutusScriptInput=!1,this);txInScript=t=>{if(!this.txInQueueItem)throw Error("Undefined input");return this.txInQueueItem.type==="PubKey"&&(this.txInQueueItem={type:"SimpleScript",txIn:this.txInQueueItem.txIn,simpleScriptTxIn:{scriptSource:{type:"Provided",script:t}}}),this.txInQueueItem.type==="Script"&&(this.txInQueueItem.scriptTxIn.scriptSource={type:"Provided",script:{code:t,version:this.plutusSpendingScriptVersion||"V2"}}),this};txInDatumValue=(t,e="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 i=t;return e==="JSON"&&(i=this.castRawDataToJsonString(t)),e==="Mesh"?(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:e,content:t}},this):(this.txInQueueItem.scriptTxIn.datumSource={type:"Provided",data:{type:e,content:i}},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");let{txHash:t,txIndex:e}=this.txInQueueItem.txIn;return t&&e.toString()&&(this.txInQueueItem.scriptTxIn.datumSource={type:"Inline",txHash:t,txIndex:e}),this};txInRedeemerValue=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>{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");return this.txInQueueItem.scriptTxIn.redeemer=this.castBuilderDataToRedeemer(t,e,i),this};txOut=(t,e)=>(this.txOutput&&(this.meshTxBuilderBody.outputs.push(this.txOutput),this.txOutput=void 0),this.txOutput={address:t,amount:e},this);txOutDatumHashValue=(t,e="Mesh")=>{let i=t;if(this.txOutput){if(e==="Mesh")return this.txOutput.datum={type:"Hash",data:{type:e,content:i}},this;e==="JSON"&&(i=this.castRawDataToJsonString(t)),this.txOutput.datum={type:"Hash",data:{type:e,content:i}}}return this};txOutInlineDatumValue=(t,e="Mesh")=>{let i=t;if(this.txOutput){if(e==="Mesh")return this.txOutput.datum={type:"Inline",data:{type:e,content:i}},this;e==="JSON"&&(i=this.castRawDataToJsonString(t)),this.txOutput.datum={type:"Inline",data:{type:e,content:i}}}return this};txOutReferenceScript=(t,e="V2")=>(this.txOutput&&(this.txOutput.referenceScript={code:t,version:e}),this);spendingPlutusScriptV1=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V1",this);spendingPlutusScriptV2=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V2",this);spendingPlutusScriptV3=()=>(this.addingPlutusScriptInput=!0,this.plutusSpendingScriptVersion="V3",this);spendingTxInReference=(t,e,i)=>{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",txHash:t,txIndex:e,scriptHash:i,version:this.plutusSpendingScriptVersion||"V2",scriptSize:"0"},this};spendingReferenceTxInInlineDatumPresent=()=>(this.txInInlineDatumPresent(),this);spendingReferenceTxInRedeemerValue=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>(this.txInRedeemerValue(t,e,i),this);readOnlyTxInReference=(t,e)=>(this.meshTxBuilderBody.referenceInputs.push({txHash:t,txIndex:e}),this);mintPlutusScriptV1=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V1",this);mintPlutusScriptV2=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V2",this);mintPlutusScriptV3=()=>(this.addingPlutusMint=!0,this.plutusMintingScriptVersion="V3",this);mint=(t,e,i)=>(this.mintItem&&this.queueMint(),this.mintItem={type:this.addingPlutusMint?"Plutus":"Native",policyId:e,assetName:i,amount:t},this.addingPlutusMint=!1,this);mintingScript=t=>{if(!this.mintItem)throw Error("Undefined mint");if(!this.mintItem.type)throw Error("Mint information missing");return this.mintItem.type==="Native"&&(this.mintItem.scriptSource={type:"Provided",scriptCode:t}),this.mintItem.type==="Plutus"&&(this.mintItem.scriptSource={type:"Provided",script:{code:t,version:this.plutusMintingScriptVersion||"V2"}}),this};mintTxInReference=(t,e)=>{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:"Inline",txHash:t,txIndex:e,version:this.plutusMintingScriptVersion,scriptSize:"0",scriptHash:""},this};mintReferenceTxInRedeemerValue=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>{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"&&!this.mintItem.policyId)throw Error("PolicyId information missing from mint asset");return this.mintItem.redeemer=this.castBuilderDataToRedeemer(t,e,i),this};mintRedeemerValue=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>(this.mintReferenceTxInRedeemerValue(t,e,i),this);requiredSignerHash=t=>(this.meshTxBuilderBody.requiredSignatures.push(t),this);txInCollateral=(t,e,i,r)=>(this.collateralQueueItem&&this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem),this.collateralQueueItem={type:"PubKey",txIn:{txHash:t,txIndex:e,amount:i,address:r}},this);withdrawalPlutusScriptV1=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V1",this);withdrawalPlutusScriptV2=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V2",this);withdrawalPlutusScriptV3=()=>(this.addingPlutusWithdrawal=!0,this.plutusWithdrawalScriptVersion="V3",this);withdrawal=(t,e)=>{if(this.withdrawalItem&&this.queueWithdrawal(),this.addingPlutusWithdrawal){let r={plutusScriptWithdrawal:{address:t,coin:e}};return this.meshTxBuilderBody.withdrawals.push(r),this}let i={pubKeyWithdrawal:{address:t,coin:e}};return this.meshTxBuilderBody.withdrawals.push(i),this};withdrawalScript=(t,e)=>{if(!this.withdrawalItem)throw Error("withdrawalScript: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalScript: Adding script to non plutus withdrawal");return this.withdrawalItem.plutusScriptWithdrawal.scriptSource={type:"Provided",script:{code:t,version:this.plutusWithdrawalScriptVersion||"V2"}},this};withdrawalTxInReference=(t,e,i,r)=>{if(!this.withdrawalItem)throw Error("withdrawalTxInReference: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalTxInReference: Adding script reference to non plutus withdrawal");this.withdrawalItem.plutusScriptWithdrawal.scriptSource={type:"Inline",txHash:t,txIndex:e,scriptHash:i,version:this.plutusWithdrawalScriptVersion||"V2",scriptSize:r||"0"}};withdrawalRedeemerValue=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>{if(!this.withdrawalItem)throw Error("withdrawalRedeemerValue: Undefined withdrawal");if(!("plutusScriptWithdrawal"in this.withdrawalItem))throw Error("withdrawalRedeemerValue: Adding redeemer to non plutus withdrawal");return this.withdrawalItem.plutusScriptWithdrawal.redeemer=this.castBuilderDataToRedeemer(t,e,i),this};registerPoolCertificate=t=>(this.meshTxBuilderBody.certificates.push({type:"RegisterPool",poolParams:t}),this);registerStakeCertificate=t=>(this.meshTxBuilderBody.certificates.push({type:"RegisterStake",stakeKeyHash:t}),this);delegateStakeCertificate=(t,e)=>(this.meshTxBuilderBody.certificates.push({type:"DelegateStake",stakeKeyHash:t,poolId:e}),this);deregisterStakeCertificate=t=>(this.meshTxBuilderBody.certificates.push({type:"DeregisterStake",stakeKeyHash:t}),this);retirePoolCertificate=(t,e)=>(this.meshTxBuilderBody.certificates.push({type:"RetirePool",poolId:t,epoch:e}),this);changeAddress=t=>(this.meshTxBuilderBody.changeAddress=t,this);invalidBefore=t=>(this.meshTxBuilderBody.validityRange.invalidBefore=t,this);invalidHereafter=t=>(this.meshTxBuilderBody.validityRange.invalidHereafter=t,this);metadataValue=(t,e)=>{let i=T.default.stringify(e);return this.meshTxBuilderBody.metadata.push({tag:t,metadata:i}),this};signingKey=t=>(this.meshTxBuilderBody.signingKey.push(t),this);selectUtxosFrom=(t,e="experimental",i="5000000",r=!0)=>{this.meshTxBuilderBody.extraInputs=t;let s={threshold:i,strategy:e,includeTxFees:r};return this.meshTxBuilderBody.selectionConfig={...this.meshTxBuilderBody.selectionConfig,...s},this};protocolParams=t=>{let e={...o.DEFAULT_PROTOCOL_PARAMETERS,...t};return this._protocolParams=e,this};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(),this.withdrawalItem&&this.queueWithdrawal()};queueInput=()=>{if(!this.txInQueueItem)throw Error("queueInput: Undefined input");if(this.txInQueueItem.type==="Script")if(this.txInQueueItem.scriptTxIn){if(!this.txInQueueItem.scriptTxIn.datumSource)throw Error("queueInput: Script input does not contain datum information");if(!this.txInQueueItem.scriptTxIn.redeemer)throw Error("queueInput: Script input does not contain redeemer information");if(!this.txInQueueItem.scriptTxIn.scriptSource)throw Error("queueInput: Script input does not contain script information")}else throw Error("queueInput: 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("queueMint: Undefined mint");if(!this.mintItem.scriptSource)throw Error("queueMint: Missing mint script information");this.meshTxBuilderBody.mints.push(this.mintItem),this.mintItem=void 0};queueWithdrawal=()=>{if(!this.withdrawalItem)throw Error("queueWithdrawal: Undefined withdrawal");if("plutusScriptWithdrawal"in this.withdrawalItem){if(!this.withdrawalItem.plutusScriptWithdrawal.scriptSource)throw Error("queueWithdrawal: Missing withdrawal script information");if(!this.withdrawalItem.plutusScriptWithdrawal.redeemer)throw Error("queueWithdrawal: Missing withdrawal redeemer information")}this.meshTxBuilderBody.withdrawals.push(this.withdrawalItem),this.withdrawalItem=void 0};castRawDataToJsonString=t=>typeof t=="object"?T.default.stringify(t):t;castBuilderDataToRedeemer=(t,e="Mesh",i={...o.DEFAULT_REDEEMER_BUDGET})=>{let r,s=t;return e==="Mesh"?(r={data:{type:e,content:s},exUnits:i},r):(e==="JSON"&&(s=this.castRawDataToJsonString(t)),r={data:{type:e,content:s},exUnits:i},r)};updateRedeemer=(t,e)=>{e.forEach(i=>{switch(i.tag){case"SPEND":{let r=t.inputs[i.index];r.type=="Script"&&r.scriptTxIn.redeemer&&(r.scriptTxIn.redeemer.exUnits.mem=Math.floor(i.budget.mem*this.txEvaluationMultiplier),r.scriptTxIn.redeemer.exUnits.steps=Math.floor(i.budget.steps*this.txEvaluationMultiplier));break}case"MINT":{let r=t.mints[i.index];r.type=="Plutus"&&r.redeemer&&(r.redeemer.exUnits.mem=Math.floor(i.budget.mem*this.txEvaluationMultiplier),r.redeemer.exUnits.steps=Math.floor(i.budget.steps*this.txEvaluationMultiplier));break}case"CERT":break;case"REWARD":break}})};addUtxosFromSelection=()=>{let t=this.meshTxBuilderBody.outputs.reduce((s,n)=>(n.amount.forEach(h=>{let{unit:c,quantity:f}=h,g=Number(s.get(c))||0;s.set(c,String(g+Number(f)))}),s),new Map);this.meshTxBuilderBody.inputs.reduce((s,n)=>(n.txIn.amount?.forEach(h=>{let{unit:c,quantity:f}=h,g=Number(s.get(c))||0;s.set(c,String(g-Number(f)))}),s),t),this.meshTxBuilderBody.mints.reduce((s,n)=>{let u={unit:n.policyId+n.assetName,quantity:String(n.amount)},h=Number(s.get(u.unit))||0;return s.set(u.unit,String(h-Number(u.quantity))),s},t);let e=this.meshTxBuilderBody.selectionConfig,i=new o.UtxoSelection(e.threshold,e.includeTxFees),r=[];switch(e.strategy){case"keepRelevant":r=i.keepRelevant(t,this.meshTxBuilderBody.extraInputs);case"largestFirst":r=i.largestFirst(t,this.meshTxBuilderBody.extraInputs);break;case"largestFirstMultiAsset":r=i.largestFirstMultiAsset(t,this.meshTxBuilderBody.extraInputs);break;default:r=i.experimental(t,this.meshTxBuilderBody.extraInputs);break}r.forEach(s=>{let n={type:"PubKey",txIn:{txHash:s.input.txHash,txIndex:s.input.outputIndex,amount:s.output.amount,address:s.output.address}};this.meshTxBuilderBody.inputs.push(n)})};removeDuplicateInputs=()=>{let{inputs:t}=this.meshTxBuilderBody,e=s=>`${s.txHash}#${s.txIndex}`,i=[],r=[];for(let s=0;s<t.length;s+=1){let n=t[s],u=e(n.txIn);i.includes(u)?(t.splice(s,1),s-=1):r.push(n)}this.meshTxBuilderBody.inputs=r};emptyTxBuilderBody=()=>(this.meshTxBuilderBody=(0,o.emptyTxBuilderBody)(),o.emptyTxBuilderBody);reset=()=>{this.meshTxBuilderBody=(0,o.emptyTxBuilderBody)(),this.txEvaluationMultiplier=1.1,this.txOutput=void 0,this.addingPlutusScriptInput=!1,this.plutusSpendingScriptVersion=void 0,this.addingPlutusMint=!1,this.plutusMintingScriptVersion=void 0,this.addingPlutusWithdrawal=!1,this.plutusWithdrawalScriptVersion=void 0,this._protocolParams=o.DEFAULT_PROTOCOL_PARAMETERS,this.mintItem=void 0,this.txInQueueItem=void 0,this.withdrawalItem=void 0,this.collateralQueueItem=void 0,this.refScriptTxInQueueItem=void 0}};var m=class extends I{serializer;fetcher;submitter;evaluator;txHex="";queriedTxHashes=new Set;queriedUTxOs={};constructor({serializer:t,fetcher:e,submitter:i,evaluator:r,params:s,isHydra:n=!1}={}){super(),t?this.serializer=t:this.serializer=new B.CSLSerializer,e&&(this.fetcher=e),i&&(this.submitter=i),r&&(this.evaluator=r),s&&this.protocolParams(s),n&&this.protocolParams({minFeeA:0,minFeeB:0,priceMem:0,priceStep:0,collateralPercent:0,coinsPerUtxoSize:0})}complete=async t=>{t?this.meshTxBuilderBody={...this.meshTxBuilderBody,...t}:this.queueAllLastItem(),this.removeDuplicateInputs();let{inputs:e,collaterals:i}=this.meshTxBuilderBody,r=[...e,...i].filter(n=>!this.isInputComplete(n));await this.queryAllTxInfo(r),r.forEach(n=>{this.completeTxInformation(n)}),this.addUtxosFromSelection();let s=this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams);if(this.evaluator){let n=await this.evaluator.evaluateTx(s).catch(u=>{throw Error(`Tx evaluation failed: ${u}`)});this.updateRedeemer(this.meshTxBuilderBody,n),s=this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams)}return this.txHex=s,s};completeSync=t=>(t?this.meshTxBuilderBody=t:this.queueAllLastItem(),this.serializer.serializeTxBody(this.meshTxBuilderBody,this._protocolParams));completeSigning=()=>{let t=this.serializer.addSigningKeys(this.txHex,this.meshTxBuilderBody.signingKey);return this.txHex=t,t};submitTx=async t=>await this.submitter?.submitTx(t);getUTxOInfo=async t=>{let e=[];this.queriedTxHashes.has(t)||(this.queriedTxHashes.add(t),e=await this.fetcher?.fetchUTxOs(t)||[],this.queriedUTxOs[t]=e)};queryAllTxInfo=t=>{let e=[];if(t.length>0&&!this.fetcher)throw Error("Transaction information is incomplete while no fetcher instance is provided");for(let i=0;i<t.length;i++){let r=t[i];this.isInputInfoComplete(r)||e.push(this.getUTxOInfo(r.txIn.txHash)),r.type==="Script"&&r.scriptTxIn.scriptSource?.type==="Inline"&&!this.isRefScriptInfoComplete(r)&&e.push(this.getUTxOInfo(r.scriptTxIn.scriptSource.txHash))}return Promise.all(e)};completeTxInformation=t=>{if(!this.isInputInfoComplete(t)){let i=this.queriedUTxOs[t.txIn.txHash]?.find(n=>n.input.outputIndex===t.txIn.txIndex),r=i?.output.amount,s=i?.output.address;if(!r||r.length===0)throw Error(`Couldn't find value information for ${t.txIn.txHash}#${t.txIn.txIndex}`);if(t.txIn.amount=r,t.type==="PubKey"){if(!s||s==="")throw Error(`Couldn't find address information for ${t.txIn.txHash}#${t.txIn.txIndex}`);t.txIn.address=s}}if(t.type==="Script"&&t.scriptTxIn.scriptSource?.type=="Inline"&&!this.isRefScriptInfoComplete(t)){let e=t.scriptTxIn.scriptSource,r=this.queriedUTxOs[e.txHash].find(s=>s.input.outputIndex===e.txIndex);if(!r)throw Error(`Couldn't find script reference utxo for ${e.txHash}#${e.txIndex}`);e.scriptHash=r?.output.scriptHash}};isInputComplete=t=>t.type==="PubKey"?this.isInputInfoComplete(t):t.type==="Script"?this.isInputInfoComplete(t)&&this.isRefScriptInfoComplete(t):!0;isInputInfoComplete=t=>{let{amount:e,address:i}=t.txIn;return!(t.type==="PubKey"&&(!e||!i)||t.type==="Script"&&!e)};isRefScriptInfoComplete=t=>{let{scriptSource:e}=t.scriptTxIn;return!(e?.type==="Inline"&&!e?.scriptHash)}};var l=require("@meshsdk/core-cst"),S=class{static withOneSignature(t){let e=(0,l.deserializeEd25519KeyHash)((0,l.resolvePaymentKeyHash)(t));return(0,l.buildScriptPubkey)(e).toCbor()}static fromNativeScript(t){return(0,l.toNativeScript)(t).toCbor()}};var d=require("@meshsdk/common"),p=require("@meshsdk/core-cst");var w=class{txBuilder;initiator;isCollateralNeeded=!1;constructor(t){this.txBuilder=new m(t),this.initiator=t.initiator}sendAssets(t,e){return typeof e=="string"&&(e=[{unit:"lovelace",quantity:e}]),typeof t=="string"&&this.txBuilder.txOut(t,e),typeof t=="object"&&(this.txBuilder.txOut(t.address,e),t.datum&&(t.datum.inline?this.txBuilder.txOutInlineDatumValue(t.datum.value):this.txBuilder.txOutDatumHashValue(t.datum.value))),this}sendLovelace(t,e){return this.sendAssets(t,e)}sendToken(t,e,i){let r=[{unit:d.SUPPORTED_TOKENS[e],quantity:i}];return this.sendAssets(t,r)}sendValue(t,e){let i=e.output.amount;return this.sendAssets(t,i)}setTxInputs(t){return t.forEach(e=>{this.txBuilder.txIn(e.input.txHash,e.input.outputIndex,e.output.amount,e.output.address)}),this}setTxRefInputs(t){return t.forEach(e=>{this.txBuilder.readOnlyTxInReference(e.input.txHash,e.input.outputIndex)}),this}setNativeScriptInput(t,e){let{scriptCbor:i}=this.txBuilder.serializer.deserializer.script.deserializeNativeScript(t);return this.txBuilder.txIn(e.input.txHash,e.input.outputIndex,e.output.amount,e.output.address).txInScript(i),this}redeemValue(t){let{value:e,script:i,datum:r,redeemer:s}=t,n=s||{data:{alternative:0,fields:["mesh"]},budget:d.DEFAULT_REDEEMER_BUDGET};if("code"in i&&(this.isCollateralNeeded=!0,this.spendingPlutusScript(i).txIn(e.input.txHash,e.input.outputIndex,e.output.amount,e.output.address).txInScript(i.code).txInRedeemerValue(n.data,"Mesh",n.budget)),"output"in i){if(!i.output.scriptRef)throw new Error("redeemValue: No script reference found in UTxO");let u=(0,p.fromScriptRef)(i.output.scriptRef);if(!u||!("code"in u))throw new Error("redeemValue: Script reference not found");this.isCollateralNeeded=!0,this.spendingPlutusScript(u).txIn(e.input.txHash,e.input.outputIndex,e.output.amount,e.output.address).spendingTxInReference(i.input.txHash,i.input.outputIndex,i.output.scriptHash).txInRedeemerValue(n.data,"Mesh",n.budget)}return r?this.txBuilder.txInDatumValue(r):this.txBuilder.txInInlineDatumPresent(),this}mintAsset(t,e,i){let r=e.assetQuantity,s=(0,d.stringToHex)(e.assetName),n=(0,d.CIP68_100)(s);e.cip68ScriptAddress&&(s=(0,d.CIP68_222)(s));let u="";switch(typeof t){case"string":u=(0,p.deserializeNativeScript)(t).hash().toString(),this.txBuilder.mint(r,u,s).mintingScript(t),e.cip68ScriptAddress&&this.txBuilder.mint(r,u,n).mintingScript(t);break;case"object":if(!i)throw new Error("burnAsset: Redeemer data is required for Plutus minting");if("code"in t){u=(0,p.deserializePlutusScript)(t.code,t.version).hash().toString(),this.isCollateralNeeded=!0,this.mintPlutusScript(t).mint(r,u,s).mintingScript(t.code).mintRedeemerValue(i.data,"Mesh",i.budget),e.cip68ScriptAddress&&this.mintPlutusScript(t).mint(r,u,n).mintingScript(t.code).mintRedeemerValue(i.data,"Mesh",i.budget);break}if("output"in t){if(!t.output.scriptRef)throw new Error("mintAsset: No script reference found in UTxO");let h=(0,p.fromScriptRef)(t.output.scriptRef);if(!h)throw new Error("mintAsset: Script reference not found");if("code"in h){if(u=(0,p.deserializePlutusScript)(h.code,h.version).hash().toString(),this.isCollateralNeeded=!0,this.mintPlutusScript(h).mint(r,u,s).mintTxInReference(t.input.txHash,t.input.outputIndex).mintRedeemerValue(i.data,"Mesh",i.budget),e.cip68ScriptAddress){this.mintPlutusScript(h).mint(r,u,n).mintTxInReference(t.input.txHash,t.input.outputIndex).mintRedeemerValue(i.data,"Mesh",i.budget);break}break}else throw new Error("mintAsset: Reference script minting not implemented")}break}return e.recipient&&this.sendAssets(e.recipient,[{unit:u+s,quantity:e.assetQuantity}]),e.cip68ScriptAddress&&this.sendAssets({address:e.cip68ScriptAddress,datum:{inline:!0,value:(0,d.metadataToCip68)(e.metadata)}},[{unit:u+n,quantity:e.assetQuantity}]),!e.cip68ScriptAddress&&e.metadata&&e.label&&((e.label==="721"||e.label==="20")&&this.setMetadata(Number(e.label),{[u]:{[e.assetName]:e.metadata}}),this.setMetadata(Number(e.label),e.metadata)),this}burnAsset(t,e,i){let r="-"+e.quantity,s={assetName:(0,d.hexToString)(e.unit.slice(d.POLICY_ID_LENGTH)),assetQuantity:r};try{this.mintAsset(t,s,i)}catch(n){throw new Error("burnAsset: "+n)}return this}setChangeAddress(t){return this.txBuilder.changeAddress(t),this}setCollateral(t){return t.forEach(e=>{this.txBuilder.txInCollateral(e.input.txHash,e.input.outputIndex,e.output.amount,e.output.address)}),this}setRequiredSigners(t){return t.forEach(e=>{let{pubKeyHash:i}=this.txBuilder.serializer.deserializer.key.deserializeAddress(e);this.txBuilder.requiredSignerHash(i)}),this}setTimeToExpire(t){return this.txBuilder.invalidHereafter(Number(t)),this}setTimeToStart(t){return this.txBuilder.invalidBefore(Number(t)),this}setMetadata(t,e){return this.txBuilder.metadataValue(t.toString(),e),this}withdrawRewards(t,e){return this.txBuilder.withdrawal(t,e),this}delegateStake(t,e){return this.txBuilder.delegateStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(t),this.txBuilder.serializer.resolver.keys.resolveEd25519KeyHash(e)),this}deregisterStake(t){return this.txBuilder.deregisterStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(t)),this}registerStake(t){return this.txBuilder.registerStakeCertificate(this.txBuilder.serializer.resolver.keys.resolveStakeKeyHash(t)),this}registerPool(t){return this.txBuilder.registerPoolCertificate(t),this}retirePool(t,e){return this.txBuilder.retirePoolCertificate(t,e),this}async build(){try{return await this.addCollateralIfNeeded(),await this.addTxInputsAsNeeded(),await this.addChangeAddress(),this.txBuilder.complete()}catch(t){throw new Error(`[Transaction] An error occurred during build: ${t}.`)}}mintPlutusScript(t){switch(t.version){case"V1":this.txBuilder.mintPlutusScriptV1();break;case"V2":this.txBuilder.mintPlutusScriptV2();break;case"V3":this.txBuilder.mintPlutusScriptV3();break}return this.txBuilder}spendingPlutusScript(t){switch(t.version){case"V1":this.txBuilder.spendingPlutusScriptV1();break;case"V2":this.txBuilder.spendingPlutusScriptV2();break;case"V3":this.txBuilder.spendingPlutusScriptV3();break}return this.txBuilder}async addCollateralIfNeeded(){if(this.isCollateralNeeded){let t=await this.initiator.getCollateral();this.setCollateral(t)}}async addTxInputsAsNeeded(){let t=await this.initiator.getUtxos();this.txBuilder.selectUtxosFrom(t)}async addChangeAddress(){if(this.txBuilder.meshTxBuilderBody.changeAddress===""){let t=await this.initiator.getChangeAddress();this.setChangeAddress(t)}}};0&&(module.exports={ForgeScript,MeshTxBuilder,Transaction});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ ForgeScript: () => ForgeScript,
34
+ MeshTxBuilder: () => MeshTxBuilder,
35
+ Transaction: () => Transaction,
36
+ utxoToTxIn: () => utxoToTxIn
37
+ });
38
+ module.exports = __toCommonJS(src_exports);
39
+
40
+ // src/mesh-tx-builder/index.ts
41
+ var import_core_csl = require("@meshsdk/core-csl");
42
+
43
+ // src/mesh-tx-builder/tx-builder-core.ts
44
+ var import_json_bigint = __toESM(require("json-bigint"), 1);
45
+ var import_common = require("@meshsdk/common");
46
+ var MeshTxBuilderCore = class {
47
+ txEvaluationMultiplier = 1.1;
48
+ txOutput;
49
+ addingPlutusScriptInput = false;
50
+ plutusSpendingScriptVersion;
51
+ addingPlutusMint = false;
52
+ plutusMintingScriptVersion;
53
+ addingPlutusWithdrawal = false;
54
+ plutusWithdrawalScriptVersion;
55
+ _protocolParams = import_common.DEFAULT_PROTOCOL_PARAMETERS;
56
+ mintItem;
57
+ txInQueueItem;
58
+ withdrawalItem;
59
+ collateralQueueItem;
60
+ refScriptTxInQueueItem;
61
+ meshTxBuilderBody;
62
+ constructor() {
63
+ this.meshTxBuilderBody = (0, import_common.emptyTxBuilderBody)();
64
+ }
65
+ /**
66
+ * Set the input for transaction
67
+ * @param txHash The transaction hash of the input UTxO
68
+ * @param txIndex The transaction index of the input UTxO
69
+ * @param amount The asset amount of index of the input UTxO
70
+ * @param address The address of the input UTxO
71
+ * @returns The MeshTxBuilder instance
72
+ */
73
+ txIn = (txHash, txIndex, amount, address) => {
74
+ if (this.txInQueueItem) {
75
+ this.queueInput();
76
+ }
77
+ if (!this.addingPlutusScriptInput) {
78
+ this.txInQueueItem = {
79
+ type: "PubKey",
80
+ txIn: {
81
+ txHash,
82
+ txIndex,
83
+ amount,
84
+ address
85
+ }
86
+ };
87
+ } else {
88
+ this.txInQueueItem = {
89
+ type: "Script",
90
+ txIn: {
91
+ txHash,
92
+ txIndex,
93
+ amount,
94
+ address
95
+ },
96
+ scriptTxIn: {}
97
+ };
98
+ }
99
+ this.addingPlutusScriptInput = false;
100
+ return this;
101
+ };
102
+ /**
103
+ * Set the script for transaction input
104
+ * @param {string} scriptCbor The CborHex of the script
105
+ * @param version Optional - The Plutus script version
106
+ * @returns The MeshTxBuilder instance
107
+ */
108
+ txInScript = (scriptCbor) => {
109
+ if (!this.txInQueueItem) throw Error("Undefined input");
110
+ if (this.txInQueueItem.type === "PubKey") {
111
+ this.txInQueueItem = {
112
+ type: "SimpleScript",
113
+ txIn: this.txInQueueItem.txIn,
114
+ simpleScriptTxIn: {
115
+ scriptSource: {
116
+ type: "Provided",
117
+ script: scriptCbor
118
+ }
119
+ }
120
+ };
121
+ }
122
+ if (this.txInQueueItem.type === "Script") {
123
+ this.txInQueueItem.scriptTxIn.scriptSource = {
124
+ type: "Provided",
125
+ script: {
126
+ code: scriptCbor,
127
+ version: this.plutusSpendingScriptVersion || "V2"
128
+ }
129
+ };
130
+ }
131
+ return this;
132
+ };
133
+ /**
134
+ * Set the input datum for transaction input
135
+ * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
136
+ * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
137
+ * @returns The MeshTxBuilder instance
138
+ */
139
+ txInDatumValue = (datum, type = "Mesh") => {
140
+ if (!this.txInQueueItem) throw Error("Undefined input");
141
+ if (this.txInQueueItem.type === "PubKey")
142
+ throw Error("Datum value attempted to be called a non script input");
143
+ if (this.txInQueueItem.type === "SimpleScript")
144
+ throw Error(
145
+ "Datum value attempted to be called on a simple script input"
146
+ );
147
+ let content = datum;
148
+ if (type === "JSON") {
149
+ content = this.castRawDataToJsonString(datum);
150
+ }
151
+ if (type === "Mesh") {
152
+ this.txInQueueItem.scriptTxIn.datumSource = {
153
+ type: "Provided",
154
+ data: {
155
+ type,
156
+ content: datum
157
+ }
158
+ };
159
+ return this;
160
+ }
161
+ this.txInQueueItem.scriptTxIn.datumSource = {
162
+ type: "Provided",
163
+ data: {
164
+ type,
165
+ content
166
+ }
167
+ };
168
+ return this;
169
+ };
170
+ /**
171
+ * Tell the transaction builder that the input UTxO has inlined datum
172
+ * @returns The MeshTxBuilder instance
173
+ */
174
+ txInInlineDatumPresent = () => {
175
+ if (!this.txInQueueItem) throw Error("Undefined input");
176
+ if (this.txInQueueItem.type === "PubKey")
177
+ throw Error(
178
+ "Inline datum present attempted to be called a non script input"
179
+ );
180
+ if (this.txInQueueItem.type === "SimpleScript")
181
+ throw Error(
182
+ "Inline datum present attempted to be called on a simple script input"
183
+ );
184
+ const { txHash, txIndex } = this.txInQueueItem.txIn;
185
+ if (txHash && txIndex.toString()) {
186
+ this.txInQueueItem.scriptTxIn.datumSource = {
187
+ type: "Inline",
188
+ txHash,
189
+ txIndex
190
+ };
191
+ }
192
+ return this;
193
+ };
194
+ // /**
195
+ // * Native script - Set the reference input where it would also be spent in the transaction
196
+ // * @param txHash The transaction hash of the reference UTxO
197
+ // * @param txIndex The transaction index of the reference UTxO
198
+ // * @param spendingScriptHash The script hash of the spending script
199
+ // * @returns The MeshTxBuilder instance
200
+ // */
201
+ // simpleScriptTxInReference = (
202
+ // txHash: string,
203
+ // txIndex: number,
204
+ // spendingScriptHash?: string
205
+ // ) => {
206
+ // if (!this.txInQueueItem) throw Error('Undefined input');
207
+ // if (this.txInQueueItem.type === 'PubKey')
208
+ // throw Error(
209
+ // 'Spending tx in reference attempted to be called a non script input'
210
+ // );
211
+ // this.txInQueueItem.scriptTxIn.scriptSource = {
212
+ // type: 'Inline',
213
+ // txInInfo: {
214
+ // txHash,
215
+ // txIndex,
216
+ // spendingScriptHash,
217
+ // },
218
+ // };
219
+ // return this;
220
+ // };
221
+ /**
222
+ * Set the redeemer for the reference input to be spent in same transaction
223
+ * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
224
+ * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
225
+ * @param exUnits The execution units budget for the redeemer
226
+ * @returns The MeshTxBuilder instance
227
+ */
228
+ txInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
229
+ if (!this.txInQueueItem) throw Error("Undefined input");
230
+ if (this.txInQueueItem.type === "PubKey")
231
+ throw Error(
232
+ "Spending tx in reference redeemer attempted to be called a non script input"
233
+ );
234
+ if (this.txInQueueItem.type === "SimpleScript")
235
+ throw Error(
236
+ "Spending tx in reference redeemer attempted to be called on a simple script input"
237
+ );
238
+ this.txInQueueItem.scriptTxIn.redeemer = this.castBuilderDataToRedeemer(
239
+ redeemer,
240
+ type,
241
+ exUnits
242
+ );
243
+ return this;
244
+ };
245
+ /**
246
+ * Set the output for transaction
247
+ * @param {string} address The recipient of the output
248
+ * @param {Asset[]} amount The amount of other native assets attached with UTxO
249
+ * @returns The MeshTxBuilder instance
250
+ */
251
+ txOut = (address, amount) => {
252
+ if (this.txOutput) {
253
+ this.meshTxBuilderBody.outputs.push(this.txOutput);
254
+ this.txOutput = void 0;
255
+ }
256
+ this.txOutput = {
257
+ address,
258
+ amount
259
+ };
260
+ return this;
261
+ };
262
+ /**
263
+ * Set the output datum hash for transaction
264
+ * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
265
+ * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
266
+ * @returns The MeshTxBuilder instance
267
+ */
268
+ txOutDatumHashValue = (datum, type = "Mesh") => {
269
+ let content = datum;
270
+ if (this.txOutput) {
271
+ if (type === "Mesh") {
272
+ this.txOutput.datum = {
273
+ type: "Hash",
274
+ data: {
275
+ type,
276
+ content
277
+ }
278
+ };
279
+ return this;
280
+ }
281
+ if (type === "JSON") {
282
+ content = this.castRawDataToJsonString(datum);
283
+ }
284
+ this.txOutput.datum = {
285
+ type: "Hash",
286
+ data: {
287
+ type,
288
+ content
289
+ }
290
+ };
291
+ }
292
+ return this;
293
+ };
294
+ /**
295
+ * Set the output inline datum for transaction
296
+ * @param datum The datum in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
297
+ * @param type The datum type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
298
+ * @returns The MeshTxBuilder instance
299
+ */
300
+ txOutInlineDatumValue = (datum, type = "Mesh") => {
301
+ let content = datum;
302
+ if (this.txOutput) {
303
+ if (type === "Mesh") {
304
+ this.txOutput.datum = {
305
+ type: "Inline",
306
+ data: {
307
+ type,
308
+ content
309
+ }
310
+ };
311
+ return this;
312
+ }
313
+ if (type === "JSON") {
314
+ content = this.castRawDataToJsonString(datum);
315
+ }
316
+ this.txOutput.datum = {
317
+ type: "Inline",
318
+ data: {
319
+ type,
320
+ content
321
+ }
322
+ };
323
+ }
324
+ return this;
325
+ };
326
+ /**
327
+ * Set the reference script to be attached with the output
328
+ * @param scriptCbor The CBOR hex of the script to be attached to UTxO as reference script
329
+ * @param version Optional - The Plutus script version
330
+ * @returns The MeshTxBuilder instance
331
+ */
332
+ txOutReferenceScript = (scriptCbor, version = "V2") => {
333
+ if (this.txOutput) {
334
+ this.txOutput.referenceScript = { code: scriptCbor, version };
335
+ }
336
+ return this;
337
+ };
338
+ /**
339
+ * Set the instruction that it is currently using V1 Plutus spending scripts
340
+ * @returns The MeshTxBuilder instance
341
+ */
342
+ spendingPlutusScriptV1 = () => {
343
+ this.addingPlutusScriptInput = true;
344
+ this.plutusSpendingScriptVersion = "V1";
345
+ return this;
346
+ };
347
+ /**
348
+ * Set the instruction that it is currently using V2 Plutus spending scripts
349
+ * @returns The MeshTxBuilder instance
350
+ */
351
+ spendingPlutusScriptV2 = () => {
352
+ this.addingPlutusScriptInput = true;
353
+ this.plutusSpendingScriptVersion = "V2";
354
+ return this;
355
+ };
356
+ /**
357
+ * Set the instruction that it is currently using V3 Plutus spending scripts
358
+ * @returns The MeshTxBuilder instance
359
+ */
360
+ spendingPlutusScriptV3 = () => {
361
+ this.addingPlutusScriptInput = true;
362
+ this.plutusSpendingScriptVersion = "V3";
363
+ return this;
364
+ };
365
+ /**
366
+ * Set the reference input where it would also be spent in the transaction
367
+ * @param txHash The transaction hash of the reference UTxO
368
+ * @param txIndex The transaction index of the reference UTxO
369
+ * @param spendingScriptHash The script hash of the spending script
370
+ * @returns The MeshTxBuilder instance
371
+ */
372
+ spendingTxInReference = (txHash, txIndex, spendingScriptHash) => {
373
+ if (!this.txInQueueItem) throw Error("Undefined input");
374
+ if (this.txInQueueItem.type === "PubKey")
375
+ throw Error(
376
+ "Spending tx in reference attempted to be called a non script input"
377
+ );
378
+ if (this.txInQueueItem.type === "SimpleScript")
379
+ throw Error(
380
+ "Spending tx in reference attempted to be called on a simple script input"
381
+ );
382
+ this.txInQueueItem.scriptTxIn.scriptSource = {
383
+ type: "Inline",
384
+ txHash,
385
+ txIndex,
386
+ scriptHash: spendingScriptHash,
387
+ version: this.plutusSpendingScriptVersion || "V2",
388
+ scriptSize: "0"
389
+ // TODO
390
+ };
391
+ return this;
392
+ };
393
+ /**
394
+ * [Alias of txInInlineDatumPresent] Set the instruction that the reference input has inline datum
395
+ * @returns The MeshTxBuilder instance
396
+ */
397
+ // Unsure how this is different from the --tx-in-inline-datum-present flag
398
+ // It seems to just be different based on if the script is a reference input
399
+ spendingReferenceTxInInlineDatumPresent = () => {
400
+ this.txInInlineDatumPresent();
401
+ return this;
402
+ };
403
+ /**
404
+ * [Alias of txInRedeemerValue] Set the redeemer for the reference input to be spent in same transaction
405
+ * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
406
+ * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
407
+ * @param exUnits The execution units budget for the redeemer
408
+ * @returns The MeshTxBuilder instance
409
+ */
410
+ spendingReferenceTxInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
411
+ this.txInRedeemerValue(redeemer, type, exUnits);
412
+ return this;
413
+ };
414
+ /**
415
+ * Specify a read only reference input. This reference input is not witnessing anything it is simply provided in the plutus script context.
416
+ * @param txHash The transaction hash of the reference UTxO
417
+ * @param txIndex The transaction index of the reference UTxO
418
+ * @returns The MeshTxBuilder instance
419
+ */
420
+ readOnlyTxInReference = (txHash, txIndex) => {
421
+ this.meshTxBuilderBody.referenceInputs.push({ txHash, txIndex });
422
+ return this;
423
+ };
424
+ /**
425
+ * Set the instruction that it is currently using V1 Plutus minting scripts
426
+ * @returns The MeshTxBuilder instance
427
+ */
428
+ mintPlutusScriptV1 = () => {
429
+ this.addingPlutusMint = true;
430
+ this.plutusMintingScriptVersion = "V1";
431
+ return this;
432
+ };
433
+ /**
434
+ * Set the instruction that it is currently using V2 Plutus minting scripts
435
+ * @returns The MeshTxBuilder instance
436
+ */
437
+ mintPlutusScriptV2 = () => {
438
+ this.addingPlutusMint = true;
439
+ this.plutusMintingScriptVersion = "V2";
440
+ return this;
441
+ };
442
+ /**
443
+ * Set the instruction that it is currently using V3 Plutus minting scripts
444
+ * @returns The MeshTxBuilder instance
445
+ */
446
+ mintPlutusScriptV3 = () => {
447
+ this.addingPlutusMint = true;
448
+ this.plutusMintingScriptVersion = "V3";
449
+ return this;
450
+ };
451
+ /**
452
+ * Set the minting value of transaction
453
+ * @param quantity The quantity of asset to be minted
454
+ * @param policy The policy id of the asset to be minted
455
+ * @param name The hex of token name of the asset to be minted
456
+ * @returns The MeshTxBuilder instance
457
+ */
458
+ mint = (quantity, policy, name) => {
459
+ if (this.mintItem) {
460
+ this.queueMint();
461
+ }
462
+ this.mintItem = {
463
+ type: this.addingPlutusMint ? "Plutus" : "Native",
464
+ policyId: policy,
465
+ assetName: name,
466
+ amount: quantity
467
+ };
468
+ this.addingPlutusMint = false;
469
+ return this;
470
+ };
471
+ /**
472
+ * Set the minting script of current mint
473
+ * @param scriptCBOR The CBOR hex of the minting policy script
474
+ * @param version Optional - The Plutus script version
475
+ * @returns The MeshTxBuilder instance
476
+ */
477
+ mintingScript = (scriptCBOR) => {
478
+ if (!this.mintItem) throw Error("Undefined mint");
479
+ if (!this.mintItem.type) throw Error("Mint information missing");
480
+ if (this.mintItem.type === "Native") {
481
+ this.mintItem.scriptSource = {
482
+ type: "Provided",
483
+ scriptCode: scriptCBOR
484
+ };
485
+ }
486
+ if (this.mintItem.type === "Plutus") {
487
+ this.mintItem.scriptSource = {
488
+ type: "Provided",
489
+ script: {
490
+ code: scriptCBOR,
491
+ version: this.plutusMintingScriptVersion || "V2"
492
+ }
493
+ };
494
+ }
495
+ return this;
496
+ };
497
+ /**
498
+ * Use reference script for minting
499
+ * @param txHash The transaction hash of the UTxO
500
+ * @param txIndex The transaction index of the UTxO
501
+ * @returns The MeshTxBuilder instance
502
+ */
503
+ mintTxInReference = (txHash, txIndex) => {
504
+ if (!this.mintItem) throw Error("Undefined mint");
505
+ if (!this.mintItem.type) throw Error("Mint information missing");
506
+ if (this.mintItem.type == "Native") {
507
+ throw Error(
508
+ "Mint tx in reference can only be used on plutus script tokens"
509
+ );
510
+ }
511
+ if (!this.mintItem.policyId)
512
+ throw Error("PolicyId information missing from mint asset");
513
+ this.mintItem.scriptSource = {
514
+ type: "Inline",
515
+ txHash,
516
+ txIndex,
517
+ version: this.plutusMintingScriptVersion,
518
+ scriptSize: "0",
519
+ // TODO
520
+ scriptHash: ""
521
+ // TODO
522
+ };
523
+ return this;
524
+ };
525
+ /**
526
+ * Set the redeemer for minting
527
+ * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
528
+ * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
529
+ * @param exUnits The execution units budget for the redeemer
530
+ * @returns The MeshTxBuilder instance
531
+ */
532
+ mintReferenceTxInRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
533
+ if (!this.mintItem) throw Error("Undefined mint");
534
+ if (this.mintItem.type == "Native") {
535
+ throw Error(
536
+ "Mint tx in reference can only be used on plutus script tokens"
537
+ );
538
+ } else if (this.mintItem.type == "Plutus") {
539
+ if (!this.mintItem.policyId)
540
+ throw Error("PolicyId information missing from mint asset");
541
+ }
542
+ this.mintItem.redeemer = this.castBuilderDataToRedeemer(
543
+ redeemer,
544
+ type,
545
+ exUnits
546
+ );
547
+ return this;
548
+ };
549
+ /**
550
+ * Set the redeemer for the reference input to be spent in same transaction
551
+ * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
552
+ * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
553
+ * @param exUnits The execution units budget for the redeemer
554
+ * @returns The MeshTxBuilder instance
555
+ */
556
+ mintRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
557
+ this.mintReferenceTxInRedeemerValue(redeemer, type, exUnits);
558
+ return this;
559
+ };
560
+ /**
561
+ * Set the required signer of the transaction
562
+ * @param pubKeyHash The PubKeyHash of the required signer
563
+ * @returns The MeshTxBuilder instance
564
+ */
565
+ requiredSignerHash = (pubKeyHash) => {
566
+ this.meshTxBuilderBody.requiredSignatures.push(pubKeyHash);
567
+ return this;
568
+ };
569
+ /**
570
+ * Set the collateral UTxO for the transaction
571
+ * @param txHash The transaction hash of the collateral UTxO
572
+ * @param txIndex The transaction index of the collateral UTxO
573
+ * @param amount The asset amount of index of the collateral UTxO
574
+ * @param address The address of the collateral UTxO
575
+ * @returns The MeshTxBuilder instance
576
+ */
577
+ txInCollateral = (txHash, txIndex, amount, address) => {
578
+ if (this.collateralQueueItem) {
579
+ this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem);
580
+ }
581
+ this.collateralQueueItem = {
582
+ type: "PubKey",
583
+ txIn: {
584
+ txHash,
585
+ txIndex,
586
+ amount,
587
+ address
588
+ }
589
+ };
590
+ return this;
591
+ };
592
+ /**
593
+ * Set the instruction that it is currently using V1 Plutus withdrawal scripts
594
+ * @returns The MeshTxBuilder instance
595
+ */
596
+ withdrawalPlutusScriptV1 = () => {
597
+ this.addingPlutusWithdrawal = true;
598
+ this.plutusWithdrawalScriptVersion = "V1";
599
+ return this;
600
+ };
601
+ /**
602
+ * Set the instruction that it is currently using V2 Plutus withdrawal scripts
603
+ * @returns The MeshTxBuilder instance
604
+ */
605
+ withdrawalPlutusScriptV2 = () => {
606
+ this.addingPlutusWithdrawal = true;
607
+ this.plutusWithdrawalScriptVersion = "V2";
608
+ return this;
609
+ };
610
+ /**
611
+ * Set the instruction that it is currently using V3 Plutus withdrawal scripts
612
+ * @returns The MeshTxBuilder instance
613
+ */
614
+ withdrawalPlutusScriptV3 = () => {
615
+ this.addingPlutusWithdrawal = true;
616
+ this.plutusWithdrawalScriptVersion = "V3";
617
+ return this;
618
+ };
619
+ /**
620
+ * Withdraw stake rewards in the MeshTxBuilder instance
621
+ * @param rewardAddress The bech32 reward address (i.e. start with `stake_xxxxx`)
622
+ * @param coin The amount of lovelaces in the withdrawal
623
+ * @returns The MeshTxBuilder instance
624
+ */
625
+ withdrawal = (rewardAddress, coin) => {
626
+ if (this.withdrawalItem) {
627
+ this.queueWithdrawal();
628
+ }
629
+ if (this.addingPlutusWithdrawal) {
630
+ const withdrawal2 = {
631
+ type: "ScriptWithdrawal",
632
+ address: rewardAddress,
633
+ coin
634
+ };
635
+ this.withdrawalItem = withdrawal2;
636
+ return this;
637
+ }
638
+ const withdrawal = {
639
+ type: "PubKeyWithdrawal",
640
+ address: rewardAddress,
641
+ coin
642
+ };
643
+ this.withdrawalItem = withdrawal;
644
+ return this;
645
+ };
646
+ /**
647
+ * Add a withdrawal script to the MeshTxBuilder instance
648
+ * @param scriptCbor The script in CBOR format
649
+ * @returns The MeshTxBuilder instance
650
+ */
651
+ withdrawalScript = (scriptCbor) => {
652
+ if (!this.withdrawalItem)
653
+ throw Error("withdrawalScript: Undefined withdrawal");
654
+ if (this.withdrawalItem.type === "PubKeyWithdrawal") {
655
+ this.withdrawalItem = {
656
+ type: "SimpleScriptWithdrawal",
657
+ address: this.withdrawalItem.address,
658
+ coin: this.withdrawalItem.coin,
659
+ scriptSource: {
660
+ type: "Provided",
661
+ scriptCode: scriptCbor
662
+ }
663
+ };
664
+ } else {
665
+ this.withdrawalItem.scriptSource = {
666
+ type: "Provided",
667
+ script: {
668
+ code: scriptCbor,
669
+ version: this.plutusWithdrawalScriptVersion || "V2"
670
+ }
671
+ };
672
+ }
673
+ return this;
674
+ };
675
+ /**
676
+ * Add a withdrawal reference to the MeshTxBuilder instance
677
+ * @param txHash The transaction hash of reference UTxO
678
+ * @param txIndex The transaction index of reference UTxO
679
+ * @param withdrawalScriptHash The script hash of the withdrawal script
680
+ * @param scriptSize The script size of the withdrawal script
681
+ * @returns The MeshTxBuilder instance
682
+ */
683
+ withdrawalTxInReference = (txHash, txIndex, withdrawalScriptHash, scriptSize) => {
684
+ if (!this.withdrawalItem)
685
+ throw Error("withdrawalTxInReference: Undefined withdrawal");
686
+ if (this.withdrawalItem.type === "PubKeyWithdrawal")
687
+ throw Error(
688
+ "withdrawalTxInReference: Adding script reference to pub key withdrawal"
689
+ );
690
+ this.withdrawalItem.scriptSource = {
691
+ type: "Inline",
692
+ txHash,
693
+ txIndex,
694
+ scriptHash: withdrawalScriptHash,
695
+ version: this.plutusWithdrawalScriptVersion || "V2",
696
+ scriptSize: scriptSize || "0"
697
+ };
698
+ return this;
699
+ };
700
+ /**
701
+ * Set the transaction withdrawal redeemer value in the MeshTxBuilder instance
702
+ * @param redeemer The redeemer in Mesh Data type, JSON in raw constructor like format, or CBOR hex string
703
+ * @param type The redeemer data type, either Mesh Data type, JSON in raw constructor like format, or CBOR hex string
704
+ * @param exUnits The execution units budget for the redeemer
705
+ * @returns The MeshTxBuilder instance
706
+ */
707
+ withdrawalRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
708
+ if (!this.withdrawalItem)
709
+ throw Error("withdrawalRedeemerValue: Undefined withdrawal");
710
+ if (!(this.withdrawalItem.type === "ScriptWithdrawal"))
711
+ throw Error(
712
+ "withdrawalRedeemerValue: Adding redeemer to non plutus withdrawal"
713
+ );
714
+ this.withdrawalItem.redeemer = this.castBuilderDataToRedeemer(
715
+ redeemer,
716
+ type,
717
+ exUnits
718
+ );
719
+ return this;
720
+ };
721
+ /**
722
+ * Creates a pool registration certificate, and adds it to the transaction
723
+ * @param poolParams Parameters for pool registration
724
+ * @returns The MeshTxBuilder instance
725
+ */
726
+ registerPoolCertificate = (poolParams) => {
727
+ this.meshTxBuilderBody.certificates.push({
728
+ type: "BasicCertificate",
729
+ certType: {
730
+ type: "RegisterPool",
731
+ poolParams
732
+ }
733
+ });
734
+ return this;
735
+ };
736
+ /**
737
+ * Creates a stake registration certificate, and adds it to the transaction
738
+ * @param rewardAddress The bech32 reward address (i.e. start with `stake_xxxxx`)
739
+ * @returns The MeshTxBuilder instance
740
+ */
741
+ registerStakeCertificate = (rewardAddress) => {
742
+ this.meshTxBuilderBody.certificates.push({
743
+ type: "BasicCertificate",
744
+ certType: {
745
+ type: "RegisterStake",
746
+ stakeKeyAddress: rewardAddress
747
+ }
748
+ });
749
+ return this;
750
+ };
751
+ /**
752
+ * Creates a stake delegation certificate, and adds it to the transaction
753
+ * This will delegate stake from the corresponding stake address to the pool
754
+ * @param rewardAddress The bech32 reward address (i.e. start with `stake_xxxxx`)
755
+ * @param poolId poolId can be in either bech32 or hex form
756
+ * @returns The MeshTxBuilder instance
757
+ */
758
+ delegateStakeCertificate = (rewardAddress, poolId) => {
759
+ this.meshTxBuilderBody.certificates.push({
760
+ type: "BasicCertificate",
761
+ certType: {
762
+ type: "DelegateStake",
763
+ stakeKeyAddress: rewardAddress,
764
+ poolId
765
+ }
766
+ });
767
+ return this;
768
+ };
769
+ /**
770
+ * Creates a stake deregister certificate, and adds it to the transaction
771
+ * @param rewardAddress The bech32 reward address (i.e. start with `stake_xxxxx`)
772
+ * @returns The MeshTxBuilder instance
773
+ */
774
+ deregisterStakeCertificate = (rewardAddress) => {
775
+ this.meshTxBuilderBody.certificates.push({
776
+ type: "BasicCertificate",
777
+ certType: {
778
+ type: "DeregisterStake",
779
+ stakeKeyAddress: rewardAddress
780
+ }
781
+ });
782
+ return this;
783
+ };
784
+ /**
785
+ * Creates a pool retire certificate, and adds it to the transaction
786
+ * @param poolId poolId can be in either bech32 or hex form
787
+ * @param epoch The intended epoch to retire the pool
788
+ * @returns The MeshTxBuilder instance
789
+ */
790
+ retirePoolCertificate = (poolId, epoch) => {
791
+ this.meshTxBuilderBody.certificates.push({
792
+ type: "BasicCertificate",
793
+ certType: {
794
+ type: "RetirePool",
795
+ poolId,
796
+ epoch
797
+ }
798
+ });
799
+ return this;
800
+ };
801
+ /**
802
+ * Adds a script witness to the certificate
803
+ * @param scriptCbor The CborHex of the script
804
+ * @param version Optional - The plutus version of the script, null version implies Native Script
805
+ */
806
+ certificateScript = (scriptCbor, version) => {
807
+ const currentCert = this.meshTxBuilderBody.certificates.pop();
808
+ if (!currentCert) {
809
+ throw Error(
810
+ "Certificate script attempted to be defined, but no certificate was found"
811
+ );
812
+ }
813
+ if (!version) {
814
+ this.meshTxBuilderBody.certificates.push({
815
+ type: "SimpleScriptCertificate",
816
+ certType: currentCert.certType,
817
+ simpleScriptSource: {
818
+ type: "Provided",
819
+ scriptCode: scriptCbor
820
+ }
821
+ });
822
+ } else {
823
+ this.meshTxBuilderBody.certificates.push({
824
+ type: "ScriptCertificate",
825
+ certType: currentCert.certType,
826
+ scriptSource: {
827
+ type: "Provided",
828
+ script: {
829
+ code: scriptCbor,
830
+ version
831
+ }
832
+ },
833
+ redeemer: currentCert.type === "ScriptCertificate" ? currentCert.redeemer : void 0
834
+ });
835
+ }
836
+ return this;
837
+ };
838
+ /**
839
+ * Adds a script witness to the certificate
840
+ * @param txHash The transaction hash of the reference UTxO
841
+ * @param txIndex The transaction index of the reference UTxO
842
+ * @param spendingScriptHash The script hash of the spending script
843
+ * @param version Optional - The plutus version of the script, null version implies Native Script
844
+ * @param scriptSize The size of the plutus script referenced
845
+ */
846
+ certificateTxInReference = (txHash, txIndex, spendingScriptHash, version, scriptSize = "0") => {
847
+ const currentCert = this.meshTxBuilderBody.certificates.pop();
848
+ if (!currentCert) {
849
+ throw Error(
850
+ "Certificate script reference attempted to be defined, but no certificate was found"
851
+ );
852
+ }
853
+ if (!version) {
854
+ this.meshTxBuilderBody.certificates.push({
855
+ type: "SimpleScriptCertificate",
856
+ certType: currentCert.certType,
857
+ simpleScriptSource: {
858
+ type: "Inline",
859
+ txHash,
860
+ txIndex,
861
+ simpleScriptHash: spendingScriptHash
862
+ }
863
+ });
864
+ } else {
865
+ this.meshTxBuilderBody.certificates.push({
866
+ type: "ScriptCertificate",
867
+ certType: currentCert.certType,
868
+ scriptSource: {
869
+ type: "Inline",
870
+ txHash,
871
+ txIndex,
872
+ scriptHash: spendingScriptHash,
873
+ scriptSize
874
+ },
875
+ redeemer: currentCert.type === "ScriptCertificate" ? currentCert.redeemer : void 0
876
+ });
877
+ }
878
+ return this;
879
+ };
880
+ certificateRedeemerValue = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
881
+ const currentCert = this.meshTxBuilderBody.certificates.pop();
882
+ if (!currentCert) {
883
+ throw Error(
884
+ "Certificate redeemer value attempted to be defined, but no certificate was found"
885
+ );
886
+ }
887
+ if (currentCert.type === "ScriptCertificate") {
888
+ currentCert.redeemer = this.castBuilderDataToRedeemer(
889
+ redeemer,
890
+ type,
891
+ exUnits
892
+ );
893
+ } else {
894
+ throw Error(
895
+ "Redeemer value attempted to be defined, but certificate has no script defined, or no script version was defined"
896
+ );
897
+ }
898
+ this.meshTxBuilderBody.certificates.push(currentCert);
899
+ return this;
900
+ };
901
+ /**
902
+ * Configure the address to accept change UTxO
903
+ * @param addr The address to accept change UTxO
904
+ * @returns The MeshTxBuilder instance
905
+ */
906
+ changeAddress = (addr) => {
907
+ this.meshTxBuilderBody.changeAddress = addr;
908
+ return this;
909
+ };
910
+ /**
911
+ * Set the transaction valid interval to be valid only after the slot
912
+ * @param slot The transaction is valid only after this slot
913
+ * @returns The MeshTxBuilder instance
914
+ */
915
+ invalidBefore = (slot) => {
916
+ this.meshTxBuilderBody.validityRange.invalidBefore = slot;
917
+ return this;
918
+ };
919
+ /**
920
+ * Set the transaction valid interval to be valid only before the slot
921
+ * @param slot The transaction is valid only before this slot
922
+ * @returns The MeshTxBuilder instance
923
+ */
924
+ invalidHereafter = (slot) => {
925
+ this.meshTxBuilderBody.validityRange.invalidHereafter = slot;
926
+ return this;
927
+ };
928
+ /**
929
+ * Add metadata to the transaction
930
+ * @param tag The tag of the metadata
931
+ * @param metadata The metadata in any format
932
+ * @returns The MeshTxBuilder instance
933
+ */
934
+ metadataValue = (tag, metadata) => {
935
+ const metadataString = import_json_bigint.default.stringify(metadata);
936
+ this.meshTxBuilderBody.metadata.push({ tag, metadata: metadataString });
937
+ return this;
938
+ };
939
+ /**
940
+ * Sign the transaction with the private key
941
+ * @param skeyHex The private key in cborHex (with or without 5820 prefix, i.e. the format when generated from cardano-cli)
942
+ * @returns
943
+ */
944
+ signingKey = (skeyHex) => {
945
+ this.meshTxBuilderBody.signingKey.push(skeyHex);
946
+ return this;
947
+ };
948
+ /**
949
+ * Selects utxos to fill output value and puts them into inputs
950
+ * @param extraInputs The inputs already placed into the object will remain, these extra inputs will be used to fill the remaining value needed
951
+ * @param strategy The strategy to be used in utxo selection
952
+ * @param threshold Extra value needed to be selected for, usually for paying fees and min UTxO value of change output
953
+ */
954
+ selectUtxosFrom = (extraInputs, strategy = "experimental", threshold = "5000000", includeTxFees = true) => {
955
+ this.meshTxBuilderBody.extraInputs = extraInputs;
956
+ const newConfig = {
957
+ threshold,
958
+ strategy,
959
+ includeTxFees
960
+ };
961
+ this.meshTxBuilderBody.selectionConfig = {
962
+ ...this.meshTxBuilderBody.selectionConfig,
963
+ ...newConfig
964
+ };
965
+ return this;
966
+ };
967
+ /**
968
+ * Set the protocol parameters to be used for the transaction other than the default one
969
+ * @param params (Part of) the protocol parameters to be used for the transaction
970
+ * @returns The MeshTxBuilder instance
971
+ */
972
+ protocolParams = (params) => {
973
+ const updatedParams = { ...import_common.DEFAULT_PROTOCOL_PARAMETERS, ...params };
974
+ this._protocolParams = updatedParams;
975
+ return this;
976
+ };
977
+ queueAllLastItem = () => {
978
+ if (this.txOutput) {
979
+ this.meshTxBuilderBody.outputs.push(this.txOutput);
980
+ this.txOutput = void 0;
981
+ }
982
+ if (this.txInQueueItem) {
983
+ this.queueInput();
984
+ }
985
+ if (this.collateralQueueItem) {
986
+ this.meshTxBuilderBody.collaterals.push(this.collateralQueueItem);
987
+ this.collateralQueueItem = void 0;
988
+ }
989
+ if (this.mintItem) {
990
+ this.queueMint();
991
+ }
992
+ if (this.withdrawalItem) {
993
+ this.queueWithdrawal();
994
+ }
995
+ };
996
+ queueInput = () => {
997
+ if (!this.txInQueueItem) throw Error("queueInput: Undefined input");
998
+ if (this.txInQueueItem.type === "Script") {
999
+ if (!this.txInQueueItem.scriptTxIn) {
1000
+ throw Error(
1001
+ "queueInput: Script input does not contain script, datum, or redeemer information"
1002
+ );
1003
+ } else {
1004
+ if (!this.txInQueueItem.scriptTxIn.datumSource)
1005
+ throw Error(
1006
+ "queueInput: Script input does not contain datum information"
1007
+ );
1008
+ if (!this.txInQueueItem.scriptTxIn.redeemer)
1009
+ throw Error(
1010
+ "queueInput: Script input does not contain redeemer information"
1011
+ );
1012
+ if (!this.txInQueueItem.scriptTxIn.scriptSource)
1013
+ throw Error(
1014
+ "queueInput: Script input does not contain script information"
1015
+ );
1016
+ }
1017
+ }
1018
+ this.meshTxBuilderBody.inputs.push(this.txInQueueItem);
1019
+ this.txInQueueItem = void 0;
1020
+ };
1021
+ queueMint = () => {
1022
+ if (!this.mintItem) throw Error("queueMint: Undefined mint");
1023
+ if (!this.mintItem.scriptSource)
1024
+ throw Error("queueMint: Missing mint script information");
1025
+ this.meshTxBuilderBody.mints.push(this.mintItem);
1026
+ this.mintItem = void 0;
1027
+ };
1028
+ queueWithdrawal = () => {
1029
+ if (!this.withdrawalItem)
1030
+ throw Error("queueWithdrawal: Undefined withdrawal");
1031
+ if (this.withdrawalItem.type === "ScriptWithdrawal") {
1032
+ if (!this.withdrawalItem.scriptSource) {
1033
+ throw Error("queueWithdrawal: Missing withdrawal script information");
1034
+ }
1035
+ if (!this.withdrawalItem.redeemer) {
1036
+ throw Error("queueWithdrawal: Missing withdrawal redeemer information");
1037
+ }
1038
+ } else if (this.withdrawalItem.type === "SimpleScriptWithdrawal") {
1039
+ if (!this.withdrawalItem.scriptSource) {
1040
+ throw Error("queueWithdrawal: Missing withdrawal script information");
1041
+ }
1042
+ }
1043
+ this.meshTxBuilderBody.withdrawals.push(this.withdrawalItem);
1044
+ this.withdrawalItem = void 0;
1045
+ };
1046
+ castRawDataToJsonString = (rawData) => {
1047
+ if (typeof rawData === "object") {
1048
+ return import_json_bigint.default.stringify(rawData);
1049
+ } else {
1050
+ return rawData;
1051
+ }
1052
+ };
1053
+ castBuilderDataToRedeemer = (redeemer, type = "Mesh", exUnits = { ...import_common.DEFAULT_REDEEMER_BUDGET }) => {
1054
+ let red;
1055
+ let content = redeemer;
1056
+ if (type === "Mesh") {
1057
+ red = {
1058
+ data: {
1059
+ type,
1060
+ content
1061
+ },
1062
+ exUnits
1063
+ };
1064
+ return red;
1065
+ }
1066
+ if (type === "JSON") {
1067
+ content = this.castRawDataToJsonString(redeemer);
1068
+ }
1069
+ red = {
1070
+ data: {
1071
+ type,
1072
+ content
1073
+ },
1074
+ exUnits
1075
+ };
1076
+ return red;
1077
+ };
1078
+ updateRedeemer = (meshTxBuilderBody, txEvaluation) => {
1079
+ txEvaluation.forEach((redeemerEvaluation) => {
1080
+ switch (redeemerEvaluation.tag) {
1081
+ case "SPEND": {
1082
+ const input = meshTxBuilderBody.inputs[redeemerEvaluation.index];
1083
+ if (input.type == "Script" && input.scriptTxIn.redeemer) {
1084
+ input.scriptTxIn.redeemer.exUnits.mem = Math.floor(
1085
+ redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1086
+ );
1087
+ input.scriptTxIn.redeemer.exUnits.steps = Math.floor(
1088
+ redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1089
+ );
1090
+ }
1091
+ break;
1092
+ }
1093
+ case "MINT": {
1094
+ const mint = meshTxBuilderBody.mints[redeemerEvaluation.index];
1095
+ if (mint.type == "Plutus" && mint.redeemer) {
1096
+ mint.redeemer.exUnits.mem = Math.floor(
1097
+ redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1098
+ );
1099
+ mint.redeemer.exUnits.steps = Math.floor(
1100
+ redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1101
+ );
1102
+ }
1103
+ break;
1104
+ }
1105
+ case "CERT":
1106
+ const cert = meshTxBuilderBody.certificates[redeemerEvaluation.index];
1107
+ if (cert.type === "ScriptCertificate" && cert.redeemer) {
1108
+ cert.redeemer.exUnits.mem = Math.floor(
1109
+ redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1110
+ );
1111
+ cert.redeemer.exUnits.steps = Math.floor(
1112
+ redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1113
+ );
1114
+ }
1115
+ break;
1116
+ case "REWARD":
1117
+ const withdrawal = meshTxBuilderBody.withdrawals[redeemerEvaluation.index];
1118
+ if (withdrawal.type === "ScriptWithdrawal" && withdrawal.redeemer) {
1119
+ withdrawal.redeemer.exUnits.mem = Math.floor(
1120
+ redeemerEvaluation.budget.mem * this.txEvaluationMultiplier
1121
+ );
1122
+ withdrawal.redeemer.exUnits.steps = Math.floor(
1123
+ redeemerEvaluation.budget.steps * this.txEvaluationMultiplier
1124
+ );
1125
+ }
1126
+ break;
1127
+ }
1128
+ });
1129
+ };
1130
+ addUtxosFromSelection = () => {
1131
+ const requiredAssets = this.meshTxBuilderBody.outputs.reduce(
1132
+ (map, output) => {
1133
+ const outputAmount = output.amount;
1134
+ outputAmount.forEach((asset) => {
1135
+ const { unit, quantity } = asset;
1136
+ const existingQuantity = Number(map.get(unit)) || 0;
1137
+ map.set(unit, String(existingQuantity + Number(quantity)));
1138
+ });
1139
+ return map;
1140
+ },
1141
+ /* @__PURE__ */ new Map()
1142
+ );
1143
+ this.meshTxBuilderBody.inputs.reduce((map, input) => {
1144
+ const inputAmount = input.txIn.amount;
1145
+ inputAmount?.forEach((asset) => {
1146
+ const { unit, quantity } = asset;
1147
+ const existingQuantity = Number(map.get(unit)) || 0;
1148
+ map.set(unit, String(existingQuantity - Number(quantity)));
1149
+ });
1150
+ return map;
1151
+ }, requiredAssets);
1152
+ this.meshTxBuilderBody.mints.reduce((map, mint) => {
1153
+ const mintAmount = {
1154
+ unit: mint.policyId + mint.assetName,
1155
+ quantity: String(mint.amount)
1156
+ };
1157
+ const existingQuantity = Number(map.get(mintAmount.unit)) || 0;
1158
+ map.set(
1159
+ mintAmount.unit,
1160
+ String(existingQuantity - Number(mintAmount.quantity))
1161
+ );
1162
+ return map;
1163
+ }, requiredAssets);
1164
+ const selectionConfig = this.meshTxBuilderBody.selectionConfig;
1165
+ const utxoSelection = new import_common.UtxoSelection(
1166
+ selectionConfig.threshold,
1167
+ selectionConfig.includeTxFees
1168
+ );
1169
+ let selectedInputs = [];
1170
+ switch (selectionConfig.strategy) {
1171
+ case "keepRelevant":
1172
+ selectedInputs = utxoSelection.keepRelevant(
1173
+ requiredAssets,
1174
+ this.meshTxBuilderBody.extraInputs
1175
+ );
1176
+ case "largestFirst":
1177
+ selectedInputs = utxoSelection.largestFirst(
1178
+ requiredAssets,
1179
+ this.meshTxBuilderBody.extraInputs
1180
+ );
1181
+ break;
1182
+ case "largestFirstMultiAsset":
1183
+ selectedInputs = utxoSelection.largestFirstMultiAsset(
1184
+ requiredAssets,
1185
+ this.meshTxBuilderBody.extraInputs
1186
+ );
1187
+ break;
1188
+ default:
1189
+ selectedInputs = utxoSelection.experimental(
1190
+ requiredAssets,
1191
+ this.meshTxBuilderBody.extraInputs
1192
+ );
1193
+ break;
1194
+ }
1195
+ selectedInputs.forEach((input) => {
1196
+ const pubKeyTxIn = {
1197
+ type: "PubKey",
1198
+ txIn: {
1199
+ txHash: input.input.txHash,
1200
+ txIndex: input.input.outputIndex,
1201
+ amount: input.output.amount,
1202
+ address: input.output.address
1203
+ }
1204
+ };
1205
+ this.meshTxBuilderBody.inputs.push(pubKeyTxIn);
1206
+ });
1207
+ };
1208
+ removeDuplicateInputs = () => {
1209
+ const { inputs } = this.meshTxBuilderBody;
1210
+ const getTxInId = (txIn) => `${txIn.txHash}#${txIn.txIndex}`;
1211
+ const currentTxInIds = [];
1212
+ const addedInputs = [];
1213
+ for (let i = 0; i < inputs.length; i += 1) {
1214
+ const currentInput = inputs[i];
1215
+ const currentTxInId = getTxInId(currentInput.txIn);
1216
+ if (currentTxInIds.includes(currentTxInId)) {
1217
+ inputs.splice(i, 1);
1218
+ i -= 1;
1219
+ } else {
1220
+ addedInputs.push(currentInput);
1221
+ }
1222
+ }
1223
+ this.meshTxBuilderBody.inputs = addedInputs;
1224
+ };
1225
+ emptyTxBuilderBody = () => {
1226
+ this.meshTxBuilderBody = (0, import_common.emptyTxBuilderBody)();
1227
+ return import_common.emptyTxBuilderBody;
1228
+ };
1229
+ reset = () => {
1230
+ this.meshTxBuilderBody = (0, import_common.emptyTxBuilderBody)();
1231
+ this.txEvaluationMultiplier = 1.1;
1232
+ this.txOutput = void 0;
1233
+ this.addingPlutusScriptInput = false;
1234
+ this.plutusSpendingScriptVersion = void 0;
1235
+ this.addingPlutusMint = false;
1236
+ this.plutusMintingScriptVersion = void 0;
1237
+ this.addingPlutusWithdrawal = false;
1238
+ this.plutusWithdrawalScriptVersion = void 0;
1239
+ this._protocolParams = import_common.DEFAULT_PROTOCOL_PARAMETERS;
1240
+ this.mintItem = void 0;
1241
+ this.txInQueueItem = void 0;
1242
+ this.withdrawalItem = void 0;
1243
+ this.collateralQueueItem = void 0;
1244
+ this.refScriptTxInQueueItem = void 0;
1245
+ };
1246
+ };
1247
+
1248
+ // src/mesh-tx-builder/utils.ts
1249
+ var utxoToTxIn = (utxo) => {
1250
+ return [
1251
+ utxo.input.txHash,
1252
+ utxo.input.outputIndex,
1253
+ utxo.output.amount,
1254
+ utxo.output.address
1255
+ ];
1256
+ };
1257
+
1258
+ // src/mesh-tx-builder/index.ts
1259
+ var MeshTxBuilder = class extends MeshTxBuilderCore {
1260
+ serializer;
1261
+ fetcher;
1262
+ submitter;
1263
+ evaluator;
1264
+ txHex = "";
1265
+ queriedTxHashes = /* @__PURE__ */ new Set();
1266
+ queriedUTxOs = {};
1267
+ constructor({
1268
+ serializer,
1269
+ fetcher,
1270
+ submitter,
1271
+ evaluator,
1272
+ params,
1273
+ isHydra = false
1274
+ } = {}) {
1275
+ super();
1276
+ if (serializer) {
1277
+ this.serializer = serializer;
1278
+ } else {
1279
+ this.serializer = new import_core_csl.CSLSerializer();
1280
+ }
1281
+ if (fetcher) this.fetcher = fetcher;
1282
+ if (submitter) this.submitter = submitter;
1283
+ if (evaluator) this.evaluator = evaluator;
1284
+ if (params) this.protocolParams(params);
1285
+ if (isHydra)
1286
+ this.protocolParams({
1287
+ minFeeA: 0,
1288
+ minFeeB: 0,
1289
+ priceMem: 0,
1290
+ priceStep: 0,
1291
+ collateralPercent: 0,
1292
+ coinsPerUtxoSize: 0
1293
+ });
1294
+ }
1295
+ /**
1296
+ * It builds the transaction and query the blockchain for missing information
1297
+ * @param customizedTx The optional customized transaction body
1298
+ * @returns The signed transaction in hex ready to submit / signed by client
1299
+ */
1300
+ complete = async (customizedTx) => {
1301
+ if (customizedTx) {
1302
+ this.meshTxBuilderBody = { ...this.meshTxBuilderBody, ...customizedTx };
1303
+ } else {
1304
+ this.queueAllLastItem();
1305
+ }
1306
+ this.removeDuplicateInputs();
1307
+ const { inputs, collaterals } = this.meshTxBuilderBody;
1308
+ const incompleteTxIns = [...inputs, ...collaterals].filter(
1309
+ (txIn) => !this.isInputComplete(txIn)
1310
+ );
1311
+ await this.queryAllTxInfo(incompleteTxIns);
1312
+ incompleteTxIns.forEach((txIn) => {
1313
+ this.completeTxInformation(txIn);
1314
+ });
1315
+ this.addUtxosFromSelection();
1316
+ let txHex = this.serializer.serializeTxBody(
1317
+ this.meshTxBuilderBody,
1318
+ this._protocolParams
1319
+ );
1320
+ if (this.evaluator) {
1321
+ const txEvaluation = await this.evaluator.evaluateTx(txHex).catch((error) => {
1322
+ throw Error(`Tx evaluation failed: ${error}`);
1323
+ });
1324
+ this.updateRedeemer(this.meshTxBuilderBody, txEvaluation);
1325
+ txHex = this.serializer.serializeTxBody(
1326
+ this.meshTxBuilderBody,
1327
+ this._protocolParams
1328
+ );
1329
+ }
1330
+ this.txHex = txHex;
1331
+ return txHex;
1332
+ };
1333
+ /**
1334
+ * It builds the transaction without dependencies
1335
+ * @param customizedTx The optional customized transaction body
1336
+ * @returns The signed transaction in hex ready to submit / signed by client
1337
+ */
1338
+ completeSync = (customizedTx) => {
1339
+ if (customizedTx) {
1340
+ this.meshTxBuilderBody = customizedTx;
1341
+ } else {
1342
+ this.queueAllLastItem();
1343
+ }
1344
+ this.addUtxosFromSelection();
1345
+ return this.serializer.serializeTxBody(
1346
+ this.meshTxBuilderBody,
1347
+ this._protocolParams
1348
+ );
1349
+ };
1350
+ /**
1351
+ * Complete the signing process
1352
+ * @returns The signed transaction in hex
1353
+ */
1354
+ completeSigning = () => {
1355
+ const signedTxHex = this.serializer.addSigningKeys(
1356
+ this.txHex,
1357
+ this.meshTxBuilderBody.signingKey
1358
+ );
1359
+ this.txHex = signedTxHex;
1360
+ return signedTxHex;
1361
+ };
1362
+ /**
1363
+ * Submit transactions to the blockchain using the fetcher instance
1364
+ * @param txHex The signed transaction in hex
1365
+ * @returns
1366
+ */
1367
+ submitTx = async (txHex) => {
1368
+ const txHash = await this.submitter?.submitTx(txHex);
1369
+ return txHash;
1370
+ };
1371
+ /**
1372
+ * Get the UTxO information from the blockchain
1373
+ * @param TxHash The TxIn object that contains the txHash and txIndex, while missing amount and address information
1374
+ */
1375
+ getUTxOInfo = async (txHash) => {
1376
+ let utxos = [];
1377
+ if (!this.queriedTxHashes.has(txHash)) {
1378
+ this.queriedTxHashes.add(txHash);
1379
+ utxos = await this.fetcher?.fetchUTxOs(txHash) || [];
1380
+ this.queriedUTxOs[txHash] = utxos;
1381
+ }
1382
+ };
1383
+ queryAllTxInfo = (incompleteTxIns) => {
1384
+ const queryUTxOPromises = [];
1385
+ if (incompleteTxIns.length > 0 && !this.fetcher)
1386
+ throw Error(
1387
+ "Transaction information is incomplete while no fetcher instance is provided"
1388
+ );
1389
+ for (let i = 0; i < incompleteTxIns.length; i++) {
1390
+ const currentTxIn = incompleteTxIns[i];
1391
+ if (!this.isInputInfoComplete(currentTxIn)) {
1392
+ queryUTxOPromises.push(this.getUTxOInfo(currentTxIn.txIn.txHash));
1393
+ }
1394
+ if (currentTxIn.type === "Script" && currentTxIn.scriptTxIn.scriptSource?.type === "Inline" && !this.isRefScriptInfoComplete(currentTxIn)) {
1395
+ queryUTxOPromises.push(
1396
+ this.getUTxOInfo(currentTxIn.scriptTxIn.scriptSource.txHash)
1397
+ );
1398
+ }
1399
+ }
1400
+ return Promise.all(queryUTxOPromises);
1401
+ };
1402
+ completeTxInformation = (input) => {
1403
+ if (!this.isInputInfoComplete(input)) {
1404
+ const utxos = this.queriedUTxOs[input.txIn.txHash];
1405
+ const utxo = utxos?.find(
1406
+ (utxo2) => utxo2.input.outputIndex === input.txIn.txIndex
1407
+ );
1408
+ const amount = utxo?.output.amount;
1409
+ const address = utxo?.output.address;
1410
+ if (!amount || amount.length === 0)
1411
+ throw Error(
1412
+ `Couldn't find value information for ${input.txIn.txHash}#${input.txIn.txIndex}`
1413
+ );
1414
+ input.txIn.amount = amount;
1415
+ if (input.type === "PubKey") {
1416
+ if (!address || address === "")
1417
+ throw Error(
1418
+ `Couldn't find address information for ${input.txIn.txHash}#${input.txIn.txIndex}`
1419
+ );
1420
+ input.txIn.address = address;
1421
+ }
1422
+ }
1423
+ if (input.type === "Script" && input.scriptTxIn.scriptSource?.type == "Inline" && !this.isRefScriptInfoComplete(input)) {
1424
+ const scriptSource = input.scriptTxIn.scriptSource;
1425
+ const refUtxos = this.queriedUTxOs[scriptSource.txHash];
1426
+ const scriptRefUtxo = refUtxos.find(
1427
+ (utxo) => utxo.input.outputIndex === scriptSource.txIndex
1428
+ );
1429
+ if (!scriptRefUtxo)
1430
+ throw Error(
1431
+ `Couldn't find script reference utxo for ${scriptSource.txHash}#${scriptSource.txIndex}`
1432
+ );
1433
+ scriptSource.scriptHash = scriptRefUtxo?.output.scriptHash;
1434
+ }
1435
+ };
1436
+ isInputComplete = (txIn) => {
1437
+ if (txIn.type === "PubKey") return this.isInputInfoComplete(txIn);
1438
+ if (txIn.type === "Script") {
1439
+ return this.isInputInfoComplete(txIn) && this.isRefScriptInfoComplete(txIn);
1440
+ }
1441
+ return true;
1442
+ };
1443
+ isInputInfoComplete = (txIn) => {
1444
+ const { amount, address } = txIn.txIn;
1445
+ if (txIn.type === "PubKey" && (!amount || !address)) return false;
1446
+ if (txIn.type === "Script") {
1447
+ if (!amount) return false;
1448
+ }
1449
+ return true;
1450
+ };
1451
+ isRefScriptInfoComplete = (scriptTxIn) => {
1452
+ const { scriptSource } = scriptTxIn.scriptTxIn;
1453
+ if (scriptSource?.type === "Inline" && !scriptSource?.scriptHash)
1454
+ return false;
1455
+ return true;
1456
+ };
1457
+ };
1458
+
1459
+ // src/scripts/forge.script.ts
1460
+ var import_core_cst = require("@meshsdk/core-cst");
1461
+ var ForgeScript = class {
1462
+ static withOneSignature(address) {
1463
+ const keyHash = (0, import_core_cst.deserializeEd25519KeyHash)((0, import_core_cst.resolvePaymentKeyHash)(address));
1464
+ return (0, import_core_cst.buildScriptPubkey)(keyHash).toCbor();
1465
+ }
1466
+ // static withAtLeastNSignatures(
1467
+ // addresses: string[], minimumRequired: number,
1468
+ // ): string {
1469
+ // const nativeScripts = csl.NativeScripts.new();
1470
+ // addresses.forEach((address) => {
1471
+ // const keyHash = deserializeEd25519KeyHash(
1472
+ // resolvePaymentKeyHash(address),
1473
+ // );
1474
+ // nativeScripts.add(buildScriptPubkey(keyHash));
1475
+ // });
1476
+ // const scriptNOfK = csl.ScriptNOfK.new(minimumRequired, nativeScripts);
1477
+ // return csl.NativeScript.new_script_any(scriptNOfK).to_hex();
1478
+ // }
1479
+ // static withAnySignature(addresses: string[]): string {
1480
+ // const nativeScripts = csl.NativeScripts.new();
1481
+ // addresses.forEach((address) => {
1482
+ // const keyHash = deserializeEd25519KeyHash(
1483
+ // resolvePaymentKeyHash(address),
1484
+ // );
1485
+ // nativeScripts.add(buildScriptPubkey(keyHash));
1486
+ // });
1487
+ // const scriptAny = csl.ScriptAny.new(nativeScripts);
1488
+ // return csl.NativeScript.new_script_any(scriptAny).to_hex();
1489
+ // }
1490
+ // static withAllSignatures(addresses: string[]): string {
1491
+ // const nativeScripts = csl.NativeScripts.new();
1492
+ // addresses.forEach((address) => {
1493
+ // const keyHash = deserializeEd25519KeyHash(
1494
+ // resolvePaymentKeyHash(address),
1495
+ // );
1496
+ // nativeScripts.add(buildScriptPubkey(keyHash));
1497
+ // });
1498
+ // const scriptAll = csl.ScriptAll.new(nativeScripts);
1499
+ // return csl.NativeScript.new_script_any(scriptAll).to_hex();
1500
+ // }
1501
+ static fromNativeScript(script) {
1502
+ return (0, import_core_cst.toNativeScript)(script).toCbor();
1503
+ }
1504
+ };
1505
+
1506
+ // src/transaction/index.ts
1507
+ var import_common2 = require("@meshsdk/common");
1508
+ var import_core_cst2 = require("@meshsdk/core-cst");
1509
+ var Transaction = class {
1510
+ txBuilder;
1511
+ initiator;
1512
+ isCollateralNeeded = false;
1513
+ constructor(options) {
1514
+ this.txBuilder = new MeshTxBuilder(options);
1515
+ this.initiator = options.initiator;
1516
+ }
1517
+ /**
1518
+ * Adds an output to the transaction.
1519
+ *
1520
+ * @param recipient The recipient of the output.
1521
+ * @param assets The assets to send. Provide string for lovelace and Asset[] for tokens and/or lovelace.
1522
+ * @returns The transaction builder.
1523
+ * @see {@link https://meshjs.dev/apis/transaction#sendAssets}
1524
+ */
1525
+ sendAssets(recipient, assets) {
1526
+ if (typeof assets === "string") {
1527
+ assets = [
1528
+ {
1529
+ unit: "lovelace",
1530
+ quantity: assets
1531
+ }
1532
+ ];
1533
+ }
1534
+ if (typeof recipient === "string") {
1535
+ this.txBuilder.txOut(recipient, assets);
1536
+ }
1537
+ if (typeof recipient === "object") {
1538
+ this.txBuilder.txOut(recipient.address, assets);
1539
+ if (recipient.datum) {
1540
+ if (recipient.datum.inline) {
1541
+ this.txBuilder.txOutInlineDatumValue(recipient.datum.value);
1542
+ } else {
1543
+ this.txBuilder.txOutDatumHashValue(recipient.datum.value);
1544
+ }
1545
+ }
1546
+ }
1547
+ return this;
1548
+ }
1549
+ /**
1550
+ * Suggest deprecated - Adds a transaction output to the transaction.
1551
+ * Use sendAssets instead:
1552
+ * ```ts
1553
+ * this.sendAssets(recipient, lovelace);
1554
+ * ```
1555
+ *
1556
+ * Deprecation reason - Unnecessary implementation which might cause confusion.
1557
+ *
1558
+ * @param {Recipient} recipient The recipient of the transaction.
1559
+ * @param {string} lovelace The amount of lovelace to send.
1560
+ * @returns {Transaction} The Transaction object.
1561
+ * @see {@link https://meshjs.dev/apis/transaction#sendAda}
1562
+ */
1563
+ sendLovelace(recipient, lovelace) {
1564
+ return this.sendAssets(recipient, lovelace);
1565
+ }
1566
+ /**
1567
+ * Suggest deprecated - Adds stable coins transaction output to the transaction.
1568
+ * Please use sendAssets with helper function to obtain token unit instead:
1569
+ * ```ts
1570
+ * const assets = [{ unit: SUPPORTED_TOKENS.GIMBAL, quantity: "100" }]
1571
+ * transaction.sendAssets(recipient, assets)
1572
+ * ```
1573
+ *
1574
+ * Deprecation reason - Required maintenance on tokens.
1575
+ *
1576
+ * @param {Recipient} recipient The recipient of the transaction.
1577
+ * @param {Token} ticker The ticker of the token to send.
1578
+ * @param {string} amount The amount of the token to send.
1579
+ * @returns {Transaction} The Transaction object.
1580
+ * @see {@link https://meshjs.dev/apis/transaction#sendToken}
1581
+ */
1582
+ sendToken(recipient, ticker, amount) {
1583
+ const assets = [{ unit: import_common2.SUPPORTED_TOKENS[ticker], quantity: amount }];
1584
+ return this.sendAssets(recipient, assets);
1585
+ }
1586
+ /**
1587
+ * Adds an output to the transaction.
1588
+ * Suggest deprecated - use sendAssets instead:
1589
+ *
1590
+ * ```ts
1591
+ * const assets = value.output.amount;
1592
+ * this.sendAssets(recipient, assets);
1593
+ * ```
1594
+ * Deprecation reason - Unnecessary implementation which might cause confusion.
1595
+ *
1596
+ * @param {Recipient} recipient The recipient of the output.
1597
+ * @param {UTxO} value The UTxO value of the output.
1598
+ * @returns {Transaction} The Transaction object.
1599
+ */
1600
+ sendValue(recipient, value) {
1601
+ const assets = value.output.amount;
1602
+ return this.sendAssets(recipient, assets);
1603
+ }
1604
+ /**
1605
+ * Sets the inputs for the transaction.
1606
+ *
1607
+ * @param {UTxO[]} inputs The inputs to set.
1608
+ * @returns {Transaction} The transaction.
1609
+ */
1610
+ setTxInputs(inputs) {
1611
+ inputs.forEach((input) => {
1612
+ this.txBuilder.txIn(
1613
+ input.input.txHash,
1614
+ input.input.outputIndex,
1615
+ input.output.amount,
1616
+ input.output.address
1617
+ );
1618
+ });
1619
+ return this;
1620
+ }
1621
+ /**
1622
+ * Sets the reference inputs for the transaction.
1623
+ *
1624
+ * @param {UTxO[]} inputs The reference inputs to set.
1625
+ * @returns {Transaction} The transaction.
1626
+ */
1627
+ setTxRefInputs(inputs) {
1628
+ inputs.forEach((input) => {
1629
+ this.txBuilder.readOnlyTxInReference(
1630
+ input.input.txHash,
1631
+ input.input.outputIndex
1632
+ );
1633
+ });
1634
+ return this;
1635
+ }
1636
+ /**
1637
+ * Sets the native script for the transaction.
1638
+ * @param {NativeScript} script The native script to spend from.
1639
+ * @param {UTxO} utxo The UTxO attached to the script.
1640
+ * @returns {Transaction} The Transaction object.
1641
+ */
1642
+ setNativeScriptInput(script, utxo) {
1643
+ const { scriptCbor } = this.txBuilder.serializer.deserializer.script.deserializeNativeScript(
1644
+ script
1645
+ );
1646
+ this.txBuilder.txIn(
1647
+ utxo.input.txHash,
1648
+ utxo.input.outputIndex,
1649
+ utxo.output.amount,
1650
+ utxo.output.address
1651
+ ).txInScript(scriptCbor);
1652
+ return this;
1653
+ }
1654
+ // TODO: nuke this probably as the input type is too confusing
1655
+ redeemValue(options) {
1656
+ const { value, script, datum, redeemer } = options;
1657
+ const red = redeemer || {
1658
+ data: { alternative: 0, fields: ["mesh"] },
1659
+ budget: import_common2.DEFAULT_REDEEMER_BUDGET
1660
+ };
1661
+ if ("code" in script) {
1662
+ this.isCollateralNeeded = true;
1663
+ this.spendingPlutusScript(script).txIn(
1664
+ value.input.txHash,
1665
+ value.input.outputIndex,
1666
+ value.output.amount,
1667
+ value.output.address
1668
+ ).txInScript(script.code).txInRedeemerValue(red.data, "Mesh", red.budget);
1669
+ }
1670
+ if ("output" in script) {
1671
+ if (!script.output.scriptRef) {
1672
+ throw new Error("redeemValue: No script reference found in UTxO");
1673
+ }
1674
+ const scriptRef = (0, import_core_cst2.fromScriptRef)(script.output.scriptRef);
1675
+ if (!scriptRef || !("code" in scriptRef)) {
1676
+ throw new Error("redeemValue: Script reference not found");
1677
+ }
1678
+ this.isCollateralNeeded = true;
1679
+ this.spendingPlutusScript(scriptRef).txIn(
1680
+ value.input.txHash,
1681
+ value.input.outputIndex,
1682
+ value.output.amount,
1683
+ value.output.address
1684
+ ).spendingTxInReference(
1685
+ script.input.txHash,
1686
+ script.input.outputIndex,
1687
+ script.output.scriptHash
1688
+ ).txInRedeemerValue(red.data, "Mesh", red.budget);
1689
+ }
1690
+ if (datum) {
1691
+ this.txBuilder.txInDatumValue(datum);
1692
+ } else {
1693
+ this.txBuilder.txInInlineDatumPresent();
1694
+ }
1695
+ return this;
1696
+ }
1697
+ // TODO: nuke this probably as the input type is too confusing
1698
+ mintAsset(forgeScript, mint, redeemer) {
1699
+ const assetQuantity = mint.assetQuantity;
1700
+ let assetNameHex = (0, import_common2.stringToHex)(mint.assetName);
1701
+ const referenceAssetNameHex = (0, import_common2.CIP68_100)(assetNameHex);
1702
+ if (mint.cip68ScriptAddress) {
1703
+ assetNameHex = (0, import_common2.CIP68_222)(assetNameHex);
1704
+ }
1705
+ let policyId = "";
1706
+ switch (typeof forgeScript) {
1707
+ case "string":
1708
+ policyId = (0, import_core_cst2.deserializeNativeScript)(forgeScript).hash().toString();
1709
+ this.txBuilder.mint(assetQuantity, policyId, assetNameHex).mintingScript(forgeScript);
1710
+ if (mint.cip68ScriptAddress) {
1711
+ this.txBuilder.mint(assetQuantity, policyId, referenceAssetNameHex).mintingScript(forgeScript);
1712
+ }
1713
+ break;
1714
+ case "object":
1715
+ if (!redeemer)
1716
+ throw new Error(
1717
+ "burnAsset: Redeemer data is required for Plutus minting"
1718
+ );
1719
+ if ("code" in forgeScript) {
1720
+ policyId = (0, import_core_cst2.deserializePlutusScript)(
1721
+ forgeScript.code,
1722
+ forgeScript.version
1723
+ ).hash().toString();
1724
+ this.isCollateralNeeded = true;
1725
+ this.mintPlutusScript(forgeScript).mint(assetQuantity, policyId, assetNameHex).mintingScript(forgeScript.code).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1726
+ if (mint.cip68ScriptAddress) {
1727
+ this.mintPlutusScript(forgeScript).mint(assetQuantity, policyId, referenceAssetNameHex).mintingScript(forgeScript.code).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1728
+ }
1729
+ break;
1730
+ }
1731
+ if ("output" in forgeScript) {
1732
+ if (!forgeScript.output.scriptRef) {
1733
+ throw new Error("mintAsset: No script reference found in UTxO");
1734
+ }
1735
+ const script = (0, import_core_cst2.fromScriptRef)(forgeScript.output.scriptRef);
1736
+ if (!script) {
1737
+ throw new Error("mintAsset: Script reference not found");
1738
+ }
1739
+ if ("code" in script) {
1740
+ policyId = (0, import_core_cst2.deserializePlutusScript)(script.code, script.version).hash().toString();
1741
+ this.isCollateralNeeded = true;
1742
+ this.mintPlutusScript(script).mint(assetQuantity, policyId, assetNameHex).mintTxInReference(
1743
+ forgeScript.input.txHash,
1744
+ forgeScript.input.outputIndex
1745
+ ).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1746
+ if (mint.cip68ScriptAddress) {
1747
+ this.mintPlutusScript(script).mint(assetQuantity, policyId, referenceAssetNameHex).mintTxInReference(
1748
+ forgeScript.input.txHash,
1749
+ forgeScript.input.outputIndex
1750
+ ).mintRedeemerValue(redeemer.data, "Mesh", redeemer.budget);
1751
+ break;
1752
+ }
1753
+ break;
1754
+ } else {
1755
+ throw new Error(
1756
+ "mintAsset: Reference script minting not implemented"
1757
+ );
1758
+ }
1759
+ }
1760
+ break;
1761
+ }
1762
+ if (mint.recipient) {
1763
+ this.sendAssets(mint.recipient, [
1764
+ { unit: policyId + assetNameHex, quantity: mint.assetQuantity }
1765
+ ]);
1766
+ }
1767
+ if (mint.cip68ScriptAddress) {
1768
+ this.sendAssets(
1769
+ {
1770
+ address: mint.cip68ScriptAddress,
1771
+ datum: { inline: true, value: (0, import_common2.metadataToCip68)(mint.metadata) }
1772
+ },
1773
+ [
1774
+ {
1775
+ unit: policyId + referenceAssetNameHex,
1776
+ quantity: mint.assetQuantity
1777
+ }
1778
+ ]
1779
+ );
1780
+ }
1781
+ if (!mint.cip68ScriptAddress && mint.metadata && mint.label) {
1782
+ if (mint.label === "721" || mint.label === "20") {
1783
+ this.setMetadata(Number(mint.label), {
1784
+ [policyId]: { [mint.assetName]: mint.metadata }
1785
+ });
1786
+ }
1787
+ this.setMetadata(Number(mint.label), mint.metadata);
1788
+ }
1789
+ return this;
1790
+ }
1791
+ // TODO: nuke this probably as the input type is too confusing
1792
+ // TO be deprecated as it doesnt support reference script minting native assets
1793
+ burnAsset(forgeScript, asset, redeemer) {
1794
+ const assetQuantity = "-" + asset.quantity;
1795
+ const mint = {
1796
+ assetName: (0, import_common2.hexToString)(asset.unit.slice(import_common2.POLICY_ID_LENGTH)),
1797
+ assetQuantity
1798
+ };
1799
+ try {
1800
+ this.mintAsset(forgeScript, mint, redeemer);
1801
+ } catch (error) {
1802
+ throw new Error("burnAsset: " + error);
1803
+ }
1804
+ return this;
1805
+ }
1806
+ /**
1807
+ * Sets the change address for the transaction.
1808
+ *
1809
+ * @param {string} changeAddress The change address.
1810
+ * @returns {Transaction} The Transaction object.
1811
+ */
1812
+ setChangeAddress(changeAddress) {
1813
+ this.txBuilder.changeAddress(changeAddress);
1814
+ return this;
1815
+ }
1816
+ /**
1817
+ * Sets the collateral for the transaction.
1818
+ *
1819
+ * @param {UTxO[]} collateral - Set the UTxO for collateral.
1820
+ * @returns {Transaction} The Transaction object.
1821
+ */
1822
+ setCollateral(collateral) {
1823
+ collateral.forEach((collateralUtxo) => {
1824
+ this.txBuilder.txInCollateral(
1825
+ collateralUtxo.input.txHash,
1826
+ collateralUtxo.input.outputIndex,
1827
+ collateralUtxo.output.amount,
1828
+ collateralUtxo.output.address
1829
+ );
1830
+ });
1831
+ return this;
1832
+ }
1833
+ /**
1834
+ * Sets the required signers for the transaction.
1835
+ *
1836
+ * @param {string[]} addresses The addresses of the required signers.
1837
+ * @returns {Transaction} The Transaction object.
1838
+ */
1839
+ setRequiredSigners(addresses) {
1840
+ addresses.forEach((address) => {
1841
+ const { pubKeyHash } = this.txBuilder.serializer.deserializer.key.deserializeAddress(address);
1842
+ this.txBuilder.requiredSignerHash(pubKeyHash);
1843
+ });
1844
+ return this;
1845
+ }
1846
+ /**
1847
+ * Set the time to live for the transaction.
1848
+ *
1849
+ * @param {string} slot The slot number to expire the transaction at.
1850
+ * @returns {Transaction} The Transaction object.
1851
+ * @see {@link https://meshjs.dev/apis/transaction#setTimeLimit}
1852
+ */
1853
+ setTimeToExpire(slot) {
1854
+ this.txBuilder.invalidHereafter(Number(slot));
1855
+ return this;
1856
+ }
1857
+ /**
1858
+ * Sets the start slot for the transaction.
1859
+ *
1860
+ * @param {string} slot The start slot for the transaction.
1861
+ * @returns {Transaction} The Transaction object.
1862
+ * @see {@link https://meshjs.dev/apis/transaction#setTimeLimit}
1863
+ */
1864
+ setTimeToStart(slot) {
1865
+ this.txBuilder.invalidBefore(Number(slot));
1866
+ return this;
1867
+ }
1868
+ /**
1869
+ * Add a JSON metadata entry to the transaction.
1870
+ *
1871
+ * @param {number} key The key to use for the metadata entry.
1872
+ * @param {unknown} value The value to use for the metadata entry.
1873
+ * @returns {Transaction} The Transaction object.
1874
+ * @see {@link https://meshjs.dev/apis/transaction#setMetadata}
1875
+ */
1876
+ setMetadata(key, value) {
1877
+ this.txBuilder.metadataValue(key.toString(), value);
1878
+ return this;
1879
+ }
1880
+ withdrawRewards(rewardAddress, lovelace) {
1881
+ this.txBuilder.withdrawal(rewardAddress, lovelace);
1882
+ return this;
1883
+ }
1884
+ delegateStake(rewardAddress, poolId) {
1885
+ this.txBuilder.delegateStakeCertificate(
1886
+ rewardAddress,
1887
+ this.txBuilder.serializer.resolver.keys.resolveEd25519KeyHash(poolId)
1888
+ );
1889
+ return this;
1890
+ }
1891
+ deregisterStake(rewardAddress) {
1892
+ this.txBuilder.deregisterStakeCertificate(rewardAddress);
1893
+ return this;
1894
+ }
1895
+ registerStake(rewardAddress) {
1896
+ this.txBuilder.registerStakeCertificate(rewardAddress);
1897
+ return this;
1898
+ }
1899
+ // TODO: test
1900
+ registerPool(params) {
1901
+ this.txBuilder.registerPoolCertificate(params);
1902
+ return this;
1903
+ }
1904
+ // TODO: test
1905
+ retirePool(poolId, epochNo) {
1906
+ this.txBuilder.retirePoolCertificate(poolId, epochNo);
1907
+ return this;
1908
+ }
1909
+ async build() {
1910
+ try {
1911
+ await this.addCollateralIfNeeded();
1912
+ await this.addTxInputsAsNeeded();
1913
+ await this.addChangeAddress();
1914
+ return this.txBuilder.complete();
1915
+ } catch (error) {
1916
+ throw new Error(
1917
+ `[Transaction] An error occurred during build: ${error}.`
1918
+ );
1919
+ }
1920
+ }
1921
+ mintPlutusScript(script) {
1922
+ switch (script.version) {
1923
+ case "V1":
1924
+ this.txBuilder.mintPlutusScriptV1();
1925
+ break;
1926
+ case "V2":
1927
+ this.txBuilder.mintPlutusScriptV2();
1928
+ break;
1929
+ case "V3":
1930
+ this.txBuilder.mintPlutusScriptV3();
1931
+ break;
1932
+ }
1933
+ return this.txBuilder;
1934
+ }
1935
+ spendingPlutusScript(script) {
1936
+ switch (script.version) {
1937
+ case "V1":
1938
+ this.txBuilder.spendingPlutusScriptV1();
1939
+ break;
1940
+ case "V2":
1941
+ this.txBuilder.spendingPlutusScriptV2();
1942
+ break;
1943
+ case "V3":
1944
+ this.txBuilder.spendingPlutusScriptV3();
1945
+ break;
1946
+ }
1947
+ return this.txBuilder;
1948
+ }
1949
+ async addCollateralIfNeeded() {
1950
+ if (this.isCollateralNeeded) {
1951
+ const collaterals = await this.initiator.getCollateral();
1952
+ if (collaterals.length > 0) {
1953
+ this.setCollateral(collaterals);
1954
+ return;
1955
+ }
1956
+ const utxos = await this.initiator.getUtxos();
1957
+ const pureLovelaceUtxos = utxos.filter(
1958
+ (utxo) => utxo.output.amount.length === 1
1959
+ );
1960
+ pureLovelaceUtxos.sort((a, b) => {
1961
+ return Number(a.output.amount[0]?.quantity) - Number(a.output.amount[0]?.quantity);
1962
+ });
1963
+ for (const utxo of pureLovelaceUtxos) {
1964
+ if (Number(utxo.output.amount[0]?.quantity) >= 5e6) {
1965
+ return [utxo];
1966
+ }
1967
+ }
1968
+ if (pureLovelaceUtxos.length === 0) {
1969
+ throw new Error("No pure lovelace utxos found for collateral");
1970
+ }
1971
+ this.setCollateral([pureLovelaceUtxos[0]]);
1972
+ }
1973
+ }
1974
+ async addTxInputsAsNeeded() {
1975
+ const utxos = await this.initiator.getUtxos();
1976
+ this.txBuilder.selectUtxosFrom(utxos);
1977
+ }
1978
+ async addChangeAddress() {
1979
+ if (this.txBuilder.meshTxBuilderBody.changeAddress === "") {
1980
+ const changeAddress = await this.initiator.getChangeAddress();
1981
+ this.setChangeAddress(changeAddress);
1982
+ }
1983
+ }
1984
+ };
1985
+ // Annotate the CommonJS export names for ESM import in node:
1986
+ 0 && (module.exports = {
1987
+ ForgeScript,
1988
+ MeshTxBuilder,
1989
+ Transaction,
1990
+ utxoToTxIn
1991
+ });