Socket
Socket
Sign inDemoInstall

@harmoniclabs/plu-ts-offchain

Package Overview
Dependencies
Maintainers
1
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@harmoniclabs/plu-ts-offchain - npm Package Compare versions

Comparing version 0.1.12 to 0.1.13-dev0

dist/txBuild/ChangeInfos/ChangeInfos.d.ts

3

dist/toOnChain/getSpendingPurposeData.d.ts
import { TxBody, TxRedeemer } from "@harmoniclabs/cardano-ledger-ts";
import type { ToDataVersion } from "@harmoniclabs/cardano-ledger-ts/dist/toData/defaultToDataVersion";
import { DataConstr } from "@harmoniclabs/plutus-data";
export declare function getSpendingPurposeData(rdmr: TxRedeemer, tx: TxBody): DataConstr;
export declare function getSpendingPurposeData(rdmr: TxRedeemer, tx: TxBody, version: ToDataVersion): DataConstr;

@@ -7,4 +7,5 @@ "use strict";

var uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
function getSpendingPurposeData(rdmr, tx) {
function getSpendingPurposeData(rdmr, tx, version) {
var _a, _b, _c, _d, _e;
version = version !== null && version !== void 0 ? version : "v2";
var tag = rdmr.tag;

@@ -34,3 +35,4 @@ var ctorIdx;

"; tx.inputs.length is: " + tx.inputs.length.toString());
purposeArgData = utxoRef.toData();
// @ts-ignore Expected 0 arguments, but got 1.t
purposeArgData = utxoRef.toData(version);
}

@@ -42,3 +44,5 @@ else if (tag === cardano_ledger_ts_1.TxRedeemerTag.Withdraw) {

throw new Error("invalid stake credentials for rewarding redeemer " + rdmr.index.toString());
purposeArgData = new cardano_ledger_ts_1.StakeCredentials("script", new cardano_ledger_ts_1.StakeValidatorHash(stakeAddr.credentials)).toData();
purposeArgData = new cardano_ledger_ts_1.StakeCredentials("script", new cardano_ledger_ts_1.StakeValidatorHash(stakeAddr.credentials))
// @ts-ignore Expected 0 arguments, but got 1.t
.toData(version);
}

@@ -50,3 +54,8 @@ else if (tag === cardano_ledger_ts_1.TxRedeemerTag.Cert) {

throw new Error("invalid certificate for certifyng redeemer " + rdmr.index.toString());
purposeArgData = cert.toData();
var tmp = void 0;
tmp = cert.toData(version);
while (tmp instanceof plutus_data_1.DataList) {
tmp = tmp.list[0];
}
purposeArgData = tmp;
}

@@ -53,0 +62,0 @@ else

@@ -6,3 +6,4 @@ import { GenesisInfos } from "../TxBuilder/GenesisInfos.js";

v1: Data | undefined;
v2: Data;
v2: Data | undefined;
v3: Data;
};

@@ -8,17 +8,26 @@ "use strict";

