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