@meshsdk/core-cst 1.6.2 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1,2680 @@
1
- import{Cardano as pi,Serialization as ui}from"@cardano-sdk/core";import de from"@stricahq/bip32ed25519";import Je from"hash.js";var K=class extends de.PrivateKey{constructor(e,r=!0){if(!r){let s=Je.sha512().update(e).digest();s[0]&&s[31]&&(s[0]&=248,s[31]&=63,s[31]|=64),e=Buffer.from(s)}super(e)}},{PublicKey:ee,Bip32PrivateKey:ce,Bip32PublicKey:mt}=de;import{Cardano as u,Serialization as n}from"@cardano-sdk/core";import*as f from"@cardano-sdk/crypto";import{typedHex as le}from"@cardano-sdk/util";var L=u.Slot,I=n.Value,k=n.Transaction,v=u.TransactionId,fe=n.TransactionBody,te=n.TransactionWitnessSet,F=n.TransactionUnspentOutput,x=n.TransactionInput,N=n.TransactionOutput,P=n.PlutusData,xe=n.PlutusList,Se=n.PlutusMap,ye=n.Redeemers,me=n.Redeemer,It=u.RedeemerPurpose,he=n.RedeemerTag,S=n.Script,ge=u.PolicyId,Ce=u.AssetName,$=u.AssetId,Ie=f.Hash28ByteBase16,V=u.Address,Y=u.RewardAddress,vt=u.AddressType,Q=u.BaseAddress,z=u.EnterpriseAddress,Pt=u.PaymentAddress,wt=u.AssetFingerprint,Bt=n.Credential,re=f.Ed25519PublicKeyHex,Tt=t=>le(t,64),bt=t=>le(t,128),ve=f.Ed25519KeyHash,G=f.Ed25519KeyHashHex,Vt=f.Hash28ByteBase16,At=f.Hash32ByteBase16,O=u.CredentialType,Ht=n.Certificate,Et=u.PoolId,Rt=n.StakeRegistration,Kt=n.StakeDelegation,Dt=u.CertificateType,Z=n.VkeyWitness,se=f.Ed25519SignatureHex,kt=f.Ed25519PublicKey,Nt=f.Ed25519Signature,Pe=f.Bip32PrivateKey,zt=f.Bip32PrivateKeyHex,g=u.PlutusLanguageVersion,h=n.NativeScript,A=n.PlutusV1Script,H=n.PlutusV2Script,E=n.PlutusV3Script,Ot=n.Costmdls,Mt=n.CostModel,Lt=n.CborWriter,we=n.ConstrPlutusData,Wt=u.RewardAccount,qt=n.Hash,j=f.Hash32ByteBase16,W=n.Datum,Be=n.ExUnits,_t=u.NetworkId,Ut=n.DatumKind,Ft=n.CborSet,Te=u.NativeScriptKind.RequireAllOf,be=u.NativeScriptKind.RequireAnyOf,Ve=u.NativeScriptKind.RequireNOf,Ae=u.NativeScriptKind.RequireSignature,He=u.NativeScriptKind.RequireTimeAfter,Ee=u.NativeScriptKind.RequireTimeBefore,$t=u.VrfVkBech32,Re=n.ScriptPubkey;var Xt=(t,e)=>{let r=Buffer.from(t),s=e.sign(r);return{key:e.toPublicKey().toBytes().toString("hex"),signature:s.toString("hex")}},er=(t,{key:e,signature:r})=>new ee(Buffer.from(e,"hex")).verify(Buffer.from(r,"hex"),Buffer.from(t));import{Cardano as ne}from"@cardano-sdk/core";import{blake2b as Ye}from"@cardano-sdk/crypto";import{HexBlob as pt}from"@cardano-sdk/util";import{pbkdf2Sync as Xe}from"pbkdf2";import{HARDENED_KEY_START as ie}from"@meshsdk/common";var pr=(t,e,r)=>Q.fromCredentials(t,{hash:e,type:O.KeyHash},{hash:r,type:O.KeyHash}),ur=(t,e)=>z.fromCredentials(t,{hash:e,type:O.KeyHash}),dr=(t,e="")=>{let i="sha512",o=d=>(d[0]!==void 0&&(d[0]&=248),d[31]!==void 0&&(d[31]&=31,d[31]|=64),d),a=Buffer.from(t,"hex"),l=Xe(e,a,4096,96,i);return Pe.fromBytes(o(l))},Ke=(t,e)=>{let r={type:O.KeyHash,hash:e};return Y.fromCredentials(t,r)},cr=(t,e,r=0)=>{if(typeof t=="string"){let i=new ce(Buffer.from(t,"hex")).derive(ie+1852).derive(ie+1815).derive(ie+e),o=i.derive(0).derive(r).toPrivateKey(),a=i.derive(2).derive(0).toPrivateKey();return{paymentKey:o,stakeKey:a}}else{let s=new K(Buffer.from(t[0],"hex"),!1),i=new K(Buffer.from(t[1],"hex"),!1);return{paymentKey:s,stakeKey:i}}},lr=t=>{let e=new Re(G(t.hex()));return h.newScriptPubkey(e)};import{Serialization as M}from"@cardano-sdk/core";import{Ed25519KeyHash as st}from"@cardano-sdk/crypto";import{HexBlob as it}from"@cardano-sdk/util";import{toBytes as Me}from"@meshsdk/common";import{TxCBOR as et}from"@cardano-sdk/core";import{Ed25519KeyHashHex as tt}from"@cardano-sdk/crypto";import{HexBlob as T}from"@cardano-sdk/util";import{toBytes as rt}from"@meshsdk/common";var Cr=t=>{let e=V.fromString(t);if(e===null)throw new Error("Invalid address");return e},Ir=t=>ve.fromBytes(rt(t)),De=t=>j.fromHexBlob(T(t)),ke=t=>P.fromCbor(T(t)),J=(t,e)=>{switch(e){case"V1":return A.fromCbor(T(t));case"V2":return H.fromCbor(T(t));case"V3":return E.fromCbor(T(t));default:throw new Error("Invalid Plutus script version")}},vr=t=>h.fromCbor(T(t)),Pr=t=>Ie.fromEd25519KeyHashHex(tt(t)),Ne=t=>S.fromCbor(T(t)),wr=t=>F.fromCbor(T(t)),Br=t=>I.fromCbor(T(t)),ze=t=>k.fromCbor(et(t)),Oe=t=>v.fromHexBlob(T(t));var D=t=>V.fromBech32(t),X=t=>Q.fromAddress(D(t)),oe=t=>z.fromAddress(D(t)),Le=t=>Y.fromAddress(D(t)),_r=t=>{let e=t.output().datum()?t.output().datum()?.toCbor().toString():void 0,r=t.output().scriptRef()?t.output().scriptRef()?.toCbor().toString():void 0,s=t.output().datum()?.asInlineData()?t.output().datum()?.asInlineData()?.toCbor().toString():void 0;return{input:{outputIndex:Number(t.input().index()),txHash:t.input().transactionId()},output:{address:t.output().address().toBech32(),amount:ot(t.output().amount()),dataHash:e,plutusData:s,scriptRef:r}}},Ur=t=>{let e=new x(Oe(t.input.txHash),BigInt(t.input.outputIndex)),r=new N(D(t.output.address),_(t.output.amount));if(t.output.dataHash!==void 0&&r.setDatum(W.fromCore(De(t.output.dataHash))),t.output.plutusData!==void 0){let s=ke(t.output.plutusData),i=new M.Datum(void 0,s);r.setDatum(i)}return t.output.scriptRef!==void 0&&r.setScriptRef(Ne(t.output.scriptRef)),new F(e,r)},Fr=t=>t.toBech32(),ot=t=>{let e=[{unit:"lovelace",quantity:t.coin().toString()}],r=t.multiasset();if(r!==void 0){let s=Array.from(r.keys());for(let i=0;i<s.length;i+=1){let o=s[i];if(o!==void 0){let a=r.get(o);a!==void 0&&e.push({unit:o,quantity:a.toString()})}}}return e},We=t=>{if("code"in t){let e=J(t.code,t.version);if(e instanceof A)return S.newPlutusV1Script(e);if(e instanceof H)return S.newPlutusV2Script(e);if(e instanceof E)return S.newPlutusV3Script(e)}return S.newNativeScript(q(t))},$r=t=>{let e=S.fromCbor(it(t)),r=e.asPlutusV3()?.toCbor().toString();if(r)return{code:r,version:"V3"};let s=e.asPlutusV2()?.toCbor().toString();if(s)return{code:s,version:"V2"};let i=e.asPlutusV1()?.toCbor().toString();if(i)return{code:i,version:"V1"};let o=e.asNative();if(!o)throw new Error("Invalid script");return qe(o)},qe=t=>{let e=r=>{let s=new Array;for(let i=0;i<r.length;i+=1){let o=r[i];o&&s.push(qe(o))}return s};switch(t.kind()){case Te:{let r=t.asScriptAll();return{type:"all",scripts:e(r.nativeScripts())}}case be:{let r=t.asScriptAny();return{type:"any",scripts:e(r.nativeScripts())}}case Ve:{let r=t.asScriptNOfK();return{type:"atLeast",required:r.required(),scripts:e(r.nativeScripts())}}case He:return{type:"after",slot:t.asTimelockStart().slot().toString()};case Ee:return{type:"before",slot:t.asTimelockExpiry().slot().toString()};case Ae:return{type:"sig",keyHash:t.asScriptPubkey().keyHash().toString()};default:throw new Error(`Script Kind: ${t.kind()}, is not supported`)}},q=t=>{let e=r=>{let s=[];return r.forEach(i=>{s.push(q(i))}),s};switch(t.type){case"all":return h.newScriptAll(new M.ScriptAll(e(t.scripts)));case"any":return h.newScriptAny(new M.ScriptAny(e(t.scripts)));case"atLeast":return h.newScriptNOfK(new M.ScriptNOfK(e(t.scripts),t.required));case"after":return h.newTimelockStart(new M.TimelockStart(L(parseInt(t.slot))));case"before":return h.newTimelockExpiry(new M.TimelockExpiry(L(parseInt(t.slot))));case"sig":return h.newScriptPubkey(new M.ScriptPubkey(st.fromBytes(Me(t.keyHash)).hex()))}},b=t=>{let e=r=>{let s=new xe;return r.forEach(i=>{s.add(b(i))}),s};switch(typeof t){case"string":return P.newBytes(Me(t));case"number":return P.newInteger(BigInt(t));case"bigint":return P.newInteger(BigInt(t));case"object":if(t instanceof Array){let r=e(t);return P.newList(r)}else if(t instanceof Map){let r=new Se;return t.forEach((s,i)=>{r.insert(b(i),b(s))}),P.newMap(r)}else return P.newConstrPlutusData(new we(BigInt(t.alternative),e(t.fields)))}},_=t=>{let e=new Map;t.filter(i=>i.unit!=="lovelace").forEach(i=>{e.set($(i.unit),BigInt(i.quantity))});let r=t.find(i=>i.unit==="lovelace"),s=new I(BigInt(r?r.quantity:0));return(t.length>1||!r)&&s.setMultiasset(e),s};function U(t,e){let r=t.multiasset()??new Map;return e.multiasset()?.forEach((s,i)=>{let o=(r.get(i)??0n)+s;o==0n?r.delete(i):r.set(i,o)}),new I(BigInt(t.coin())+BigInt(e.coin()),r.size>0?r:void 0)}function nt(t){let e=t.multiasset()?.entries(),r=new Map;if(e)for(let s of e)r.set(s[0],-s[1]);return new I(-t.coin(),r)}function _e(t,e){return U(t,nt(e))}function Ue(t){let e=t.multiasset()?.entries(),r=t.coin()<0n?t.coin():0n,s=new Map;if(e)for(let i of e)i[1]<0n&&s.set(i[0],i[1]);return new I(r,s)}function at(t){let e=t.coin()==0n?0:1,r=t.multiasset();return r&&r.forEach(()=>{e+=1}),e}function Fe(t){return at(t)==0}var $e=t=>Buffer.from(t,"hex");var ds=t=>b(t).hash().toString(),cs=(t,e=0)=>{let r=q(t);return z.fromCredentials(e,{hash:r.hash(),type:ne.CredentialType.ScriptHash}).toAddress().toBech32()},ls=t=>q(t).hash().toString(),fs=t=>{try{let e=[X(t)?.getPaymentCredential().hash,oe(t)?.getPaymentCredential().hash].find(r=>r!==void 0);if(e!==void 0)return e.toString();throw new Error(`Couldn't resolve payment key hash from address: ${t}`)}catch(e){throw new Error(`An error occurred during resolvePaymentKeyHash: ${e}.`)}},xs=(t,e=0)=>{let r=J(t.code,t.version);return z.fromCredentials(e,{hash:r.hash(),type:ne.CredentialType.ScriptHash}).toAddress().toBech32()},Ss=t=>{try{let r=oe(t)?.getPaymentCredential().hash;if(r!==void 0)return r.toString();throw new Error(`Couldn't resolve script hash from address: ${t}`)}catch(e){throw new Error(`An error occurred during resolveScriptHash: ${e}.`)}},ys=t=>G(t).toString(),ms=t=>"not implemented",hs=t=>We(t).toCbor().toString(),gs=t=>{try{let e=D(t),s=X(t)?.getStakeCredential().hash;if(s!==void 0)return Ke(e.getNetworkId(),s).toAddress().toBech32();throw new Error(`Couldn't resolve reward address from address: ${t}`)}catch(e){throw new Error(`An error occurred during resolveRewardAddress: ${e}.`)}},Cs=t=>{try{let e=[X(t)?.getStakeCredential().hash,Le(t)?.getPaymentCredential().hash].find(r=>r!==void 0);if(e!==void 0)return e.toString();throw new Error(`Couldn't resolve stake key hash from address: ${t}`)}catch(e){throw new Error(`An error occurred during resolveStakeKeyHash: ${e}.`)}},Is=t=>{let e=ze(t).body(),r=Ye(Ye.BYTES).update($e(e.toCbor())).digest();return ne.TransactionId.fromHexBlob(pt.fromBytes(r))};import{Serialization as y,TxCBOR as Ze}from"@cardano-sdk/core";import{HexBlob as C}from"@cardano-sdk/util";import{DEFAULT_V1_COST_MODEL_LIST as ft,DEFAULT_V2_COST_MODEL_LIST as xt}from"@meshsdk/common";import{Serialization as Qe}from"@cardano-sdk/core";import*as pe from"@cardano-sdk/crypto";import{Hash32ByteBase16 as ut}from"@cardano-sdk/crypto";import{HexBlob as dt}from"@cardano-sdk/util";var ct=new Uint8Array([128]),lt=new Uint8Array([160]),ae=t=>{let e=new Qe.CborWriter;e.writeStartArray(t.length);for(let r of t)e.writeEncodedValue(Buffer.from(r.toCbor(),"hex"));return e.encode()},Ge=(t,e,r)=>{let s=new Qe.CborWriter;if(r&&r.length>0&&(!e||e.length===0))s.writeEncodedValue(ct),s.writeEncodedValue(ae(r)),s.writeEncodedValue(lt);else{if(!e||e.length===0)return;s.writeEncodedValue(ae(e)),r&&r.length>0&&s.writeEncodedValue(ae(r)),s.writeEncodedValue(Buffer.from(t.languageViewsEncoding(),"hex"))}return ut.fromHexBlob(dt.fromBytes(pe.blake2b(pe.blake2b.BYTES).update(s.encode()).digest()))};var je=class{txBody;txWitnessSet;utxoContext=new Map;redeemerContext=new Map;scriptsProvided=new Set;datumsProvided=new Set;usedLanguages={0:!1,1:!1,2:!1};constructor(){this.txBody=new fe(y.CborSet.fromCore([],x.fromCore),[],BigInt(0),void 0),this.txWitnessSet=new te}serializePoolId(e){throw new Error("Method not implemented.")}serializeAddress(e,r){throw new Error("Method not implemented.")}serializeData(e){throw new Error("Method not implemented.")}deserializer={key:{deserializeAddress:function(e){throw new Error("Function not implemented.")}},script:{deserializeNativeScript:function(e){throw new Error("Function not implemented.")},deserializePlutusScript:function(e){throw new Error("Function not implemented.")}},cert:{deserializePoolId:function(e){throw new Error("Function not implemented.")}}};resolver={keys:{resolveStakeKeyHash:function(e){let r=D(e);return r.asReward()?.getPaymentCredential().type===O.KeyHash?r.asReward().getPaymentCredential().hash:""},resolvePrivateKey:function(e){throw new Error("Function not implemented.")},resolveRewardAddress:function(e){throw new Error("Function not implemented.")},resolveEd25519KeyHash:function(e){throw new Error("Function not implemented.")}},tx:{resolveTxHash:function(e){return k.fromCbor(Ze(e)).getId()}},data:{resolveDataHash:function(e){throw new Error("Function not implemented.")}},script:{resolveScriptRef:function(e){throw new Error("Function not implemented.")}}};serializeTxBody=(e,r)=>{let{inputs:s,outputs:i,collaterals:o,referenceInputs:a,mints:l,changeAddress:d,certificates:R,validityRange:w,requiredSignatures:m,metadata:B}=e;return l.sort((p,c)=>p.policyId.localeCompare(c.policyId)),s.sort((p,c)=>p.txIn.txHash===c.txIn.txHash?p.txIn.txIndex-c.txIn.txIndex:p.txIn.txHash.localeCompare(c.txIn.txHash)),this.addAllInputs(s),this.addAllOutputs(i),this.addAllMints(l),this.addAllCollateralInputs(o),this.addAllReferenceInputs(a),this.setValidityInterval(w),this.buildWitnessSet(),this.balanceTx(d,m.length,r),new k(this.txBody,this.txWitnessSet).toCbor()};addSigningKeys=(e,r)=>{let s=k.fromCbor(Ze(e)),i=s.witnessSet(),o=i.vkeys(),a=o?[...o.values()]:[];for(let l=0;l<r.length;l++){let d=r[l];if(d){d.length===68&&d.substring(0,4)==="5820"&&(d=d.substring(4));let R=new K(Buffer.from(d,"hex"),!1),w=R.sign(Buffer.from(s.getId(),"hex"));a.push(new Z(re(R.toPublicKey().toBytes().toString("hex")),se(w.toString("hex"))))}}return i.setVkeys(y.CborSet.fromCore(a.map(l=>l.toCore()),Z.fromCore)),s.setWitnessSet(i),s.toCbor()};addAllInputs=e=>{for(let r=0;r<e.length;r+=1){let s=e[r];if(s)switch(s.type){case"PubKey":this.addTxIn(s);break;case"Script":this.addScriptTxIn(s);break;case"SimpleScript":this.addSimpleScriptTxIn(s)}}};addTxIn=e=>{let r=new x(v(e.txIn.txHash),BigInt(e.txIn.txIndex)),s=this.txBody.inputs(),i=[...s.values()];if(i.find(a=>{a.index()==r.index()&&a.transactionId==r.transactionId}))throw new Error("Duplicate input added to tx body");i.push(r),s.setValues(i);let o=new N(V.fromBech32(e.txIn.address),_(e.txIn.amount));this.utxoContext.set(r,o),this.txBody.setInputs(s)};addScriptTxIn=e=>{if(this.addTxIn({type:"PubKey",txIn:e.txIn}),!e.scriptTxIn.scriptSource)throw new Error("A script input had no script source");if(!e.scriptTxIn.datumSource)throw new Error("A script input had no datum source");if(!e.scriptTxIn.redeemer)throw new Error("A script input had no redeemer");if(e.scriptTxIn.scriptSource.type==="Provided")switch(e.scriptTxIn.scriptSource.script.version){case"V1":{this.scriptsProvided.add(S.newPlutusV1Script(A.fromCbor(C(e.scriptTxIn.scriptSource.script.code)))),this.usedLanguages[g.V1]=!0;break}case"V2":{this.scriptsProvided.add(S.newPlutusV2Script(H.fromCbor(C(e.scriptTxIn.scriptSource.script.code)))),this.usedLanguages[g.V2]=!0;break}case"V3":{this.scriptsProvided.add(S.newPlutusV3Script(E.fromCbor(C(e.scriptTxIn.scriptSource.script.code)))),this.usedLanguages[g.V3]=!0;break}}else if(e.scriptTxIn.scriptSource.type==="Inline"){let i=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),o=[...i.values()];switch(o.push(new x(v(e.scriptTxIn.scriptSource.txHash),BigInt(e.scriptTxIn.scriptSource.txIndex))),i.setValues(o),this.txBody.setReferenceInputs(i),e.scriptTxIn.scriptSource.version){case"V1":{this.usedLanguages[g.V1]=!0;break}case"V2":{this.usedLanguages[g.V2]=!0;break}case"V3":{this.usedLanguages[g.V3]=!0;break}}}if(e.scriptTxIn.datumSource.type==="Provided")this.datumsProvided.add(b(e.scriptTxIn.datumSource.data.content));else if(e.scriptTxIn.datumSource.type==="Inline"){let i=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),o=[...i.values()];o.push(new x(v(e.txIn.txHash),BigInt(e.txIn.txIndex))),i.setValues(o),this.txBody.setReferenceInputs(i)}let r=new x(v(e.txIn.txHash),BigInt(e.txIn.txIndex)),s=e.scriptTxIn.redeemer.exUnits;this.redeemerContext.set(r,new me(he.Spend,BigInt(0),b(e.scriptTxIn.redeemer.data.content),new Be(BigInt(s.mem),BigInt(s.steps))))};addSimpleScriptTxIn=e=>{if(this.addTxIn({type:"PubKey",txIn:e.txIn}),!e.simpleScriptTxIn.scriptSource)throw new Error("A native script input had no script source");if(e.simpleScriptTxIn.scriptSource.type==="Provided")this.scriptsProvided.add(S.newNativeScript(h.fromCbor(C(e.simpleScriptTxIn.scriptSource.script))));else if(e.simpleScriptTxIn.scriptSource.type==="Inline"&&e.simpleScriptTxIn.scriptSource.txInInfo.type==="Inline"){let r=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),s=[...r.values()];s.push(new x(v(e.simpleScriptTxIn.scriptSource.txInInfo.txHash),BigInt(e.simpleScriptTxIn.scriptSource.txInInfo.txIndex))),r.setValues(s),this.txBody.setReferenceInputs(r)}};addAllOutputs=e=>{for(let r=0;r<e.length;r++)this.addOutput(e[r])};addOutput=e=>{let r=this.txBody.outputs(),s=new N(V.fromBech32(e.address),_(e.amount));if(e.datum?.type==="Hash"?s.setDatum(W.newDataHash(j.fromHexBlob(C(b(e.datum.data.content).hash())))):e.datum?.type==="Inline"&&s.setDatum(W.newInlineData(b(e.datum.data.content))),e.referenceScript)switch(e.referenceScript.version){case"V1":{s.setScriptRef(S.newPlutusV1Script(A.fromCbor(C(e.referenceScript.code))));break}case"V2":{s.setScriptRef(S.newPlutusV2Script(H.fromCbor(C(e.referenceScript.code))));break}case"V3":{s.setScriptRef(S.newPlutusV3Script(E.fromCbor(C(e.referenceScript.code))));break}}r.push(s),this.txBody.setOutputs(r)};addAllReferenceInputs=e=>{for(let r=0;r<e.length;r++)this.addReferenceIput(e[r])};addReferenceIput=e=>{let r=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),s=[...r.values()];s.push(new x(v.fromHexBlob(C(e.txHash)),BigInt(e.txIndex))),r.setValues(s),this.txBody.setReferenceInputs(r)};addAllMints=e=>{for(let r=0;r<e.length;r++)this.addMint(e[r])};addMint=e=>{let r=this.txBody.mint()??new Map,s=e.policyId+e.assetName;for(let i of r.keys())if(i.toString()==s)throw new Error("The same asset is already in the mint field");if(r.set($.fromParts(ge(e.policyId),Ce(e.assetName)),BigInt(e.amount)),this.txBody.setMint(r),e.type==="Native"){if(!e.scriptSource)throw new Error("Script source not provided for native script mint");let i=e.scriptSource;if(!i)throw new Error("A script source for a native script was not a native script somehow");if(i.type==="Provided")this.scriptsProvided.add(S.newNativeScript(h.fromCbor(C(i.scriptCode))));else if(i.type==="Inline"){let o=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),a=[...o.values()];a.push(new x(v(i.txHash),BigInt(i.txIndex))),o.setValues(a),this.txBody.setReferenceInputs(o)}}else if(e.type==="Plutus"){if(!e.scriptSource)throw new Error("Script source not provided for plutus script mint");let i=e.scriptSource;if(!i)throw new Error("A script source for a plutus mint was not plutus script somehow");if(i.type==="Provided")switch(i.script.version){case"V1":this.scriptsProvided.add(S.newPlutusV1Script(A.fromCbor(C(i.script.code))));break;case"V2":this.scriptsProvided.add(S.newPlutusV2Script(H.fromCbor(C(i.script.code))));break;case"V3":this.scriptsProvided.add(S.newPlutusV3Script(E.fromCbor(C(i.script.code))));break}else if(i.type==="Inline"){let o=this.txBody.referenceInputs()??y.CborSet.fromCore([],x.fromCore),a=[...o.values()];switch(a.push(new x(v(i.txHash),BigInt(i.txIndex))),o.setValues(a),this.txBody.setReferenceInputs(o),i.version){case"V1":{this.usedLanguages[g.V1]=!0;break}case"V2":{this.usedLanguages[g.V2]=!0;break}case"V3":{this.usedLanguages[g.V3]=!0;break}}}}};addAllCollateralInputs=e=>{for(let r=0;r<e.length;r++)this.addCollateralInput(e[r])};addCollateralInput=e=>{let r=new x(v(e.txIn.txHash),BigInt(e.txIn.txIndex)),s=this.txBody.collateral()??y.CborSet.fromCore([],x.fromCore),i=[...s.values()];if(i.find(a=>{a.index()==r.index()&&a.transactionId==r.transactionId}))throw new Error("Duplicate input added to tx body");i.push(r),s.setValues(i);let o=new N(V.fromBech32(e.txIn.address),_(e.txIn.amount));this.utxoContext.set(r,o),this.txBody.setCollateral(s)};setValidityInterval=e=>{e.invalidBefore&&this.txBody.setValidityStartInterval(L(e.invalidBefore)),e.invalidHereafter&&this.txBody.setTtl(L(e.invalidHereafter))};buildWitnessSet=()=>{let e=this.txBody.inputs();for(let p=0;p<e.size();p+=1){let c=e.values().at(p);if(c){let ue=this.redeemerContext.get(c);ue&&ue.setIndex(BigInt(p))}}let r=this.txWitnessSet.redeemers()??ye.fromCore([]),s=[...r.values()];this.redeemerContext.forEach(p=>{s.push(p)}),r.setValues(s),this.txWitnessSet.setRedeemers(r);let i=this.txWitnessSet.nativeScripts()??y.CborSet.fromCore([],h.fromCore),o=this.txWitnessSet.plutusV1Scripts()??y.CborSet.fromCore([],A.fromCore),a=this.txWitnessSet.plutusV2Scripts()??y.CborSet.fromCore([],H.fromCore),l=this.txWitnessSet.plutusV3Scripts()??y.CborSet.fromCore([],E.fromCore);this.scriptsProvided.forEach(p=>{if(p.asNative()!==void 0){let c=[...i.values()];c.push(p.asNative()),i.setValues(c)}else if(p.asPlutusV1()!==void 0){let c=[...o.values()];c.push(p.asPlutusV1()),o.setValues(c)}else if(p.asPlutusV2()!==void 0){let c=[...a.values()];c.push(p.asPlutusV2()),a.setValues(c)}else if(p.asPlutusV3()!==void 0){let c=[...l.values()];c.push(p.asPlutusV3()),l.setValues(c)}this.txWitnessSet.setNativeScripts(i),this.txWitnessSet.setPlutusV1Scripts(o),this.txWitnessSet.setPlutusV2Scripts(a),this.txWitnessSet.setPlutusV3Scripts(l)});let d=this.txWitnessSet.plutusData()??y.CborSet.fromCore([],P.fromCore);this.datumsProvided.forEach(p=>{let c=[...d.values()];c.push(p),d.setValues(c)}),this.txWitnessSet.setPlutusData(d);let R=y.CostModel.newPlutusV1(ft),w=y.CostModel.newPlutusV2(xt),m=new y.Costmdls;this.usedLanguages[g.V1]&&m.insert(R),this.usedLanguages[g.V2]&&m.insert(w),this.usedLanguages[g.V3];let B=Ge(m,r.size()>0?[...r.values()]:void 0,d.size()>0?[...d.values()]:void 0);B&&this.txBody.setScriptDataHash(B)};balanceTx=(e,r,s)=>{if(e==="")throw new Error("Can't balance tx without a change address");let i=this.txBody.inputs().values(),o=new I(BigInt(0));for(let m=0;m<i.length;m++){let B=i[m];if(!B)throw new Error("Invalid input found");let p=this.utxoContext.get(B);if(!p)throw new Error(`Unable to resolve input: ${B.toCbor()}`);o=U(o,p.amount())}let a=this.txBody.withdrawals();a&&a.forEach(m=>{o=U(o,new I(m))}),o=U(o,new I(BigInt(0),this.txBody.mint()));let l=this.txBody.outputs();for(let m=0;m<l.length;m++){let B=l.at(m);B&&(o=_e(o,B.amount()))}if(o.coin()<0||!Fe(Ue(o)))throw new Error("Not enough funds to satisfy outputs");l.push(new N(V.fromBech32(e),o)),this.txBody.setOutputs(l),this.txBody.setFee(BigInt("10000000"));let d=this.createDummyTx(r),R=s.minFeeB+d.toCbor().length/2*Number(s.coinsPerUtxoSize);this.txBody.setFee(BigInt(R));let w=l.pop();if(!w)throw new Error("Somehow the output length was 0 after attempting to calculate fees");w.amount().setCoin(w.amount().coin()-BigInt(R)),l.push(w),this.txBody.setOutputs(l)};createDummyTx=e=>{let r=new te,s=[];for(let i=0;i<e;i++)s.push([re("0".repeat(64)),se("0".repeat(128))]);return r.setVkeys(y.CborSet.fromCore(s,Z.fromCore)),new k(this.txBody,r)}};import*as mi from"@cardano-sdk/util";import*as hi from"@cardano-sdk/crypto";import*as gi from"@cardano-sdk/core";export{V as Address,vt as AddressType,wt as AssetFingerprint,$ as AssetId,Ce as AssetName,Q as BaseAddress,Pe as Bip32PrivateKey,zt as Bip32PrivateKeyHex,pi as Cardano,gi as CardanoSDK,je as CardanoSDKSerializer,mi as CardanoSDKUtil,Ft as CborSet,Lt as CborWriter,Ht as Certificate,Dt as CertificateType,we as ConstrPlutusData,Mt as CostModel,Ot as Costmdls,Bt as Credential,O as CredentialType,hi as Crypto,W as Datum,j as DatumHash,Ut as DatumKind,ve as Ed25519KeyHash,G as Ed25519KeyHashHex,bt as Ed25519PrivateExtendedKeyHex,Tt as Ed25519PrivateNormalKeyHex,kt as Ed25519PublicKey,re as Ed25519PublicKeyHex,Nt as Ed25519Signature,se as Ed25519SignatureHex,z as EnterpriseAddress,Be as ExUnits,qt as Hash,Vt as Hash28ByteBase16,At as Hash32ByteBase16,h as NativeScript,_t as NetworkId,Pt as PaymentAddress,P as PlutusData,g as PlutusLanguageVersion,xe as PlutusList,Se as PlutusMap,A as PlutusV1Script,H as PlutusV2Script,E as PlutusV3Script,ge as PolicyId,Et as PoolId,K as PrivateKey,ee as PublicKey,me as Redeemer,It as RedeemerPurpose,he as RedeemerTag,ye as Redeemers,Te as RequireAllOf,be as RequireAnyOf,Ve as RequireNOf,Ae as RequireSignature,He as RequireTimeAfter,Ee as RequireTimeBefore,Wt as RewardAccount,Y as RewardAddress,S as Script,Ie as ScriptHash,Re as ScriptPubkey,ui as Serialization,L as Slot,Kt as StakeDelegation,Rt as StakeRegistration,k as Transaction,fe as TransactionBody,v as TransactionId,x as TransactionInput,N as TransactionOutput,F as TransactionUnspentOutput,te as TransactionWitnessSet,I as Value,Z as VkeyWitness,$t as VrfVkBech32,Fr as addressToBech32,at as assetTypes,pr as buildBaseAddress,dr as buildBip32PrivateKey,ur as buildEnterpriseAddress,cr as buildKeys,Ke as buildRewardAddress,lr as buildScriptPubkey,er as checkSignature,Cr as deserializeAddress,De as deserializeDataHash,Ir as deserializeEd25519KeyHash,vr as deserializeNativeScript,ke as deserializePlutusData,J as deserializePlutusScript,Pr as deserializeScriptHash,Ne as deserializeScriptRef,ze as deserializeTx,Oe as deserializeTxHash,wr as deserializeTxUnspentOutput,Br as deserializeValue,Fe as empty,qe as fromNativeScript,$r as fromScriptRef,_r as fromTxUnspentOutput,ot as fromValue,U as mergeValue,nt as negateValue,Ue as negatives,ds as resolveDataHash,cs as resolveNativeScriptAddress,ls as resolveNativeScriptHash,fs as resolvePaymentKeyHash,xs as resolvePlutusScriptAddress,Ss as resolvePlutusScriptHash,ys as resolvePoolId,ms as resolvePrivateKey,gs as resolveRewardAddress,hs as resolveScriptRef,Cs as resolveStakeKeyHash,Is as resolveTxHash,Xt as signData,_e as subValue,D as toAddress,X as toBaseAddress,oe as toEnterpriseAddress,q as toNativeScript,b as toPlutusData,Le as toRewardAddress,We as toScriptRef,Ur as toTxUnspentOutput,_ as toValue};
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../../node_modules/blakejs/util.js
28
+ var require_util = __commonJS({
29
+ "../../node_modules/blakejs/util.js"(exports, module) {
30
+ "use strict";
31
+ var ERROR_MSG_INPUT = "Input must be an string, Buffer or Uint8Array";
32
+ function normalizeInput(input) {
33
+ let ret;
34
+ if (input instanceof Uint8Array) {
35
+ ret = input;
36
+ } else if (typeof input === "string") {
37
+ const encoder = new TextEncoder();
38
+ ret = encoder.encode(input);
39
+ } else {
40
+ throw new Error(ERROR_MSG_INPUT);
41
+ }
42
+ return ret;
43
+ }
44
+ function toHex(bytes) {
45
+ return Array.prototype.map.call(bytes, function(n) {
46
+ return (n < 16 ? "0" : "") + n.toString(16);
47
+ }).join("");
48
+ }
49
+ function uint32ToHex(val) {
50
+ return (4294967296 + val).toString(16).substring(1);
51
+ }
52
+ function debugPrint(label, arr, size) {
53
+ let msg = "\n" + label + " = ";
54
+ for (let i = 0; i < arr.length; i += 2) {
55
+ if (size === 32) {
56
+ msg += uint32ToHex(arr[i]).toUpperCase();
57
+ msg += " ";
58
+ msg += uint32ToHex(arr[i + 1]).toUpperCase();
59
+ } else if (size === 64) {
60
+ msg += uint32ToHex(arr[i + 1]).toUpperCase();
61
+ msg += uint32ToHex(arr[i]).toUpperCase();
62
+ } else throw new Error("Invalid size " + size);
63
+ if (i % 6 === 4) {
64
+ msg += "\n" + new Array(label.length + 4).join(" ");
65
+ } else if (i < arr.length - 2) {
66
+ msg += " ";
67
+ }
68
+ }
69
+ console.log(msg);
70
+ }
71
+ function testSpeed(hashFn, N, M) {
72
+ let startMs = (/* @__PURE__ */ new Date()).getTime();
73
+ const input = new Uint8Array(N);
74
+ for (let i = 0; i < N; i++) {
75
+ input[i] = i % 256;
76
+ }
77
+ const genMs = (/* @__PURE__ */ new Date()).getTime();
78
+ console.log("Generated random input in " + (genMs - startMs) + "ms");
79
+ startMs = genMs;
80
+ for (let i = 0; i < M; i++) {
81
+ const hashHex = hashFn(input);
82
+ const hashMs = (/* @__PURE__ */ new Date()).getTime();
83
+ const ms = hashMs - startMs;
84
+ startMs = hashMs;
85
+ console.log("Hashed in " + ms + "ms: " + hashHex.substring(0, 20) + "...");
86
+ console.log(
87
+ Math.round(N / (1 << 20) / (ms / 1e3) * 100) / 100 + " MB PER SECOND"
88
+ );
89
+ }
90
+ }
91
+ module.exports = {
92
+ normalizeInput,
93
+ toHex,
94
+ debugPrint,
95
+ testSpeed
96
+ };
97
+ }
98
+ });
99
+
100
+ // ../../node_modules/blakejs/blake2b.js
101
+ var require_blake2b = __commonJS({
102
+ "../../node_modules/blakejs/blake2b.js"(exports, module) {
103
+ "use strict";
104
+ var util = require_util();
105
+ function ADD64AA(v2, a, b) {
106
+ const o0 = v2[a] + v2[b];
107
+ let o1 = v2[a + 1] + v2[b + 1];
108
+ if (o0 >= 4294967296) {
109
+ o1++;
110
+ }
111
+ v2[a] = o0;
112
+ v2[a + 1] = o1;
113
+ }
114
+ function ADD64AC(v2, a, b0, b1) {
115
+ let o0 = v2[a] + b0;
116
+ if (b0 < 0) {
117
+ o0 += 4294967296;
118
+ }
119
+ let o1 = v2[a + 1] + b1;
120
+ if (o0 >= 4294967296) {
121
+ o1++;
122
+ }
123
+ v2[a] = o0;
124
+ v2[a + 1] = o1;
125
+ }
126
+ function B2B_GET32(arr, i) {
127
+ return arr[i] ^ arr[i + 1] << 8 ^ arr[i + 2] << 16 ^ arr[i + 3] << 24;
128
+ }
129
+ function B2B_G(a, b, c, d, ix, iy) {
130
+ const x0 = m[ix];
131
+ const x1 = m[ix + 1];
132
+ const y0 = m[iy];
133
+ const y1 = m[iy + 1];
134
+ ADD64AA(v, a, b);
135
+ ADD64AC(v, a, x0, x1);
136
+ let xor0 = v[d] ^ v[a];
137
+ let xor1 = v[d + 1] ^ v[a + 1];
138
+ v[d] = xor1;
139
+ v[d + 1] = xor0;
140
+ ADD64AA(v, c, d);
141
+ xor0 = v[b] ^ v[c];
142
+ xor1 = v[b + 1] ^ v[c + 1];
143
+ v[b] = xor0 >>> 24 ^ xor1 << 8;
144
+ v[b + 1] = xor1 >>> 24 ^ xor0 << 8;
145
+ ADD64AA(v, a, b);
146
+ ADD64AC(v, a, y0, y1);
147
+ xor0 = v[d] ^ v[a];
148
+ xor1 = v[d + 1] ^ v[a + 1];
149
+ v[d] = xor0 >>> 16 ^ xor1 << 16;
150
+ v[d + 1] = xor1 >>> 16 ^ xor0 << 16;
151
+ ADD64AA(v, c, d);
152
+ xor0 = v[b] ^ v[c];
153
+ xor1 = v[b + 1] ^ v[c + 1];
154
+ v[b] = xor1 >>> 31 ^ xor0 << 1;
155
+ v[b + 1] = xor0 >>> 31 ^ xor1 << 1;
156
+ }
157
+ var BLAKE2B_IV32 = new Uint32Array([
158
+ 4089235720,
159
+ 1779033703,
160
+ 2227873595,
161
+ 3144134277,
162
+ 4271175723,
163
+ 1013904242,
164
+ 1595750129,
165
+ 2773480762,
166
+ 2917565137,
167
+ 1359893119,
168
+ 725511199,
169
+ 2600822924,
170
+ 4215389547,
171
+ 528734635,
172
+ 327033209,
173
+ 1541459225
174
+ ]);
175
+ var SIGMA8 = [
176
+ 0,
177
+ 1,
178
+ 2,
179
+ 3,
180
+ 4,
181
+ 5,
182
+ 6,
183
+ 7,
184
+ 8,
185
+ 9,
186
+ 10,
187
+ 11,
188
+ 12,
189
+ 13,
190
+ 14,
191
+ 15,
192
+ 14,
193
+ 10,
194
+ 4,
195
+ 8,
196
+ 9,
197
+ 15,
198
+ 13,
199
+ 6,
200
+ 1,
201
+ 12,
202
+ 0,
203
+ 2,
204
+ 11,
205
+ 7,
206
+ 5,
207
+ 3,
208
+ 11,
209
+ 8,
210
+ 12,
211
+ 0,
212
+ 5,
213
+ 2,
214
+ 15,
215
+ 13,
216
+ 10,
217
+ 14,
218
+ 3,
219
+ 6,
220
+ 7,
221
+ 1,
222
+ 9,
223
+ 4,
224
+ 7,
225
+ 9,
226
+ 3,
227
+ 1,
228
+ 13,
229
+ 12,
230
+ 11,
231
+ 14,
232
+ 2,
233
+ 6,
234
+ 5,
235
+ 10,
236
+ 4,
237
+ 0,
238
+ 15,
239
+ 8,
240
+ 9,
241
+ 0,
242
+ 5,
243
+ 7,
244
+ 2,
245
+ 4,
246
+ 10,
247
+ 15,
248
+ 14,
249
+ 1,
250
+ 11,
251
+ 12,
252
+ 6,
253
+ 8,
254
+ 3,
255
+ 13,
256
+ 2,
257
+ 12,
258
+ 6,
259
+ 10,
260
+ 0,
261
+ 11,
262
+ 8,
263
+ 3,
264
+ 4,
265
+ 13,
266
+ 7,
267
+ 5,
268
+ 15,
269
+ 14,
270
+ 1,
271
+ 9,
272
+ 12,
273
+ 5,
274
+ 1,
275
+ 15,
276
+ 14,
277
+ 13,
278
+ 4,
279
+ 10,
280
+ 0,
281
+ 7,
282
+ 6,
283
+ 3,
284
+ 9,
285
+ 2,
286
+ 8,
287
+ 11,
288
+ 13,
289
+ 11,
290
+ 7,
291
+ 14,
292
+ 12,
293
+ 1,
294
+ 3,
295
+ 9,
296
+ 5,
297
+ 0,
298
+ 15,
299
+ 4,
300
+ 8,
301
+ 6,
302
+ 2,
303
+ 10,
304
+ 6,
305
+ 15,
306
+ 14,
307
+ 9,
308
+ 11,
309
+ 3,
310
+ 0,
311
+ 8,
312
+ 12,
313
+ 2,
314
+ 13,
315
+ 7,
316
+ 1,
317
+ 4,
318
+ 10,
319
+ 5,
320
+ 10,
321
+ 2,
322
+ 8,
323
+ 4,
324
+ 7,
325
+ 6,
326
+ 1,
327
+ 5,
328
+ 15,
329
+ 11,
330
+ 9,
331
+ 14,
332
+ 3,
333
+ 12,
334
+ 13,
335
+ 0,
336
+ 0,
337
+ 1,
338
+ 2,
339
+ 3,
340
+ 4,
341
+ 5,
342
+ 6,
343
+ 7,
344
+ 8,
345
+ 9,
346
+ 10,
347
+ 11,
348
+ 12,
349
+ 13,
350
+ 14,
351
+ 15,
352
+ 14,
353
+ 10,
354
+ 4,
355
+ 8,
356
+ 9,
357
+ 15,
358
+ 13,
359
+ 6,
360
+ 1,
361
+ 12,
362
+ 0,
363
+ 2,
364
+ 11,
365
+ 7,
366
+ 5,
367
+ 3
368
+ ];
369
+ var SIGMA82 = new Uint8Array(
370
+ SIGMA8.map(function(x) {
371
+ return x * 2;
372
+ })
373
+ );
374
+ var v = new Uint32Array(32);
375
+ var m = new Uint32Array(32);
376
+ function blake2bCompress(ctx, last) {
377
+ let i = 0;
378
+ for (i = 0; i < 16; i++) {
379
+ v[i] = ctx.h[i];
380
+ v[i + 16] = BLAKE2B_IV32[i];
381
+ }
382
+ v[24] = v[24] ^ ctx.t;
383
+ v[25] = v[25] ^ ctx.t / 4294967296;
384
+ if (last) {
385
+ v[28] = ~v[28];
386
+ v[29] = ~v[29];
387
+ }
388
+ for (i = 0; i < 32; i++) {
389
+ m[i] = B2B_GET32(ctx.b, 4 * i);
390
+ }
391
+ for (i = 0; i < 12; i++) {
392
+ B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]);
393
+ B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]);
394
+ B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]);
395
+ B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]);
396
+ B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]);
397
+ B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]);
398
+ B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]);
399
+ B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]);
400
+ }
401
+ for (i = 0; i < 16; i++) {
402
+ ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16];
403
+ }
404
+ }
405
+ var parameterBlock = new Uint8Array([
406
+ 0,
407
+ 0,
408
+ 0,
409
+ 0,
410
+ // 0: outlen, keylen, fanout, depth
411
+ 0,
412
+ 0,
413
+ 0,
414
+ 0,
415
+ // 4: leaf length, sequential mode
416
+ 0,
417
+ 0,
418
+ 0,
419
+ 0,
420
+ // 8: node offset
421
+ 0,
422
+ 0,
423
+ 0,
424
+ 0,
425
+ // 12: node offset
426
+ 0,
427
+ 0,
428
+ 0,
429
+ 0,
430
+ // 16: node depth, inner length, rfu
431
+ 0,
432
+ 0,
433
+ 0,
434
+ 0,
435
+ // 20: rfu
436
+ 0,
437
+ 0,
438
+ 0,
439
+ 0,
440
+ // 24: rfu
441
+ 0,
442
+ 0,
443
+ 0,
444
+ 0,
445
+ // 28: rfu
446
+ 0,
447
+ 0,
448
+ 0,
449
+ 0,
450
+ // 32: salt
451
+ 0,
452
+ 0,
453
+ 0,
454
+ 0,
455
+ // 36: salt
456
+ 0,
457
+ 0,
458
+ 0,
459
+ 0,
460
+ // 40: salt
461
+ 0,
462
+ 0,
463
+ 0,
464
+ 0,
465
+ // 44: salt
466
+ 0,
467
+ 0,
468
+ 0,
469
+ 0,
470
+ // 48: personal
471
+ 0,
472
+ 0,
473
+ 0,
474
+ 0,
475
+ // 52: personal
476
+ 0,
477
+ 0,
478
+ 0,
479
+ 0,
480
+ // 56: personal
481
+ 0,
482
+ 0,
483
+ 0,
484
+ 0
485
+ // 60: personal
486
+ ]);
487
+ function blake2bInit(outlen, key, salt, personal) {
488
+ if (outlen === 0 || outlen > 64) {
489
+ throw new Error("Illegal output length, expected 0 < length <= 64");
490
+ }
491
+ if (key && key.length > 64) {
492
+ throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");
493
+ }
494
+ if (salt && salt.length !== 16) {
495
+ throw new Error("Illegal salt, expected Uint8Array with length is 16");
496
+ }
497
+ if (personal && personal.length !== 16) {
498
+ throw new Error("Illegal personal, expected Uint8Array with length is 16");
499
+ }
500
+ const ctx = {
501
+ b: new Uint8Array(128),
502
+ h: new Uint32Array(16),
503
+ t: 0,
504
+ // input count
505
+ c: 0,
506
+ // pointer within buffer
507
+ outlen
508
+ // output length in bytes
509
+ };
510
+ parameterBlock.fill(0);
511
+ parameterBlock[0] = outlen;
512
+ if (key) parameterBlock[1] = key.length;
513
+ parameterBlock[2] = 1;
514
+ parameterBlock[3] = 1;
515
+ if (salt) parameterBlock.set(salt, 32);
516
+ if (personal) parameterBlock.set(personal, 48);
517
+ for (let i = 0; i < 16; i++) {
518
+ ctx.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameterBlock, i * 4);
519
+ }
520
+ if (key) {
521
+ blake2bUpdate(ctx, key);
522
+ ctx.c = 128;
523
+ }
524
+ return ctx;
525
+ }
526
+ function blake2bUpdate(ctx, input) {
527
+ for (let i = 0; i < input.length; i++) {
528
+ if (ctx.c === 128) {
529
+ ctx.t += ctx.c;
530
+ blake2bCompress(ctx, false);
531
+ ctx.c = 0;
532
+ }
533
+ ctx.b[ctx.c++] = input[i];
534
+ }
535
+ }
536
+ function blake2bFinal(ctx) {
537
+ ctx.t += ctx.c;
538
+ while (ctx.c < 128) {
539
+ ctx.b[ctx.c++] = 0;
540
+ }
541
+ blake2bCompress(ctx, true);
542
+ const out = new Uint8Array(ctx.outlen);
543
+ for (let i = 0; i < ctx.outlen; i++) {
544
+ out[i] = ctx.h[i >> 2] >> 8 * (i & 3);
545
+ }
546
+ return out;
547
+ }
548
+ function blake2b5(input, key, outlen, salt, personal) {
549
+ outlen = outlen || 64;
550
+ input = util.normalizeInput(input);
551
+ if (salt) {
552
+ salt = util.normalizeInput(salt);
553
+ }
554
+ if (personal) {
555
+ personal = util.normalizeInput(personal);
556
+ }
557
+ const ctx = blake2bInit(outlen, key, salt, personal);
558
+ blake2bUpdate(ctx, input);
559
+ return blake2bFinal(ctx);
560
+ }
561
+ function blake2bHex(input, key, outlen, salt, personal) {
562
+ const output = blake2b5(input, key, outlen, salt, personal);
563
+ return util.toHex(output);
564
+ }
565
+ module.exports = {
566
+ blake2b: blake2b5,
567
+ blake2bHex,
568
+ blake2bInit,
569
+ blake2bUpdate,
570
+ blake2bFinal
571
+ };
572
+ }
573
+ });
574
+
575
+ // ../../node_modules/blakejs/blake2s.js
576
+ var require_blake2s = __commonJS({
577
+ "../../node_modules/blakejs/blake2s.js"(exports, module) {
578
+ "use strict";
579
+ var util = require_util();
580
+ function B2S_GET32(v2, i) {
581
+ return v2[i] ^ v2[i + 1] << 8 ^ v2[i + 2] << 16 ^ v2[i + 3] << 24;
582
+ }
583
+ function B2S_G(a, b, c, d, x, y) {
584
+ v[a] = v[a] + v[b] + x;
585
+ v[d] = ROTR32(v[d] ^ v[a], 16);
586
+ v[c] = v[c] + v[d];
587
+ v[b] = ROTR32(v[b] ^ v[c], 12);
588
+ v[a] = v[a] + v[b] + y;
589
+ v[d] = ROTR32(v[d] ^ v[a], 8);
590
+ v[c] = v[c] + v[d];
591
+ v[b] = ROTR32(v[b] ^ v[c], 7);
592
+ }
593
+ function ROTR32(x, y) {
594
+ return x >>> y ^ x << 32 - y;
595
+ }
596
+ var BLAKE2S_IV = new Uint32Array([
597
+ 1779033703,
598
+ 3144134277,
599
+ 1013904242,
600
+ 2773480762,
601
+ 1359893119,
602
+ 2600822924,
603
+ 528734635,
604
+ 1541459225
605
+ ]);
606
+ var SIGMA = new Uint8Array([
607
+ 0,
608
+ 1,
609
+ 2,
610
+ 3,
611
+ 4,
612
+ 5,
613
+ 6,
614
+ 7,
615
+ 8,
616
+ 9,
617
+ 10,
618
+ 11,
619
+ 12,
620
+ 13,
621
+ 14,
622
+ 15,
623
+ 14,
624
+ 10,
625
+ 4,
626
+ 8,
627
+ 9,
628
+ 15,
629
+ 13,
630
+ 6,
631
+ 1,
632
+ 12,
633
+ 0,
634
+ 2,
635
+ 11,
636
+ 7,
637
+ 5,
638
+ 3,
639
+ 11,
640
+ 8,
641
+ 12,
642
+ 0,
643
+ 5,
644
+ 2,
645
+ 15,
646
+ 13,
647
+ 10,
648
+ 14,
649
+ 3,
650
+ 6,
651
+ 7,
652
+ 1,
653
+ 9,
654
+ 4,
655
+ 7,
656
+ 9,
657
+ 3,
658
+ 1,
659
+ 13,
660
+ 12,
661
+ 11,
662
+ 14,
663
+ 2,
664
+ 6,
665
+ 5,
666
+ 10,
667
+ 4,
668
+ 0,
669
+ 15,
670
+ 8,
671
+ 9,
672
+ 0,
673
+ 5,
674
+ 7,
675
+ 2,
676
+ 4,
677
+ 10,
678
+ 15,
679
+ 14,
680
+ 1,
681
+ 11,
682
+ 12,
683
+ 6,
684
+ 8,
685
+ 3,
686
+ 13,
687
+ 2,
688
+ 12,
689
+ 6,
690
+ 10,
691
+ 0,
692
+ 11,
693
+ 8,
694
+ 3,
695
+ 4,
696
+ 13,
697
+ 7,
698
+ 5,
699
+ 15,
700
+ 14,
701
+ 1,
702
+ 9,
703
+ 12,
704
+ 5,
705
+ 1,
706
+ 15,
707
+ 14,
708
+ 13,
709
+ 4,
710
+ 10,
711
+ 0,
712
+ 7,
713
+ 6,
714
+ 3,
715
+ 9,
716
+ 2,
717
+ 8,
718
+ 11,
719
+ 13,
720
+ 11,
721
+ 7,
722
+ 14,
723
+ 12,
724
+ 1,
725
+ 3,
726
+ 9,
727
+ 5,
728
+ 0,
729
+ 15,
730
+ 4,
731
+ 8,
732
+ 6,
733
+ 2,
734
+ 10,
735
+ 6,
736
+ 15,
737
+ 14,
738
+ 9,
739
+ 11,
740
+ 3,
741
+ 0,
742
+ 8,
743
+ 12,
744
+ 2,
745
+ 13,
746
+ 7,
747
+ 1,
748
+ 4,
749
+ 10,
750
+ 5,
751
+ 10,
752
+ 2,
753
+ 8,
754
+ 4,
755
+ 7,
756
+ 6,
757
+ 1,
758
+ 5,
759
+ 15,
760
+ 11,
761
+ 9,
762
+ 14,
763
+ 3,
764
+ 12,
765
+ 13,
766
+ 0
767
+ ]);
768
+ var v = new Uint32Array(16);
769
+ var m = new Uint32Array(16);
770
+ function blake2sCompress(ctx, last) {
771
+ let i = 0;
772
+ for (i = 0; i < 8; i++) {
773
+ v[i] = ctx.h[i];
774
+ v[i + 8] = BLAKE2S_IV[i];
775
+ }
776
+ v[12] ^= ctx.t;
777
+ v[13] ^= ctx.t / 4294967296;
778
+ if (last) {
779
+ v[14] = ~v[14];
780
+ }
781
+ for (i = 0; i < 16; i++) {
782
+ m[i] = B2S_GET32(ctx.b, 4 * i);
783
+ }
784
+ for (i = 0; i < 10; i++) {
785
+ B2S_G(0, 4, 8, 12, m[SIGMA[i * 16 + 0]], m[SIGMA[i * 16 + 1]]);
786
+ B2S_G(1, 5, 9, 13, m[SIGMA[i * 16 + 2]], m[SIGMA[i * 16 + 3]]);
787
+ B2S_G(2, 6, 10, 14, m[SIGMA[i * 16 + 4]], m[SIGMA[i * 16 + 5]]);
788
+ B2S_G(3, 7, 11, 15, m[SIGMA[i * 16 + 6]], m[SIGMA[i * 16 + 7]]);
789
+ B2S_G(0, 5, 10, 15, m[SIGMA[i * 16 + 8]], m[SIGMA[i * 16 + 9]]);
790
+ B2S_G(1, 6, 11, 12, m[SIGMA[i * 16 + 10]], m[SIGMA[i * 16 + 11]]);
791
+ B2S_G(2, 7, 8, 13, m[SIGMA[i * 16 + 12]], m[SIGMA[i * 16 + 13]]);
792
+ B2S_G(3, 4, 9, 14, m[SIGMA[i * 16 + 14]], m[SIGMA[i * 16 + 15]]);
793
+ }
794
+ for (i = 0; i < 8; i++) {
795
+ ctx.h[i] ^= v[i] ^ v[i + 8];
796
+ }
797
+ }
798
+ function blake2sInit(outlen, key) {
799
+ if (!(outlen > 0 && outlen <= 32)) {
800
+ throw new Error("Incorrect output length, should be in [1, 32]");
801
+ }
802
+ const keylen = key ? key.length : 0;
803
+ if (key && !(keylen > 0 && keylen <= 32)) {
804
+ throw new Error("Incorrect key length, should be in [1, 32]");
805
+ }
806
+ const ctx = {
807
+ h: new Uint32Array(BLAKE2S_IV),
808
+ // hash state
809
+ b: new Uint8Array(64),
810
+ // input block
811
+ c: 0,
812
+ // pointer within block
813
+ t: 0,
814
+ // input count
815
+ outlen
816
+ // output length in bytes
817
+ };
818
+ ctx.h[0] ^= 16842752 ^ keylen << 8 ^ outlen;
819
+ if (keylen > 0) {
820
+ blake2sUpdate(ctx, key);
821
+ ctx.c = 64;
822
+ }
823
+ return ctx;
824
+ }
825
+ function blake2sUpdate(ctx, input) {
826
+ for (let i = 0; i < input.length; i++) {
827
+ if (ctx.c === 64) {
828
+ ctx.t += ctx.c;
829
+ blake2sCompress(ctx, false);
830
+ ctx.c = 0;
831
+ }
832
+ ctx.b[ctx.c++] = input[i];
833
+ }
834
+ }
835
+ function blake2sFinal(ctx) {
836
+ ctx.t += ctx.c;
837
+ while (ctx.c < 64) {
838
+ ctx.b[ctx.c++] = 0;
839
+ }
840
+ blake2sCompress(ctx, true);
841
+ const out = new Uint8Array(ctx.outlen);
842
+ for (let i = 0; i < ctx.outlen; i++) {
843
+ out[i] = ctx.h[i >> 2] >> 8 * (i & 3) & 255;
844
+ }
845
+ return out;
846
+ }
847
+ function blake2s(input, key, outlen) {
848
+ outlen = outlen || 32;
849
+ input = util.normalizeInput(input);
850
+ const ctx = blake2sInit(outlen, key);
851
+ blake2sUpdate(ctx, input);
852
+ return blake2sFinal(ctx);
853
+ }
854
+ function blake2sHex(input, key, outlen) {
855
+ const output = blake2s(input, key, outlen);
856
+ return util.toHex(output);
857
+ }
858
+ module.exports = {
859
+ blake2s,
860
+ blake2sHex,
861
+ blake2sInit,
862
+ blake2sUpdate,
863
+ blake2sFinal
864
+ };
865
+ }
866
+ });
867
+
868
+ // ../../node_modules/blakejs/index.js
869
+ var require_blakejs = __commonJS({
870
+ "../../node_modules/blakejs/index.js"(exports, module) {
871
+ "use strict";
872
+ var b2b = require_blake2b();
873
+ var b2s = require_blake2s();
874
+ module.exports = {
875
+ blake2b: b2b.blake2b,
876
+ blake2bHex: b2b.blake2bHex,
877
+ blake2bInit: b2b.blake2bInit,
878
+ blake2bUpdate: b2b.blake2bUpdate,
879
+ blake2bFinal: b2b.blake2bFinal,
880
+ blake2s: b2s.blake2s,
881
+ blake2sHex: b2s.blake2sHex,
882
+ blake2sInit: b2s.blake2sInit,
883
+ blake2sUpdate: b2s.blake2sUpdate,
884
+ blake2sFinal: b2s.blake2sFinal
885
+ };
886
+ }
887
+ });
888
+
889
+ // src/index.ts
890
+ import { Cardano as Cardano4, Serialization as Serialization5 } from "@cardano-sdk/core";
891
+
892
+ // src/stricahq/index.ts
893
+ import strica2 from "@stricahq/bip32ed25519";
894
+
895
+ // src/stricahq/coseSign1.ts
896
+ var import_blakejs = __toESM(require_blakejs(), 1);
897
+ import { Buffer as Buffer2 } from "buffer";
898
+ import { PublicKey } from "@stricahq/bip32ed25519";
899
+ import { Decoder, Encoder } from "@stricahq/cbors";
900
+ var CoseSign1 = class _CoseSign1 {
901
+ protectedMap;
902
+ unProtectedMap;
903
+ payload;
904
+ signature;
905
+ constructor(payload) {
906
+ this.protectedMap = payload.protectedMap;
907
+ this.unProtectedMap = payload.unProtectedMap;
908
+ this.payload = payload.payload;
909
+ if (this.unProtectedMap.get("hashed") == null) {
910
+ this.unProtectedMap.set("hashed", false);
911
+ }
912
+ this.signature = payload.signature;
913
+ }
914
+ static fromCbor(cbor) {
915
+ const decoded = Decoder.decode(Buffer2.from(cbor, "hex"));
916
+ if (!(decoded.value instanceof Array)) throw Error("Invalid CBOR");
917
+ if (decoded.value.length !== 4) throw Error("Invalid COSE_SIGN1");
918
+ let protectedMap;
919
+ const protectedSerialized = decoded.value[0];
920
+ try {
921
+ protectedMap = Decoder.decode(protectedSerialized).value;
922
+ if (!(protectedMap instanceof Map)) {
923
+ throw Error();
924
+ }
925
+ } catch (error) {
926
+ throw Error("Invalid protected");
927
+ }
928
+ const unProtectedMap = decoded.value[1];
929
+ if (!(unProtectedMap instanceof Map)) throw Error("Invalid unprotected");
930
+ const payload = decoded.value[2];
931
+ const signature = decoded.value[3];
932
+ return new _CoseSign1({
933
+ protectedMap,
934
+ unProtectedMap,
935
+ payload,
936
+ signature
937
+ });
938
+ }
939
+ createSigStructure(externalAad = Buffer2.alloc(0)) {
940
+ let protectedSerialized = Buffer2.alloc(0);
941
+ if (this.protectedMap.size !== 0) {
942
+ protectedSerialized = Encoder.encode(this.protectedMap);
943
+ }
944
+ const structure = [
945
+ "Signature1",
946
+ protectedSerialized,
947
+ externalAad,
948
+ this.payload
949
+ ];
950
+ return Encoder.encode(structure);
951
+ }
952
+ buildMessage(signature) {
953
+ this.signature = signature;
954
+ let protectedSerialized = Buffer2.alloc(0);
955
+ if (this.protectedMap.size !== 0) {
956
+ protectedSerialized = Encoder.encode(this.protectedMap);
957
+ }
958
+ const coseSign1 = [
959
+ protectedSerialized,
960
+ this.unProtectedMap,
961
+ this.payload,
962
+ this.signature
963
+ ];
964
+ return Encoder.encode(coseSign1);
965
+ }
966
+ verifySignature({
967
+ externalAad = Buffer2.alloc(0),
968
+ publicKeyBuffer
969
+ } = {}) {
970
+ if (!publicKeyBuffer) {
971
+ publicKeyBuffer = this.getPublicKey();
972
+ }
973
+ if (!publicKeyBuffer) throw Error("Public key not found");
974
+ if (!this.signature) throw Error("Signature not found");
975
+ const publicKey = new PublicKey(publicKeyBuffer);
976
+ return publicKey.verify(
977
+ this.signature,
978
+ this.createSigStructure(externalAad)
979
+ );
980
+ }
981
+ hashPayload() {
982
+ if (!this.unProtectedMap) throw Error("Invalid unprotected map");
983
+ if (!this.payload) throw Error("Invalid payload");
984
+ if (this.unProtectedMap.get("hashed"))
985
+ throw Error("Payload already hashed");
986
+ if (this.unProtectedMap.get("hashed") != false)
987
+ throw Error("Invalid unprotected map");
988
+ this.unProtectedMap.set("hashed", true);
989
+ const hash2 = (0, import_blakejs.blake2b)(this.payload, void 0, 24);
990
+ this.payload = Buffer2.from(hash2);
991
+ }
992
+ getAddress() {
993
+ return this.protectedMap.get("address");
994
+ }
995
+ getPublicKey() {
996
+ return this.protectedMap.get(4);
997
+ }
998
+ getSignature() {
999
+ return this.signature;
1000
+ }
1001
+ getPayload() {
1002
+ return this.payload;
1003
+ }
1004
+ };
1005
+ var getPublicKeyFromCoseKey = (cbor) => {
1006
+ const decodedCoseKey = Decoder.decode(Buffer2.from(cbor, "hex"));
1007
+ const publicKeyBuffer = decodedCoseKey.value.get(-2);
1008
+ if (publicKeyBuffer) {
1009
+ return publicKeyBuffer;
1010
+ }
1011
+ throw Error("Public key not found");
1012
+ };
1013
+ var getCoseKeyFromPublicKey = (cbor) => {
1014
+ const coseKeyMap = /* @__PURE__ */ new Map();
1015
+ coseKeyMap.set(1, 1);
1016
+ coseKeyMap.set(3, -8);
1017
+ coseKeyMap.set(6, -2);
1018
+ coseKeyMap.set(-2, Buffer2.from(cbor, "hex"));
1019
+ return Encoder.encode(coseKeyMap);
1020
+ };
1021
+
1022
+ // src/stricahq/privateKey.ts
1023
+ import strica from "@stricahq/bip32ed25519";
1024
+ import hash from "hash.js";
1025
+ var PrivateKey = class extends strica.PrivateKey {
1026
+ constructor(privKey, extended = true) {
1027
+ if (!extended) {
1028
+ let extendedSecret = hash.sha512().update(privKey).digest();
1029
+ if (extendedSecret[0] && extendedSecret[31]) {
1030
+ extendedSecret[0] &= 248;
1031
+ extendedSecret[31] &= 63;
1032
+ extendedSecret[31] |= 64;
1033
+ }
1034
+ privKey = Buffer.from(extendedSecret);
1035
+ }
1036
+ super(privKey);
1037
+ }
1038
+ };
1039
+
1040
+ // src/stricahq/index.ts
1041
+ var { PublicKey: PublicKey2, Bip32PrivateKey, Bip32PublicKey } = strica2;
1042
+
1043
+ // src/types/cardano-sdk.ts
1044
+ import { Cardano, Serialization } from "@cardano-sdk/core";
1045
+ import * as Crypto from "@cardano-sdk/crypto";
1046
+ import { typedHex } from "@cardano-sdk/util";
1047
+ var Slot = Cardano.Slot;
1048
+ var Value = Serialization.Value;
1049
+ var Transaction = Serialization.Transaction;
1050
+ var TransactionId = Cardano.TransactionId;
1051
+ var TransactionBody = Serialization.TransactionBody;
1052
+ var TransactionWitnessSet = Serialization.TransactionWitnessSet;
1053
+ var TransactionUnspentOutput = Serialization.TransactionUnspentOutput;
1054
+ var TransactionInput = Serialization.TransactionInput;
1055
+ var TransactionOutput = Serialization.TransactionOutput;
1056
+ var PlutusData = Serialization.PlutusData;
1057
+ var PlutusList = Serialization.PlutusList;
1058
+ var PlutusMap = Serialization.PlutusMap;
1059
+ var Redeemers = Serialization.Redeemers;
1060
+ var Redeemer = Serialization.Redeemer;
1061
+ var RedeemerPurpose = Cardano.RedeemerPurpose;
1062
+ var RedeemerTag = Serialization.RedeemerTag;
1063
+ var Script = Serialization.Script;
1064
+ var PolicyId = Cardano.PolicyId;
1065
+ var AssetName = Cardano.AssetName;
1066
+ var AssetId = Cardano.AssetId;
1067
+ var ScriptHash = Crypto.Hash28ByteBase16;
1068
+ var Address = Cardano.Address;
1069
+ var RewardAddress = Cardano.RewardAddress;
1070
+ var AddressType = Cardano.AddressType;
1071
+ var BaseAddress = Cardano.BaseAddress;
1072
+ var EnterpriseAddress = Cardano.EnterpriseAddress;
1073
+ var PaymentAddress = Cardano.PaymentAddress;
1074
+ var AssetFingerprint = Cardano.AssetFingerprint;
1075
+ var Credential = Serialization.Credential;
1076
+ var Ed25519PublicKeyHex2 = Crypto.Ed25519PublicKeyHex;
1077
+ var Ed25519PrivateNormalKeyHex = (value) => typedHex(value, 64);
1078
+ var Ed25519PrivateExtendedKeyHex = (value) => typedHex(value, 128);
1079
+ var Ed25519KeyHash2 = Crypto.Ed25519KeyHash;
1080
+ var Ed25519KeyHashHex2 = Crypto.Ed25519KeyHashHex;
1081
+ var Hash28ByteBase162 = Crypto.Hash28ByteBase16;
1082
+ var Hash32ByteBase162 = Crypto.Hash32ByteBase16;
1083
+ var CredentialType = Cardano.CredentialType;
1084
+ var Certificate = Serialization.Certificate;
1085
+ var PoolId = Cardano.PoolId;
1086
+ var StakeRegistration = Serialization.StakeRegistration;
1087
+ var StakeDelegation = Serialization.StakeDelegation;
1088
+ var CertificateType = Cardano.CertificateType;
1089
+ var VkeyWitness = Serialization.VkeyWitness;
1090
+ var Ed25519SignatureHex2 = Crypto.Ed25519SignatureHex;
1091
+ var Ed25519PublicKey2 = Crypto.Ed25519PublicKey;
1092
+ var Ed25519Signature2 = Crypto.Ed25519Signature;
1093
+ var Bip32PrivateKey3 = Crypto.Bip32PrivateKey;
1094
+ var Bip32PrivateKeyHex2 = Crypto.Bip32PrivateKeyHex;
1095
+ var PlutusLanguageVersion = Cardano.PlutusLanguageVersion;
1096
+ var NativeScript = Serialization.NativeScript;
1097
+ var PlutusV1Script = Serialization.PlutusV1Script;
1098
+ var PlutusV2Script = Serialization.PlutusV2Script;
1099
+ var PlutusV3Script = Serialization.PlutusV3Script;
1100
+ var Costmdls = Serialization.Costmdls;
1101
+ var CostModel = Serialization.CostModel;
1102
+ var CborWriter = Serialization.CborWriter;
1103
+ var ConstrPlutusData = Serialization.ConstrPlutusData;
1104
+ var RewardAccount = Cardano.RewardAccount;
1105
+ var Hash = Serialization.Hash;
1106
+ var DatumHash = Crypto.Hash32ByteBase16;
1107
+ var Datum = Serialization.Datum;
1108
+ var ExUnits = Serialization.ExUnits;
1109
+ var NetworkId = Cardano.NetworkId;
1110
+ var DatumKind = Serialization.DatumKind;
1111
+ var CborSet = Serialization.CborSet;
1112
+ var RequireAllOf = Cardano.NativeScriptKind.RequireAllOf;
1113
+ var RequireAnyOf = Cardano.NativeScriptKind.RequireAnyOf;
1114
+ var RequireNOf = Cardano.NativeScriptKind.RequireNOf;
1115
+ var RequireSignature = Cardano.NativeScriptKind.RequireSignature;
1116
+ var RequireTimeAfter = Cardano.NativeScriptKind.RequireTimeAfter;
1117
+ var RequireTimeBefore = Cardano.NativeScriptKind.RequireTimeBefore;
1118
+ var VrfVkBech32 = Cardano.VrfVkBech32;
1119
+ var ScriptPubkey = Serialization.ScriptPubkey;
1120
+ var DRepID = Cardano.DRepID;
1121
+
1122
+ // ../../node_modules/nanoid/index.js
1123
+ import crypto from "crypto";
1124
+ var POOL_SIZE_MULTIPLIER = 128;
1125
+ var pool;
1126
+ var poolOffset;
1127
+ var fillPool = (bytes) => {
1128
+ if (!pool || pool.length < bytes) {
1129
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
1130
+ crypto.randomFillSync(pool);
1131
+ poolOffset = 0;
1132
+ } else if (poolOffset + bytes > pool.length) {
1133
+ crypto.randomFillSync(pool);
1134
+ poolOffset = 0;
1135
+ }
1136
+ poolOffset += bytes;
1137
+ };
1138
+ var random = (bytes) => {
1139
+ fillPool(bytes -= 0);
1140
+ return pool.subarray(poolOffset - bytes, poolOffset);
1141
+ };
1142
+ var customRandom = (alphabet, defaultSize, getRandom) => {
1143
+ let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
1144
+ let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
1145
+ return (size = defaultSize) => {
1146
+ let id = "";
1147
+ while (true) {
1148
+ let bytes = getRandom(step);
1149
+ let i = step;
1150
+ while (i--) {
1151
+ id += alphabet[bytes[i] & mask] || "";
1152
+ if (id.length === size) return id;
1153
+ }
1154
+ }
1155
+ };
1156
+ };
1157
+ var customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random);
1158
+
1159
+ // src/message-signing/index.ts
1160
+ import { stringToHex } from "@meshsdk/common";
1161
+ var signData = (data, signer) => {
1162
+ const payload = Buffer.from(data, "hex");
1163
+ const publicKey = signer.key.toPublicKey().toBytes();
1164
+ const protectedMap = /* @__PURE__ */ new Map();
1165
+ protectedMap.set(1, -8);
1166
+ protectedMap.set(4, publicKey);
1167
+ protectedMap.set("address", Buffer.from(signer.address.toBytes(), "hex"));
1168
+ const coseSign1Builder = new CoseSign1({
1169
+ protectedMap,
1170
+ unProtectedMap: /* @__PURE__ */ new Map(),
1171
+ payload
1172
+ });
1173
+ const signature = signer.key.sign(coseSign1Builder.createSigStructure());
1174
+ const coseSignature = coseSign1Builder.buildMessage(signature).toString("hex");
1175
+ return {
1176
+ key: getCoseKeyFromPublicKey(publicKey.toString("hex")).toString("hex"),
1177
+ signature: coseSignature
1178
+ };
1179
+ };
1180
+ var checkSignature = (data, { key, signature }) => {
1181
+ const builder = CoseSign1.fromCbor(signature);
1182
+ if (builder.getPayload() === null) {
1183
+ return false;
1184
+ }
1185
+ if (Buffer.from(data, "hex").compare(builder.getPayload()) !== 0) {
1186
+ return false;
1187
+ }
1188
+ return builder.verifySignature({
1189
+ publicKeyBuffer: getPublicKeyFromCoseKey(key)
1190
+ });
1191
+ };
1192
+ var generateNonce = (label = "", length = 32) => {
1193
+ if (length <= 0 || length > 2048) {
1194
+ throw new Error("Length must be bewteen 1 and 2048");
1195
+ }
1196
+ const randomString = customAlphabet(
1197
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
1198
+ );
1199
+ const payload = randomString(length);
1200
+ return stringToHex(`${label}${payload}`);
1201
+ };
1202
+
1203
+ // src/resolvers/index.ts
1204
+ import { Cardano as Cardano2 } from "@cardano-sdk/core";
1205
+ import { blake2b as blake2b3 } from "@cardano-sdk/crypto";
1206
+ import { HexBlob as HexBlob4 } from "@cardano-sdk/util";
1207
+
1208
+ // src/utils/builder.ts
1209
+ import { blake2b as blake2b2 } from "@cardano-sdk/crypto";
1210
+ import { HexBlob } from "@cardano-sdk/util";
1211
+ import { pbkdf2Sync } from "pbkdf2";
1212
+ import { HARDENED_KEY_START } from "@meshsdk/common";
1213
+ var buildBaseAddress = (networkId, paymentKeyHash, stakeKeyHash) => {
1214
+ return BaseAddress.fromCredentials(
1215
+ networkId,
1216
+ {
1217
+ hash: paymentKeyHash,
1218
+ type: CredentialType.KeyHash
1219
+ },
1220
+ {
1221
+ hash: stakeKeyHash,
1222
+ type: CredentialType.KeyHash
1223
+ }
1224
+ );
1225
+ };
1226
+ var buildEnterpriseAddress = (networkId, paymentKeyHash) => {
1227
+ return EnterpriseAddress.fromCredentials(networkId, {
1228
+ hash: paymentKeyHash,
1229
+ type: CredentialType.KeyHash
1230
+ });
1231
+ };
1232
+ var buildBip32PrivateKey = (entropy, password = "") => {
1233
+ const PBKDF2_ITERATIONS = 4096;
1234
+ const PBKDF2_KEY_SIZE = 96;
1235
+ const PBKDF2_DIGEST_ALGORITHM = "sha512";
1236
+ const clampScalar = (scalar) => {
1237
+ if (scalar[0] !== void 0) {
1238
+ scalar[0] &= 248;
1239
+ }
1240
+ if (scalar[31] !== void 0) {
1241
+ scalar[31] &= 31;
1242
+ scalar[31] |= 64;
1243
+ }
1244
+ return scalar;
1245
+ };
1246
+ const _entropy = Buffer.from(entropy, "hex");
1247
+ const xprv = pbkdf2Sync(
1248
+ password,
1249
+ _entropy,
1250
+ PBKDF2_ITERATIONS,
1251
+ PBKDF2_KEY_SIZE,
1252
+ PBKDF2_DIGEST_ALGORITHM
1253
+ );
1254
+ return Bip32PrivateKey3.fromBytes(clampScalar(xprv));
1255
+ };
1256
+ var buildRewardAddress = (networkId, stakeKeyHash) => {
1257
+ const cred = {
1258
+ type: CredentialType.KeyHash,
1259
+ hash: stakeKeyHash
1260
+ };
1261
+ return RewardAddress.fromCredentials(networkId, cred);
1262
+ };
1263
+ var buildKeys = (entropy, accountIndex, keyIndex = 0) => {
1264
+ if (typeof entropy === "string") {
1265
+ const rootKey = new Bip32PrivateKey(Buffer.from(entropy, "hex"));
1266
+ const accountKey = rootKey.derive(HARDENED_KEY_START + 1852).derive(HARDENED_KEY_START + 1815).derive(HARDENED_KEY_START + accountIndex);
1267
+ const paymentKey = accountKey.derive(0).derive(keyIndex).toPrivateKey();
1268
+ const stakeKey = accountKey.derive(2).derive(0).toPrivateKey();
1269
+ return { paymentKey, stakeKey };
1270
+ } else {
1271
+ const paymentKey = new PrivateKey(
1272
+ Buffer.from(entropy[0], "hex"),
1273
+ false
1274
+ );
1275
+ const stakeKey = new PrivateKey(
1276
+ Buffer.from(entropy[1], "hex"),
1277
+ false
1278
+ );
1279
+ return { paymentKey, stakeKey };
1280
+ }
1281
+ };
1282
+ var buildScriptPubkey = (keyHash) => {
1283
+ const scriptPubkey = new ScriptPubkey(Ed25519KeyHashHex2(keyHash.hex()));
1284
+ return NativeScript.newScriptPubkey(scriptPubkey);
1285
+ };
1286
+ var buildDRepID = (dRepKey, networkId = NetworkId.Testnet, addressType = AddressType.EnterpriseKey) => {
1287
+ const dRepKeyBytes = Buffer.from(dRepKey, "hex");
1288
+ const dRepIdHex = blake2b2(28).update(dRepKeyBytes).digest("hex");
1289
+ const paymentAddress = EnterpriseAddress.packParts({
1290
+ networkId,
1291
+ paymentPart: {
1292
+ hash: Hash28ByteBase162(dRepIdHex),
1293
+ type: CredentialType.KeyHash
1294
+ },
1295
+ type: addressType
1296
+ });
1297
+ return HexBlob.toTypedBech32(
1298
+ "drep",
1299
+ HexBlob.fromBytes(paymentAddress)
1300
+ );
1301
+ };
1302
+
1303
+ // src/utils/converter.ts
1304
+ import { Serialization as Serialization2 } from "@cardano-sdk/core";
1305
+ import { Ed25519KeyHash as Ed25519KeyHash4 } from "@cardano-sdk/crypto";
1306
+ import { HexBlob as HexBlob3 } from "@cardano-sdk/util";
1307
+ import {
1308
+ toBytes as toBytes2
1309
+ } from "@meshsdk/common";
1310
+
1311
+ // src/utils/deserializer.ts
1312
+ import { TxCBOR } from "@cardano-sdk/core";
1313
+ import { Ed25519KeyHashHex as Ed25519KeyHashHex3 } from "@cardano-sdk/crypto";
1314
+ import { HexBlob as HexBlob2 } from "@cardano-sdk/util";
1315
+ import { toBytes } from "@meshsdk/common";
1316
+ var deserializeAddress = (address) => {
1317
+ const _address = Address.fromString(address);
1318
+ if (_address === null) throw new Error("Invalid address");
1319
+ return _address;
1320
+ };
1321
+ var deserializeEd25519KeyHash = (ed25519KeyHash) => Ed25519KeyHash2.fromBytes(toBytes(ed25519KeyHash));
1322
+ var deserializeDataHash = (dataHash) => DatumHash.fromHexBlob(HexBlob2(dataHash));
1323
+ var deserializePlutusData = (plutusData) => PlutusData.fromCbor(HexBlob2(plutusData));
1324
+ var deserializePlutusScript = (plutusScript, version) => {
1325
+ switch (version) {
1326
+ case "V1":
1327
+ return PlutusV1Script.fromCbor(HexBlob2(plutusScript));
1328
+ case "V2":
1329
+ return PlutusV2Script.fromCbor(HexBlob2(plutusScript));
1330
+ case "V3":
1331
+ return PlutusV3Script.fromCbor(HexBlob2(plutusScript));
1332
+ default:
1333
+ throw new Error("Invalid Plutus script version");
1334
+ }
1335
+ };
1336
+ var deserializeNativeScript = (nativeScript) => NativeScript.fromCbor(HexBlob2(nativeScript));
1337
+ var deserializeScriptHash = (scriptHash) => ScriptHash.fromEd25519KeyHashHex(Ed25519KeyHashHex3(scriptHash));
1338
+ var deserializeScriptRef = (scriptRef) => Script.fromCbor(HexBlob2(scriptRef));
1339
+ var deserializeTxUnspentOutput = (txUnspentOutput) => TransactionUnspentOutput.fromCbor(HexBlob2(txUnspentOutput));
1340
+ var deserializeValue = (value) => Value.fromCbor(HexBlob2(value));
1341
+ var deserializeTx = (tx) => Transaction.fromCbor(TxCBOR(tx));
1342
+ var deserializeTxHash = (txHash) => TransactionId.fromHexBlob(HexBlob2(txHash));
1343
+
1344
+ // src/utils/converter.ts
1345
+ var toAddress = (bech32) => Address.fromBech32(bech32);
1346
+ var toBaseAddress = (bech32) => {
1347
+ return BaseAddress.fromAddress(toAddress(bech32));
1348
+ };
1349
+ var toEnterpriseAddress = (bech32) => {
1350
+ return EnterpriseAddress.fromAddress(toAddress(bech32));
1351
+ };
1352
+ var toRewardAddress = (bech32) => RewardAddress.fromAddress(toAddress(bech32));
1353
+ var fromTxUnspentOutput = (txUnspentOutput) => {
1354
+ const dataHash = txUnspentOutput.output().datum() ? txUnspentOutput.output().datum()?.toCbor().toString() : void 0;
1355
+ const scriptRef = txUnspentOutput.output().scriptRef() ? txUnspentOutput.output().scriptRef()?.toCbor().toString() : void 0;
1356
+ const plutusData = txUnspentOutput.output().datum()?.asInlineData() ? txUnspentOutput.output().datum()?.asInlineData()?.toCbor().toString() : void 0;
1357
+ return {
1358
+ input: {
1359
+ outputIndex: Number(txUnspentOutput.input().index()),
1360
+ txHash: txUnspentOutput.input().transactionId()
1361
+ },
1362
+ output: {
1363
+ address: txUnspentOutput.output().address().toBech32(),
1364
+ amount: fromValue(txUnspentOutput.output().amount()),
1365
+ dataHash,
1366
+ // todo not sure if correct
1367
+ plutusData,
1368
+ // todo not sure if correct
1369
+ scriptRef
1370
+ // todo not sure if correct
1371
+ }
1372
+ };
1373
+ };
1374
+ var toTxUnspentOutput = (utxo) => {
1375
+ const txInput = new TransactionInput(
1376
+ deserializeTxHash(utxo.input.txHash),
1377
+ BigInt(utxo.input.outputIndex)
1378
+ );
1379
+ const txOutput = new TransactionOutput(
1380
+ toAddress(utxo.output.address),
1381
+ toValue(utxo.output.amount)
1382
+ );
1383
+ if (utxo.output.dataHash !== void 0) {
1384
+ txOutput.setDatum(
1385
+ Datum.fromCore(deserializeDataHash(utxo.output.dataHash))
1386
+ );
1387
+ }
1388
+ if (utxo.output.plutusData !== void 0) {
1389
+ const plutusData = deserializePlutusData(utxo.output.plutusData);
1390
+ const datum = new Serialization2.Datum(void 0, plutusData);
1391
+ txOutput.setDatum(datum);
1392
+ }
1393
+ if (utxo.output.scriptRef !== void 0) {
1394
+ txOutput.setScriptRef(deserializeScriptRef(utxo.output.scriptRef));
1395
+ }
1396
+ return new TransactionUnspentOutput(txInput, txOutput);
1397
+ };
1398
+ var addressToBech32 = (address) => {
1399
+ return address.toBech32();
1400
+ };
1401
+ var fromValue = (value) => {
1402
+ const assets = [
1403
+ { unit: "lovelace", quantity: value.coin().toString() }
1404
+ ];
1405
+ const multiAsset = value.multiasset();
1406
+ if (multiAsset !== void 0) {
1407
+ const _assets = Array.from(multiAsset.keys());
1408
+ for (let i = 0; i < _assets.length; i += 1) {
1409
+ const assetId = _assets[i];
1410
+ if (assetId !== void 0) {
1411
+ const assetQuantity = multiAsset.get(assetId);
1412
+ if (assetQuantity !== void 0) {
1413
+ assets.push({
1414
+ unit: assetId,
1415
+ quantity: assetQuantity.toString()
1416
+ });
1417
+ }
1418
+ }
1419
+ }
1420
+ }
1421
+ return assets;
1422
+ };
1423
+ var toScriptRef = (script) => {
1424
+ if ("code" in script) {
1425
+ const plutusScript = deserializePlutusScript(script.code, script.version);
1426
+ if (plutusScript instanceof PlutusV1Script)
1427
+ return Script.newPlutusV1Script(plutusScript);
1428
+ if (plutusScript instanceof PlutusV2Script)
1429
+ return Script.newPlutusV2Script(plutusScript);
1430
+ if (plutusScript instanceof PlutusV3Script)
1431
+ return Script.newPlutusV3Script(plutusScript);
1432
+ }
1433
+ return Script.newNativeScript(toNativeScript(script));
1434
+ };
1435
+ var fromScriptRef = (scriptRef) => {
1436
+ const script = Script.fromCbor(HexBlob3(scriptRef));
1437
+ const plutusScriptCodeV3 = script.asPlutusV3()?.toCbor().toString();
1438
+ if (plutusScriptCodeV3) {
1439
+ return {
1440
+ code: plutusScriptCodeV3,
1441
+ version: "V3"
1442
+ };
1443
+ }
1444
+ const plutusScriptCodeV2 = script.asPlutusV2()?.toCbor().toString();
1445
+ if (plutusScriptCodeV2) {
1446
+ return {
1447
+ code: plutusScriptCodeV2,
1448
+ version: "V2"
1449
+ };
1450
+ }
1451
+ const plutusScriptCodeV1 = script.asPlutusV1()?.toCbor().toString();
1452
+ if (plutusScriptCodeV1) {
1453
+ return {
1454
+ code: plutusScriptCodeV1,
1455
+ version: "V1"
1456
+ };
1457
+ }
1458
+ const nativeScript = script.asNative();
1459
+ if (!nativeScript) {
1460
+ throw new Error("Invalid script");
1461
+ }
1462
+ return fromNativeScript(nativeScript);
1463
+ };
1464
+ var fromNativeScript = (script) => {
1465
+ const fromNativeScripts = (scripts) => {
1466
+ const nativeScripts = new Array();
1467
+ for (let index = 0; index < scripts.length; index += 1) {
1468
+ const script2 = scripts[index];
1469
+ if (script2) {
1470
+ nativeScripts.push(fromNativeScript(script2));
1471
+ }
1472
+ }
1473
+ return nativeScripts;
1474
+ };
1475
+ switch (script.kind()) {
1476
+ case RequireAllOf: {
1477
+ const scriptAll = script.asScriptAll();
1478
+ return {
1479
+ type: "all",
1480
+ scripts: fromNativeScripts(scriptAll.nativeScripts())
1481
+ };
1482
+ }
1483
+ case RequireAnyOf: {
1484
+ const scriptAny = script.asScriptAny();
1485
+ return {
1486
+ type: "any",
1487
+ scripts: fromNativeScripts(scriptAny.nativeScripts())
1488
+ };
1489
+ }
1490
+ case RequireNOf: {
1491
+ const scriptNOfK = script.asScriptNOfK();
1492
+ return {
1493
+ type: "atLeast",
1494
+ required: scriptNOfK.required(),
1495
+ scripts: fromNativeScripts(scriptNOfK.nativeScripts())
1496
+ };
1497
+ }
1498
+ case RequireTimeAfter: {
1499
+ const timelockStart = script.asTimelockStart();
1500
+ return {
1501
+ type: "after",
1502
+ slot: timelockStart.slot().toString()
1503
+ };
1504
+ }
1505
+ case RequireTimeBefore: {
1506
+ const timelockExpiry = script.asTimelockExpiry();
1507
+ return {
1508
+ type: "before",
1509
+ slot: timelockExpiry.slot().toString()
1510
+ };
1511
+ }
1512
+ case RequireSignature: {
1513
+ const scriptPubkey = script.asScriptPubkey();
1514
+ return {
1515
+ type: "sig",
1516
+ keyHash: scriptPubkey.keyHash().toString()
1517
+ };
1518
+ }
1519
+ default:
1520
+ throw new Error(`Script Kind: ${script.kind()}, is not supported`);
1521
+ }
1522
+ };
1523
+ var toNativeScript = (script) => {
1524
+ const toNativeScripts = (scripts) => {
1525
+ const nativeScripts = [];
1526
+ scripts.forEach((script2) => {
1527
+ nativeScripts.push(toNativeScript(script2));
1528
+ });
1529
+ return nativeScripts;
1530
+ };
1531
+ switch (script.type) {
1532
+ case "all":
1533
+ return NativeScript.newScriptAll(
1534
+ new Serialization2.ScriptAll(toNativeScripts(script.scripts))
1535
+ );
1536
+ case "any":
1537
+ return NativeScript.newScriptAny(
1538
+ new Serialization2.ScriptAny(toNativeScripts(script.scripts))
1539
+ );
1540
+ case "atLeast":
1541
+ return NativeScript.newScriptNOfK(
1542
+ new Serialization2.ScriptNOfK(
1543
+ toNativeScripts(script.scripts),
1544
+ script.required
1545
+ )
1546
+ );
1547
+ case "after":
1548
+ return NativeScript.newTimelockStart(
1549
+ new Serialization2.TimelockStart(Slot(parseInt(script.slot)))
1550
+ );
1551
+ case "before":
1552
+ return NativeScript.newTimelockExpiry(
1553
+ new Serialization2.TimelockExpiry(Slot(parseInt(script.slot)))
1554
+ );
1555
+ case "sig":
1556
+ return NativeScript.newScriptPubkey(
1557
+ new Serialization2.ScriptPubkey(
1558
+ Ed25519KeyHash4.fromBytes(toBytes2(script.keyHash)).hex()
1559
+ )
1560
+ );
1561
+ }
1562
+ };
1563
+ var toPlutusData = (data) => {
1564
+ const toPlutusList = (data2) => {
1565
+ const plutusList = new PlutusList();
1566
+ data2.forEach((element) => {
1567
+ plutusList.add(toPlutusData(element));
1568
+ });
1569
+ return plutusList;
1570
+ };
1571
+ switch (typeof data) {
1572
+ case "string":
1573
+ return PlutusData.newBytes(toBytes2(data));
1574
+ case "number":
1575
+ return PlutusData.newInteger(BigInt(data));
1576
+ case "bigint":
1577
+ return PlutusData.newInteger(BigInt(data));
1578
+ case "object":
1579
+ if (data instanceof Array) {
1580
+ const plutusList = toPlutusList(data);
1581
+ return PlutusData.newList(plutusList);
1582
+ } else if (data instanceof Map) {
1583
+ const plutusMap = new PlutusMap();
1584
+ data.forEach((value, key) => {
1585
+ plutusMap.insert(toPlutusData(key), toPlutusData(value));
1586
+ });
1587
+ return PlutusData.newMap(plutusMap);
1588
+ } else {
1589
+ return PlutusData.newConstrPlutusData(
1590
+ new ConstrPlutusData(
1591
+ BigInt(data.alternative),
1592
+ toPlutusList(data.fields)
1593
+ )
1594
+ );
1595
+ }
1596
+ }
1597
+ };
1598
+ var toValue = (assets) => {
1599
+ const multiAsset = /* @__PURE__ */ new Map();
1600
+ assets.filter((asset) => asset.unit !== "lovelace").forEach((asset) => {
1601
+ multiAsset.set(AssetId(asset.unit), BigInt(asset.quantity));
1602
+ });
1603
+ const lovelace = assets.find((asset) => asset.unit === "lovelace");
1604
+ const value = new Value(BigInt(lovelace ? lovelace.quantity : 0));
1605
+ if (assets.length > 1 || !lovelace) {
1606
+ value.setMultiasset(multiAsset);
1607
+ }
1608
+ return value;
1609
+ };
1610
+
1611
+ // src/utils/value.ts
1612
+ function mergeValue(a, b) {
1613
+ const ma = a.multiasset() ?? /* @__PURE__ */ new Map();
1614
+ b.multiasset()?.forEach((v, k) => {
1615
+ const newVal = (ma.get(k) ?? 0n) + v;
1616
+ if (newVal == 0n) {
1617
+ ma.delete(k);
1618
+ } else {
1619
+ ma.set(k, newVal);
1620
+ }
1621
+ });
1622
+ return new Value(
1623
+ BigInt(a.coin()) + BigInt(b.coin()),
1624
+ ma.size > 0 ? ma : void 0
1625
+ );
1626
+ }
1627
+ function negateValue(v) {
1628
+ const entries = v.multiasset()?.entries();
1629
+ const tokenMap = /* @__PURE__ */ new Map();
1630
+ if (entries) {
1631
+ for (const entry of entries) {
1632
+ tokenMap.set(entry[0], -entry[1]);
1633
+ }
1634
+ }
1635
+ return new Value(-v.coin(), tokenMap);
1636
+ }
1637
+ function subValue(a, b) {
1638
+ return mergeValue(a, negateValue(b));
1639
+ }
1640
+ function negatives(v) {
1641
+ const entries = v.multiasset()?.entries();
1642
+ const coin = v.coin() < 0n ? v.coin() : 0n;
1643
+ const tokenMap = /* @__PURE__ */ new Map();
1644
+ if (entries) {
1645
+ for (const entry of entries) {
1646
+ if (entry[1] < 0n) {
1647
+ tokenMap.set(entry[0], entry[1]);
1648
+ }
1649
+ }
1650
+ }
1651
+ return new Value(coin, tokenMap);
1652
+ }
1653
+ function assetTypes(v) {
1654
+ let count = v.coin() == 0n ? 0 : 1;
1655
+ const entries = v.multiasset();
1656
+ if (entries) {
1657
+ entries.forEach(() => {
1658
+ count += 1;
1659
+ });
1660
+ }
1661
+ return count;
1662
+ }
1663
+ function empty(v) {
1664
+ return assetTypes(v) == 0;
1665
+ }
1666
+
1667
+ // src/utils/encoding.ts
1668
+ var hexToBytes = (hex) => Buffer.from(hex, "hex");
1669
+
1670
+ // src/resolvers/index.ts
1671
+ var resolveDataHash = (data) => {
1672
+ const plutusData = toPlutusData(data);
1673
+ return plutusData.hash().toString();
1674
+ };
1675
+ var resolveNativeScriptAddress = (script, networkId = 0) => {
1676
+ const nativeScript = toNativeScript(script);
1677
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
1678
+ hash: nativeScript.hash(),
1679
+ type: Cardano2.CredentialType.ScriptHash
1680
+ });
1681
+ return enterpriseAddress.toAddress().toBech32();
1682
+ };
1683
+ var resolveNativeScriptHash = (script) => {
1684
+ return toNativeScript(script).hash().toString();
1685
+ };
1686
+ var resolvePaymentKeyHash = (bech32) => {
1687
+ try {
1688
+ const paymentKeyHash = [
1689
+ toBaseAddress(bech32)?.getPaymentCredential().hash,
1690
+ toEnterpriseAddress(bech32)?.getPaymentCredential().hash
1691
+ ].find((kh) => kh !== void 0);
1692
+ if (paymentKeyHash !== void 0) return paymentKeyHash.toString();
1693
+ throw new Error(
1694
+ `Couldn't resolve payment key hash from address: ${bech32}`
1695
+ );
1696
+ } catch (error) {
1697
+ throw new Error(
1698
+ `An error occurred during resolvePaymentKeyHash: ${error}.`
1699
+ );
1700
+ }
1701
+ };
1702
+ var resolvePlutusScriptAddress = (script, networkId = 0) => {
1703
+ const plutusScript = deserializePlutusScript(script.code, script.version);
1704
+ const enterpriseAddress = EnterpriseAddress.fromCredentials(networkId, {
1705
+ hash: plutusScript.hash(),
1706
+ type: Cardano2.CredentialType.ScriptHash
1707
+ });
1708
+ return enterpriseAddress.toAddress().toBech32();
1709
+ };
1710
+ var resolvePlutusScriptHash = (bech32) => {
1711
+ try {
1712
+ const enterpriseAddress = toEnterpriseAddress(bech32);
1713
+ const scriptHash = enterpriseAddress?.getPaymentCredential().hash;
1714
+ if (scriptHash !== void 0) return scriptHash.toString();
1715
+ throw new Error(`Couldn't resolve script hash from address: ${bech32}`);
1716
+ } catch (error) {
1717
+ throw new Error(`An error occurred during resolveScriptHash: ${error}.`);
1718
+ }
1719
+ };
1720
+ var resolvePoolId = (hash2) => {
1721
+ return Ed25519KeyHashHex2(hash2).toString();
1722
+ };
1723
+ var resolvePrivateKey = (words) => {
1724
+ return "not implemented";
1725
+ };
1726
+ var resolveScriptRef = (script) => {
1727
+ return toScriptRef(script).toCbor().toString();
1728
+ };
1729
+ var resolveRewardAddress = (bech32) => {
1730
+ try {
1731
+ const address = toAddress(bech32);
1732
+ const baseAddress = toBaseAddress(bech32);
1733
+ const stakeKeyHash = baseAddress?.getStakeCredential().hash;
1734
+ if (stakeKeyHash !== void 0)
1735
+ return buildRewardAddress(address.getNetworkId(), stakeKeyHash).toAddress().toBech32();
1736
+ throw new Error(`Couldn't resolve reward address from address: ${bech32}`);
1737
+ } catch (error) {
1738
+ throw new Error(`An error occurred during resolveRewardAddress: ${error}.`);
1739
+ }
1740
+ };
1741
+ var resolveStakeKeyHash = (bech32) => {
1742
+ try {
1743
+ const stakeKeyHash = [
1744
+ toBaseAddress(bech32)?.getStakeCredential().hash,
1745
+ toRewardAddress(bech32)?.getPaymentCredential().hash
1746
+ ].find((kh) => kh !== void 0);
1747
+ if (stakeKeyHash !== void 0) return stakeKeyHash.toString();
1748
+ throw new Error(`Couldn't resolve stake key hash from address: ${bech32}`);
1749
+ } catch (error) {
1750
+ throw new Error(`An error occurred during resolveStakeKeyHash: ${error}.`);
1751
+ }
1752
+ };
1753
+ var resolveTxHash = (txHex) => {
1754
+ const txBody = deserializeTx(txHex).body();
1755
+ const hash2 = blake2b3(blake2b3.BYTES).update(hexToBytes(txBody.toCbor())).digest();
1756
+ return Cardano2.TransactionId.fromHexBlob(HexBlob4.fromBytes(hash2));
1757
+ };
1758
+
1759
+ // src/serializer/index.ts
1760
+ import { Serialization as Serialization4, TxCBOR as TxCBOR2 } from "@cardano-sdk/core";
1761
+ import { HexBlob as HexBlob6 } from "@cardano-sdk/util";
1762
+ import {
1763
+ DEFAULT_V1_COST_MODEL_LIST,
1764
+ DEFAULT_V2_COST_MODEL_LIST
1765
+ } from "@meshsdk/common";
1766
+
1767
+ // src/utils/script-data-hash.ts
1768
+ import { Serialization as Serialization3 } from "@cardano-sdk/core";
1769
+ import * as Crypto2 from "@cardano-sdk/crypto";
1770
+ import { Hash32ByteBase16 as Hash32ByteBase163 } from "@cardano-sdk/crypto";
1771
+ import { HexBlob as HexBlob5 } from "@cardano-sdk/util";
1772
+ var CBOR_EMPTY_LIST = new Uint8Array([128]);
1773
+ var CBOR_EMPTY_MAP = new Uint8Array([160]);
1774
+ var getCborEncodedArray = (items) => {
1775
+ const writer = new Serialization3.CborWriter();
1776
+ writer.writeStartArray(items.length);
1777
+ for (const item of items) {
1778
+ writer.writeEncodedValue(Buffer.from(item.toCbor(), "hex"));
1779
+ }
1780
+ return writer.encode();
1781
+ };
1782
+ var hashScriptData = (costModels, redemeers, datums) => {
1783
+ const writer = new Serialization3.CborWriter();
1784
+ if (datums && datums.length > 0 && (!redemeers || redemeers.length === 0)) {
1785
+ writer.writeEncodedValue(CBOR_EMPTY_LIST);
1786
+ writer.writeEncodedValue(getCborEncodedArray(datums));
1787
+ writer.writeEncodedValue(CBOR_EMPTY_MAP);
1788
+ } else {
1789
+ if (!redemeers || redemeers.length === 0) return void 0;
1790
+ writer.writeEncodedValue(getCborEncodedArray(redemeers));
1791
+ if (datums && datums.length > 0)
1792
+ writer.writeEncodedValue(getCborEncodedArray(datums));
1793
+ writer.writeEncodedValue(
1794
+ Buffer.from(costModels.languageViewsEncoding(), "hex")
1795
+ );
1796
+ }
1797
+ return Hash32ByteBase163.fromHexBlob(
1798
+ HexBlob5.fromBytes(
1799
+ Crypto2.blake2b(Crypto2.blake2b.BYTES).update(writer.encode()).digest()
1800
+ )
1801
+ );
1802
+ };
1803
+
1804
+ // src/serializer/index.ts
1805
+ var CardanoSDKSerializer = class {
1806
+ txBody;
1807
+ txWitnessSet;
1808
+ utxoContext = /* @__PURE__ */ new Map();
1809
+ redeemerContext = /* @__PURE__ */ new Map();
1810
+ scriptsProvided = /* @__PURE__ */ new Set();
1811
+ datumsProvided = /* @__PURE__ */ new Set();
1812
+ usedLanguages = {
1813
+ [0]: false,
1814
+ [1]: false,
1815
+ [2]: false
1816
+ };
1817
+ constructor() {
1818
+ this.txBody = new TransactionBody(
1819
+ Serialization4.CborSet.fromCore([], TransactionInput.fromCore),
1820
+ [],
1821
+ BigInt(0),
1822
+ void 0
1823
+ );
1824
+ this.txWitnessSet = new TransactionWitnessSet();
1825
+ }
1826
+ serializeRewardAddress(stakeKeyHash, isScriptHash, network_id) {
1827
+ throw new Error("Method not implemented.");
1828
+ }
1829
+ serializePoolId(hash2) {
1830
+ throw new Error("Method not implemented.");
1831
+ }
1832
+ serializeAddress(address, networkId) {
1833
+ throw new Error("Method not implemented.");
1834
+ }
1835
+ serializeData(data) {
1836
+ throw new Error("Method not implemented.");
1837
+ }
1838
+ deserializer = {
1839
+ key: {
1840
+ deserializeAddress: function(bech32) {
1841
+ throw new Error("Function not implemented.");
1842
+ }
1843
+ },
1844
+ script: {
1845
+ deserializeNativeScript: function(script) {
1846
+ throw new Error("Function not implemented.");
1847
+ },
1848
+ deserializePlutusScript: function(script) {
1849
+ throw new Error("Function not implemented.");
1850
+ }
1851
+ },
1852
+ cert: {
1853
+ deserializePoolId: function(poolId) {
1854
+ throw new Error("Function not implemented.");
1855
+ }
1856
+ }
1857
+ };
1858
+ resolver = {
1859
+ keys: {
1860
+ // resolvePaymentKeyHash: function (bech32: string): string {
1861
+ // const cardanoAddress = toAddress(bech32);
1862
+ // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
1863
+ // CredentialType.KeyHash
1864
+ // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
1865
+ // : "";
1866
+ // },
1867
+ // resolvePlutusScriptHash: function (bech32: string): string {
1868
+ // const cardanoAddress = toAddress(bech32);
1869
+ // return cardanoAddress.asEnterprise()?.getPaymentCredential().type ===
1870
+ // CredentialType.ScriptHash
1871
+ // ? cardanoAddress.asEnterprise()!.getPaymentCredential().hash
1872
+ // : "";
1873
+ // },
1874
+ resolveStakeKeyHash: function(bech32) {
1875
+ const cardanoAddress = toAddress(bech32);
1876
+ return cardanoAddress.asReward()?.getPaymentCredential().type === CredentialType.KeyHash ? cardanoAddress.asReward().getPaymentCredential().hash : "";
1877
+ },
1878
+ // resolveStakeScriptHash(bech32: string): string {
1879
+ // const cardanoAddress = toAddress(bech32);
1880
+ // return cardanoAddress.asReward()?.getPaymentCredential().type ===
1881
+ // CredentialType.ScriptHash
1882
+ // ? cardanoAddress.asReward()!.getPaymentCredential().hash
1883
+ // : "";
1884
+ // },
1885
+ resolvePrivateKey: function(words) {
1886
+ throw new Error("Function not implemented.");
1887
+ },
1888
+ resolveRewardAddress: function(bech32) {
1889
+ throw new Error("Function not implemented.");
1890
+ },
1891
+ resolveEd25519KeyHash: function(bech32) {
1892
+ throw new Error("Function not implemented.");
1893
+ }
1894
+ },
1895
+ tx: {
1896
+ resolveTxHash: function(txHex) {
1897
+ return Transaction.fromCbor(TxCBOR2(txHex)).getId();
1898
+ }
1899
+ },
1900
+ data: {
1901
+ resolveDataHash: function(data) {
1902
+ throw new Error("Function not implemented.");
1903
+ }
1904
+ },
1905
+ script: {
1906
+ // resolveNativeScript: function (script: CommonNativeScript): string {
1907
+ // return toNativeScript(script).toCbor();
1908
+ // },
1909
+ resolveScriptRef: function(script) {
1910
+ throw new Error("Function not implemented.");
1911
+ }
1912
+ }
1913
+ };
1914
+ serializeTxBody = (txBuilderBody, protocolParams) => {
1915
+ const {
1916
+ inputs,
1917
+ outputs,
1918
+ collaterals,
1919
+ referenceInputs,
1920
+ mints,
1921
+ changeAddress,
1922
+ // certificates,
1923
+ validityRange,
1924
+ requiredSignatures
1925
+ // metadata,
1926
+ } = txBuilderBody;
1927
+ mints.sort((a, b) => a.policyId.localeCompare(b.policyId));
1928
+ inputs.sort((a, b) => {
1929
+ if (a.txIn.txHash === b.txIn.txHash) {
1930
+ return a.txIn.txIndex - b.txIn.txIndex;
1931
+ } else {
1932
+ return a.txIn.txHash.localeCompare(b.txIn.txHash);
1933
+ }
1934
+ });
1935
+ this.addAllInputs(inputs);
1936
+ this.addAllOutputs(outputs);
1937
+ this.addAllMints(mints);
1938
+ this.addAllCollateralInputs(collaterals);
1939
+ this.addAllReferenceInputs(referenceInputs);
1940
+ this.setValidityInterval(validityRange);
1941
+ this.buildWitnessSet();
1942
+ this.balanceTx(changeAddress, requiredSignatures.length, protocolParams);
1943
+ return new Transaction(this.txBody, this.txWitnessSet).toCbor();
1944
+ };
1945
+ addSigningKeys = (txHex, signingKeys) => {
1946
+ let cardanoTx = Transaction.fromCbor(TxCBOR2(txHex));
1947
+ let currentWitnessSet = cardanoTx.witnessSet();
1948
+ let currentWitnessSetVkeys = currentWitnessSet.vkeys();
1949
+ let currentWitnessSetVkeysValues = currentWitnessSetVkeys ? [...currentWitnessSetVkeys.values()] : [];
1950
+ for (let i = 0; i < signingKeys.length; i++) {
1951
+ let keyHex = signingKeys[i];
1952
+ if (keyHex) {
1953
+ if (keyHex.length === 68 && keyHex.substring(0, 4) === "5820") {
1954
+ keyHex = keyHex.substring(4);
1955
+ }
1956
+ const cardanoSigner = new PrivateKey(
1957
+ Buffer.from(keyHex, "hex"),
1958
+ false
1959
+ );
1960
+ const signature = cardanoSigner.sign(
1961
+ Buffer.from(cardanoTx.getId(), "hex")
1962
+ );
1963
+ currentWitnessSetVkeysValues.push(
1964
+ new VkeyWitness(
1965
+ Ed25519PublicKeyHex2(
1966
+ cardanoSigner.toPublicKey().toBytes().toString("hex")
1967
+ ),
1968
+ Ed25519SignatureHex2(signature.toString("hex"))
1969
+ )
1970
+ );
1971
+ }
1972
+ }
1973
+ currentWitnessSet.setVkeys(
1974
+ Serialization4.CborSet.fromCore(
1975
+ currentWitnessSetVkeysValues.map((vkw) => vkw.toCore()),
1976
+ VkeyWitness.fromCore
1977
+ )
1978
+ );
1979
+ cardanoTx.setWitnessSet(currentWitnessSet);
1980
+ return cardanoTx.toCbor();
1981
+ };
1982
+ addAllInputs = (inputs) => {
1983
+ for (let i = 0; i < inputs.length; i += 1) {
1984
+ const currentTxIn = inputs[i];
1985
+ if (!currentTxIn) continue;
1986
+ switch (currentTxIn.type) {
1987
+ case "PubKey":
1988
+ this.addTxIn(currentTxIn);
1989
+ break;
1990
+ case "Script":
1991
+ this.addScriptTxIn(
1992
+ currentTxIn
1993
+ );
1994
+ break;
1995
+ case "SimpleScript":
1996
+ this.addSimpleScriptTxIn(
1997
+ currentTxIn
1998
+ );
1999
+ }
2000
+ }
2001
+ };
2002
+ addTxIn = (currentTxIn) => {
2003
+ let cardanoTxIn = new TransactionInput(
2004
+ TransactionId(currentTxIn.txIn.txHash),
2005
+ BigInt(currentTxIn.txIn.txIndex)
2006
+ );
2007
+ const inputs = this.txBody.inputs();
2008
+ const txInputsList = [...inputs.values()];
2009
+ if (txInputsList.find((input) => {
2010
+ input.index() == cardanoTxIn.index() && input.transactionId == cardanoTxIn.transactionId;
2011
+ })) {
2012
+ throw new Error("Duplicate input added to tx body");
2013
+ }
2014
+ txInputsList.push(cardanoTxIn);
2015
+ inputs.setValues(txInputsList);
2016
+ const cardanoTxOut = new TransactionOutput(
2017
+ Address.fromBech32(currentTxIn.txIn.address),
2018
+ toValue(currentTxIn.txIn.amount)
2019
+ );
2020
+ this.utxoContext.set(cardanoTxIn, cardanoTxOut);
2021
+ this.txBody.setInputs(inputs);
2022
+ };
2023
+ addScriptTxIn = (currentTxIn) => {
2024
+ this.addTxIn({
2025
+ type: "PubKey",
2026
+ txIn: currentTxIn.txIn
2027
+ });
2028
+ if (!currentTxIn.scriptTxIn.scriptSource) {
2029
+ throw new Error("A script input had no script source");
2030
+ }
2031
+ if (!currentTxIn.scriptTxIn.datumSource) {
2032
+ throw new Error("A script input had no datum source");
2033
+ }
2034
+ if (!currentTxIn.scriptTxIn.redeemer) {
2035
+ throw new Error("A script input had no redeemer");
2036
+ }
2037
+ if (currentTxIn.scriptTxIn.scriptSource.type === "Provided") {
2038
+ switch (currentTxIn.scriptTxIn.scriptSource.script.version) {
2039
+ case "V1": {
2040
+ this.scriptsProvided.add(
2041
+ Script.newPlutusV1Script(
2042
+ PlutusV1Script.fromCbor(
2043
+ HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2044
+ )
2045
+ )
2046
+ );
2047
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
2048
+ break;
2049
+ }
2050
+ case "V2": {
2051
+ this.scriptsProvided.add(
2052
+ Script.newPlutusV2Script(
2053
+ PlutusV2Script.fromCbor(
2054
+ HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2055
+ )
2056
+ )
2057
+ );
2058
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
2059
+ break;
2060
+ }
2061
+ case "V3": {
2062
+ this.scriptsProvided.add(
2063
+ Script.newPlutusV3Script(
2064
+ PlutusV3Script.fromCbor(
2065
+ HexBlob6(currentTxIn.scriptTxIn.scriptSource.script.code)
2066
+ )
2067
+ )
2068
+ );
2069
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
2070
+ break;
2071
+ }
2072
+ }
2073
+ } else if (currentTxIn.scriptTxIn.scriptSource.type === "Inline") {
2074
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2075
+ let referenceInputsList = [...referenceInputs.values()];
2076
+ referenceInputsList.push(
2077
+ new TransactionInput(
2078
+ TransactionId(currentTxIn.scriptTxIn.scriptSource.txHash),
2079
+ BigInt(currentTxIn.scriptTxIn.scriptSource.txIndex)
2080
+ )
2081
+ );
2082
+ referenceInputs.setValues(referenceInputsList);
2083
+ this.txBody.setReferenceInputs(referenceInputs);
2084
+ switch (currentTxIn.scriptTxIn.scriptSource.version) {
2085
+ case "V1": {
2086
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
2087
+ break;
2088
+ }
2089
+ case "V2": {
2090
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
2091
+ break;
2092
+ }
2093
+ case "V3": {
2094
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
2095
+ break;
2096
+ }
2097
+ }
2098
+ }
2099
+ if (currentTxIn.scriptTxIn.datumSource.type === "Provided") {
2100
+ this.datumsProvided.add(
2101
+ toPlutusData(currentTxIn.scriptTxIn.datumSource.data.content)
2102
+ // TODO: handle json / raw datum
2103
+ );
2104
+ } else if (currentTxIn.scriptTxIn.datumSource.type === "Inline") {
2105
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2106
+ let referenceInputsList = [...referenceInputs.values()];
2107
+ referenceInputsList.push(
2108
+ new TransactionInput(
2109
+ TransactionId(currentTxIn.txIn.txHash),
2110
+ BigInt(currentTxIn.txIn.txIndex)
2111
+ )
2112
+ );
2113
+ referenceInputs.setValues(referenceInputsList);
2114
+ this.txBody.setReferenceInputs(referenceInputs);
2115
+ }
2116
+ let cardanoTxIn = new TransactionInput(
2117
+ TransactionId(currentTxIn.txIn.txHash),
2118
+ BigInt(currentTxIn.txIn.txIndex)
2119
+ );
2120
+ let exUnits = currentTxIn.scriptTxIn.redeemer.exUnits;
2121
+ this.redeemerContext.set(
2122
+ cardanoTxIn,
2123
+ new Redeemer(
2124
+ RedeemerTag.Spend,
2125
+ BigInt(0),
2126
+ toPlutusData(currentTxIn.scriptTxIn.redeemer.data.content),
2127
+ // TODO: handle json / raw datum
2128
+ new ExUnits(BigInt(exUnits.mem), BigInt(exUnits.steps))
2129
+ )
2130
+ );
2131
+ };
2132
+ addSimpleScriptTxIn = (currentTxIn) => {
2133
+ this.addTxIn({
2134
+ type: "PubKey",
2135
+ txIn: currentTxIn.txIn
2136
+ });
2137
+ if (!currentTxIn.simpleScriptTxIn.scriptSource) {
2138
+ throw new Error("A native script input had no script source");
2139
+ }
2140
+ if (currentTxIn.simpleScriptTxIn.scriptSource.type === "Provided") {
2141
+ this.scriptsProvided.add(
2142
+ Script.newNativeScript(
2143
+ NativeScript.fromCbor(
2144
+ HexBlob6(currentTxIn.simpleScriptTxIn.scriptSource.script)
2145
+ )
2146
+ )
2147
+ );
2148
+ } else if (currentTxIn.simpleScriptTxIn.scriptSource.type === "Inline" && currentTxIn.simpleScriptTxIn.scriptSource.txInInfo.type === "Inline") {
2149
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2150
+ let referenceInputsList = [...referenceInputs.values()];
2151
+ referenceInputsList.push(
2152
+ new TransactionInput(
2153
+ TransactionId(
2154
+ currentTxIn.simpleScriptTxIn.scriptSource.txInInfo.txHash
2155
+ ),
2156
+ BigInt(currentTxIn.simpleScriptTxIn.scriptSource.txInInfo.txIndex)
2157
+ )
2158
+ );
2159
+ referenceInputs.setValues(referenceInputsList);
2160
+ this.txBody.setReferenceInputs(referenceInputs);
2161
+ }
2162
+ };
2163
+ addAllOutputs = (outputs) => {
2164
+ for (let i = 0; i < outputs.length; i++) {
2165
+ this.addOutput(outputs[i]);
2166
+ }
2167
+ };
2168
+ addOutput = (output) => {
2169
+ const currentOutputs = this.txBody.outputs();
2170
+ const cardanoOutput = new TransactionOutput(
2171
+ Address.fromBech32(output.address),
2172
+ toValue(output.amount)
2173
+ );
2174
+ if (output.datum?.type === "Hash") {
2175
+ cardanoOutput.setDatum(
2176
+ Datum.newDataHash(
2177
+ DatumHash.fromHexBlob(
2178
+ HexBlob6(toPlutusData(output.datum.data.content).hash())
2179
+ )
2180
+ )
2181
+ );
2182
+ } else if (output.datum?.type === "Inline") {
2183
+ cardanoOutput.setDatum(
2184
+ Datum.newInlineData(
2185
+ toPlutusData(output.datum.data.content)
2186
+ // TODO: handle json / raw datum
2187
+ )
2188
+ );
2189
+ }
2190
+ if (output.referenceScript) {
2191
+ switch (output.referenceScript.version) {
2192
+ case "V1": {
2193
+ cardanoOutput.setScriptRef(
2194
+ Script.newPlutusV1Script(
2195
+ PlutusV1Script.fromCbor(HexBlob6(output.referenceScript.code))
2196
+ )
2197
+ );
2198
+ break;
2199
+ }
2200
+ case "V2": {
2201
+ cardanoOutput.setScriptRef(
2202
+ Script.newPlutusV2Script(
2203
+ PlutusV2Script.fromCbor(HexBlob6(output.referenceScript.code))
2204
+ )
2205
+ );
2206
+ break;
2207
+ }
2208
+ case "V3": {
2209
+ cardanoOutput.setScriptRef(
2210
+ Script.newPlutusV3Script(
2211
+ PlutusV3Script.fromCbor(HexBlob6(output.referenceScript.code))
2212
+ )
2213
+ );
2214
+ break;
2215
+ }
2216
+ }
2217
+ }
2218
+ currentOutputs.push(cardanoOutput);
2219
+ this.txBody.setOutputs(currentOutputs);
2220
+ };
2221
+ addAllReferenceInputs = (refInputs) => {
2222
+ for (let i = 0; i < refInputs.length; i++) {
2223
+ this.addReferenceIput(refInputs[i]);
2224
+ }
2225
+ };
2226
+ addReferenceIput = (refInput) => {
2227
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2228
+ let referenceInputsList = [...referenceInputs.values()];
2229
+ referenceInputsList.push(
2230
+ new TransactionInput(
2231
+ TransactionId.fromHexBlob(HexBlob6(refInput.txHash)),
2232
+ BigInt(refInput.txIndex)
2233
+ )
2234
+ );
2235
+ referenceInputs.setValues(referenceInputsList);
2236
+ this.txBody.setReferenceInputs(referenceInputs);
2237
+ };
2238
+ addAllMints = (mints) => {
2239
+ for (let i = 0; i < mints.length; i++) {
2240
+ this.addMint(mints[i]);
2241
+ }
2242
+ };
2243
+ addMint = (mint) => {
2244
+ const currentMint = this.txBody.mint() ?? /* @__PURE__ */ new Map();
2245
+ const mintAssetId = mint.policyId + mint.assetName;
2246
+ for (const asset of currentMint.keys()) {
2247
+ if (asset.toString() == mintAssetId) {
2248
+ throw new Error("The same asset is already in the mint field");
2249
+ }
2250
+ }
2251
+ currentMint.set(
2252
+ AssetId.fromParts(PolicyId(mint.policyId), AssetName(mint.assetName)),
2253
+ BigInt(mint.amount)
2254
+ );
2255
+ this.txBody.setMint(currentMint);
2256
+ if (mint.type === "Native") {
2257
+ if (!mint.scriptSource)
2258
+ throw new Error("Script source not provided for native script mint");
2259
+ const nativeScriptSource = mint.scriptSource;
2260
+ if (!nativeScriptSource)
2261
+ throw new Error(
2262
+ "A script source for a native script was not a native script somehow"
2263
+ );
2264
+ if (nativeScriptSource.type === "Provided") {
2265
+ this.scriptsProvided.add(
2266
+ Script.newNativeScript(
2267
+ NativeScript.fromCbor(HexBlob6(nativeScriptSource.scriptCode))
2268
+ )
2269
+ );
2270
+ } else if (nativeScriptSource.type === "Inline") {
2271
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2272
+ let referenceInputsList = [...referenceInputs.values()];
2273
+ referenceInputsList.push(
2274
+ new TransactionInput(
2275
+ TransactionId(nativeScriptSource.txHash),
2276
+ BigInt(nativeScriptSource.txIndex)
2277
+ )
2278
+ );
2279
+ referenceInputs.setValues(referenceInputsList);
2280
+ this.txBody.setReferenceInputs(referenceInputs);
2281
+ }
2282
+ } else if (mint.type === "Plutus") {
2283
+ if (!mint.scriptSource)
2284
+ throw new Error("Script source not provided for plutus script mint");
2285
+ const plutusScriptSource = mint.scriptSource;
2286
+ if (!plutusScriptSource) {
2287
+ throw new Error(
2288
+ "A script source for a plutus mint was not plutus script somehow"
2289
+ );
2290
+ }
2291
+ if (plutusScriptSource.type === "Provided") {
2292
+ switch (plutusScriptSource.script.version) {
2293
+ case "V1":
2294
+ this.scriptsProvided.add(
2295
+ Script.newPlutusV1Script(
2296
+ PlutusV1Script.fromCbor(
2297
+ HexBlob6(plutusScriptSource.script.code)
2298
+ )
2299
+ )
2300
+ );
2301
+ break;
2302
+ case "V2":
2303
+ this.scriptsProvided.add(
2304
+ Script.newPlutusV2Script(
2305
+ PlutusV2Script.fromCbor(
2306
+ HexBlob6(plutusScriptSource.script.code)
2307
+ )
2308
+ )
2309
+ );
2310
+ break;
2311
+ case "V3":
2312
+ this.scriptsProvided.add(
2313
+ Script.newPlutusV3Script(
2314
+ PlutusV3Script.fromCbor(
2315
+ HexBlob6(plutusScriptSource.script.code)
2316
+ )
2317
+ )
2318
+ );
2319
+ break;
2320
+ }
2321
+ } else if (plutusScriptSource.type === "Inline") {
2322
+ let referenceInputs = this.txBody.referenceInputs() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2323
+ let referenceInputsList = [...referenceInputs.values()];
2324
+ referenceInputsList.push(
2325
+ new TransactionInput(
2326
+ TransactionId(plutusScriptSource.txHash),
2327
+ BigInt(plutusScriptSource.txIndex)
2328
+ )
2329
+ );
2330
+ referenceInputs.setValues(referenceInputsList);
2331
+ this.txBody.setReferenceInputs(referenceInputs);
2332
+ switch (plutusScriptSource.version) {
2333
+ case "V1": {
2334
+ this.usedLanguages[PlutusLanguageVersion.V1] = true;
2335
+ break;
2336
+ }
2337
+ case "V2": {
2338
+ this.usedLanguages[PlutusLanguageVersion.V2] = true;
2339
+ break;
2340
+ }
2341
+ case "V3": {
2342
+ this.usedLanguages[PlutusLanguageVersion.V3] = true;
2343
+ break;
2344
+ }
2345
+ }
2346
+ }
2347
+ }
2348
+ };
2349
+ addAllCollateralInputs = (collaterals) => {
2350
+ for (let i = 0; i < collaterals.length; i++) {
2351
+ this.addCollateralInput(
2352
+ collaterals[i]
2353
+ );
2354
+ }
2355
+ };
2356
+ addCollateralInput = (collateral) => {
2357
+ let cardanoTxIn = new TransactionInput(
2358
+ TransactionId(collateral.txIn.txHash),
2359
+ BigInt(collateral.txIn.txIndex)
2360
+ );
2361
+ const collateralInputs = this.txBody.collateral() ?? Serialization4.CborSet.fromCore([], TransactionInput.fromCore);
2362
+ const collateralInputsList = [
2363
+ ...collateralInputs.values()
2364
+ ];
2365
+ if (collateralInputsList.find((input) => {
2366
+ input.index() == cardanoTxIn.index() && input.transactionId == cardanoTxIn.transactionId;
2367
+ })) {
2368
+ throw new Error("Duplicate input added to tx body");
2369
+ }
2370
+ collateralInputsList.push(cardanoTxIn);
2371
+ collateralInputs.setValues(collateralInputsList);
2372
+ const cardanoTxOut = new TransactionOutput(
2373
+ Address.fromBech32(collateral.txIn.address),
2374
+ toValue(collateral.txIn.amount)
2375
+ );
2376
+ this.utxoContext.set(cardanoTxIn, cardanoTxOut);
2377
+ this.txBody.setCollateral(collateralInputs);
2378
+ };
2379
+ setValidityInterval = (validity) => {
2380
+ if (validity.invalidBefore) {
2381
+ this.txBody.setValidityStartInterval(Slot(validity.invalidBefore));
2382
+ }
2383
+ if (validity.invalidHereafter) {
2384
+ this.txBody.setTtl(Slot(validity.invalidHereafter));
2385
+ }
2386
+ };
2387
+ buildWitnessSet = () => {
2388
+ const inputs = this.txBody.inputs();
2389
+ for (let i = 0; i < inputs.size(); i += 1) {
2390
+ const input = inputs.values().at(i);
2391
+ if (input) {
2392
+ let redeemer = this.redeemerContext.get(input);
2393
+ if (redeemer) {
2394
+ redeemer.setIndex(BigInt(i));
2395
+ }
2396
+ }
2397
+ }
2398
+ let redeemers = this.txWitnessSet.redeemers() ?? Redeemers.fromCore([]);
2399
+ let redeemersList = [...redeemers.values()];
2400
+ this.redeemerContext.forEach((redeemer) => {
2401
+ redeemersList.push(redeemer);
2402
+ });
2403
+ redeemers.setValues(redeemersList);
2404
+ this.txWitnessSet.setRedeemers(redeemers);
2405
+ let nativeScripts = this.txWitnessSet.nativeScripts() ?? Serialization4.CborSet.fromCore([], NativeScript.fromCore);
2406
+ let v1Scripts = this.txWitnessSet.plutusV1Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV1Script.fromCore);
2407
+ let v2Scripts = this.txWitnessSet.plutusV2Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV2Script.fromCore);
2408
+ let v3Scripts = this.txWitnessSet.plutusV3Scripts() ?? Serialization4.CborSet.fromCore([], PlutusV3Script.fromCore);
2409
+ this.scriptsProvided.forEach((script) => {
2410
+ if (script.asNative() !== void 0) {
2411
+ let nativeScriptsList = [...nativeScripts.values()];
2412
+ nativeScriptsList.push(script.asNative());
2413
+ nativeScripts.setValues(nativeScriptsList);
2414
+ } else if (script.asPlutusV1() !== void 0) {
2415
+ let v1ScriptsList = [...v1Scripts.values()];
2416
+ v1ScriptsList.push(script.asPlutusV1());
2417
+ v1Scripts.setValues(v1ScriptsList);
2418
+ } else if (script.asPlutusV2() !== void 0) {
2419
+ let v2ScriptsList = [...v2Scripts.values()];
2420
+ v2ScriptsList.push(script.asPlutusV2());
2421
+ v2Scripts.setValues(v2ScriptsList);
2422
+ } else if (script.asPlutusV3() !== void 0) {
2423
+ let v3ScriptsList = [...v3Scripts.values()];
2424
+ v3ScriptsList.push(script.asPlutusV3());
2425
+ v3Scripts.setValues(v3ScriptsList);
2426
+ }
2427
+ this.txWitnessSet.setNativeScripts(nativeScripts);
2428
+ this.txWitnessSet.setPlutusV1Scripts(v1Scripts);
2429
+ this.txWitnessSet.setPlutusV2Scripts(v2Scripts);
2430
+ this.txWitnessSet.setPlutusV3Scripts(v3Scripts);
2431
+ });
2432
+ let datums = this.txWitnessSet.plutusData() ?? Serialization4.CborSet.fromCore([], PlutusData.fromCore);
2433
+ this.datumsProvided.forEach((datum) => {
2434
+ let datumsList = [...datums.values()];
2435
+ datumsList.push(datum);
2436
+ datums.setValues(datumsList);
2437
+ });
2438
+ this.txWitnessSet.setPlutusData(datums);
2439
+ let costModelV1 = Serialization4.CostModel.newPlutusV1(
2440
+ DEFAULT_V1_COST_MODEL_LIST
2441
+ );
2442
+ let costModelV2 = Serialization4.CostModel.newPlutusV2(
2443
+ DEFAULT_V2_COST_MODEL_LIST
2444
+ );
2445
+ let costModels = new Serialization4.Costmdls();
2446
+ if (this.usedLanguages[PlutusLanguageVersion.V1]) {
2447
+ costModels.insert(costModelV1);
2448
+ }
2449
+ if (this.usedLanguages[PlutusLanguageVersion.V2]) {
2450
+ costModels.insert(costModelV2);
2451
+ }
2452
+ if (this.usedLanguages[PlutusLanguageVersion.V3]) {
2453
+ }
2454
+ let scriptDataHash = hashScriptData(
2455
+ costModels,
2456
+ redeemers.size() > 0 ? [...redeemers.values()] : void 0,
2457
+ datums.size() > 0 ? [...datums.values()] : void 0
2458
+ );
2459
+ if (scriptDataHash) {
2460
+ this.txBody.setScriptDataHash(scriptDataHash);
2461
+ }
2462
+ };
2463
+ balanceTx = (changeAddress, numberOfRequiredWitnesses, protocolParams) => {
2464
+ if (changeAddress === "") {
2465
+ throw new Error("Can't balance tx without a change address");
2466
+ }
2467
+ const inputs = this.txBody.inputs().values();
2468
+ let remainingValue = new Value(BigInt(0));
2469
+ for (let i = 0; i < inputs.length; i++) {
2470
+ let input = inputs[i];
2471
+ if (!input) {
2472
+ throw new Error("Invalid input found");
2473
+ }
2474
+ const output = this.utxoContext.get(input);
2475
+ if (!output) {
2476
+ throw new Error(`Unable to resolve input: ${input.toCbor()}`);
2477
+ }
2478
+ remainingValue = mergeValue(remainingValue, output.amount());
2479
+ }
2480
+ const withdrawals = this.txBody.withdrawals();
2481
+ if (withdrawals) {
2482
+ withdrawals.forEach((coin) => {
2483
+ remainingValue = mergeValue(remainingValue, new Value(coin));
2484
+ });
2485
+ }
2486
+ remainingValue = mergeValue(
2487
+ remainingValue,
2488
+ new Value(BigInt(0), this.txBody.mint())
2489
+ );
2490
+ const currentOutputs = this.txBody.outputs();
2491
+ for (let i = 0; i < currentOutputs.length; i++) {
2492
+ let output = currentOutputs.at(i);
2493
+ if (output) {
2494
+ remainingValue = subValue(remainingValue, output.amount());
2495
+ }
2496
+ }
2497
+ if (remainingValue.coin() < 0 || !empty(negatives(remainingValue))) {
2498
+ throw new Error(`Not enough funds to satisfy outputs`);
2499
+ }
2500
+ currentOutputs.push(
2501
+ new TransactionOutput(Address.fromBech32(changeAddress), remainingValue)
2502
+ );
2503
+ this.txBody.setOutputs(currentOutputs);
2504
+ this.txBody.setFee(BigInt("10000000"));
2505
+ const dummyTx = this.createDummyTx(numberOfRequiredWitnesses);
2506
+ const fee = protocolParams.minFeeB + dummyTx.toCbor().length / 2 * Number(protocolParams.coinsPerUtxoSize);
2507
+ this.txBody.setFee(BigInt(fee));
2508
+ const changeOutput = currentOutputs.pop();
2509
+ if (!changeOutput) {
2510
+ throw new Error(
2511
+ "Somehow the output length was 0 after attempting to calculate fees"
2512
+ );
2513
+ }
2514
+ changeOutput.amount().setCoin(changeOutput.amount().coin() - BigInt(fee));
2515
+ currentOutputs.push(changeOutput);
2516
+ this.txBody.setOutputs(currentOutputs);
2517
+ };
2518
+ createDummyTx = (numberOfRequiredWitnesses) => {
2519
+ let dummyWitnessSet = new TransactionWitnessSet();
2520
+ const dummyVkeyWitnesses = [];
2521
+ for (let i = 0; i < numberOfRequiredWitnesses; i++) {
2522
+ dummyVkeyWitnesses.push([
2523
+ Ed25519PublicKeyHex2("0".repeat(64)),
2524
+ Ed25519SignatureHex2("0".repeat(128))
2525
+ ]);
2526
+ }
2527
+ dummyWitnessSet.setVkeys(
2528
+ Serialization4.CborSet.fromCore(dummyVkeyWitnesses, VkeyWitness.fromCore)
2529
+ );
2530
+ return new Transaction(this.txBody, dummyWitnessSet);
2531
+ };
2532
+ };
2533
+
2534
+ // src/index.ts
2535
+ import * as CardanoSDKUtil from "@cardano-sdk/util";
2536
+ import * as Crypto3 from "@cardano-sdk/crypto";
2537
+ import * as CardanoSDK from "@cardano-sdk/core";
2538
+ export {
2539
+ Address,
2540
+ AddressType,
2541
+ AssetFingerprint,
2542
+ AssetId,
2543
+ AssetName,
2544
+ BaseAddress,
2545
+ Bip32PrivateKey3 as Bip32PrivateKey,
2546
+ Bip32PrivateKeyHex2 as Bip32PrivateKeyHex,
2547
+ Cardano4 as Cardano,
2548
+ CardanoSDK,
2549
+ CardanoSDKSerializer,
2550
+ CardanoSDKUtil,
2551
+ CborSet,
2552
+ CborWriter,
2553
+ Certificate,
2554
+ CertificateType,
2555
+ ConstrPlutusData,
2556
+ CostModel,
2557
+ Costmdls,
2558
+ Credential,
2559
+ CredentialType,
2560
+ Crypto3 as Crypto,
2561
+ DRepID,
2562
+ Datum,
2563
+ DatumHash,
2564
+ DatumKind,
2565
+ Ed25519KeyHash2 as Ed25519KeyHash,
2566
+ Ed25519KeyHashHex2 as Ed25519KeyHashHex,
2567
+ Ed25519PrivateExtendedKeyHex,
2568
+ Ed25519PrivateNormalKeyHex,
2569
+ Ed25519PublicKey2 as Ed25519PublicKey,
2570
+ Ed25519PublicKeyHex2 as Ed25519PublicKeyHex,
2571
+ Ed25519Signature2 as Ed25519Signature,
2572
+ Ed25519SignatureHex2 as Ed25519SignatureHex,
2573
+ EnterpriseAddress,
2574
+ ExUnits,
2575
+ Hash,
2576
+ Hash28ByteBase162 as Hash28ByteBase16,
2577
+ Hash32ByteBase162 as Hash32ByteBase16,
2578
+ NativeScript,
2579
+ NetworkId,
2580
+ PaymentAddress,
2581
+ PlutusData,
2582
+ PlutusLanguageVersion,
2583
+ PlutusList,
2584
+ PlutusMap,
2585
+ PlutusV1Script,
2586
+ PlutusV2Script,
2587
+ PlutusV3Script,
2588
+ PolicyId,
2589
+ PoolId,
2590
+ Redeemer,
2591
+ RedeemerPurpose,
2592
+ RedeemerTag,
2593
+ Redeemers,
2594
+ RequireAllOf,
2595
+ RequireAnyOf,
2596
+ RequireNOf,
2597
+ RequireSignature,
2598
+ RequireTimeAfter,
2599
+ RequireTimeBefore,
2600
+ RewardAccount,
2601
+ RewardAddress,
2602
+ Script,
2603
+ ScriptHash,
2604
+ ScriptPubkey,
2605
+ Serialization5 as Serialization,
2606
+ Slot,
2607
+ StakeDelegation,
2608
+ StakeRegistration,
2609
+ Bip32PrivateKey as StricaBip32PrivateKey,
2610
+ Bip32PublicKey as StricaBip32PublicKey,
2611
+ CoseSign1 as StricaCoseSign1,
2612
+ PrivateKey as StricaPrivateKey,
2613
+ PublicKey2 as StricaPublicKey,
2614
+ Transaction,
2615
+ TransactionBody,
2616
+ TransactionId,
2617
+ TransactionInput,
2618
+ TransactionOutput,
2619
+ TransactionUnspentOutput,
2620
+ TransactionWitnessSet,
2621
+ Value,
2622
+ VkeyWitness,
2623
+ VrfVkBech32,
2624
+ addressToBech32,
2625
+ assetTypes,
2626
+ buildBaseAddress,
2627
+ buildBip32PrivateKey,
2628
+ buildDRepID,
2629
+ buildEnterpriseAddress,
2630
+ buildKeys,
2631
+ buildRewardAddress,
2632
+ buildScriptPubkey,
2633
+ checkSignature,
2634
+ deserializeAddress,
2635
+ deserializeDataHash,
2636
+ deserializeEd25519KeyHash,
2637
+ deserializeNativeScript,
2638
+ deserializePlutusData,
2639
+ deserializePlutusScript,
2640
+ deserializeScriptHash,
2641
+ deserializeScriptRef,
2642
+ deserializeTx,
2643
+ deserializeTxHash,
2644
+ deserializeTxUnspentOutput,
2645
+ deserializeValue,
2646
+ empty,
2647
+ fromNativeScript,
2648
+ fromScriptRef,
2649
+ fromTxUnspentOutput,
2650
+ fromValue,
2651
+ generateNonce,
2652
+ getCoseKeyFromPublicKey,
2653
+ getPublicKeyFromCoseKey,
2654
+ mergeValue,
2655
+ negateValue,
2656
+ negatives,
2657
+ resolveDataHash,
2658
+ resolveNativeScriptAddress,
2659
+ resolveNativeScriptHash,
2660
+ resolvePaymentKeyHash,
2661
+ resolvePlutusScriptAddress,
2662
+ resolvePlutusScriptHash,
2663
+ resolvePoolId,
2664
+ resolvePrivateKey,
2665
+ resolveRewardAddress,
2666
+ resolveScriptRef,
2667
+ resolveStakeKeyHash,
2668
+ resolveTxHash,
2669
+ signData,
2670
+ subValue,
2671
+ toAddress,
2672
+ toBaseAddress,
2673
+ toEnterpriseAddress,
2674
+ toNativeScript,
2675
+ toPlutusData,
2676
+ toRewardAddress,
2677
+ toScriptRef,
2678
+ toTxUnspentOutput,
2679
+ toValue
2680
+ };