@lucid-evolution/lucid
Version:
Next-generation transaction builder for highly scalable dApps on Cardano
512 lines (500 loc) • 22 kB
text/typescript
import { Network, Wallet, PrivateKey, TransactionWitnesses, Address, UTxO, RedeemerBuilder, Assets, Script, RewardAddress, PaymentKeyHash, StakeKeyHash, Lovelace, Anchor, PoolId, Redeemer, DRep, Label, TxOutput, ScriptType, Provider, ProtocolParameters, Transaction, WalletApi, UnixTime, Credential, OutRef, Delegation } from '@lucid-evolution/core-types';
export * from '@lucid-evolution/core-types';
import * as CML from '@anastasia-labs/cardano-multiplatform-lib-nodejs';
export { CML };
import * as effect_Either from 'effect/Either';
import { Either } from 'effect/Either';
import { Effect, Context } from 'effect';
import * as effect_Cause from 'effect/Cause';
import * as effect_Types from 'effect/Types';
import { Data } from '@lucid-evolution/plutus';
export * from '@lucid-evolution/plutus';
export * from '@lucid-evolution/core-utils';
export * from '@lucid-evolution/provider';
export * from '@lucid-evolution/sign_data';
export * from '@lucid-evolution/utils';
export * from '@lucid-evolution/wallet';
declare const makeReturn: <A, E>(program: Effect.Effect<A, E>) => {
unsafeRun: () => Promise<A>;
safeRun: () => Promise<effect_Either.Either<A, E>>;
program: () => Effect.Effect<A, E, never>;
};
type Hash = string;
type CBORHex = string;
type OutputDatum = {
kind: "hash";
value: Hash;
} | {
kind: "asHash";
value: CBORHex;
} | {
kind: "inline";
value: CBORHex;
};
type TransactionMetadata = string | number | Uint8Array | ReadonlyArray<TransactionMetadata> | {
[key: string]: TransactionMetadata;
};
declare const ERROR_MESSAGE: {
readonly MULTIPLE_POLICIES: "MULTIPLE_POLICIES: Only one policy id allowed. You can chain multiple mintAssets functions together if you need to mint assets with different policy ids. ";
readonly EMPTY_UTXO: "EMPTY_UTXO: UTxO array is empty. If a Tx has been recently submitted, consider waiting for chain sync";
readonly MISSING_WALLET: "MISSING_WALLET: please ensure that your wallet has been properly configured and initialized";
readonly MISSING_REDEEMER: "MISSING_REDEEMER: redeemer can not be undefined";
readonly DATUM_NOT_SET: "DATUM_NOT_SET: Script inputs becomes unspendable without datum.";
readonly EMPTY_ASSETS: "EMPTY_ASSETS: Attempting to pay to an address with an empty assets object";
readonly MISSING_REWARD_TYPE: "MISSING_REWARD_TYPE: Address type must be Reward type.";
readonly MISSING_STAKE_CREDENTIAL: "MISSING_STAKE_CREDENTIAL: Address does not contain stake credential";
readonly MISSING_PAYMENT_CREDENTIAL: "MISSING_PAYMENT_CREDENTIAL: Address does not contain payment credential";
readonly INVALID_METADATA: "INVALID_METADATA: metadata is invalid";
readonly SCRIPT_CREDENTIAL_NOT_ALLOWED: "SCRIPT_CREDENTIAL_NOT_ALLOWED: Only verification key credential is allowed";
readonly INVALID_SCRIPT: "INVALID_SCRIPT: Script is invalid";
readonly EXPECTED_KEY_HASH: "EXPECTED_KEY_HASH";
readonly INVALID_NETWORK: (address: string, actualNetworkId: number, network: Network) => string;
readonly MISSING_SCRIPT: (hash: string) => string;
readonly MISSING_POLICY: (policyId: string) => string;
};
declare const NullableError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "NullableError";
} & Readonly<A>;
declare class NullableError extends NullableError_base<{
readonly message: string;
}> {
}
declare const UnauthorizedNetwork_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "UnauthorizedNetwork";
} & Readonly<A>;
declare class UnauthorizedNetwork extends UnauthorizedNetwork_base<{
readonly message: string;
}> {
}
declare const TxBuilderError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "TxBuilderError";
} & Readonly<A>;
declare class TxBuilderError extends TxBuilderError_base<{
readonly cause: unknown;
}> {
get message(): string;
}
type TransactionError = RunTimeError | TxBuilderError;
declare const TxSignerError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "TxSignerError";
} & Readonly<A>;
declare class TxSignerError extends TxSignerError_base<{
readonly cause: unknown;
}> {
get message(): string;
}
type TransactionSignError = RunTimeError | TxSignerError;
declare const TxSubmitError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "TxSubmitError";
} & Readonly<A>;
declare class TxSubmitError extends TxSubmitError_base<{
readonly cause: unknown;
}> {
get message(): string;
}
declare const RunTimeError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
readonly _tag: "RunTimeError";
} & Readonly<A>;
declare class RunTimeError extends RunTimeError_base<{
cause: unknown;
}> {
get message(): string;
}
interface TxSigned {
/** Submits the transaction and returns the transaction hash.
*
* Supports both canonical and non-canonical formats.
*
* Canonical format follows [RFC 7049 Section 3.9](https://datatracker.ietf.org/doc/html/rfc7049#section-3.9) rules
*
* Non-canonical format example:
* ```typescript
* .submit();
* ```
* Canonical format example:
* ```typescript
* .submit({ canonical: true });
* ```
*/
submit: (options?: {
canonical: boolean;
}) => Promise<string>;
/** Submits the transaction and returns the transaction hash or error as an effect.
*
* Supports both canonical and non-canonical formats.
*
* Canonical format follows [RFC 7049 Section 3.9](https://datatracker.ietf.org/doc/html/rfc7049#section-3.9) rules
*
* Non-canonical format example:
* ```typescript
* .submitProgram();
* ```
* Canonical format example:
* ```typescript
* .submitProgram({ canonical: true });
* ```
*/
submitProgram: (options?: {
canonical: boolean;
}) => Effect.Effect<string, TxSubmitError, never>;
/** Safely submits the transaction, returning the transaction hash or an error as promise either type.
*
* Supports both canonical and non-canonical formats.
*
* Canonical format follows [RFC 7049 Section 3.9](https://datatracker.ietf.org/doc/html/rfc7049#section-3.9) rules
*
* Non-canonical format example:
* ```typescript
* .submitSafe();
* ```
* Canonical format example:
* ```typescript
* .submitSafe({ canonical: true });
* ```
*/
submitSafe: (options?: {
canonical: boolean;
}) => Promise<Either<string, TxSubmitError>>;
/**
* Converts the transaction to CBOR (Concise Binary Object Representation) format.
*
* Supports both canonical and non-canonical formats.
*
* Canonical format follows [RFC 7049 Section 3.9](https://datatracker.ietf.org/doc/html/rfc7049#section-3.9) rules
*
* Non-canonical format example:
* ```typescript
* .toCBOR();
* ```
* Canonical format example:
* ```typescript
* .toCBOR({ canonical: true });
* ```
*/
toCBOR: (options?: {
canonical: boolean;
}) => CBORHex;
toTransaction: () => CML.Transaction;
/** Converts the transaction (transaction body and witnesses) to JSON format. */
toJSON: () => object;
/** Computes the hash of the transaction. */
toHash: () => Hash;
}
declare const makeSubmit: (wallet: Wallet, txSigned: CML.Transaction) => TxSigned;
interface TxSignBuilderConfig {
txComplete: CML.Transaction;
witnessSetBuilder: CML.TransactionWitnessSetBuilder;
programs: Effect.Effect<void, TransactionSignError, never>[];
wallet: Wallet | undefined;
fee: number;
exUnits: {
cpu: number;
mem: number;
} | null;
}
interface TxSignBuilder {
sign: {
/** Signs the transaction with a wallet. */
withWallet: () => TxSignBuilder;
/** Signs the transaction with a private key. */
withPrivateKey: (privateKey: PrivateKey) => TxSignBuilder;
};
partialSign: {
/** Partially signs the transaction with a wallet. */
withWallet: () => Promise<TransactionWitnesses>;
/** Partially signs the transaction with a wallet and returns an effect. */
withWalletEffect: () => Effect.Effect<TransactionWitnesses, TransactionSignError>;
/** Safely partially signs the transaction with a wallet. */
withWalletSafe: () => Promise<Either<TransactionWitnesses, TransactionSignError>>;
/** Partially signs the transaction with a private key. */
withPrivateKey: (privateKey: PrivateKey) => Promise<TransactionWitnesses>;
/** Partially signs the transaction with a private key and returns an effect. */
withPrivateKeyEffect: (privateKey: PrivateKey) => Effect.Effect<TransactionWitnesses, TransactionSignError>;
/** Safely partially signs the transaction with a private key. */
withPrivateKeySafe: (privateKey: PrivateKey) => Promise<Either<TransactionWitnesses, TransactionSignError>>;
};
/** Assembles the transaction with the given witnesses. */
assemble: (witnesses: TransactionWitnesses[]) => TxSignBuilder;
/**
* Converts the transaction to CBOR (Concise Binary Object Representation) format.
*
* Supports both canonical and non-canonical formats.
*
* Canonical format follows [RFC 7049 Section 3.9](https://datatracker.ietf.org/doc/html/rfc7049#section-3.9) rules
*
* Non-canonical format example:
* ```typescript
* .toCBOR();
* ```
* Canonical format example:
* ```typescript
* .toCBOR({ canonical: true });
* ```
*/
toCBOR: (options?: {
canonical: boolean;
}) => CBORHex;
toTransaction: () => CML.Transaction;
/** Converts the transaction body to JSON format. */
toJSON: () => object;
/** Computes the hash of the transaction body. */
toHash: () => Hash;
complete: () => Promise<TxSigned>;
/** Completes the transaction and returns an effect. */
completeProgram: () => Effect.Effect<TxSigned, TransactionSignError, never>;
/** Safely completes the transaction. */
completeSafe: () => Promise<Either<TxSigned, TransactionSignError>>;
}
declare const makeTxSignBuilder: (wallet: Wallet | undefined, tx: CML.Transaction) => TxSignBuilder;
declare const TxConfig_base: Context.TagClass<TxConfig, "TxConfig", {
readonly config: TxBuilderConfig;
}>;
declare class TxConfig extends TxConfig_base {
}
type CompleteOptions = {
/**
* Enable coin selection algorithm
* @default true
*/
coinSelection?: boolean;
/**
* Address to send change to
* @default wallet.address()
*/
changeAddress?: Address;
/**
* Enable local UPLC evaluation
* @default true
*/
localUPLCEval?: boolean;
/**
* Amount to set as collateral
* @default 5_000_000n
*/
setCollateral?: bigint;
/**
* Use canonical ordering
* @default false
*/
canonical?: boolean;
/**
* Include leftover lovelace in the transaction fee if there are no additional inputs available to cover the change output address.
* @default false
*/
includeLeftoverLovelaceAsFee?: boolean;
/**
* Preset UTXOs from the wallet to include in coin selection.
* If not provided, wallet UTXOs will be fetched by the provider.
*
* Note:
* UTXOs already specified in `collectFrom` will not cause duplication
* @default []
*/
presetWalletInputs?: UTxO[];
};
type TxBuilderConfig = {
readonly lucidConfig: LucidConfig;
readonly txBuilder: CML.TransactionBuilder;
walletInputs: UTxO[];
collectedInputs: UTxO[];
readInputs: UTxO[];
consumedInputs: UTxO[];
totalOutputAssets: Assets;
payToOutputs: TxOutput[];
mintedAssets: Assets;
scripts: Map<string, {
type: ScriptType;
script: string;
}>;
programs: Effect.Effect<void, TransactionError, TxConfig>[];
partialPrograms: Map<RedeemerBuilder, (redeemer?: string) => Effect.Effect<void, TransactionError, TxConfig>>;
minFee: bigint | undefined;
};
type TxBuilder = {
readFrom: (utxos: UTxO[]) => TxBuilder;
collectFrom: (utxos: UTxO[], redeemer?: string | RedeemerBuilder) => TxBuilder;
pay: {
ToAddress: (address: string, assets: Assets) => TxBuilder;
/**
* Creates an output that lock funds to a target address, with optional parameters for attaching a datum, assets, and a reference script.
*
* **Warning:** When working with Plutus V1 or V2 contracts, omitting the `outputDatum` can result in a permanently locked UTXO.
*
* @example
* ```ts
* const refScript: Script = {
* type: "PlutusV3",
* script: "450100002499",
* };
*
* const signBuilder = await user
* .newTx()
* .pay.ToAddressWithData(
* "addr1q98wl3hnya9l94rt58ky533deyqe9t8zz5n9su26k8e5g23yar4q0adtaax9q9g0kphpv2ws7vxqwu6ln6pqx7j29nfqsfy9mg",
* {
* kind: "inline",
* value: "d8799f44deadbeefff",
* },
* { lovelace: 10_000_000n },
* refScript
* )
* .complete();
* ```
*/
ToAddressWithData: (address: string, outputDatum?: OutputDatum, assets?: Assets | undefined, scriptRef?: Script | undefined) => TxBuilder;
/**
* Creates an output that lock funds to a target address, with optional parameters for attaching a datum, assets, and a reference script.
*
* **Warning:** When working with Plutus V1 or V2 contracts, omitting the `outputDatum` can result in a permanently locked UTXO.
*
* @example
* ```ts
* const refScript: Script = {
* type: "PlutusV3",
* script: "450100002499",
* };
*
* const signBuilder = await user
* .newTx()
* .pay.ToContract(
* "addr1q98wl3hnya9l94rt58ky533deyqe9t8zz5n9su26k8e5g23yar4q0adtaax9q9g0kphpv2ws7vxqwu6ln6pqx7j29nfqsfy9mg",
* {
* kind: "inline",
* value: "d8799f44deadbeefff",
* },
* { lovelace: 10_000_000n },
* refScript
* )
* .complete();
* ```
*/
ToContract: (address: string, outputDatum?: OutputDatum, assets?: Assets | undefined, scriptRef?: Script | undefined) => TxBuilder;
};
addSigner: (address: Address | RewardAddress) => TxBuilder;
addSignerKey: (keyHash: PaymentKeyHash | StakeKeyHash) => TxBuilder;
/**
* NOTE: Deprecate in future version
*/
registerStake: (rewardAddress: RewardAddress) => TxBuilder;
/**
* NOTE: Deprecate in future version
*/
deRegisterStake: (rewardAddress: RewardAddress, redeemer?: string) => TxBuilder;
withdraw: (rewardAddress: RewardAddress, amount: Lovelace, redeemer?: string | RedeemerBuilder) => TxBuilder;
register: {
Stake: (rewardAddress: RewardAddress) => TxBuilder;
DRep: (rewardAddress: RewardAddress, anchor?: Anchor, redeemer?: string) => TxBuilder;
};
deregister: {
Stake: (rewardAddress: RewardAddress, redeemer?: string) => TxBuilder;
DRep: (rewardAddress: RewardAddress, redeemer?: string) => TxBuilder;
};
mintAssets: (assets: Assets, redeemer?: string | RedeemerBuilder) => TxBuilder;
validFrom: (unixTime: number) => TxBuilder;
validTo: (unixTime: number) => TxBuilder;
/**
* NOTE: Deprecate in future version
*/
delegateTo: (rewardAddress: RewardAddress, poolId: PoolId, redeemer?: Redeemer) => TxBuilder;
delegate: {
ToPool: (rewardAddress: RewardAddress, poolId: PoolId, redeemer?: Redeemer) => TxBuilder;
VoteToDRep: (rewardAddress: RewardAddress, drep: DRep, redeemer?: Redeemer) => TxBuilder;
VoteToPoolAndDRep: (rewardAddress: RewardAddress, poolId: PoolId, drep: DRep, redeemer?: Redeemer) => TxBuilder;
};
registerAndDelegate: {
ToPool: (rewardAddress: RewardAddress, poolId: PoolId, redeemer?: Redeemer) => TxBuilder;
ToDRep: (rewardAddress: RewardAddress, drep: DRep, redeemer?: Redeemer) => TxBuilder;
ToPoolAndDRep: (rewardAddress: RewardAddress, poolId: PoolId, drep: DRep, redeemer?: Redeemer) => TxBuilder;
};
updateDRep: (rewardAddress: RewardAddress, anchor?: Anchor, redeemer?: Redeemer) => TxBuilder;
authCommitteeHot: (coldAddress: RewardAddress, hotAddress: RewardAddress) => TxBuilder;
resignCommitteeHot: (coldAddress: RewardAddress, anchor?: Anchor) => TxBuilder;
attachMetadata: (label: Label, metadata: TransactionMetadata) => TxBuilder;
attach: {
Script: (script: Script) => TxBuilder;
SpendingValidator: (spendingValidator: Script) => TxBuilder;
MintingPolicy: (mintingPolicy: Script) => TxBuilder;
CertificateValidator: (certValidator: Script) => TxBuilder;
WithdrawalValidator: (withdrawalValidator: Script) => TxBuilder;
VoteValidator: (voteValidator: Script) => TxBuilder;
ProposeValidator: (proposeValidator: Script) => TxBuilder;
};
compose: (tx: TxBuilder | null) => TxBuilder;
setMinFee: (fee: bigint) => TxBuilder;
complete: (options?: CompleteOptions) => Promise<TxSignBuilder>;
completeProgram: (options?: CompleteOptions) => Effect.Effect<TxSignBuilder, TransactionError>;
completeSafe: (options?: CompleteOptions) => Promise<Either<TxSignBuilder, TransactionError>>;
chainProgram: (options?: CompleteOptions) => Effect.Effect<[
UTxO[],
UTxO[],
TxSignBuilder
], TransactionError, never>;
chain: (options?: CompleteOptions) => Promise<[UTxO[], UTxO[], TxSignBuilder]>;
chainSafe: (options?: CompleteOptions) => Promise<Either<[UTxO[], UTxO[], TxSignBuilder], TransactionError>>;
/**
* **Warning:** This method executes all programs and mutates the TxBuilder state.
*
* Calling `.complete()` after executing this function will lead to unexpected behavior.
*
* It is recommended to call `.config()` only for debugging purposes
*/
config: () => Promise<TxBuilderConfig>;
/**
* Returns the raw TxBuilderConfig
*/
rawConfig: () => TxBuilderConfig;
/**
* Returns the current lucid instance configuration
*/
lucidConfig: () => LucidConfig;
/**
* Returns the current txbuilder programs
*/
getPrograms: () => Effect.Effect<void, TransactionError, TxConfig>[];
};
declare function makeTxBuilder(lucidConfig: LucidConfig): TxBuilder;
type LucidEvolution = {
config: () => Partial<LucidConfig>;
wallet: () => Wallet;
overrideUTxOs: (utxos: UTxO[]) => void;
switchProvider: (provider: Provider) => Promise<void>;
newTx: () => TxBuilder;
fromTx: (tx: Transaction) => TxSignBuilder;
selectWallet: {
fromSeed: (seed: string, options?: {
addressType?: "Base" | "Enterprise";
accountIndex?: number;
password?: string;
}) => void;
fromPrivateKey: (privateKey: PrivateKey) => void;
fromAPI: (walletAPI: WalletApi) => void;
fromAddress: (address: string, utxos: UTxO[]) => void;
};
currentSlot: () => number;
unixTimeToSlot: (unixTime: UnixTime) => number;
utxosAt: (addressOrCredential: string | Credential) => Promise<UTxO[]>;
utxosAtWithUnit: (addressOrCredential: string | Credential, unit: string) => Promise<UTxO[]>;
utxoByUnit: (unit: string) => Promise<UTxO>;
utxosByOutRef: (outRefs: OutRef[]) => Promise<UTxO[]>;
delegationAt: (rewardAddress: string) => Promise<Delegation>;
awaitTx: (txHash: string, checkInterval?: number | undefined) => Promise<boolean>;
datumOf: <T extends Data>(utxo: UTxO, type?: T | undefined) => Promise<T>;
metadataOf: <T = any>(unit: string) => Promise<T>;
};
type LucidConfig = {
provider: Provider;
network: Network;
wallet: Wallet | undefined;
txbuilderconfig: CML.TransactionBuilderConfig;
costModels: CML.CostModels;
protocolParameters: ProtocolParameters;
};
type LucidOptions = {
/**
* Predefined protocol parameters to use instead of retrieving them from the provider.
* If not specified, it will fetch the latest protocol parameters from the provider.
*/
presetProtocolParameters?: ProtocolParameters;
};
declare const Lucid: (provider?: Provider | undefined, network?: Network, options?: LucidOptions) => Promise<LucidEvolution>;
export { type CBORHex, ERROR_MESSAGE, type Hash, Lucid, type LucidConfig, type LucidEvolution, NullableError, type OutputDatum, RunTimeError, type TransactionError, type TransactionSignError, type TxBuilder, type TxBuilderConfig, TxBuilderError, type TxSignBuilder, type TxSignBuilderConfig, type TxSigned, TxSignerError, TxSubmitError, UnauthorizedNetwork, makeReturn, makeSubmit, makeTxBuilder, makeTxSignBuilder };