From f1551766b18ebe6a548de3caed50877598ca953c Mon Sep 17 00:00:00 2001 From: Micah Kendall Date: Thu, 28 Dec 2023 00:27:56 +1100 Subject: [PATCH] support 4.0.1 more --- src/misc/sign_data.ts | 6 +- src/plutus/data.ts | 16 +- src/provider/kupmios.ts | 2 - src/translucent/tx.ts | 42 ++--- src/translucent/tx_complete.ts | 29 ++-- src/utils/cost_model.ts | 24 +-- src/utils/utils.ts | 297 +++++++++++---------------------- 7 files changed, 156 insertions(+), 260 deletions(-) diff --git a/src/misc/sign_data.ts b/src/misc/sign_data.ts index 4c1a247..cbc4409 100644 --- a/src/misc/sign_data.ts +++ b/src/misc/sign_data.ts @@ -30,7 +30,7 @@ export function signData( const priv = C.PrivateKey.from_bech32(privateKey); - const signedSigStruc = priv.sign(toSign).to_bytes(); + const signedSigStruc = priv.sign(toSign).to_raw_bytes(); const coseSign1 = builder.build(signedSigStruc); const key = M.COSEKey.new( @@ -45,7 +45,7 @@ export function signData( ); // crv (-1) set to Ed25519 (6) key.set_header( M.Label.new_int(M.Int.new_negative(M.BigNum.from_str("2"))), - M.CBORValue.new_bytes(priv.to_public().as_bytes()), + M.CBORValue.new_bytes(priv.to_public().to_raw_bytes()), ); // x (-2) set to public key return { @@ -137,7 +137,7 @@ export function verifyData( } })(); - const signature = C.Ed25519Signature.from_bytes(cose1.signature()); + const signature = C.Ed25519Signature.from_raw_bytes(cose1.signature()); const data = cose1.signed_data(undefined, undefined).to_bytes(); diff --git a/src/plutus/data.ts b/src/plutus/data.ts index fd92e7c..d661f32 100644 --- a/src/plutus/data.ts +++ b/src/plutus/data.ts @@ -271,18 +271,18 @@ function to(data: Exact, type?: T): Datum | Redeemer { return C.PlutusData.new_bytes(fromHex(data)); } else if (data instanceof Constr) { const { index, fields } = data; - const plutusList = C.PlutusList.new(); + const plutusList = C.PlutusDataList.new(); fields.forEach((field) => plutusList.add(serialize(field))); return C.PlutusData.new_constr_plutus_data( C.ConstrPlutusData.new( - C.BigNum.from_str(index.toString()), + BigInt(index), plutusList, ), ); } else if (data instanceof Array) { - const plutusList = C.PlutusList.new(); + const plutusList = C.PlutusDataList.new(); data.forEach((arg) => plutusList.add(serialize(arg))); @@ -291,7 +291,7 @@ function to(data: Exact, type?: T): Datum | Redeemer { const plutusMap = C.PlutusMap.new(); for (const [key, value] of data.entries()) { - plutusMap.insert(serialize(key), serialize(value)); + plutusMap.set(serialize(key), serialize(value)); } return C.PlutusData.new_map(plutusMap); @@ -302,7 +302,7 @@ function to(data: Exact, type?: T): Datum | Redeemer { } } const d = type ? castTo(data, type) : (data as Data); - return toHex(serialize(d).to_bytes()) as Datum | Redeemer; + return toHex(serialize(d).to_cbor_bytes()) as Datum | Redeemer; } /** @@ -313,12 +313,12 @@ function from(raw: Datum | Redeemer, type?: T): T { function deserialize(data: C.PlutusData): Data { if (data.kind() === 0) { const constr = data.as_constr_plutus_data()!; - const l = constr.data(); + const l = constr.fields(); const desL = []; for (let i = 0; i < l.len(); i++) { desL.push(deserialize(l.get(i))); } - return new Constr(parseInt(constr.alternative().to_str()), desL); + return new Constr(parseInt(constr.alternative().toString()), desL); } else if (data.kind() === 1) { const m = data.as_map()!; const desM: Map = new Map(); @@ -341,7 +341,7 @@ function from(raw: Datum | Redeemer, type?: T): T { } throw new Error("Unsupported type"); } - const data = deserialize(C.PlutusData.from_bytes(fromHex(raw))); + const data = deserialize(C.PlutusData.from_cbor_hex(raw)); return type ? castFrom(data, type) : (data as T); } diff --git a/src/provider/kupmios.ts b/src/provider/kupmios.ts index 2d26c68..3324673 100644 --- a/src/provider/kupmios.ts +++ b/src/provider/kupmios.ts @@ -20,8 +20,6 @@ import { costModelKeys, fromHex, fromUnit, - toHex, - Utils, } from "../utils/mod.ts"; import * as ogmios from "@cardano-ogmios/schema"; diff --git a/src/translucent/tx.ts b/src/translucent/tx.ts index 1275679..bc6d35e 100644 --- a/src/translucent/tx.ts +++ b/src/translucent/tx.ts @@ -197,7 +197,7 @@ export class Tx { C.PartialPlutusWitness.new( //C.Script.new_plutus_v2(C.PlutusV2Script.from_cbor_hex(script.inlineScript)) C.PlutusScriptWitness.from_script(script.inlineScript), - C.PlutusData.from_bytes(fromHex(redeemer)), + C.PlutusData.from_cbor_hex(redeemer), ), C.RequiredSigners.new(), ); @@ -205,7 +205,7 @@ export class Tx { mr = mintBuilder.plutus_script( C.PartialPlutusWitness.new( C.PlutusScriptWitness.from_ref(script.referenceScript.hash()), - C.PlutusData.from_bytes(fromHex(redeemer)), + C.PlutusData.from_cbor_hex(redeemer), ), C.RequiredSigners.new(), ); @@ -392,7 +392,7 @@ export class Tx { if ("inlineScript" in script) { cr = certBuilder.plutus_script( C.PartialPlutusWitness.new( - C.PlutusScriptWitness.from_script(script.inlineScript), + C.PlutusScriptWitness.from(script.inlineScript), C.PlutusData.from_cbor_hex(redeemer), ), C.RequiredSigners.new(), @@ -620,12 +620,12 @@ export class Tx { ); } } else { - if (rewAdd.payment_cred().kind() == 0) { + if (rewAdd.to_address().payment_cred()!.kind() == 0) { wr = certBuilder.payment_key(); } else { let ns = this.native_scripts[ - rewAdd.payment_cred()?.to_scripthash()?.to_hex()! + rewAdd.to_address().payment_cred()!.as_script()!.to_hex() ]; if (!ns) { throw "Script with no redeemer should be a nativescript, but none provided"; @@ -709,12 +709,7 @@ export class Tx { let md = C.Metadata.new() md.set(BigInt(label), C.TransactionMetadatum.new_text(JSON.stringify(metadata))) - let aux = C.AuxiliaryData.new(); - aux.add_json_metadatum_with_schema( - BigInt(label), - JSON.stringify(metadata), - C.MetadataJsonSchema.BasicConversions, - ); + let aux = C.AuxiliaryData.new_shelley(md); that.txBuilder.add_auxiliary_data(aux); }); return this; @@ -723,12 +718,10 @@ export class Tx { /* Same as above but MORE detailed! */ attachMetadataWithDetailedConversion(label: Label, metadata: Json): Tx { this.tasks.push((that) => { - let aux = C.AuxiliaryData.new(); - aux.add_json_metadatum_with_schema( - C.BigNum.from_str(label.toString()), - JSON.stringify(metadata), - C.MetadataJsonSchema.DetailedSchema, - ); + let md = C.Metadata.new() + md.set(BigInt(label), C.TransactionMetadatum.new_text(JSON.stringify(metadata))) + + let aux = C.AuxiliaryData.new_shelley(md); that.txBuilder.add_auxiliary_data(aux); }); return this; @@ -919,6 +912,7 @@ export class Tx { draftTx = C.Transaction.new( draftTx.body(), witnessSet, + draftTx.is_valid(), draftTx.auxiliary_data(), ); } @@ -928,7 +922,7 @@ export class Tx { draftTxBytes, allUtxos.map((x) => x.input().to_bytes()), allUtxos.map((x) => x.output().to_bytes()), - costMdls.to_bytes(), + costMdls.to_cbor_bytes(), protocolParameters.maxTxExSteps, protocolParameters.maxTxExMem, BigInt(slotConfig.zeroTime), @@ -987,16 +981,16 @@ async function createPoolRegistration( switch (relay.type) { case "SingleHostIp": { const ipV4 = relay.ipV4 - ? C.Ipv4.new( + ? C.Ipv4.from_cbor_bytes( new Uint8Array(relay.ipV4.split(".").map((b) => parseInt(b))), ) : undefined; const ipV6 = relay.ipV6 - ? C.Ipv6.new(fromHex(relay.ipV6.replaceAll(":", ""))) + ? C.Ipv6.from_cbor_hex(relay.ipV6.replaceAll(":", "")) : undefined; relays.add( C.Relay.new_single_host_addr( - C.SingleHostAddr.new(relay.port, ipV4, ipV6), + relay.port, ipV4, ipV6, ), ); break; @@ -1004,10 +998,8 @@ async function createPoolRegistration( case "SingleHostDomainName": { relays.add( C.Relay.new_single_host_name( - C.SingleHostName.new( relay.port, - C.DNSRecordAorAAAA.new(relay.domainName!), - ), + C.DnsName.from_cbor_hex(relay.domainName!), ), ); break; @@ -1015,7 +1007,7 @@ async function createPoolRegistration( case "MultiHost": { relays.add( C.Relay.new_multi_host_name( - C.MultiHostName.new(C.DNSRecordSRV.new(relay.domainName!)), + C.DnsName.from_cbor_hex(relay.domainName!), ), ); break; diff --git a/src/translucent/tx_complete.ts b/src/translucent/tx_complete.ts index 68a2688..e3184f1 100644 --- a/src/translucent/tx_complete.ts +++ b/src/translucent/tx_complete.ts @@ -23,14 +23,14 @@ export class TxComplete { this.witnessSetBuilder = C.TransactionWitnessSetBuilder.new(); this.tasks = []; - this.fee = parseInt(tx.body().fee().to_str()); + this.fee = Number(tx.body().fee().valueOf()); const redeemers = tx.witness_set().redeemers(); if (redeemers) { const exUnits = { cpu: 0, mem: 0 }; for (let i = 0; i < redeemers.len(); i++) { const redeemer = redeemers.get(i); - exUnits.cpu += parseInt(redeemer.ex_units().steps().to_str()); - exUnits.mem += parseInt(redeemer.ex_units().mem().to_str()); + exUnits.cpu += Number(redeemer.ex_units().steps().valueOf()); + exUnits.mem += Number(redeemer.ex_units().mem().valueOf()); } this.exUnits = exUnits; } @@ -46,9 +46,9 @@ export class TxComplete { /** Add an extra signature from a private key. */ signWithPrivateKey(privateKey: PrivateKey): TxComplete { const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, + const witness = C.Vkeywitness.new( + priv.to_public(), + priv.sign(this.txComplete.body().to_cbor_bytes()) ); this.witnessSetBuilder.add_vkey(witness); return this; @@ -58,7 +58,7 @@ export class TxComplete { async partialSign(): Promise { const witnesses = await this.translucent.wallet.signTx(this.txComplete); this.witnessSetBuilder.add_existing(witnesses); - return toHex(witnesses.to_bytes()); + return toHex(witnesses.to_cbor_bytes()); } /** @@ -67,21 +67,21 @@ export class TxComplete { */ partialSignWithPrivateKey(privateKey: PrivateKey): TransactionWitnesses { const priv = C.PrivateKey.from_bech32(privateKey); - const witness = C.make_vkey_witness( - C.hash_transaction(this.txComplete.body()), - priv, + const witness = C.Vkeywitness.new( + priv.to_public(), + priv.sign(this.txComplete.body().to_cbor_bytes()) ); this.witnessSetBuilder.add_vkey(witness); const witnesses = C.TransactionWitnessSetBuilder.new(); witnesses.add_vkey(witness); - return toHex(witnesses.build().to_bytes()); + return toHex(witnesses.build().to_cbor_bytes()); } /** Sign the transaction with the given witnesses. */ assemble(witnesses: TransactionWitnesses[]): TxComplete { witnesses.forEach((witness) => { - const witnessParsed = C.TransactionWitnessSet.from_bytes( - fromHex(witness), + const witnessParsed = C.TransactionWitnessSet.from_cbor_hex( + witness ); this.witnessSetBuilder.add_existing(witnessParsed); }); @@ -97,6 +97,7 @@ export class TxComplete { const signedTx = C.Transaction.new( this.txComplete.body(), this.witnessSetBuilder.build(), + this.txComplete.is_valid(), this.txComplete.auxiliary_data(), ); return new TxSigned(this.translucent, signedTx); @@ -104,7 +105,7 @@ export class TxComplete { /** Return the transaction in Hex encoded Cbor. */ toString(): Transaction { - return toHex(this.txComplete.to_bytes()); + return this.txComplete.to_cbor_hex(); } /** Return the transaction hash. */ diff --git a/src/utils/cost_model.ts b/src/utils/cost_model.ts index 19d611a..ed3dd59 100644 --- a/src/utils/cost_model.ts +++ b/src/utils/cost_model.ts @@ -2,22 +2,22 @@ import { C } from "../core/mod.ts"; import { CostModels } from "../mod.ts"; import { ProtocolParameters } from "../types/types.ts"; -export function createCostModels(costModels: CostModels): C.Costmdls { - const costmdls = C.Costmdls.new(); +export function createCostModels(costModels: CostModels): C.CostModels { + const costmdls = C.CostModels.new(); // add plutus v1 - const costmdlV1 = C.CostModel.empty_model(C.Language.new_plutus_v1()); - Object.values(costModels.PlutusV1).forEach((cost, index) => { - costmdlV1.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(costmdlV1); + const costmdlV1 = C.IntList.new() + for (const cost of Object.values(costModels.PlutusV1)){ + costmdlV1.add(C.Int.new(BigInt(cost))) + } + costmdls.set_plutus_v1(costmdlV1) // add plutus v2 - const costmdlV2 = C.CostModel.empty_model(C.Language.new_plutus_v2()); - Object.values(costModels.PlutusV2 || []).forEach((cost, index) => { - costmdlV2.set(index, C.Int.new(C.BigNum.from_str(cost.toString()))); - }); - costmdls.insert(costmdlV2); + const costmdlV2 = C.IntList.new() + for (const cost of Object.values(costModels.PlutusV2)){ + costmdlV2.add(C.Int.new(BigInt(cost))) + } + costmdls.set_plutus_v2(costmdlV2); return costmdls; } diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 62e0d47..f475985 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -47,7 +47,7 @@ export class Utils { ): Address { const validatorHash = this.validatorToScriptHash(validator); if (stakeCredential) { - return C.BaseAddress.new( + return C.Address.new( networkToId(this.translucent.network), C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)), stakeCredential.type === "Key" @@ -68,6 +68,7 @@ export class Utils { .to_address() .to_bech32(undefined); } + } credentialToAddress( @@ -114,7 +115,7 @@ export class Utils { validator: CertificateValidator | WithdrawalValidator, ): RewardAddress { const validatorHash = this.validatorToScriptHash(validator); - return C.RewardAddress.new( + return C.Address.new( networkToId(this.translucent.network), C.StakeCredential.from_scripthash(C.ScriptHash.from_hex(validatorHash)), ) @@ -138,29 +139,24 @@ export class Utils { } validatorToScriptHash(validator: Validator): ScriptHash { - switch (validator.type) { - case "Native": - return C.NativeScript.from_bytes(fromHex(validator.script)) - .hash() - .to_hex(); - case "PlutusV1": - return C.PlutusScript.from_v1( - C.PlutusV1Script.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)), - ), + if (validator.type === "Native") { + return C.NativeScript.from_cbor_hex(validator.script) + .hash() + .to_hex(); + } else if (validator.type === "PlutusV1") { + return C.PlutusV1Script.from_cbor_hex( + applyDoubleCborEncoding(validator.script), ) - .hash() - .to_hex(); - case "PlutusV2": - return C.PlutusScript.from_v2( - C.PlutusV2Script.from_bytes( - fromHex(applyDoubleCborEncoding(validator.script)), - ), - ) - .hash() - .to_hex(); - default: - throw new Error("No variant matched"); + .hash() + .to_hex(); + } else if (validator.type === "PlutusV2") { + return C.PlutusV2Script.from_cbor_hex( + applyDoubleCborEncoding(validator.script), + ) + .hash() + .to_hex(); + } else { + throw new Error("No variant matched"); } } @@ -169,7 +165,7 @@ export class Utils { } datumToHash(datum: Datum): DatumHash { - return C.hash_plutus_data(C.PlutusData.from_bytes(fromHex(datum))).to_hex(); + return C.hash_plutus_data(C.PlutusData.from_cbor_hex(datum)).to_hex(); } scriptHashToCredential(scriptHash: ScriptHash): Credential { @@ -232,7 +228,7 @@ export class Utils { function addressFromHexOrBech32(address: string): C.Address { try { - return C.Address.from_bytes(fromHex(address)); + return C.Address.from_hex(address); } catch (_e) { try { return C.Address.from_bech32(address); @@ -246,129 +242,37 @@ function addressFromHexOrBech32(address: string): C.Address { export function getAddressDetails(address: string): AddressDetails { // Base Address try { - const parsedAddress = C.BaseAddress.from_address( - addressFromHexOrBech32(address), - )!; + const parsedAddress = addressFromHexOrBech32(address) const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 + parsedAddress.payment_cred()!.kind() === 0 ? { type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), + hash: parsedAddress.payment_cred()!.as_pub_key()!.to_hex(), } : { type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes(), - ), + hash: + parsedAddress.payment_cred()!.as_script()!.to_hex(), + }; const stakeCredential: Credential = - parsedAddress.stake_cred().kind() === 0 + parsedAddress.staking_cred()!.kind() === 0 ? { type: "Key", - hash: toHex(parsedAddress.stake_cred().to_keyhash()!.to_bytes()), + hash: parsedAddress.staking_cred()!.as_pub_key()!.to_hex(), } : { type: "Script", - hash: toHex(parsedAddress.stake_cred().to_scripthash()!.to_bytes()), + hash: parsedAddress.staking_cred()!.as_script()!.to_hex(), }; return { type: "Base", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - stakeCredential, - }; - } catch (_e) { - /* pass */ - } - - // Enterprise Address - try { - const parsedAddress = C.EnterpriseAddress.from_address( - addressFromHexOrBech32(address), - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes(), - ), - }; - return { - type: "Enterprise", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, - paymentCredential, - }; - } catch (_e) { - /* pass */ - } - - // Pointer Address - try { - const parsedAddress = C.PointerAddress.from_address( - addressFromHexOrBech32(address), - )!; - const paymentCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes(), - ), - }; - return { - type: "Pointer", - networkId: parsedAddress.to_address().network_id(), + networkId: parsedAddress.network_id(), address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), + bech32: parsedAddress.to_bech32(undefined), + hex: parsedAddress.to_hex(), }, paymentCredential, - }; - } catch (_e) { - /* pass */ - } - - // Reward Address - try { - const parsedAddress = C.RewardAddress.from_address( - addressFromHexOrBech32(address), - )!; - const stakeCredential: Credential = - parsedAddress.payment_cred().kind() === 0 - ? { - type: "Key", - hash: toHex(parsedAddress.payment_cred().to_keyhash()!.to_bytes()), - } - : { - type: "Script", - hash: toHex( - parsedAddress.payment_cred().to_scripthash()!.to_bytes(), - ), - }; - return { - type: "Reward", - networkId: parsedAddress.to_address().network_id(), - address: { - bech32: parsedAddress.to_address().to_bech32(undefined), - hex: toHex(parsedAddress.to_address().to_bytes()), - }, stakeCredential, }; } catch (_e) { @@ -379,7 +283,7 @@ export function getAddressDetails(address: string): AddressDetails { try { const parsedAddress = ((address: string): C.ByronAddress => { try { - return C.ByronAddress.from_bytes(fromHex(address)); + return C.ByronAddress.from_address(C.Address.from_hex(address))!; } catch (_e) { try { return C.ByronAddress.from_base58(address); @@ -394,7 +298,7 @@ export function getAddressDetails(address: string): AddressDetails { networkId: parsedAddress.to_address().network_id(), address: { bech32: "", - hex: toHex(parsedAddress.to_address().to_bytes()), + hex: toHex(parsedAddress.to_address().to_raw_bytes()), }, }; } catch (_e) { @@ -434,19 +338,19 @@ export function generateSeedPhrase(): string { export function valueToAssets(value: C.Value): Assets { const assets: Assets = {}; - assets["lovelace"] = BigInt(value.coin().to_str()); - const ma = value.multiasset(); + assets["lovelace"] = value.coin() + const ma = value.multi_asset(); if (ma) { const multiAssets = ma.keys(); for (let j = 0; j < multiAssets.len(); j++) { const policy = multiAssets.get(j); - const policyAssets = ma.get(policy)!; + const policyAssets = ma.get_assets(policy)!; const assetNames = policyAssets.keys(); for (let k = 0; k < assetNames.len(); k++) { const policyAsset = assetNames.get(k); const quantity = policyAssets.get(policyAsset)!; - const unit = toHex(policy.to_bytes()) + toHex(policyAsset.name()); - assets[unit] = BigInt(quantity.to_str()); + const unit = toHex(policy.to_raw_bytes()) + fromText(policyAsset.to_str()); + assets[unit] = quantity; } } } @@ -466,70 +370,65 @@ export function assetsToValue(assets: Assets): C.Value { ); policies.forEach((policy) => { const policyUnits = units.filter((unit) => unit.slice(0, 56) === policy); - const assetsValue = C.Assets.new(); + const assetsValue = C.MapAssetNameToCoin.new(); policyUnits.forEach((unit) => { assetsValue.insert( - C.AssetName.new(fromHex(unit.slice(56))), - C.BigNum.from_str(assets[unit].toString()), + C.AssetName.from_str(toText(unit.slice(56))), + assets[unit], ); }); - multiAsset.insert(C.ScriptHash.from_bytes(fromHex(policy)), assetsValue); + multiAsset.insert_assets(C.ScriptHash.from_hex(policy), assetsValue); }); const value = C.Value.new( - C.BigNum.from_str(lovelace ? lovelace.toString() : "0"), + lovelace, + multiAsset ); - if (units.length > 1 || !lovelace) value.set_multiasset(multiAsset); return value; } -export function fromScriptRef(scriptRef: C.ScriptRef): Script { - const kind = scriptRef.script().kind(); - switch (kind) { - case 0: - return { - type: "Native", - script: toHex(scriptRef.script().as_native()!.to_bytes()), - }; - case 1: - return { - type: "PlutusV1", - script: toHex(scriptRef.script().as_plutus_v1()!.to_bytes()), - }; - case 2: - return { - type: "PlutusV2", - script: toHex(scriptRef.script().as_plutus_v2()!.to_bytes()), - }; - default: - throw new Error("No variant matched."); +export function fromScriptRef(scriptRef: C.Script): Script { + const kind = scriptRef.kind(); + if (kind === 0) { + return { + type: "Native", + script: toHex(scriptRef.as_native()!.to_cbor_bytes()), + }; + } else if (kind === 1) { + return { + type: "PlutusV1", + script: toHex(scriptRef.as_plutus_v1()!.to_cbor_bytes()), + }; + } else if (kind === 2) { + return { + type: "PlutusV2", + script: toHex(scriptRef.as_plutus_v2()!.to_cbor_bytes()), + }; + } else { + throw new Error("No variant matched."); } } export function toScriptRef(script: Script): C.Script { - switch (script.type) { - case "Native": - return C.Script.new_native( - C.Script.new_native(C.NativeScript.from_bytes(fromHex(script.script))), - ); - case "PlutusV1": - return C.Script.new_plutus_v1( - C.Script.new_plutus_v1( - C.PlutusV1Script.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)), - ), + if (script.type === "Native") { + return C.Script.new_native( + C.NativeScript.from_cbor_hex(script.script), + ); + } + if (script.type === "PlutusV1") { + return C.Script.new_plutus_v1( + C.PlutusV1Script.from_cbor_hex( + applyDoubleCborEncoding(script.script), ), - ); - case "PlutusV2": - return C.Script.new_plutus_v1( - C.Script.new_plutus_v2( - C.PlutusV2Script.from_bytes( - fromHex(applyDoubleCborEncoding(script.script)), - ), + ); + } + if (script.type === "PlutusV2") { + return C.Script.new_plutus_v1( + C.PlutusV2Script.from_cbor_hex( + applyDoubleCborEncoding(script.script), ), - ); - default: - throw new Error("No variant matched."); - } + ); + } + throw new Error("No script variant matched for toScriptRef."); } export function utxoToCore(utxo: UTxO): C.TransactionUnspentOutput { @@ -540,29 +439,35 @@ export function utxoToCore(utxo: UTxO): C.TransactionUnspentOutput { return C.ByronAddress.from_base58(utxo.address).to_address(); } })(); - const output = C.TransactionOutput.new(address, assetsToValue(utxo.assets)); + const output: { + address: C.Address, + value: C.Value, + datum: C.DatumOption | undefined, + script_reference: C.Script | undefined, + } = { + address, + value: assetsToValue(utxo.assets), + datum: undefined, + script_reference: undefined, + } if (utxo.datumHash) { - output.set_datum( - C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash))), - ); + output.datum = C.DatumOption.new_hash(C.DatumHash.from_hex(utxo.datumHash)) } // inline datum if (!utxo.datumHash && utxo.datum) { - output.set_datum( - C.Datum.new_data(C.PlutusData.from_bytes(fromHex(utxo.datum))), - ); + output.datum = C.DatumOption.new_datum(C.PlutusData.from_cbor_hex(utxo.datum!)) } if (utxo.scriptRef) { - output.set_script_ref(toScriptRef(utxo.scriptRef)); + output.script_reference = toScriptRef(utxo.scriptRef) } return C.TransactionUnspentOutput.new( C.TransactionInput.new( - C.TransactionHash.from_bytes(fromHex(utxo.txHash)), - C.BigNum.from_str(utxo.outputIndex.toString()), + C.TransactionHash.from_hex(utxo.txHash), + BigInt(utxo.outputIndex), ), - output, + C.TransactionOutput.new(output.address, output.value, output.datum, output.script_reference), ); }