var getSpendingPurposeData_1 = require("./getSpendingPurposeData.js");
var uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
function sortUTxO(a, b) {
var ord = (0, uint8array_utils_1.lexCompare)(a.utxoRef.id.toBuffer(), b.utxoRef.id.toBuffer());
// if equal tx id order based on tx output index
if (ord === 0)
return a.utxoRef.index - b.utxoRef.index;
// else order by tx id
return ord;
}
function getTxInfos(transaction, genesisInfos) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
var tx = transaction.body, witnesses = transaction.witnesses;
function redeemerToDataPair(rdmr) {
return new plutus_data_1.DataPair((0, getSpendingPurposeData_1.getSpendingPurposeData)(rdmr, tx), rdmr.data.clone());
function redeemerToDataPair(rdmr, version) {
return new plutus_data_1.DataPair((0, getSpendingPurposeData_1.getSpendingPurposeData)(rdmr, tx, version), rdmr.data.clone());
}
var sortedInputs = tx.inputs.slice().sort(sortUTxO);
var sortedRefInputs = (_a = tx.refInputs) === null || _a === void 0 ? void 0 : _a.slice().sort(sortUTxO);
var feeData = cardano_ledger_ts_1.Value.lovelaces(tx.fee).toData();
var mintData = ((_a = tx.mint) !== null && _a !== void 0 ? _a : cardano_ledger_ts_1.Value.lovelaces(0)).toData();
var certsData = new plutus_data_1.DataList((_c = (_b = tx.certs) === null || _b === void 0 ? void 0 : _b.map(function (cert) { return cert.toData(); })) !== null && _c !== void 0 ? _c : []);
var withdrawsData = (_e = (_d = tx.withdrawals) === null || _d === void 0 ? void 0 : _d.toData()) !== null && _e !== void 0 ? _e : new plutus_data_1.DataMap([]);
var mintData = ((_b = tx.mint) !== null && _b !== void 0 ? _b : cardano_ledger_ts_1.Value.lovelaces(0)).toData();
var intervalData = (0, getTxIntervalData_1.getTxIntervalData)(tx.validityIntervalStart, tx.ttl, genesisInfos);
var sigsData = new plutus_data_1.DataList((_g = (_f = tx.requiredSigners) === null || _f === void 0 ? void 0 : _f.map(function (sig) { return sig.toData(); })) !== null && _g !== void 0 ? _g : []);
var datumsData = new plutus_data_1.DataMap((_j = (_h = witnesses.datums) === null || _h === void 0 ? void 0 : _h.map(function (dat) {
var sigsData = new plutus_data_1.DataList((_d = (_c = tx.requiredSigners) === null || _c === void 0 ? void 0 : _c.map(function (sig) { return sig.toData(); })) !== null && _d !== void 0 ? _d : []);
var datumsData = new plutus_data_1.DataMap((_f = (_e = witnesses.datums) === null || _e === void 0 ? void 0 : _e.map(function (dat) {
return new plutus_data_1.DataPair(new plutus_data_1.DataB((0, plutus_data_1.hashData)(dat)), dat);
})) !== null && _j !== void 0 ? _j : []);
})) !== null && _f !== void 0 ? _f : []);
var txIdData = new plutus_data_1.DataB(tx.hash.toBuffer());

@@ -30,3 +39,3 @@ var v1 = undefined;

// inputs
new plutus_data_1.DataList(tx.inputs.map(function (input) { return input.toData("v1"); })),
new plutus_data_1.DataList(sortedInputs.map(function (input) { return input.toData("v1"); })),
// outputs

@@ -39,5 +48,5 @@ new plutus_data_1.DataList(tx.outputs.map(function (out) { return out.toData("v1"); })),

// dCertificates
certsData.clone(),
new plutus_data_1.DataList((_h = (_g = tx.certs) === null || _g === void 0 ? void 0 : _g.map(function (cert) { return cert.toData("v1"); })) !== null && _h !== void 0 ? _h : []),
// withderawals
withdrawsData.clone(),
(_k = (_j = tx.withdrawals) === null || _j === void 0 ? void 0 : _j.toData("v1")) !== null && _k !== void 0 ? _k : new plutus_data_1.DataMap([]),
// interval

@@ -54,13 +63,46 @@ intervalData.clone(),

catch ( // input or output can't be v1 (inline datums etc...)
_p) { // input or output can't be v1 (inline datums etc...)
_0) { // input or output can't be v1 (inline datums etc...)
v1 = undefined;
}
var v2 = new plutus_data_1.DataConstr(0, // PTxInfo; only costructor
var v2 = undefined;
try {
v2 = new plutus_data_1.DataConstr(0, // PTxInfo; only costructor
[
// inputs
new plutus_data_1.DataList(sortedInputs.map(function (input) { return input.toData("v2"); })),
// refInputs
new plutus_data_1.DataList((_l = sortedRefInputs === null || sortedRefInputs === void 0 ? void 0 : sortedRefInputs.map(function (refIn) { return refIn.toData("v2"); })) !== null && _l !== void 0 ? _l : []),
// outputs
new plutus_data_1.DataList(tx.outputs.map(function (out) { return out.toData("v2"); })),
// fee
feeData,
// mint
mintData,
// dCertificates
new plutus_data_1.DataList((_o = (_m = tx.certs) === null || _m === void 0 ? void 0 : _m.map(function (cert) { return cert.toData("v2"); })) !== null && _o !== void 0 ? _o : []),
// withderawals
(_q = (_p = tx.withdrawals) === null || _p === void 0 ? void 0 : _p.toData("v2")) !== null && _q !== void 0 ? _q : new plutus_data_1.DataMap([]),
// interval
intervalData,
// signatories
sigsData,
// redeemers
new plutus_data_1.DataMap((_s = (_r = witnesses.redeemers) === null || _r === void 0 ? void 0 : _r.map(function (rdmr) { return redeemerToDataPair(rdmr, "v2"); })) !== null && _s !== void 0 ? _s : []),
// datums
datumsData,
// id
txIdData
]);
}
catch (_1) {
v2 = undefined;
}
var v3 = new plutus_data_1.DataConstr(0, // PTxInfo; only costructor
[
// inputs
new plutus_data_1.DataList(tx.inputs.map(function (input) { return input.toData("v2"); })),
new plutus_data_1.DataList(sortedInputs.map(function (input) { return input.toData("v3"); })),
// refInputs
new plutus_data_1.DataList((_l = (_k = tx.refInputs) === null || _k === void 0 ? void 0 : _k.map(function (refIn) { return refIn.toData("v2"); })) !== null && _l !== void 0 ? _l : []),
new plutus_data_1.DataList((_t = sortedRefInputs === null || sortedRefInputs === void 0 ? void 0 : sortedRefInputs.map(function (refIn) { return refIn.toData("v3"); })) !== null && _t !== void 0 ? _t : []),
// outputs
new plutus_data_1.DataList(tx.outputs.map(function (out) { return out.toData("v2"); })),
new plutus_data_1.DataList(tx.outputs.map(function (out) { return out.toData("v3"); })),
// fee

@@ -71,5 +113,5 @@ feeData,

// dCertificates
certsData,
new plutus_data_1.DataList((_v = (_u = tx.certs) === null || _u === void 0 ? void 0 : _u.map(function (cert) { return cert.toData("v3"); })) !== null && _v !== void 0 ? _v : []),
// withderawals
withdrawsData,
(_x = (_w = tx.withdrawals) === null || _w === void 0 ? void 0 : _w.toData("v3")) !== null && _x !== void 0 ? _x : new plutus_data_1.DataMap([]),
// interval

@@ -80,3 +122,3 @@ intervalData,

// redeemers
new plutus_data_1.DataMap((_o = (_m = witnesses.redeemers) === null || _m === void 0 ? void 0 : _m.map(redeemerToDataPair)) !== null && _o !== void 0 ? _o : []),
new plutus_data_1.DataMap((_z = (_y = witnesses.redeemers) === null || _y === void 0 ? void 0 : _y.map(function (rdmr) { return redeemerToDataPair(rdmr, "v3"); })) !== null && _z !== void 0 ? _z : []),
// datums

@@ -87,4 +129,4 @@ datumsData,

]);
return { v1: v1, v2: v2 };
return { v1: v1, v2: v2, v3: v3 };
}
exports.getTxInfos = getTxInfos;
export * from "./ITxBuildArgs.js";
export * from "./ITxBuildCert.js";
export * from "./ITxBuildInput.js";
export * from "./ITxBuildInput/ITxBuildInput.js";
export * from "./ITxBuildMint.js";

@@ -5,0 +5,0 @@ export * from "./ITxBuildOptions.js";

@@ -19,3 +19,3 @@ "use strict";

__exportStar(require("./ITxBuildCert.js"), exports);
__exportStar(require("./ITxBuildInput.js"), exports);
__exportStar(require("./ITxBuildInput/ITxBuildInput.js"), exports);
__exportStar(require("./ITxBuildMint.js"), exports);

@@ -22,0 +22,0 @@ __exportStar(require("./ITxBuildOptions.js"), exports);

@@ -1,19 +0,15 @@

import { Address, AddressStr, Hash32, ProtocolUpdateProposal, PubKeyHash, Script, TxMetadata, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { type ITxBuildCert } from "./ITxBuildCert.js";
import { type ITxBuildInput } from "./ITxBuildInput.js";
import { type ITxBuildMint } from "./ITxBuildMint.js";
import { Address, AddressStr, CanBeHash28, IProposalProcedure, IUTxO, IVotingProceduresEntry, PubKeyHash, TxMetadata, TxOut, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { NormalizedITxBuildCert, type ITxBuildCert } from "./ITxBuildCert.js";
import { NormalizedITxBuildInput, type ITxBuildInput } from "./ITxBuildInput/ITxBuildInput.js";
import { NormalizedITxBuildMint, type ITxBuildMint } from "./ITxBuildMint.js";
import { type ITxBuildOutput } from "./ITxBuildOutput.js";
import { type ITxBuildWithdrawal } from "./ITxBuildWithdrawal.js";
import { NormalizedITxBuildWithdrawal, type ITxBuildWithdrawal } from "./ITxBuildWithdrawal.js";
import { CanBeUInteger } from "../utils/ints.js";
import { CanBeData } from "../utils/CanBeData.js";
export interface ChangeInfos {
address: Address | AddressStr;
datum?: Hash32 | CanBeData;
refScript?: Script;
}
export declare function cloneChangeInfos(change: ChangeInfos): ChangeInfos;
import { ChangeInfos, NormalizedChangeInfos } from "./ChangeInfos/ChangeInfos.js";
import { ITxBuildVotingProcedure, NormalizedITxBuildVotingProcedure } from "./ITxBuildVotingProcedure.js";
import { ITxBuildProposalProcedure, NormalizedITxBuildProposalProcedure } from "./ITxBuildProposalProcedure.js";
export interface ITxBuildArgs {
inputs: ITxBuildInput[];
inputs: (ITxBuildInput | IUTxO)[];
/**
* same as
* same as `changeAddress` but allows to specify datums and ref scripts
* @example

@@ -29,5 +25,5 @@ * ```ts

outputs?: ITxBuildOutput[];
readonlyRefInputs?: UTxO[];
requiredSigners?: PubKeyHash[];
collaterals?: UTxO[];
readonlyRefInputs?: IUTxO[];
requiredSigners?: CanBeHash28[];
collaterals?: IUTxO[];
collateralReturn?: ITxBuildOutput;

@@ -40,4 +36,29 @@ mints?: ITxBuildMint[];

metadata?: TxMetadata;
protocolUpdateProposal?: ProtocolUpdateProposal;
votingProcedures?: (IVotingProceduresEntry | ITxBuildVotingProcedure)[];
proposalProcedures?: (IProposalProcedure | ITxBuildProposalProcedure)[];
currentTreasuryValue?: CanBeUInteger;
paymentToTreasury?: CanBeUInteger;
}
export declare function cloneITxBuildArgs(args: Partial<ITxBuildArgs>): ITxBuildArgs;
export interface NormalizedITxBuildArgs extends ITxBuildArgs {
inputs: NormalizedITxBuildInput[];
changeAddress?: Address;
change?: NormalizedChangeInfos;
outputs?: TxOut[];
readonlyRefInputs?: UTxO[];
requiredSigners?: PubKeyHash[];
collaterals?: UTxO[];
collateralReturn?: TxOut;
mints?: NormalizedITxBuildMint[];
invalidBefore?: CanBeUInteger;
invalidAfter?: CanBeUInteger;
certificates?: NormalizedITxBuildCert[];
withdrawals?: NormalizedITxBuildWithdrawal[];
metadata?: TxMetadata;
votingProcedures?: NormalizedITxBuildVotingProcedure[];
proposalProcedures?: NormalizedITxBuildProposalProcedure[];
currentTreasuryValue?: bigint;
paymentToTreasury?: bigint;
}
export declare function normalizeITxBuildArgs({ inputs, change, changeAddress, outputs, readonlyRefInputs, requiredSigners, collaterals, collateralReturn, mints, invalidBefore, invalidAfter, certificates, withdrawals, metadata, votingProcedures, proposalProcedures, currentTreasuryValue, paymentToTreasury }: ITxBuildArgs): NormalizedITxBuildArgs;
/** @deprecated use `normalizeITxBuildArgs` instead */
export declare function cloneITxBuildArgs(args: ITxBuildArgs): ITxBuildArgs;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneITxBuildArgs = exports.cloneChangeInfos = void 0;
exports.cloneITxBuildArgs = exports.normalizeITxBuildArgs = void 0;
var cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
var ITxBuildCert_1 = require("./ITxBuildCert.js");
var ITxBuildInput_1 = require("./ITxBuildInput.js");
var ITxBuildInput_1 = require("./ITxBuildInput/ITxBuildInput.js");
var ITxBuildMint_1 = require("./ITxBuildMint.js");
var ITxBuildOutput_1 = require("./ITxBuildOutput.js");
var ITxBuildWithdrawal_1 = require("./ITxBuildWithdrawal.js");
var CanBeData_1 = require("../utils/CanBeData.js");
function cloneChangeInfos(change) {
var ChangeInfos_1 = require("./ChangeInfos/ChangeInfos.js");
var ITxBuildVotingProcedure_1 = require("./ITxBuildVotingProcedure.js");
var ITxBuildProposalProcedure_1 = require("./ITxBuildProposalProcedure.js");
function normalizeITxBuildArgs(_a) {
var inputs = _a.inputs, change = _a.change, changeAddress = _a.changeAddress, outputs = _a.outputs, readonlyRefInputs = _a.readonlyRefInputs, requiredSigners = _a.requiredSigners, collaterals = _a.collaterals, collateralReturn = _a.collateralReturn, mints = _a.mints, invalidBefore = _a.invalidBefore, invalidAfter = _a.invalidAfter, certificates = _a.certificates, withdrawals = _a.withdrawals, metadata = _a.metadata, votingProcedures = _a.votingProcedures, proposalProcedures = _a.proposalProcedures, currentTreasuryValue = _a.currentTreasuryValue, paymentToTreasury = _a.paymentToTreasury;
return {
address: change.address.toString(),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum.clone() :
(0, CanBeData_1.cloneCanBeData)(change.datum)) :
undefined,
refScript: change.refScript ? change.refScript.clone() : undefined
inputs: inputs.map(normalizeITxBuildArgsInputs),
change: change ? (0, ChangeInfos_1.normalizeChangeInfos)(change) : undefined,
changeAddress: changeAddress ? (typeof changeAddress === "string" ?
cardano_ledger_ts_1.Address.fromString(changeAddress) :
changeAddress) : undefined,
outputs: outputs === null || outputs === void 0 ? void 0 : outputs.map(ITxBuildOutput_1.txBuildOutToTxOut),
readonlyRefInputs: readonlyRefInputs === null || readonlyRefInputs === void 0 ? void 0 : readonlyRefInputs.map(toUTxONoClone),
requiredSigners: requiredSigners === null || requiredSigners === void 0 ? void 0 : requiredSigners.map(toPubKeyHash),
collaterals: collaterals === null || collaterals === void 0 ? void 0 : collaterals.map(toUTxONoClone),
collateralReturn: collateralReturn ? (0, ITxBuildOutput_1.txBuildOutToTxOut)(collateralReturn) : undefined,
mints: mints === null || mints === void 0 ? void 0 : mints.map(ITxBuildMint_1.normalizeITxBuildMint),
invalidBefore: invalidBefore === undefined ? undefined : BigInt(invalidBefore),
invalidAfter: invalidAfter === undefined ? undefined : BigInt(invalidAfter),
certificates: certificates === null || certificates === void 0 ? void 0 : certificates.map(ITxBuildCert_1.normalizeITxBuildCert),
withdrawals: withdrawals === null || withdrawals === void 0 ? void 0 : withdrawals.map(ITxBuildWithdrawal_1.normalizeITxBuildWithdrawal),
metadata: metadata,
votingProcedures: Array.isArray(votingProcedures) ?
votingProcedures.map(function (entry) {
if ((0, cardano_ledger_ts_1.isIVotingProceduresEntry)(entry))
entry = {
votingProcedure: entry,
script: undefined // for js shape optimization
};
return (0, ITxBuildVotingProcedure_1.normalizeITxBuildVotingProcedure)(entry);
}) : undefined,
proposalProcedures: Array.isArray(proposalProcedures) ?
proposalProcedures.map(function (entry) {
if ((0, cardano_ledger_ts_1.isIProposalProcedure)(entry))
entry = {
proposalProcedure: entry,
script: undefined
};
return (0, ITxBuildProposalProcedure_1.normalizeITxBuildProposalProcedure)(entry);
}) : undefined,
currentTreasuryValue: currentTreasuryValue === undefined ? undefined : BigInt(currentTreasuryValue),
paymentToTreasury: paymentToTreasury === undefined ? undefined : BigInt(paymentToTreasury),
};
}
exports.cloneChangeInfos = cloneChangeInfos;
exports.normalizeITxBuildArgs = normalizeITxBuildArgs;
function normalizeITxBuildArgsInputs(input) {
if ((0, cardano_ledger_ts_1.isIUTxO)(input))
return { utxo: new cardano_ledger_ts_1.UTxO(input) };
return (0, ITxBuildInput_1.normalizeITxBuildInput)(input);
}
function toUTxONoClone(utxo) {
return utxo instanceof cardano_ledger_ts_1.UTxO ? utxo : new cardano_ledger_ts_1.UTxO(utxo);
}
function toPubKeyHash(hash) {
return new cardano_ledger_ts_1.PubKeyHash(hash);
}
/** @deprecated use `normalizeITxBuildArgs` instead */
function cloneITxBuildArgs(args) {
var _a, _b, _c, _d, _e, _f, _g, _h;
return {
inputs: (_a = args === null || args === void 0 ? void 0 : args.inputs) === null || _a === void 0 ? void 0 : _a.map(ITxBuildInput_1.cloneITxBuildInput),
changeAddress: args.changeAddress === undefined ? undefined :
args.changeAddress instanceof cardano_ledger_ts_1.Address ? args.changeAddress.clone() :
cardano_ledger_ts_1.Address.fromString(args.changeAddress.toString()),
change: args.change ? cloneChangeInfos(args.change) : undefined,
outputs: (_b = args.outputs) === null || _b === void 0 ? void 0 : _b.map(ITxBuildOutput_1.cloneITxBuildOutput),
// era: Era // latest
readonlyRefInputs: (_c = args.readonlyRefInputs) === null || _c === void 0 ? void 0 : _c.map(function (u) { return u.clone(); }),
requiredSigners: (_d = args.requiredSigners) === null || _d === void 0 ? void 0 : _d.map(function (sig) { return sig.clone(); }),
collaterals: (_e = args.collaterals) === null || _e === void 0 ? void 0 : _e.map(function (u) { return u.clone(); }),
collateralReturn: args.collateralReturn ? (0, ITxBuildOutput_1.cloneITxBuildOutput)(args.collateralReturn) : undefined,
mints: (_f = args.mints) === null || _f === void 0 ? void 0 : _f.map(ITxBuildMint_1.cloneITxBuildMint),
invalidBefore: args.invalidBefore,
invalidAfter: args.invalidAfter,
certificates: (_g = args.certificates) === null || _g === void 0 ? void 0 : _g.map(ITxBuildCert_1.cloneITxBuildCert),
withdrawals: (_h = args.withdrawals) === null || _h === void 0 ? void 0 : _h.map(ITxBuildWithdrawal_1.cloneITxBuildWithdrawal),
metadata: args.metadata ? cardano_ledger_ts_1.TxMetadata.fromCborObj(args.metadata.toCborObj()) : undefined,
protocolUpdateProposal: args.protocolUpdateProposal === undefined ? undefined :
(0, cardano_ledger_ts_1.protocolUpdateProposalFromCborObj)((0, cardano_ledger_ts_1.protocolUpdateProposalToCborObj)(args.protocolUpdateProposal))
};
return normalizeITxBuildArgs(args);
}
exports.cloneITxBuildArgs = cloneITxBuildArgs;

@@ -1,13 +0,13 @@

import { AnyCertificate, Script, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { CanBeData } from "../utils/CanBeData.js";
import { Certificate, CertificateLike } from "@harmoniclabs/cardano-ledger-ts";
import { IScriptWithRedeemer, ScriptWithRedeemer } from "./ScriptWithRedeemer.js";
export interface ITxBuildCert {
cert: AnyCertificate;
script?: {
inline: Script;
redeemer: CanBeData;
} | {
ref: UTxO;
redeemer: CanBeData;
};
cert: CertificateLike;
script?: IScriptWithRedeemer;
}
export interface NormalizedITxBuildCert extends ITxBuildCert {
cert: Certificate;
script?: ScriptWithRedeemer;
}
export declare function normalizeITxBuildCert({ cert, script }: ITxBuildCert): NormalizedITxBuildCert;
/** @deprecated use `normalizeITxBuildCert` instead */
export declare function cloneITxBuildCert(cert: ITxBuildCert): ITxBuildCert;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneITxBuildCert = void 0;
exports.cloneITxBuildCert = exports.normalizeITxBuildCert = void 0;
var cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
var CanBeData_1 = require("../utils/CanBeData.js");
var obj_utils_1 = require("@harmoniclabs/obj-utils");
var plutus_data_1 = require("@harmoniclabs/plutus-data");
;
function cloneITxBuildCert(cert) {
var script = cert.script === undefined ? undefined : (0, obj_utils_1.hasOwn)(cert.script, "inline") ?
{
inline: cert.script.inline.clone(),
redeemer: (0, plutus_data_1.isData)(cert.script.redeemer) ? (0, plutus_data_1.cloneData)(cert.script.redeemer) : (0, CanBeData_1.forceData)(cert.script.redeemer)
} :
{
ref: cert.script.ref.clone(),
redeemer: (0, plutus_data_1.isData)(cert.script.redeemer) ? (0, plutus_data_1.cloneData)(cert.script.redeemer) : (0, CanBeData_1.forceData)(cert.script.redeemer)
;
function normalizeITxBuildCert(_a) {
var cert = _a.cert, script = _a.script;
if (!(0, obj_utils_1.isObject)(script) ||
!(0, CanBeData_1.canBeData)(script.redeemer)) {
script = undefined;
}
else if ((0, cardano_ledger_ts_1.isIUTxO)(script.ref)) {
script = {
ref: new cardano_ledger_ts_1.UTxO(script.ref),
redeemer: (0, CanBeData_1.forceData)(script.redeemer)
};
}
else {
script = {
inline: script.inline.clone(),
redeemer: (0, CanBeData_1.forceData)(script.redeemer)
};
}
return {
cert: cardano_ledger_ts_1.Certificate.fromCborObj(cert.cert.toCborObj()),
cert: (0, cardano_ledger_ts_1.certificateFromCertificateLike)(cert),
script: script
};
}
exports.normalizeITxBuildCert = normalizeITxBuildCert;
/** @deprecated use `normalizeITxBuildCert` instead */
function cloneITxBuildCert(cert) {
return normalizeITxBuildCert(cert);
}
exports.cloneITxBuildCert = cloneITxBuildCert;

@@ -1,15 +0,30 @@

import { Value, Script, Hash32, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { Value, Script, UTxO, Hash28, IUTxO, IValuePolicyEntry, NormalizedIValuePolicyEntry } from "@harmoniclabs/cardano-ledger-ts";
import { CanBeData } from "../utils/CanBeData.js";
import { Data } from "@harmoniclabs/plutus-data";
export interface ITxBuildMint {
value: Value;
value: IValuePolicyEntry | Value;
script: {
inline: Script;
policyId: Hash32;
/** @deprecated, policy inferred from value */
policyId?: Hash28;
redeemer: CanBeData;
} | {
ref: UTxO;
policyId: Hash32;
ref: IUTxO;
/** @deprecated, policy inferred from value */
policyId?: Hash28;
redeemer: CanBeData;
};
}
export interface NormalizedITxBuildMint extends ITxBuildMint {
value: NormalizedIValuePolicyEntry;
script: {
inline: Script;
redeemer: Data;
} | {
ref: UTxO;
redeemer: Data;
};
}
export declare function normalizeITxBuildMint({ value, script }: ITxBuildMint): NormalizedITxBuildMint;
/** @deprecated use `normalizeITxBuildMint` instead */
export declare function cloneITxBuildMint(mint: ITxBuildMint): ITxBuildMint;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneITxBuildMint = void 0;
exports.cloneITxBuildMint = exports.normalizeITxBuildMint = void 0;
var cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
var CanBeData_1 = require("../utils/CanBeData.js");
var obj_utils_1 = require("@harmoniclabs/obj-utils");
var plutus_data_1 = require("@harmoniclabs/plutus-data");
;
function cloneITxBuildMint(mint) {
var script = (0, obj_utils_1.hasOwn)(mint.script, "inline") ?
{
inline: mint.script.inline.clone(),
policyId: mint.script.policyId.clone(),
redeemer: (0, plutus_data_1.isData)(mint.script.redeemer) ? (0, plutus_data_1.cloneData)(mint.script.redeemer) : (0, CanBeData_1.forceData)(mint.script.redeemer)
} :
{
ref: mint.script.ref.clone(),
policyId: mint.script.policyId.clone(),
redeemer: (0, plutus_data_1.isData)(mint.script.redeemer) ? (0, plutus_data_1.cloneData)(mint.script.redeemer) : (0, CanBeData_1.forceData)(mint.script.redeemer)
function normalizeITxBuildMint(_a) {
var value = _a.value, script = _a.script;
if (value instanceof cardano_ledger_ts_1.Value) {
if (value.map.length !== 2)
throw new Error("invalid mint value, only single policy allowed");
value = value.map[1];
}
if (!isNormalizedIValuePolicyEntry(value)) {
value = {
policy: new cardano_ledger_ts_1.Hash28(value.policy),
assets: value.assets.map(cardano_ledger_ts_1.normalizeIValueAsset)
};
}
if (!(0, obj_utils_1.isObject)(script) || !(0, CanBeData_1.canBeData)(script.redeemer))
throw new Error("invalid ITxBuildMint to normalize");
if ((0, cardano_ledger_ts_1.isIUTxO)(script.ref)) {
script = {
ref: new cardano_ledger_ts_1.UTxO(script.ref),
redeemer: (0, CanBeData_1.forceData)(script.redeemer)
};
}
else {
script = {
inline: script.inline.clone(),
redeemer: (0, CanBeData_1.forceData)(script.redeemer)
};
}
return {
value: mint.value.clone(),
value: value,
script: script
};
}
exports.normalizeITxBuildMint = normalizeITxBuildMint;
function isNormalizedIValuePolicyEntry(stuff) {
return (0, obj_utils_1.isObject)(stuff) && (stuff.policy instanceof cardano_ledger_ts_1.Hash28 &&
Array.isArray(stuff.assets) &&
stuff.assets.every(isIValueAssetBI));
}
function isIValueAssetBI(stuff) {
return (0, obj_utils_1.isObject)(stuff) && (stuff.name instanceof Uint8Array &&
typeof stuff.quantity === "bigint");
}
/** @deprecated use `normalizeITxBuildMint` instead */
function cloneITxBuildMint(mint) {
return normalizeITxBuildMint(mint);
}
exports.cloneITxBuildMint = cloneITxBuildMint;

@@ -1,7 +0,7 @@

import { Address, Value, Hash32, Script, TxOut } from "@harmoniclabs/cardano-ledger-ts";
import { Address, Value, Script, TxOut, CanBeHash32, AddressStr, IValue } from "@harmoniclabs/cardano-ledger-ts";
import { CanBeData } from "../utils/CanBeData.js";
export interface ITxBuildOutput {
address: Address;
value: Value;
datum?: Hash32 | CanBeData;
address: Address | AddressStr;
value: Value | IValue;
datum?: CanBeHash32 | CanBeData;
refScript?: Script;

@@ -8,0 +8,0 @@ }

@@ -6,9 +6,9 @@ "use strict";

var CanBeData_1 = require("../utils/CanBeData.js");
var plutus_data_1 = require("@harmoniclabs/plutus-data");
function txBuildOutToTxOut(_a) {
var address = _a.address, value = _a.value, datum = _a.datum, refScript = _a.refScript;
return new cardano_ledger_ts_1.TxOut({
address: address.clone(),
value: value.clone(),
datum: (0, CanBeData_1.canBeData)(datum) ? (0, CanBeData_1.forceData)(datum) : datum,
address: typeof address === "string" ? cardano_ledger_ts_1.Address.fromString(address) : address.clone(),
value: value instanceof cardano_ledger_ts_1.Value ? value.clone() : new cardano_ledger_ts_1.Value(value),
datum: (0, CanBeData_1.canBeData)(datum) ? (0, CanBeData_1.forceData)(datum) :
((0, cardano_ledger_ts_1.canBeHash32)(datum) ? new cardano_ledger_ts_1.Hash32(datum) : undefined),
refScript: refScript

@@ -21,7 +21,6 @@ });

return {
address: address.clone(),
value: value.clone(),
datum: (0, CanBeData_1.canBeData)(datum) ?
((0, plutus_data_1.isData)(datum) ? (0, plutus_data_1.cloneData)(datum) : (0, CanBeData_1.forceData)(datum))
: datum,
address: typeof address === "string" ? cardano_ledger_ts_1.Address.fromString(address) : address.clone(),
value: value instanceof cardano_ledger_ts_1.Value ? value.clone() : new cardano_ledger_ts_1.Value(value),
datum: (0, CanBeData_1.canBeData)(datum) ? (0, CanBeData_1.forceData)(datum) :
((0, cardano_ledger_ts_1.canBeHash32)(datum) ? new cardano_ledger_ts_1.Hash32(datum) : undefined),
refScript: refScript === undefined ? undefined : refScript.clone()

@@ -28,0 +27,0 @@ };

@@ -1,5 +0,6 @@

import { TxWithdrawalsEntry, Script, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { Hash28, ITxWithdrawalsEntry, ITxWithdrawalsEntryBigInt, IUTxO, Script, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { CanBeData } from "../utils/CanBeData.js";
import { Data } from "@harmoniclabs/plutus-data";
export interface ITxBuildWithdrawal {
withdrawal: TxWithdrawalsEntry;
withdrawal: ITxWithdrawalsEntry;
script?: {

@@ -9,6 +10,21 @@ inline: Script;

} | {
ref: UTxO;
ref: IUTxO;
redeemer: CanBeData;
};
}
export interface NormalizedITxBuildWithdrawal extends ITxBuildWithdrawal {
withdrawal: ITxWithdrawalsEntryBigInt | {
rewardAccount: Hash28;
amount: bigint;
};
script?: {
inline: Script;
redeemer: Data;
} | {
ref: UTxO;
redeemer: Data;
};
}
export declare function normalizeITxBuildWithdrawal({ withdrawal, script }: ITxBuildWithdrawal): NormalizedITxBuildWithdrawal;
/** @deprecated use `normalizeITxBuildWithdrawal` instead */
export declare function cloneITxBuildWithdrawal(stuff: ITxBuildWithdrawal): ITxBuildWithdrawal;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneITxBuildWithdrawal = void 0;
exports.cloneITxBuildWithdrawal = exports.normalizeITxBuildWithdrawal = void 0;
var cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
var CanBeData_1 = require("../utils/CanBeData.js");

@@ -8,16 +9,18 @@ var obj_utils_1 = require("@harmoniclabs/obj-utils");

;
function cloneITxBuildWithdrawal(stuff) {
var script = stuff.script === undefined ? undefined : (0, obj_utils_1.hasOwn)(stuff.script, "inline") ?
;
function normalizeITxBuildWithdrawal(_a) {
var withdrawal = _a.withdrawal, script = _a.script;
script = script === undefined ? undefined : (0, obj_utils_1.hasOwn)(script, "ref") ?
{
inline: stuff.script.inline.clone(),
redeemer: (0, plutus_data_1.isData)(stuff.script.redeemer) ? (0, plutus_data_1.cloneData)(stuff.script.redeemer) : (0, CanBeData_1.forceData)(stuff.script.redeemer)
ref: script.ref.clone(),
redeemer: (0, plutus_data_1.isData)(script.redeemer) ? (0, plutus_data_1.cloneData)(script.redeemer) : (0, CanBeData_1.forceData)(script.redeemer)
} :
{
ref: stuff.script.ref.clone(),
redeemer: (0, plutus_data_1.isData)(stuff.script.redeemer) ? (0, plutus_data_1.cloneData)(stuff.script.redeemer) : (0, CanBeData_1.forceData)(stuff.script.redeemer)
inline: script.inline.clone(),
redeemer: (0, plutus_data_1.isData)(script.redeemer) ? (0, plutus_data_1.cloneData)(script.redeemer) : (0, CanBeData_1.forceData)(script.redeemer)
};
return {
withdrawal: {
rewardAccount: stuff.withdrawal.rewardAccount.clone(),
amount: stuff.withdrawal.amount
rewardAccount: (0, cardano_ledger_ts_1.canBeHash28)(withdrawal.rewardAccount) ? new cardano_ledger_ts_1.Hash28(withdrawal.rewardAccount) : withdrawal.rewardAccount,
amount: BigInt(withdrawal.amount)
},

@@ -27,2 +30,7 @@ script: script

}
exports.normalizeITxBuildWithdrawal = normalizeITxBuildWithdrawal;
/** @deprecated use `normalizeITxBuildWithdrawal` instead */
function cloneITxBuildWithdrawal(stuff) {
return normalizeITxBuildWithdrawal(stuff);
}
exports.cloneITxBuildWithdrawal = cloneITxBuildWithdrawal;

@@ -1,2 +0,2 @@

import { Address, AddressStr, Hash32, ProtocolParamters, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { Address, AddressStr, Hash32, ProtocolParameters, UTxO } from "@harmoniclabs/cardano-ledger-ts";
import { CanResolveToUTxO } from "../CanResolveToUTxO/CanResolveToUTxO.js";

@@ -9,3 +9,3 @@ import { GenesisInfos } from "../GenesisInfos.js";

export interface IGetProtocolParameters {
getProtocolParameters: () => Promise<ProtocolParamters>;
getProtocolParameters: () => Promise<ProtocolParameters>;
}

@@ -12,0 +12,0 @@ export interface IResolveUTxOs {

@@ -17,3 +17,3 @@ "use strict";

var multiAssetIns = initialUTxOSet.filter(function (input) {
return input.utxo.resolved.value.toUnits()
return new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
.filter(function (asset) { return asset.unit !== "lovelace"; })

@@ -38,7 +38,7 @@ .some(function (asset) { return reqOutputKeys.includes(asset.unit); });

function getTotLovelaces(multiAsset) {
return multiAsset.reduce(function (sum, input) { return sum + input.utxo.resolved.value.lovelaces; }, BigInt(0));
return multiAsset.reduce(function (sum, input) { return sum + new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.lovelaces; }, BigInt(0));
}
;
function remainingLovelace(quantity, initialUTxOSet) {
var sortedUTxOs = initialUTxOSet.sort(function (a, b) { return parseInt(BigInt(a.utxo.resolved.value.lovelaces - b.utxo.resolved.value.lovelaces).toString()); });
var sortedUTxOs = initialUTxOSet.sort(function (a, b) { return parseInt(BigInt(new cardano_ledger_ts_1.UTxO(a.utxo).resolved.value.lovelaces - new cardano_ledger_ts_1.UTxO(b.utxo).resolved.value.lovelaces).toString()); });
var requestedOutputSet = {

@@ -55,7 +55,7 @@ lovelace: quantity

.filter(function (input) {
return input.utxo.resolved.value.toUnits()
return new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
.some(function (a) { return a.unit === unit; });
})
.reduce(function (selectedQuantity, input) {
var utxoQuantity = input.utxo.resolved.value.toUnits()
var utxoQuantity = new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
.reduce(function (quantity, a) { return quantity + unit === a.unit ? BigInt(a.quantity) : BigInt(0); }, BigInt(0));

@@ -79,5 +79,5 @@ return selectedQuantity + utxoQuantity;

return Object.keys(assets).some(function (unit) {
return input.utxo.resolved.value.toUnits()
return new cardano_ledger_ts_1.UTxO(input.utxo).resolved.value.toUnits()
.some(function (asset) { return asset.unit === unit; });
});
}
import { GenesisInfos } from "./GenesisInfos.js";
import { ProtocolParamters, Tx, Value, ValueUnits, TxOut, TxRedeemer, ScriptDataHash } from "@harmoniclabs/cardano-ledger-ts";
import { Tx, Value, ValueUnits, TxOut, TxRedeemerTag, ScriptType, TxRedeemer, ScriptDataHash } from "@harmoniclabs/cardano-ledger-ts";
import { CborString, CanBeCborString } from "@harmoniclabs/cbor";
import { Data } from "@harmoniclabs/plutus-data";
import { ITxBuildArgs, ITxBuildOptions, ITxBuildInput, ITxBuildSyncOptions } from "../txBuild/index.js";

@@ -8,11 +9,10 @@ import { CanBeUInteger } from "../utils/ints.js";

import { ITxRunnerProvider } from "./IProvider/index.js";
import { TxBuilderProtocolParams, ValidatedTxBuilderProtocolParams } from "./TxBuilderProtocolParams.js";
import { ChangeInfos } from "../txBuild/ChangeInfos/ChangeInfos.js";
export declare class TxBuilder {
readonly protocolParamters: ProtocolParamters;
readonly protocolParamters: ValidatedTxBuilderProtocolParams;
readonly genesisInfos?: GenesisInfos;
setGenesisInfos: (geneisInfos: GenesisInfos) => void;
/**
* @experimental
*/
runWithProvider(provider: Partial<ITxRunnerProvider>): TxBuilderRunner;
constructor(protocolParamters: Readonly<ProtocolParamters>, genesisInfos?: GenesisInfos);
constructor(protocolParamters?: Readonly<TxBuilderProtocolParams>, genesisInfos?: GenesisInfos);
keepRelevant(requestedOutputSet: Value | ValueUnits, initialUTxOSet: ITxBuildInput[], minimumLovelaceRequired?: CanBeUInteger): ITxBuildInput[];

@@ -39,6 +39,50 @@ calcLinearFee(tx: Tx | CborString): bigint;

*/
build: (args: ITxBuildArgs, opts?: ITxBuildOptions) => Promise<Tx>;
build(buildArgs: ITxBuildArgs, buildOpts?: ITxBuildOptions): Promise<Tx>;
/**
* replaces the redeemers and clears vkeyWitnesses in the witness set
* and re-computes the `scriptDataHash` in the body
*
* the input transaction is readonly and is not modified
*
* **A NEW TRANSACTION IS CREATED** with vkey witness set empty
* (the new transaction is unsigned)
*
* to summarize, the new transaction differs in:
* 1) `tx.body.scriptDataHash`
* 2) `tx.witnesses.redeemers`
* 3) `tx.witnesses.vkeyWitnesses` (empty)
*/
overrideTxRedeemers(tx: Tx, newRedeemers: TxRedeemer[]): Tx;
buildSync(buildArgs: ITxBuildArgs, { onScriptInvalid, onScriptResult }?: ITxBuildSyncOptions): Tx;
assertMinOutLovelaces(txOuts: TxOut[]): void;
/**
* extracts the important data from the input
* and returns it in an easier way to opearte with
*
* if the transaction is simple enough (aka. it doesn't include plutus scripts)
* this is all that either `build` or `buildSync` needs to do
**/
protected initTxBuild(buildArgs: ITxBuildArgs): {
tx: Tx;
scriptsToExec: ScriptToExecEntry[];
minFee: bigint;
datumsScriptData: number[];
languageViews: Uint8Array;
totInputValue: Value;
requiredOutputValue: Value;
outs: TxOut[];
change: ChangeInfos;
};
}
type ScriptToExecEntry = {
rdmrTag: TxRedeemerTag;
index: number;
script: {
type: ScriptType;
bytes: Uint8Array;
hash: string;
};
datum?: Data;
};
export declare function getScriptDataHash(rdmrs: TxRedeemer[], datumsScriptData: number[], languageViews: Uint8Array): ScriptDataHash | undefined;
export {};

@@ -49,2 +49,13 @@ "use strict";

};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __read = (this && this.__read) || function (o, n) {

@@ -91,6 +102,7 @@ var m = typeof Symbol === "function" && o[Symbol.iterator];

var obj_utils_1 = require("@harmoniclabs/obj-utils");
var assert_1 = require("../utils/assert.js");
var TxBuilderRunner_1 = require("./TxBuilderRunner/TxBuilderRunner.js");
var CanBeData_1 = require("../utils/CanBeData.js");
var getSpendingPurposeData_1 = require("../toOnChain/getSpendingPurposeData.js");
var TxBuilderProtocolParams_1 = require("./TxBuilderProtocolParams.js");
var utils_1 = require("./utils.js");
var scriptCache = {};

@@ -112,4 +124,2 @@ function getScriptLikeUplc(scriptLike) {

function TxBuilder(protocolParamters, genesisInfos) {
var _this = this;
var _a, _b;
var _genesisInfos = undefined;

@@ -136,42 +146,18 @@ var _setGenesisInfos = function (genInfos) {

});
(0, assert_1.assert)((0, cardano_ledger_ts_1.isPartialProtocolParameters)(protocolParamters), "invlaid 'protocolParamters' argument while constructing a 'TxBuilder' instance");
var pp = (0, TxBuilderProtocolParams_1.completeTxBuilderProtocolParams)(protocolParamters);
(0, obj_utils_1.defineReadOnlyProperty)(this, "protocolParamters", (0, obj_utils_1.freezeAll)(protocolParamters));
var costmdls = protocolParamters.costModels;
var cekVersion = (0, cardano_costmodels_ts_1.isCostModelsV2)(costmdls.PlutusScriptV2) ? plutus_machine_1.machineVersionV2 :
(0, cardano_costmodels_ts_1.isCostModelsV1)(costmdls.PlutusScriptV1) ? plutus_machine_1.machineVersionV1 : "none";
var costs = cekVersion === plutus_machine_1.machineVersionV2 ?
(_a = costmdls.PlutusScriptV2) !== null && _a !== void 0 ? _a : cardano_costmodels_ts_1.defaultV2Costs :
(_b = costmdls.PlutusScriptV1) !== null && _b !== void 0 ? _b : cardano_costmodels_ts_1.defaultV1Costs;
if (cekVersion !== "none")
(0, obj_utils_1.definePropertyIfNotPresent)(this, "cek", {
// define as getter so that it can be reused without messing around things
get: function () { return new plutus_machine_1.Machine(cekVersion, costs); },
// set does nothing ( aka. readonly )
set: function () {
var _whatever = [];
for (var _i = 0; _i < arguments.length; _i++) {
_whatever[_i] = arguments[_i];
}
},
enumerable: false,
configurable: false
});
///////////////////////////////////////////////////////////////////////////////////////
// -------------------------------- private stuff -------------------------------- //
// -------------------------------- AND things that -------------------------------- //
// -------------------------------- needs to access -------------------------------- //
// -------------------------------- private stuff -------------------------------- //
///////////////////////////////////////////////////////////////////////////////////////
(0, obj_utils_1.defineReadOnlyProperty)(this, "build", function (buildArgs, buildOpts) {
if (buildOpts === void 0) { buildOpts = {}; }
return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.buildSync(buildArgs, buildOpts)];
});
});
var costmdls = pp.costModels;
var costs = (0, cardano_costmodels_ts_1.isCostModelsV3)(costmdls.PlutusScriptV3) ? costmdls.PlutusScriptV3 :
(0, cardano_costmodels_ts_1.isCostModelsV2)(costmdls.PlutusScriptV2) ? costmdls.PlutusScriptV2 :
(0, cardano_costmodels_ts_1.isCostModelsV1)(costmdls.PlutusScriptV1) ? costmdls.PlutusScriptV1 :
cardano_costmodels_ts_1.defaultV3Costs;
(0, obj_utils_1.definePropertyIfNotPresent)(this, "cek", {
// define as getter so that it can be reused without messing around things
get: function () { return new plutus_machine_1.Machine(__assign({}, costs)); },
// set does nothing ( aka. readonly )
set: function () { },
enumerable: false,
configurable: false
});
}
/**
* @experimental
*/
TxBuilder.prototype.runWithProvider = function (provider) {

@@ -190,5 +176,8 @@ return new TxBuilderRunner_1.TxBuilderRunner(this, provider);

TxBuilder.prototype.getMinimumOutputLovelaces = function (tx_out) {
var size = BigInt(0);
if (tx_out instanceof cardano_ledger_ts_1.TxOut)
tx_out = tx_out.toCbor().toBuffer();
if (!(tx_out instanceof Uint8Array)) {
if (typeof tx_out === "string")
size = BigInt(Math.ceil(tx_out.length / 2));
else if (!(tx_out instanceof Uint8Array)) {
if ((0, obj_utils_1.isObject)(tx_out) &&

@@ -201,3 +190,4 @@ (0, obj_utils_1.hasOwn)(tx_out, "toBuffer") &&

}
var size = BigInt(tx_out.length);
if (tx_out instanceof Uint8Array)
size = BigInt(tx_out.length);
return BigInt(this.protocolParamters.utxoCostPerByte) * size;

@@ -228,6 +218,43 @@ };

};
/**
* here mainly for forward compability
*
* internally calls `buildSync` so really what `build` is doing is wrapping it in a `Promise`
*
* In future this method might implement multi-threading using `Worker`s
*/
TxBuilder.prototype.build = function (buildArgs, buildOpts) {
if (buildOpts === void 0) { buildOpts = {}; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.buildSync(buildArgs, buildOpts)];
});
});
};
/**
* replaces the redeemers and clears vkeyWitnesses in the witness set
* and re-computes the `scriptDataHash` in the body
*
* the input transaction is readonly and is not modified
*
* **A NEW TRANSACTION IS CREATED** with vkey witness set empty
* (the new transaction is unsigned)
*
* to summarize, the new transaction differs in:
* 1) `tx.body.scriptDataHash`
* 2) `tx.witnesses.redeemers`
* 3) `tx.witnesses.vkeyWitnesses` (empty)
*/
TxBuilder.prototype.overrideTxRedeemers = function (tx, newRedeemers) {
var _a;
// datums passed by hash
var datums = (_a = tx.witnesses.datums) !== null && _a !== void 0 ? _a : [];
return new cardano_ledger_ts_1.Tx(__assign(__assign({}, tx), { body: new cardano_ledger_ts_1.TxBody(__assign(__assign({}, tx.body), { scriptDataHash: getScriptDataHash(newRedeemers, datums.length > 0 ?
Array.from(cbor_1.Cbor.encode(new cbor_1.CborArray(datums.map(plutus_data_1.dataToCborObj))).toBuffer())
: [], (0, cardano_costmodels_ts_1.costModelsToLanguageViewCbor)(this.protocolParamters.costModels, { mustHaveV2: true, mustHaveV1: false }).toBuffer()) })), witnesses: new cardano_ledger_ts_1.TxWitnessSet(__assign(__assign({}, tx.witnesses), { vkeyWitnesses: [], redeemers: newRedeemers })) }));
};
TxBuilder.prototype.buildSync = function (buildArgs, _a) {
var _b;
var _c = _a === void 0 ? {} : _a, onScriptInvalid = _c.onScriptInvalid, onScriptResult = _c.onScriptResult;
var _initBuild = initTxBuild.bind(this)(buildArgs);
var _initBuild = this.initTxBuild(buildArgs);
var

@@ -250,9 +277,4 @@ // tx,

var executionUnitPrices = this.protocolParamters.executionUnitPrices;
var _d = __read(Array.isArray(executionUnitPrices) ?
executionUnitPrices :
// fixed in 0.1.9 ( memory in first place )
[
cbor_1.CborPositiveRational.fromNumber(executionUnitPrices.priceMemory),
cbor_1.CborPositiveRational.fromNumber(executionUnitPrices.priceSteps),
], 2), memRational = _d[0], cpuRational = _d[1];
var _d = __read(executionUnitPrices, 2), memRational = _d[0], cpuRational = _d[1];
// group by purpose so we can use the redeemer index to find the script
var spendScriptsToExec = scriptsToExec.filter(function (elem) { return elem.rdmrTag === cardano_ledger_ts_1.TxRedeemerTag.Spend; });

@@ -262,2 +284,4 @@ var mintScriptsToExec = scriptsToExec.filter(function (elem) { return elem.rdmrTag === cardano_ledger_ts_1.TxRedeemerTag.Mint; });

var withdrawScriptsToExec = scriptsToExec.filter(function (elem) { return elem.rdmrTag === cardano_ledger_ts_1.TxRedeemerTag.Withdraw; });
var voteScriptsToExec = scriptsToExec.filter(function (elem) { return elem.rdmrTag === cardano_ledger_ts_1.TxRedeemerTag.Voting; });
var proposeScriptsToExec = scriptsToExec.filter(function (elem) { return elem.rdmrTag === cardano_ledger_ts_1.TxRedeemerTag.Proposing; });
var maxRound = 3;

@@ -269,3 +293,3 @@ var _isScriptValid = true;

prevFee = fee;
var _e = (0, toOnChain_1.getTxInfos)(tx, this_1.genesisInfos), txInfosV1 = _e.v1, txInfosV2 = _e.v2;
var _e = (0, toOnChain_1.getTxInfos)(tx, this_1.genesisInfos), txInfosV1 = _e.v1, txInfosV2 = _e.v2, txInfosV3 = _e.v3;
var totExBudget = new plutus_machine_1.ExBudget({ mem: 0, cpu: 0 });

@@ -277,3 +301,3 @@ var _loop_2 = function (i) {

var index = rdmr_idx + (tag === cardano_ledger_ts_1.TxRedeemerTag.Mint ? 1 : 0);
var spendingPurpose = (0, getSpendingPurposeData_1.getSpendingPurposeData)(rdmr, tx.body);
// const spendingPurpose = getSpendingPurposeData( rdmr, tx.body );
var onlyRedeemerArg = function (purposeScriptsToExec) {

@@ -286,4 +310,7 @@ var _a;

if (script === undefined)
throw new Error("missing script for " + (0, cardano_ledger_ts_1.txRdmrTagToString)(tag) + " redeemer " + (index - 1));
var ctxData = getCtx(script.type, spendingPurpose, txInfosV1, txInfosV2);
throw new Error("missing script for " + (0, cardano_ledger_ts_1.txRedeemerTagToString)(tag) + " redeemer " + (index - 1));
var expectedVersion = (0, utils_1.scriptTypeToDataVersion)(script.type);
if (typeof expectedVersion !== "string")
throw new Error("unexpected redeemer for native script");
var ctxData = getCtx(script.type, (0, getSpendingPurposeData_1.getSpendingPurposeData)(rdmr, tx.body, expectedVersion), txInfosV1, txInfosV2, txInfosV3);
var _b = cek.eval(new uplc_1.Application(new uplc_1.Application(getScriptLikeUplc(script), uplc_1.UPLCConst.data(rdmrData)), uplc_1.UPLCConst.data(ctxData))), result = _b.result, budgetSpent = _b.budgetSpent, logs = _b.logs;

@@ -305,3 +332,6 @@ _isScriptValid = onEvaluationResult(i, totExBudget, rdmr, result, budgetSpent, logs, [

throw new Error("missing datum for spend redeemer " + index);
var ctxData = getCtx(script.type, spendingPurpose, txInfosV1, txInfosV2);
var expectedVersion = (0, utils_1.scriptTypeToDataVersion)(script.type);
if (typeof expectedVersion !== "string")
throw new Error("unexpected redeemer for native script");
var ctxData = getCtx(script.type, (0, getSpendingPurposeData_1.getSpendingPurposeData)(rdmr, tx.body, expectedVersion), txInfosV1, txInfosV2, txInfosV3);
var _f = cek.eval(new uplc_1.Application(new uplc_1.Application(new uplc_1.Application(getScriptLikeUplc(script), uplc_1.UPLCConst.data(datum)), uplc_1.UPLCConst.data(rdmrData)), uplc_1.UPLCConst.data(ctxData))), result = _f.result, budgetSpent = _f.budgetSpent, logs = _f.logs;

@@ -320,2 +350,6 @@ _isScriptValid = onEvaluationResult(i, totExBudget, rdmr, result, budgetSpent, logs, [

onlyRedeemerArg(withdrawScriptsToExec);
else if (tag === cardano_ledger_ts_1.TxRedeemerTag.Voting)
onlyRedeemerArg(voteScriptsToExec);
else if (tag === cardano_ledger_ts_1.TxRedeemerTag.Proposing)
onlyRedeemerArg(proposeScriptsToExec);
else

@@ -343,4 +377,4 @@ throw new Error("unrecoignized redeemer tag " + tag);

value: cardano_ledger_ts_1.Value.sub(totInputValue, cardano_ledger_ts_1.Value.add(requiredOutputValue, cardano_ledger_ts_1.Value.lovelaces(fee))),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum :
datum: change.datum ? ((0, cardano_ledger_ts_1.canBeHash32)(change.datum) ?
new cardano_ledger_ts_1.Hash32(change.datum) :
(0, CanBeData_1.forceData)(change.datum)) : undefined,

@@ -375,88 +409,72 @@ refScript: change.refScript

};
return TxBuilder;
}());
exports.TxBuilder = TxBuilder;
function resolveNetwork(addr) {
if (typeof addr === "string") {
return addr.startsWith("addr_test") ? "testnet" : "mainnet";
}
return addr.network;
}
function eqUTxOByRef(a, b) {
return a === b || a.utxoRef === b.utxoRef || (a.utxoRef.index === b.utxoRef.index &&
a.utxoRef.id.toString() === b.utxoRef.id.toString());
}
function pushUniqueScript(arr, toPush) {
if (!arr.some(function (script) {
return script.hash.toString() === toPush.hash.toString();
}))
arr.push(toPush);
}
/**
* extracts the important data from the input
* and returns it in an easier way to opearte with
*
* it the transaction is simple enough (aka. it doesn't include plutus scripts)
* this is all that either `build` or `buildSync` needs to do
**/
function initTxBuild(_a) {
var _b, _c, _d;
var inputs = _a.inputs, change = _a.change, changeAddress = _a.changeAddress, outputs = _a.outputs, readonlyRefInputs = _a.readonlyRefInputs, requiredSigners = _a.requiredSigners, collaterals = _a.collaterals, collateralReturn = _a.collateralReturn, mints = _a.mints, invalidBefore = _a.invalidBefore, invalidAfter = _a.invalidAfter, certificates = _a.certificates, withdrawals = _a.withdrawals, metadata = _a.metadata, protocolUpdateProposal = _a.protocolUpdateProposal;
if (change) {
changeAddress = change.address;
}
if (!changeAddress) {
throw new Error("missing changAddress and change entry while constructing a transaciton; unable to balance inputs and outpus");
}
if (!change) {
change = { address: changeAddress };
}
;
var network = resolveNetwork(changeAddress);
var undef = void 0;
// filter inputs so that are unique
inputs = inputs.reduce(function (accum, input) {
var samePresent = accum.find(function (_a) {
var accumUtxo = _a.utxo;
return eqUTxOByRef(accumUtxo, input.utxo);
});
if (samePresent === undef) {
accum.push(input);
}
return accum;
}, []);
// filter refIns so that are unique
readonlyRefInputs = readonlyRefInputs === null || readonlyRefInputs === void 0 ? void 0 : readonlyRefInputs.reduce(function (accum, utxo) {
var samePresent = accum.find(function (accumUtxo) { return eqUTxOByRef(accumUtxo, utxo); });
if (samePresent === undef) {
accum.push(utxo);
}
return accum;
}, []);
var totInputValue = (_b = mints === null || mints === void 0 ? void 0 : mints.reduce(function (prev, curr) { return cardano_ledger_ts_1.Value.add(prev, curr.value); }, cardano_ledger_ts_1.Value.zero)) !== null && _b !== void 0 ? _b : cardano_ledger_ts_1.Value.zero;
var refIns = (_c = readonlyRefInputs === null || readonlyRefInputs === void 0 ? void 0 : readonlyRefInputs.slice()) !== null && _c !== void 0 ? _c : [];
var outs = (_d = outputs === null || outputs === void 0 ? void 0 : outputs.map(txBuild_1.txBuildOutToTxOut)) !== null && _d !== void 0 ? _d : [];
var requiredOutputValue = outs.reduce(function (acc, out) { return cardano_ledger_ts_1.Value.add(acc, out.value); }, cardano_ledger_ts_1.Value.zero);
var vkeyWitnesses = [];
var nativeScriptsWitnesses = [];
var bootstrapWitnesses = [];
var plutusV1ScriptsWitnesses = [];
var datums = [];
var plutusV2ScriptsWitnesses = [];
var dummyExecBudget = plutus_machine_1.ExBudget.maxCborSize;
var spendRedeemers = [];
var mintRedeemers = [];
var certRedeemers = [];
var withdrawRedeemers = [];
var scriptsToExec = [];
/**
* needed in `getScriptDataHash` to understand whoich cost model to transform in language view
*/
var _hasV1Scripts = false;
/**
* needed in `getScriptDataHash` to understand whoich cost model to transform in language view
*/
var _hasV2Scripts = false;
function pushScriptToExec(idx, tag, script, datum) {
if (script.type !== cardano_ledger_ts_1.ScriptType.NativeScript) {
* extracts the important data from the input
* and returns it in an easier way to opearte with
*
* if the transaction is simple enough (aka. it doesn't include plutus scripts)
* this is all that either `build` or `buildSync` needs to do
**/
TxBuilder.prototype.initTxBuild = function (buildArgs) {
var _a = (0, txBuild_1.normalizeITxBuildArgs)(buildArgs), outputs = _a.outputs, requiredSigners = _a.requiredSigners, collaterals = _a.collaterals, collateralReturn = _a.collateralReturn, mints = _a.mints, invalidAfter = _a.invalidAfter, certificates = _a.certificates, withdrawals = _a.withdrawals, metadata = _a.metadata, votingProcedures = _a.votingProcedures, proposalProcedures = _a.proposalProcedures, currentTreasuryValue = _a.currentTreasuryValue, paymentToTreasury = _a.paymentToTreasury, args = __rest(_a, ["outputs", "requiredSigners", "collaterals", "collateralReturn", "mints", "invalidAfter", "certificates", "withdrawals", "metadata", "votingProcedures", "proposalProcedures", "currentTreasuryValue", "paymentToTreasury"]);
// mutable args
var inputs = args.inputs, changeAddress = args.changeAddress, change = args.change, invalidBefore = args.invalidBefore, readonlyRefInputs = args.readonlyRefInputs;
if (change)
changeAddress = change.address;
if (!changeAddress)
throw new Error("missing changAddress and change entry while constructing a transaciton; unable to balance inputs and outpus");
if (!change)
change = { address: changeAddress };
var network = changeAddress.network;
var undef = void 0;
// filter inputs so that are unique
inputs = inputs.reduce(function (accum, input) {
var samePresent = accum.some(function (_a) {
var accumUtxo = _a.utxo;
return eqUTxOByRef(accumUtxo, input.utxo);
});
if (!samePresent)
accum.push(input);
return accum;
}, []);
// filter refIns so that are unique
readonlyRefInputs = readonlyRefInputs === null || readonlyRefInputs === void 0 ? void 0 : readonlyRefInputs.reduce(function (accum, utxo) {
var samePresent = accum.some(function (accumUtxo) { return eqUTxOByRef(accumUtxo, utxo); });
if (!samePresent)
accum.push(utxo);
return accum;
}, []);
var totInputValue = cardano_ledger_ts_1.Value.zero;
var refIns = readonlyRefInputs !== null && readonlyRefInputs !== void 0 ? readonlyRefInputs : [];
var outs = outputs !== null && outputs !== void 0 ? outputs : [];
var requiredOutputValue = outs.reduce(function (acc, out) { return cardano_ledger_ts_1.Value.add(acc, out.value); }, cardano_ledger_ts_1.Value.zero);
var vkeyWitnesses = [];
var nativeScriptsWitnesses = [];
var bootstrapWitnesses = [];
var plutusV1ScriptsWitnesses = [];
var datums = [];
var plutusV2ScriptsWitnesses = [];
var plutusV3ScriptsWitnesses = [];
var dummyExecBudget = plutus_machine_1.ExBudget.maxCborSize;
var spendRedeemers = [];
var mintRedeemers = [];
var certRedeemers = [];
var withdrawRedeemers = [];
var voteRedeemers = [];
var proposeRedeemers = [];
var scriptsToExec = [];
/**
* needed in `getScriptDataHash` to understand whoich cost model to transform in language view
*/
var _hasV1Scripts = false;
/**
* needed in `getScriptDataHash` to understand whoich cost model to transform in language view
*/
var _hasV2Scripts = false;
/**
* needed in `getScriptDataHash` to understand whoich cost model to transform in language view
*/
var _hasV3Scripts = false;
function pushScriptToExec(idx, tag, script, datum) {
if (script.type == cardano_ledger_ts_1.ScriptType.NativeScript)
return;
// keep track of exsisting csript versions

@@ -466,5 +484,8 @@ if (!_hasV1Scripts && script.type === "PlutusScriptV1") {

}
if (!_hasV2Scripts && script.type === "PlutusScriptV2") {
else if (!_hasV2Scripts && script.type === "PlutusScriptV2") {
_hasV2Scripts = true;
}
else if (!_hasV3Scripts && script.type === "PlutusScriptV3") {
_hasV3Scripts = true;
}
scriptsToExec.push({

@@ -475,3 +496,3 @@ index: idx,

type: script.type,
bytes: script.bytes.slice(),
bytes: script.bytes,
hash: script.hash.toString()

@@ -482,322 +503,379 @@ },

}
}
function pushWitScript(script) {
var t = script.type;
if (t === "NativeScript")
pushUniqueScript(nativeScriptsWitnesses, script);
else if (t === "PlutusScriptV1")
pushUniqueScript(plutusV1ScriptsWitnesses, script);
else if (t === "PlutusScriptV2")
pushUniqueScript(plutusV2ScriptsWitnesses, script);
}
/**
* @returns `Script` to execute
*/
function checkScriptAndPushIfInline(script) {
if ((0, obj_utils_1.hasOwn)(script, "inline")) {
if ((0, obj_utils_1.hasOwn)(script, "ref"))
throw new Error("multiple scripts specified");
pushWitScript(script.inline);
return script.inline;
function pushWitScript(script) {
var t = script.type;
if (t === "NativeScript")
pushUniqueScript(nativeScriptsWitnesses, script);
else if (t === "PlutusScriptV1")
pushUniqueScript(plutusV1ScriptsWitnesses, script);
else if (t === "PlutusScriptV2")
pushUniqueScript(plutusV2ScriptsWitnesses, script);
else if (t === "PlutusScriptV3")
pushUniqueScript(plutusV3ScriptsWitnesses, script);
}
if ((0, obj_utils_1.hasOwn)(script, "ref")) {
if ((0, obj_utils_1.hasOwn)(script, "inline"))
throw new Error("multiple scripts specified");
var refScript = script.ref.resolved.refScript;
if (refScript === (void 0))
throw new Error("script was specified to be a reference script " +
"but the provided utxo is missing any attached script");
var sameRefPresent = refIns.find(function (u) { return eqUTxOByRef(u, script.ref); });
if (sameRefPresent === undef) {
refIns.push(script.ref);
/**
* @returns `Script` to execute
*/
function checkScriptAndPushIfInline(script) {
var _a, _b;
if ((0, obj_utils_1.hasOwn)(script, "inline")) {
if ((0, obj_utils_1.hasOwn)(script, "ref"))
throw new Error("multiple scripts specified");
pushWitScript(script.inline);
return script.inline;
}
return refScript;
if ((0, obj_utils_1.hasOwn)(script, "ref")) {
if ((0, obj_utils_1.hasOwn)(script, "inline"))
throw new Error("multiple scripts specified");
var refScript = (_b = (_a = script.ref) === null || _a === void 0 ? void 0 : _a.resolved) === null || _b === void 0 ? void 0 : _b.refScript;
if (refScript === (void 0))
throw new Error("script was specified to be a reference script " +
"but the provided utxo is missing any attached script");
if (!refIns.some(function (u) { return eqUTxOByRef(u, script.ref); })) {
refIns.push(script.ref);
}
return refScript;
}
throw new Error("unexpected execution flow 'checkScriptAndPushIfInline' in TxBuilder");
}
throw "unexpected execution flow 'checkScriptAndPushIfInline' in TxBuilder";
}
/**
*
* @param datum
* @param inlineDatum
* @returns the `Data` of the datum
*/
function pushWitDatum(datum, inlineDatum) {
if (datum === "inline") {
if (!(0, CanBeData_1.canBeData)(inlineDatum))
throw new Error("datum was specified to be inline; but inline datum is missing");
// no need to push to witnesses
return (0, CanBeData_1.forceData)(inlineDatum);
/**
*
* @param datum
* @param inlineDatum
* @returns the `Data` of the datum
*/
function pushWitDatum(datum, inlineDatum) {
if (datum === "inline") {
if (!(0, CanBeData_1.canBeData)(inlineDatum))
throw new Error("datum was specified to be inline; but inline datum is missing");
// no need to push to witnesses
return (0, CanBeData_1.forceData)(inlineDatum);
}
else {
var dat = (0, CanBeData_1.forceData)(datum);
// add datum to witnesses
// the node finds it trough the datum hash (on the utxo)
datums.push(dat);
return dat;
}
}
else {
var dat = (0, CanBeData_1.forceData)(datum);
// add datum to witnesses
// the node finds it trough the datum hash (on the utxo)
datums.push(dat);
return dat;
}
}
var isScriptValid = true;
// `sort` mutates the array; so we `slice` (clone) first
var sortedIns = inputs.slice().sort(function (a, b) {
var ord = (0, uint8array_utils_1.lexCompare)(a.utxo.utxoRef.id.toBuffer(), b.utxo.utxoRef.id.toBuffer());
// if equal tx id order based on tx output index
if (ord === 0)
return a.utxo.utxoRef.index - b.utxo.utxoRef.index;
// else order by tx id
return ord;
});
var _inputs = inputs.map(function (input) {
var utxo = input.utxo, referenceScriptV2 = input.referenceScriptV2, inputScript = input.inputScript;
var addr = utxo.resolved.address;
totInputValue = cardano_ledger_ts_1.Value.add(totInputValue, utxo.resolved.value);
if (addr.paymentCreds.type === "script" &&
referenceScriptV2 === undef &&
inputScript === undef)
throw new Error("spending script utxo \"" + utxo.utxoRef.toString() + "\" without script source");
if (referenceScriptV2 !== undef) {
if (inputScript !== undef)
throw new Error("invalid input; multiple scripts specified");
var datum = referenceScriptV2.datum, redeemer = referenceScriptV2.redeemer, refUtxo_1 = referenceScriptV2.refUtxo;
var refScript = refUtxo_1.resolved.refScript;
if (refScript === undefined)
throw new Error("reference utxo specified (" + refUtxo_1.toString() + ") is missing an attached reference Script");
var sameRefPresent = refIns.find(function (u) { return eqUTxOByRef(u, refUtxo_1); });
if (sameRefPresent === undef) {
refIns.push(refUtxo_1);
var isScriptValid = true;
// `sort` mutates the array; so we `slice` (clone) first
var sortedIns = inputs.slice().sort(function (a, b) {
var ord = (0, uint8array_utils_1.lexCompare)(a.utxo.utxoRef.id.toBuffer(), b.utxo.utxoRef.id.toBuffer());
// if equal tx id order based on tx output index
if (ord === 0)
return a.utxo.utxoRef.index - b.utxo.utxoRef.index;
// else order by tx id
return ord;
});
var _inputs = inputs.map(function (input) {
var utxo = input.utxo, referenceScript = input.referenceScript, inputScript = input.inputScript;
var addr = utxo.resolved.address;
totInputValue = cardano_ledger_ts_1.Value.add(totInputValue, utxo.resolved.value);
if (addr.paymentCreds.type === cardano_ledger_ts_1.CredentialType.Script &&
referenceScript === undef &&
inputScript === undef)
throw new Error("spending script utxo \"" + utxo.utxoRef.toString() + "\" without script source");
if (referenceScript !== undef) {
if (inputScript !== undef)
throw new Error("invalid input; multiple scripts specified");
var datum = referenceScript.datum, redeemer = referenceScript.redeemer, refUtxo_1 = referenceScript.refUtxo;
var refScript = refUtxo_1.resolved.refScript;
if (refScript === undefined)
throw new Error("reference utxo specified (" + refUtxo_1.toString() + ") is missing an attached reference Script");
var sameRefPresent = refIns.find(function (u) { return eqUTxOByRef(u, refUtxo_1); });
if (sameRefPresent === undef) {
refIns.push(refUtxo_1);
}
var dat = pushWitDatum(datum, utxo.resolved.datum);
var i = sortedIns.indexOf(input);
if (i < 0)
throw new Error("input missing in sorted");
spendRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Spend
}));
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Spend, refScript, dat);
}
var dat = pushWitDatum(datum, utxo.resolved.datum);
var i = sortedIns.indexOf(input);
if (i < 0)
throw new Error("input missing in sorted");
spendRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Spend
}));
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Spend, refScript, dat);
}
if (inputScript !== undefined) {
if (referenceScriptV2 !== undefined)
throw new Error("invalid input; multiple scripts specified");
var datum = inputScript.datum, redeemer = inputScript.redeemer, script = inputScript.script;
pushWitScript(script);
var dat = pushWitDatum(datum, utxo.resolved.datum);
var i = sortedIns.indexOf(input);
if (i < 0)
throw new Error("input missing in sorted");
spendRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Spend
}));
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Spend, script, dat);
}
return new cardano_ledger_ts_1.TxIn(utxo);
});
// good luck spending more than 4294.967295 ADA in fees
// also 16.777215 ADA (3 bytes) is a lot; but CBOR only uses 2 or 4 bytes integers
// and 2 are ~0.06 ADA (too low) so go for 4;
var dummyFee = BigInt("0xffffffff");
var dummyOuts = outs.map(function (txO) { return txO.clone(); });
// add dummy change address output
dummyOuts.push(new cardano_ledger_ts_1.TxOut({
address: change.address,
value: cardano_ledger_ts_1.Value.sub(totInputValue, cardano_ledger_ts_1.Value.add(requiredOutputValue, cardano_ledger_ts_1.Value.lovelaces((0, ints_1.forceBigUInt)(this.protocolParamters.txFeePerByte)))),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum :
(0, CanBeData_1.forceData)(change.datum)) : undef,
refScript: change.refScript
}));
// index to be modified
var dummyMintRedeemers = [];
var _mint = mints === null || mints === void 0 ? void 0 : mints.reduce(function (accum, _a, i) {
var script = _a.script, value = _a.value;
var redeemer = script.redeemer;
var policyId = script.policyId;
var toExec = checkScriptAndPushIfInline(script);
dummyMintRedeemers.push([
policyId,
toExec,
new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Mint
})
]);
if (!(value.lovelaces === BigInt(0))) {
throw new Error("mint value containing non-zero ADA; lovelaces can't be minted or burned");
}
return cardano_ledger_ts_1.Value.add(accum, value);
}, cardano_ledger_ts_1.Value.zero);
function indexOfPolicy(policy) {
var _a;
var policyStr = policy.toString();
return (_a = _mint === null || _mint === void 0 ? void 0 : _mint.map.findIndex(function (entry) { return entry.policy.toString() === policyStr; })) !== null && _a !== void 0 ? _a : -1;
}
dummyMintRedeemers.forEach(function (_a) {
var _b = __read(_a, 3), policy = _b[0], toExec = _b[1], dummyRdmr = _b[2];
var i = indexOfPolicy(policy);
mintRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: dummyRdmr.data,
index: i - 1,
execUnits: dummyRdmr.execUnits,
tag: cardano_ledger_ts_1.TxRedeemerTag.Mint
if (inputScript !== undefined) {
if (referenceScript !== undefined)
throw new Error("invalid input; multiple scripts specified");
var datum = inputScript.datum, redeemer = inputScript.redeemer, script = inputScript.script;
pushWitScript(script);
var dat = pushWitDatum(datum, utxo.resolved.datum);
var i = sortedIns.indexOf(input);
if (i < 0)
throw new Error("input missing in sorted");
spendRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Spend
}));
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Spend, script, dat);
}
return new cardano_ledger_ts_1.TxIn(utxo);
});
// good luck spending more than 4294.967295 ADA in fees
// also 16.777215 ADA (3 bytes) is a lot; but CBOR only uses 2 or 4 bytes integers
// and 2 are ~0.06 ADA (too low) so go for 4;
var dummyFee = BigInt("0xffffffff");
var dummyOuts = outs.map(function (txO) { return txO.clone(); });
// add dummy change address output
dummyOuts.push(new cardano_ledger_ts_1.TxOut({
address: change.address,
value: cardano_ledger_ts_1.Value.sub(totInputValue, cardano_ledger_ts_1.Value.add(requiredOutputValue, cardano_ledger_ts_1.Value.lovelaces((0, ints_1.forceBigUInt)(this.protocolParamters.txFeePerByte)))),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum :
(0, CanBeData_1.forceData)(change.datum)) : undef,
refScript: change.refScript
}));
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Mint, toExec);
});
var _certs = certificates === null || certificates === void 0 ? void 0 : certificates.map(function (_a, i) {
var cert = _a.cert, script = _a.script;
if (script !== undef) {
certRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Cert
}));
// index to be modified
var dummyMintRedeemers = [];
var _mint = mints === null || mints === void 0 ? void 0 : mints.reduce(function (accum, _a, i) {
var script = _a.script, value = _a.value;
var redeemer = script.redeemer;
var policyId = value.policy;
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Cert, toExec);
dummyMintRedeemers.push([
policyId,
toExec,
new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Mint
})
]);
return cardano_ledger_ts_1.Value.add(accum, new cardano_ledger_ts_1.Value([value]));
}, cardano_ledger_ts_1.Value.zero);
totInputValue = _mint instanceof cardano_ledger_ts_1.Value ? cardano_ledger_ts_1.Value.add(totInputValue, _mint) : totInputValue;
function indexOfPolicy(policy) {
var _a;
var policyStr = policy.toString();
return (_a = _mint === null || _mint === void 0 ? void 0 : _mint.map.findIndex(function (entry) { return entry.policy.toString() === policyStr; })) !== null && _a !== void 0 ? _a : -1;
}
return cert;
});
var _wits = withdrawals === null || withdrawals === void 0 ? void 0 : withdrawals.sort(function (_a, _b) {
var fst = _a.withdrawal;
var snd = _b.withdrawal;
return (0, uint8array_utils_1.lexCompare)(fst.rewardAccount instanceof cardano_ledger_ts_1.Hash28 ?
fst.rewardAccount.toBuffer() :
fst.rewardAccount.credentials.toBuffer(), snd.rewardAccount instanceof cardano_ledger_ts_1.Hash28 ?
snd.rewardAccount.toBuffer() :
snd.rewardAccount.credentials.toBuffer());
}).map(function (_a, i) {
var withdrawal = _a.withdrawal, script = _a.script;
if (script !== undef) {
withdrawRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Withdraw
dummyMintRedeemers.forEach(function (_a) {
var _b = __read(_a, 3), policy = _b[0], toExec = _b[1], dummyRdmr = _b[2];
var i = indexOfPolicy(policy);
mintRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: dummyRdmr.data,
index: i - 1,
execUnits: dummyRdmr.execUnits,
tag: cardano_ledger_ts_1.TxRedeemerTag.Mint
}));
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Withdraw, toExec);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Mint, toExec);
});
var _certs = certificates === null || certificates === void 0 ? void 0 : certificates.map(function (_a, i) {
var cert = _a.cert, script = _a.script;
if (script !== undef) {
certRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Cert
}));
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Cert, toExec);
}
return cert;
});
var _wits = withdrawals === null || withdrawals === void 0 ? void 0 : withdrawals.sort(function (_a, _b) {
var fst = _a.withdrawal;
var snd = _b.withdrawal;
return (0, uint8array_utils_1.lexCompare)(fst.rewardAccount instanceof cardano_ledger_ts_1.Hash28 ?
fst.rewardAccount.toBuffer() :
fst.rewardAccount.credentials.toBuffer(), snd.rewardAccount instanceof cardano_ledger_ts_1.Hash28 ?
snd.rewardAccount.toBuffer() :
snd.rewardAccount.credentials.toBuffer());
}).map(function (_a, i) {
var withdrawal = _a.withdrawal, script = _a.script;
if (script !== undef) {
withdrawRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Withdraw
}));
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Withdraw, toExec);
}
return withdrawal;
});
var _votingProcedures = Array.isArray(votingProcedures) ?
new cardano_ledger_ts_1.VotingProcedures(votingProcedures === null || votingProcedures === void 0 ? void 0 : votingProcedures.map(function (_a, i) {
var votingProcedure = _a.votingProcedure, script = _a.script;
if (script !== undef) {
voteRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Voting
}));
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Voting, toExec);
}
return votingProcedure;
})) : undef;
// TODO
var _proposalProcedures = Array.isArray(proposalProcedures) ?
proposalProcedures.map(function (_a, i) {
var proposalProcedure = _a.proposalProcedure, script = _a.script;
if (script !== undef) {
voteRedeemers.push(new cardano_ledger_ts_1.TxRedeemer({
data: (0, CanBeData_1.forceData)(script.redeemer),
index: i,
execUnits: dummyExecBudget.clone(),
tag: cardano_ledger_ts_1.TxRedeemerTag.Proposing
}));
var toExec = checkScriptAndPushIfInline(script);
pushScriptToExec(i, cardano_ledger_ts_1.TxRedeemerTag.Proposing, toExec);
}
return new cardano_ledger_ts_1.ProposalProcedure(proposalProcedure);
}) : undef;
var auxData = metadata !== undefined ? new cardano_ledger_ts_1.AuxiliaryData({ metadata: metadata }) : undefined;
var redeemers = spendRedeemers
.concat(mintRedeemers)
.concat(withdrawRedeemers)
.concat(certRedeemers)
.concat(voteRedeemers)
.concat(proposeRedeemers);
var dummyTxWitnesses = new cardano_ledger_ts_1.TxWitnessSet({
vkeyWitnesses: vkeyWitnesses,
bootstrapWitnesses: bootstrapWitnesses,
datums: datums,
redeemers: redeemers,
nativeScripts: nativeScriptsWitnesses,
plutusV1Scripts: plutusV1ScriptsWitnesses,
plutusV2Scripts: plutusV2ScriptsWitnesses,
plutusV3Scripts: plutusV3ScriptsWitnesses
});
var datumsScriptData = datums.length > 0 ?
Array.from(cbor_1.Cbor.encode(new cbor_1.CborArray(datums.map(plutus_data_1.dataToCborObj))).toBuffer())
: [];
var languageViews = (0, cardano_costmodels_ts_1.costModelsToLanguageViewCbor)(this.protocolParamters.costModels, {
mustHaveV1: _hasV1Scripts,
mustHaveV2: _hasV2Scripts
}).toBuffer();
invalidBefore = invalidBefore === undef ? undef : (0, ints_1.forceBigUInt)(invalidBefore);
// if( invalidAfter !== undef )
// {
// if( invalidBefore === undef ) invalidBefore = 0;
// }
if ((0, ints_1.canBeUInteger)(invalidBefore) &&
(0, ints_1.canBeUInteger)(invalidAfter)) {
if (invalidBefore >= invalidAfter)
throw new Error("invalid validity interval; invalidAfter: "
+ invalidAfter.toString() +
"; was smaller (previous point in time) than invalidBefore:"
+ invalidBefore.toString());
}
return withdrawal;
});
var auxData = metadata !== undefined ? new cardano_ledger_ts_1.AuxiliaryData({ metadata: metadata }) : undefined;
var redeemers = spendRedeemers
.concat(mintRedeemers)
.concat(withdrawRedeemers)
.concat(certRedeemers);
var dummyTxWitnesses = new cardano_ledger_ts_1.TxWitnessSet({
vkeyWitnesses: vkeyWitnesses,
bootstrapWitnesses: bootstrapWitnesses,
datums: datums,
redeemers: redeemers,
nativeScripts: nativeScriptsWitnesses,
plutusV1Scripts: plutusV1ScriptsWitnesses,
plutusV2Scripts: plutusV2ScriptsWitnesses
});
var datumsScriptData = datums.length > 0 ?
Array.from(cbor_1.Cbor.encode(new cbor_1.CborArray(datums.map(plutus_data_1.dataToCborObj))).toBuffer())
: [];
var languageViews = (0, cardano_costmodels_ts_1.costModelsToLanguageViewCbor)(this.protocolParamters.costModels, {
mustHaveV1: _hasV1Scripts,
mustHaveV2: _hasV2Scripts
}).toBuffer();
invalidBefore = invalidBefore === undef ? undef : (0, ints_1.forceBigUInt)(invalidBefore);
// if( invalidAfter !== undef )
// {
// if( invalidBefore === undef ) invalidBefore = 0;
// }
if ((0, ints_1.canBeUInteger)(invalidBefore) &&
(0, ints_1.canBeUInteger)(invalidAfter)) {
if (invalidBefore >= invalidAfter)
throw new Error("invalid validity interval; invalidAfter: "
+ invalidAfter.toString() +
"; was smaller (previous point in time) than invalidBefore:"
+ invalidBefore.toString());
}
// assert collateral is present if needed
if (scriptsToExec.filter(function (s) { return s.script.type !== "NativeScript"; }).length > 0) {
if (!Array.isArray(collaterals) ||
collaterals.length <= 0)
throw new Error("tx includes plutus scripts to execute but no collateral input was provided");
var collateralValue = collaterals.reduce(function (accum, collateral) { return cardano_ledger_ts_1.Value.add(accum, collateral.resolved.value); }, cardano_ledger_ts_1.Value.zero);
if (!cardano_ledger_ts_1.Value.isAdaOnly(collateralValue)) {
if (!collateralReturn)
throw new Error("total collateral input value was including non-ADA value; no collateral return was specified\n" +
"total collateral input value was: ".concat(JSON.stringify(collateralValue.toJson(), undef, 2)));
var realCollValue = cardano_ledger_ts_1.Value.sub(collateralValue, collateralReturn.value);
if (!cardano_ledger_ts_1.Value.isAdaOnly(realCollValue))
throw new Error("total collateral value was including non-ADA value;\n" +
"total collateral value was: ".concat(JSON.stringify(realCollValue.toJson(), undef, 2)));
// assert collateral is present if needed
if (scriptsToExec.filter(function (s) { return s.script.type !== "NativeScript"; }).length > 0) {
if (!Array.isArray(collaterals) ||
collaterals.length <= 0)
throw new Error("tx includes plutus scripts to execute but no collateral input was provided");
var collateralValue = collaterals.reduce(function (accum, collateral) { return cardano_ledger_ts_1.Value.add(accum, collateral.resolved.value); }, cardano_ledger_ts_1.Value.zero);
if (!cardano_ledger_ts_1.Value.isAdaOnly(collateralValue)) {
if (!collateralReturn)
throw new Error("total collateral input value was including non-ADA value; no collateral return was specified\n" +
"total collateral input value was: ".concat(JSON.stringify(collateralValue.toJson(), undef, 2)));
var realCollValue = cardano_ledger_ts_1.Value.sub(collateralValue, collateralReturn.value);
if (!cardano_ledger_ts_1.Value.isAdaOnly(realCollValue))
throw new Error("total collateral value was including non-ADA value;\n" +
"total collateral value was: ".concat(JSON.stringify(realCollValue.toJson(), undef, 2)));
}
}
}
var dummyTx = new cardano_ledger_ts_1.Tx({
body: new cardano_ledger_ts_1.TxBody({
inputs: _inputs,
outputs: dummyOuts,
fee: dummyFee,
mint: _mint,
certs: _certs,
withdrawals: _wits,
refInputs: refIns.length === 0 ? undef : refIns.map(function (refIn) { return refIn instanceof cardano_ledger_ts_1.TxIn ? refIn : new cardano_ledger_ts_1.TxIn(refIn); }),
protocolUpdate: protocolUpdateProposal,
requiredSigners: requiredSigners,
collateralInputs: collaterals,
collateralReturn: collateralReturn === undef ?
undef :
(0, txBuild_1.txBuildOutToTxOut)(collateralReturn),
totCollateral: undef,
validityIntervalStart: invalidBefore === undef ?
undef :
(0, ints_1.forceBigUInt)(invalidBefore),
ttl: invalidAfter === undef ?
undef :
(0, ints_1.forceBigUInt)(invalidAfter),
auxDataHash: auxData === null || auxData === void 0 ? void 0 : auxData.hash,
scriptDataHash: getScriptDataHash(redeemers, datumsScriptData, languageViews),
network: network
}),
witnesses: dummyTxWitnesses,
auxiliaryData: auxData,
isScriptValid: isScriptValid
});
var minFeeMultiplier = (0, ints_1.forceBigUInt)(this.protocolParamters.txFeePerByte);
var nVkeyWits = BigInt((0, cardano_ledger_ts_1.getNSignersNeeded)(dummyTx.body));
var minFee = this.calcLinearFee(dummyTx) +
// consider also vkeys witnesses to be added
// each vkey witness has fixed size of 102 cbor bytes
// (1 bytes cbor array tag (length 2)) + (34 cbor bytes of length 32) + (67 cbor bytes of length 64)
// for a fixed length of 102
BigInt(102) * nVkeyWits * minFeeMultiplier +
// we add some more bytes for the array tag
BigInt(nVkeyWits < 24 ? 1 : (nVkeyWits < 256 ? 2 : 3)) * minFeeMultiplier;
var txOuts = new Array(outs.length + 1);
outs.forEach(function (txO, i) { return txOuts[i] = txO.clone(); });
txOuts[txOuts.length - 1] = (new cardano_ledger_ts_1.TxOut({
address: change.address,
value: cardano_ledger_ts_1.Value.sub(totInputValue, cardano_ledger_ts_1.Value.add(requiredOutputValue, cardano_ledger_ts_1.Value.lovelaces(minFee))),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum :
(0, CanBeData_1.forceData)(change.datum)) : undef,
refScript: change.refScript
}));
var tx = new cardano_ledger_ts_1.Tx(__assign(__assign({}, dummyTx), { body: new cardano_ledger_ts_1.TxBody(__assign(__assign({}, dummyTx.body), { outputs: txOuts, fee: minFee })) }));
return {
tx: tx,
scriptsToExec: scriptsToExec,
minFee: minFee,
datumsScriptData: datumsScriptData,
languageViews: languageViews,
totInputValue: totInputValue,
requiredOutputValue: requiredOutputValue,
outs: outs,
change: change
var dummyTx = new cardano_ledger_ts_1.Tx({
body: new cardano_ledger_ts_1.TxBody({
inputs: _inputs,
outputs: dummyOuts,
fee: dummyFee,
mint: _mint,
certs: _certs,
withdrawals: _wits,
refInputs: refIns.length === 0 ? undef : refIns.map(function (refIn) { return refIn instanceof cardano_ledger_ts_1.TxIn ? refIn : new cardano_ledger_ts_1.TxIn(refIn); }),
// protocolUpdate: protocolUpdateProposal,
requiredSigners: requiredSigners,
collateralInputs: collaterals,
collateralReturn: collateralReturn === undef ?
undef :
(0, txBuild_1.txBuildOutToTxOut)(collateralReturn),
totCollateral: undef,
validityIntervalStart: invalidBefore === undef ?
undef :
(0, ints_1.forceBigUInt)(invalidBefore),
ttl: invalidAfter === undef ?
undef :
(0, ints_1.forceBigUInt)(invalidAfter),
auxDataHash: auxData === null || auxData === void 0 ? void 0 : auxData.hash,
scriptDataHash: getScriptDataHash(redeemers, datumsScriptData, languageViews),
network: network,
votingProcedures: _votingProcedures,
proposalProcedures: _proposalProcedures,
currentTreasuryValue: currentTreasuryValue,
donation: paymentToTreasury,
}),
witnesses: dummyTxWitnesses,
auxiliaryData: auxData,
isScriptValid: isScriptValid
});
var minFeeMultiplier = (0, ints_1.forceBigUInt)(this.protocolParamters.txFeePerByte);
var nVkeyWits = BigInt((0, cardano_ledger_ts_1.getNSignersNeeded)(dummyTx.body));
var minFee = this.calcLinearFee(dummyTx) +
// consider also vkeys witnesses to be added
// each vkey witness has fixed size of 102 cbor bytes
// (1 bytes cbor array tag (length 2)) + (34 cbor bytes of length 32) + (67 cbor bytes of length 64)
// for a fixed length of 102
BigInt(102) * nVkeyWits * minFeeMultiplier +
// we add some more bytes for the array tag
BigInt(nVkeyWits < 24 ? 1 : (nVkeyWits < 256 ? 2 : 3)) * minFeeMultiplier;
var txOuts = new Array(outs.length + 1);
outs.forEach(function (txO, i) { return txOuts[i] = txO.clone(); });
txOuts[txOuts.length - 1] = (new cardano_ledger_ts_1.TxOut({
address: change.address,
value: cardano_ledger_ts_1.Value.sub(totInputValue, cardano_ledger_ts_1.Value.add(requiredOutputValue, cardano_ledger_ts_1.Value.lovelaces(minFee))),
datum: change.datum ? (change.datum instanceof cardano_ledger_ts_1.Hash32 ?
change.datum :
(0, CanBeData_1.forceData)(change.datum)) : undef,
refScript: change.refScript
}));
var tx = new cardano_ledger_ts_1.Tx(__assign(__assign({}, dummyTx), { body: new cardano_ledger_ts_1.TxBody(__assign(__assign({}, dummyTx.body), { outputs: txOuts, fee: minFee })) }));
return {
tx: tx,
scriptsToExec: scriptsToExec,
minFee: minFee,
datumsScriptData: datumsScriptData,
languageViews: languageViews,
totInputValue: totInputValue,
requiredOutputValue: requiredOutputValue,
outs: outs,
change: change
};
};
return TxBuilder;
}());
exports.TxBuilder = TxBuilder;
function eqUTxOByRef(a, b) {
return a === b || a.utxoRef === b.utxoRef || (a.utxoRef.index === b.utxoRef.index &&
a.utxoRef.id.toString() === b.utxoRef.id.toString());
}
function getCtx(scriptType, spendingPurpose, txInfosV1, txInfosV2) {
if (scriptType === cardano_ledger_ts_1.ScriptType.PlutusV2) {
function pushUniqueScript(arr, toPush) {
var hashToPush = toPush.hash.toString();
if (!arr.some(function (script) { return script.hash.toString() === hashToPush; }))
arr.push(toPush);
}
function getCtx(scriptType, spendingPurpose, txInfosV1, txInfosV2, txInfosV3) {
if (scriptType === cardano_ledger_ts_1.ScriptType.PlutusV3) {
return new plutus_data_1.DataConstr(0, [
txInfosV3,
spendingPurpose
]);
}
else if (scriptType === cardano_ledger_ts_1.ScriptType.PlutusV2) {
if (txInfosV2 === undefined)
throw new Error("plutus script v1 included in a v2 transaction");
return new plutus_data_1.DataConstr(0, [
txInfosV2,

@@ -809,3 +887,3 @@ spendingPurpose

if (txInfosV1 === undefined)
throw new Error("plutus script v1 included in a v2 transaction");
throw new Error("plutus script v1 included in a v2 or v3 transaction");
return new plutus_data_1.DataConstr(0, [

@@ -812,0 +890,0 @@ txInfosV1,

import type { ITxRunnerProvider } from "../IProvider/index.js";
import type { TxBuilder } from "../TxBuilder.js";
import { ITxBuildArgs } from "../../txBuild/index.js";
import { Address, AddressStr, Hash28, ITxOut, ITxOutRef, IUTxO, IValuePolicyEntry, PlutusScriptType, PoolParams, Script, ScriptType, StakeAddress, StakeAddressBech32, StakeCredentials, Tx, TxIn, TxMetadatum, TxOutRefStr, UTxO, Value } from "@harmoniclabs/cardano-ledger-ts";
import { NormalizedITxBuildArgs } from "../../txBuild/index.js";
import { Address, AddressStr, Hash28, ITxOut, ITxOutRef, IUTxO, IValuePolicyEntry, PlutusScriptType, Script, ScriptType, StakeAddress, StakeAddressBech32, Credential, Tx, TxIn, TxMetadatum, TxOutRefStr, UTxO, Value, IPoolParams, CanBeHash28, Vote, IAnchor, IVoter, ProtocolParameters, IProposalProcedure, ITxWithdrawals, TxWithdrawals, INewCommitteeEntry, IConstitution } from "@harmoniclabs/cardano-ledger-ts";
import { CanBeUInteger } from "../../utils/ints.js";
import { CanResolveToUTxO } from "../CanResolveToUTxO/CanResolveToUTxO.js";
import { CanBeData } from "../../utils/CanBeData.js";
import { CanBePoolKeyHash } from "./CanBePoolKeyHash.js";
import { CanBeStakeCreds } from "./CanBeStakeCreds.js";
import { IProtocolVerision } from "@harmoniclabs/cardano-ledger-ts/dist/ledger/protocol/protocolVersion";
import { Rational } from "../../utils/Rational.js";
declare const enum TxBuilderTaskKind {

@@ -35,3 +39,20 @@ ResolveUTxO = 0,

export declare class TxBuilderRunner {
/**
* if any unresolved data was passed it is resolved via the provider passed;
*
* if the method needed are not present on the provider throws an `Error`;
*
* finalizes the `TxBuilderRunner` instance,
* so that it can be re-used for other transactions,
*
* @returns {Promise<Tx>} a `Tx` instance
*/
readonly build: () => Promise<Tx>;
/**
* clears the `TxBuilderRunner` instance,
* so that it can be re-used for other transactions,
* making sure no other action where specified
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly reset: () => TxBuilderRunner;

@@ -42,2 +63,16 @@ /**

readonly addSigner: (signer: Address | StakeAddress | AddressStr | StakeAddressBech32) => TxBuilderRunner;
/**
* adds the **all** credentials of the address to the `requiredSigners`
* field of a `Tx` instance.
*
* only the signers included in that field are passed to a contract's `ScriptContext`.
*
* that includes payment credentials and, if present, stake credentials.
*
* if you have an address with both payment and stake credentials,
* but wish only to include one of them,
* consider using the `addRequiredSignerKey` method
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly addRequiredSigner: (signer: Address | StakeAddress | AddressStr | StakeAddressBech32) => TxBuilderRunner;

@@ -48,31 +83,105 @@ /**

readonly addSignerKey: (signerKey: Hash28) => TxBuilderRunner;
/**
* adds the given key hash to the `requiredSigners` field of a `Tx` instance.
*
* only the signers included in that field are passed to a contract's `ScriptContext`.
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly addRequiredSignerKey: (signerKey: Hash28) => TxBuilderRunner;
/** alias for `attachValidator` */
readonly attachCertificateValidator: (validator: Script<PlutusScriptType>) => TxBuilderRunner;
/** alias for `attachValidator` */
readonly attachMintingValidator: (validator: Script<PlutusScriptType>) => TxBuilderRunner;
/** alias for `attachValidator` */
readonly attachSpendingValidator: (validator: Script<PlutusScriptType>) => TxBuilderRunner;
/** alias for `attachValidator` */
readonly attachWithdrawalValidator: (validator: Script<PlutusScriptType>) => TxBuilderRunner;
/**
* includes the script in the witnessSet field of the resulting `Tx`
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly attachValidator: (validator: Script<PlutusScriptType>) => TxBuilderRunner;
/**
* adds a metadata entry for the given `label`,
* or overrides if the same `label` was already present.
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly attachMetadata: (label: CanBeUInteger, metadata: TxMetadatum) => TxBuilderRunner;
/** alias for `attachMetadata` */
/**
* alias for `attachMetadata`
*
* adds a metadata entry for the given `label`,
* or overrides if the same `label` was already present.
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly setMetadata: (label: CanBeUInteger, metadata: TxMetadatum) => TxBuilderRunner;
/**
* like [`attachMetadata`](./attachMetadata),
* adds a metadata entry for the given `label`,
* or overrides if the same `label` was already present.
*
* `metadataJson` is a jsavascript value converted as follows
*
* - `object` -> `TxMetadatumMap`
* - `array` -> `TxMetadatumList`
* - `string` -> `TxMetadatumText`
* (use `attachMetadataJsonWithConversion`
* for explicit conversion to `TxMetadatumBytes`
* or consider using `attachMetadata`)
* - `number` -> `TxMetadatumInt`
* - `bigint` -> `TxMetadatumInt`
*
* @returns a reference to the same [`TxBuilderRunner`](./TxBuilderRunner).
*/
readonly attachMetadataJson: (label: CanBeUInteger, metadataJson: any) => TxBuilderRunner;
/** like `attachMetadataJson` but if a strings starts with `0x` is treated as an hexadecimal byte string */
/** like `attachMetadataJson` but if a string starts with `0x` is treated as an hexadecimal byte string */
readonly attachMetadataJsonWithConversion: (label: CanBeUInteger, metadataJson: any) => TxBuilderRunner;
/**
* explicitly set the change address;
* if missing the first input's address with `PubKeyHash` credentials (not script) will be used
* explicitly sets the change address;
*
* if missing, an attempt to call the `ITxRunnerProvider` `getChangeAddress` method is done
*
* if still missing the first input's address with `PubKeyHash`
* payment credentials (not script) will be used
*
* if all the above fail, a call to the `build` method will throw an `Error`.
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly setChangeAddress: (changeAddr: Address | AddressStr) => TxBuilderRunner;
/**
* explicitly sets the collateral
* Sets the collateral input, and optionally output, for a transaction.
*
* if missing and the collateral is needed the tx builder will try to
* use one of the tx inputs as collateral
* If this method is not used,
* but the transaction needs collateral due to the presence of a plutus script,
* the `TxBuilderRunner` instance will try to use one of the normal inputs as collateral,
* see `setCollateralAmount`./setCollateralAmount for more infos.
*
* `collateral` can either be a resolved `UTxO`
* or an unresolved `ITxOutRef`
*
* in case it is an unresolved `ITxOutRef`
* a call to the `ITxRunnerProvider` `resolveUtxos` method
* is done in the `build` method;
* if `resolveUtxos` is missing on the provider the `build` method will throw an `Error`.
*
* an additional `collateralOutput` may be specified.
*
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly setCollateral: (collateral: CanResolveToUTxO, collateralOutput?: ITxOut) => TxBuilderRunner;
/**
* if no collateral is explicitly set (using `setCollateral`)
* Sets the collateral amount for a transaction.
*
* the tx builder will try to use one of the inputs as collateral
* in that case is possible to modify the collateral amount
* If `setCollateral` is not used,
* but the transaction needs collateral due to the presence of a plutus script,
* the `TxBuilderRunner` instance will try to use one of the normal inputs as collateral.
*
* In case this happens, it is possible to limit the amount of the collateral using this method.
*
* @returns a reference to the same `TxBuilderRunner`.
**/

@@ -85,32 +194,45 @@ readonly setCollateralAmount: (lovelaces: CanBeUInteger) => TxBuilderRunner;

/**
* @param {CanResolveToUTxO[]} utxos
* utxo (or utxo references to be resolved) to use as inputs
* @param {CanBeData | undefined} redeemer
* data used as redeemer in the event the utxo is locked in a script
* @param {UTxO | Script | undefined} script_or_ref
* optional script source; either by reference script (`UTxO`) or inline (`Script`)
* if none is provided the tx builder will try to get the matching to the UTxO associated address
* from scripts aviable trough any of the `addValidator` functions or any of the tef UTxOs aviable trough `referenceUtxos`
* @param {CanBeData | undefined} datum
* optional datum to be used in the event the spending utxo has datum setted as an hash
* if missing the provider `resolveDatumHashes` function will be used
* adds the given `utxos` to the transaction inputs;
* the elements of the array that don't satisfy the `IUTxO` interface
* will be resolved using the provider `resolveUtxos` method.
*
* this method does not allow to specify plutus realated arguments.
*
* for inputs that need redeemers, scripts and datums use `addInput`.
*
* @returns a reference to the same `TxBuilderRunner`.
**/
readonly addInputs: (utxos: CanResolveToUTxO[], redeemer?: CanBeData, script_or_ref?: UTxO | Script<PlutusScriptType>, datum?: CanBeData) => TxBuilderRunner;
readonly addInputs: (utxos: CanResolveToUTxO[]) => TxBuilderRunner;
/**
* @param {CanResolveToUTxO} utxos
* utxo (or utxo references to be resolved) to use as inputs
* @param {CanBeData | undefined} redeemer
* data used as redeemer in the event the utxo is locked in a script
* @param {UTxO | Script | undefined} script_or_ref
* optional script source; either by reference script (`UTxO`) or inline (`Script`)
* if none is provided the tx builder will try to get the matching to the UTxO associated address
* from scripts aviable trough any of the `addValidator` functions or any of the tef UTxOs aviable trough `referenceUtxos`
* @param {CanBeData | undefined} datum
* optional datum to be used in the event the spending utxo has datum setted as an hash
* if missing the provider `resolveDatumHashes` function will be used
* adds the given `utxo` to the transaction inputs;
* if`utxo` doesn't satisfy the `IUTxO` interface
* it will be resolved using the provider `resolveUtxos` method.
*
* `redeemer` and `script_or_ref` must be specified together;
* if `datum` is missing defaults to `"inline"`.
*
* if `script_or_ref` is a `Script`
* it will be included in the `witnesses`
* field of the resulting `Tx`;
*
* if `script_or_ref` satisfies the `IUTxO` interface
* it will be used as reference input to provide the attached reference script
* (`build` fails if missing)
*
* if `script_or_ref` satisfies the `ITxOutRef` interface
* or the `TxOutRefStr` type alias
* it will be resolved using the provider `resolveUtxos` method and
* it will be used as reference input to provide the attached reference script
* (`build` fails if missing)
*
* @returns a reference to the same `TxBuilderRunner`.
**/
readonly addInput: (utxos: CanResolveToUTxO, redeemer?: CanBeData, script_or_ref?: UTxO | Script<PlutusScriptType>, datum?: CanBeData) => TxBuilderRunner;
readonly addInput: (utxos: CanResolveToUTxO, redeemer?: CanBeData, script_or_ref?: CanResolveToUTxO | Script<PlutusScriptType>, datum?: CanBeData | "inline") => TxBuilderRunner;
/**
* adds an output to the transaction
* adds a transaction output.
*
* if `amount` is `number` or `bigint` it is intended to be lovelaces only.
*
* if `datum` is present is always added as inline datum.
*
* @param address receiver address

@@ -120,12 +242,13 @@ * @param amount Value to sent

* @param refScript optional reference script to attach
* @returns a reference to the same `TxBuilderRunner`.
*/
readonly payTo: (address: Address | AddressStr, amount: CanBeUInteger | Value, datum?: CanBeData, refScript?: Script<ScriptType.PlutusV2>) => TxBuilderRunner;
readonly mintAssets: (assets: IValuePolicyEntry, script_or_ref: Script | CanResolveToUTxO, redeemer?: CanBeData) => TxBuilderRunner;
readonly withdraw: (stakeAddress: CanBeStakeCreds, amount: CanBeUInteger, redeemer?: CanBeData, script_or_ref?: Script | CanResolveToUTxO) => TxBuilderRunner;
readonly delegateTo: (delegator: CanBeStakeCreds, poolId: CanBePoolKeyHash, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly deregisterStake: (delegator: CanBeStakeCreds, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly mintAssets: (assets: IValuePolicyEntry, redeemer?: CanBeData, script_or_ref?: Script | CanResolveToUTxO) => TxBuilderRunner;
readonly withdraw: (stakeAddress: CanBeStakeCreds, amount: CanBeUInteger, redeemer?: CanBeData, script_or_ref?: Script | CanResolveToUTxO) => TxBuilderRunner;
readonly registerPool: (params: PoolParams) => TxBuilderRunner;
readonly retirePool: (poolId: Hash28, epoch: CanBeUInteger) => TxBuilderRunner;
readonly registerPool: (params: IPoolParams) => TxBuilderRunner;
readonly retirePool: (poolId: CanBeHash28, epoch: CanBeUInteger) => TxBuilderRunner;
readonly registerStake: (delegator: CanBeStakeCreds, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly registerStakeAddress: (delegator: CanBeStakeCreds, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly deregisterStake: (delegator: CanBeStakeCreds, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
/**

@@ -142,11 +265,21 @@ * @deprecated `readFrom` is an ugly name; use `referenceUtxos` instead

readonly invalidAfterSlot: (slot: CanBeUInteger) => TxBuilderRunner;
readonly vote: (voter: IVoter, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly voteDRep: (drepKeyHash: CanBeHash28, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined) => TxBuilderRunner;
readonly voteScriptDRep: (drepScriptHash: CanBeHash28, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly voteConstitutionalComittee: (memberKeyHash: CanBeHash28, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined) => TxBuilderRunner;
readonly voteScriptConstitutionalComittee: (memberScriptHash: CanBeHash28, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly voteStakePool: (poolId: CanBeHash28, governanceActionId: ITxOutRef | TxOutRefStr, vote: Vote, anchor?: IAnchor | undefined) => TxBuilderRunner;
readonly propose: (proposal: IProposalProcedure, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeParametersChanges: (changes: Partial<ProtocolParameters>, procedureInfos: Omit<IProposalProcedure, "govAction">, govActionId?: ITxOutRef | TxOutRefStr, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeHardForkInitiation: (nextProtocolVersion: IProtocolVerision, procedureInfos: Omit<IProposalProcedure, "govAction">, govActionId?: ITxOutRef | TxOutRefStr, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeTreasuryWithdrawal: (withdrawals: ITxWithdrawals | TxWithdrawals, procedureInfos: Omit<IProposalProcedure, "govAction">, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeNoConfidence: (procedureInfos: Omit<IProposalProcedure, "govAction">, govActionId?: ITxOutRef | TxOutRefStr, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeComitteeUpdate: (toRemove: Credential[], toAdd: INewCommitteeEntry[], threshold: Rational, procedureInfos: Omit<IProposalProcedure, "govAction">, govActionId?: ITxOutRef | TxOutRefStr, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeNewConstitution: (constitution: IConstitution, procedureInfos: Omit<IProposalProcedure, "govAction">, govActionId?: ITxOutRef | TxOutRefStr, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly proposeInfos: (procedureInfos: Omit<IProposalProcedure, "govAction">, redeemer?: CanBeData, script_or_ref?: Script<PlutusScriptType> | CanResolveToUTxO) => TxBuilderRunner;
readonly tasks: TxBuilderTask[];
readonly buildArgs: ITxBuildArgs;
/**
* @experimental
*/
readonly buildArgs: NormalizedITxBuildArgs;
constructor(txBuilder: TxBuilder, provider: Partial<ITxRunnerProvider>);
}
export type CanBeStakeCreds = StakeAddress | StakeAddressBech32 | StakeCredentials | Script<PlutusScriptType>;
export type CanBePoolKeyHash = Hash28 | `pool1${string}` | `pool_test1${string}` | string | Uint8Array;
export declare function eqITxOutRef(a: ITxOutRef, b: ITxOutRef): boolean;
export {};
{
"name": "@harmoniclabs/plu-ts-offchain",
"version": "0.1.12",
"version": "0.1.13-dev0",
"description": "An embedded DSL for Cardano smart contracts creation coupled with a library for Cardano transactions, all in Typescript",

@@ -57,15 +57,15 @@ "main": "./dist/index.js",

"@harmoniclabs/bigint-utils": "^1.0.0",
"@harmoniclabs/crypto": "^0.1.0",
"@harmoniclabs/obj-utils": "^1.0.0",
"@harmoniclabs/uint8array-utils": "^1.0.0"
"@harmoniclabs/crypto": "^0.2.4",
"@harmoniclabs/uint8array-utils": "^1.0.0",
"@harmoniclabs/obj-utils": "^1.0.0"
},
"peerDependencies": {
"@harmoniclabs/pair": "^1.0.0",
"@harmoniclabs/bytestring": "^1.0.0",
"@harmoniclabs/cardano-costmodels-ts": "^1.0.0",
"@harmoniclabs/cardano-ledger-ts": "^0.1.3",
"@harmoniclabs/cbor": "^1.1.1",
"@harmoniclabs/pair": "^1.0.0",
"@harmoniclabs/plutus-data": "^1.0.0",
"@harmoniclabs/plutus-machine": "^1.0.2",
"@harmoniclabs/uplc": "^1.1.0"
"@harmoniclabs/cbor": "^1.3.0",
"@harmoniclabs/plutus-data": "^1.2.4",
"@harmoniclabs/cardano-costmodels-ts": "^1.1.0",
"@harmoniclabs/plutus-machine": "^1.1.2",
"@harmoniclabs/uplc": "^1.2.3",
"@harmoniclabs/cardano-ledger-ts": "^0.2.0-dev5"
},

@@ -81,8 +81,6 @@ "devDependencies": {

"jest-environment-jsdom": "^29.4.3",
"rollup": "^3.18.0",
"tsc-alias": "^1.7.1",
"typescript": "^4.6.3",
"v8-profiler-next": "^1.9.0"
"typescript": "^4.6.3"
},
"funding": "https://github.com/sponsors/HarmonicLabs"
}

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc