Utility Functions
Cardano DevKit provides comprehensive utility functions for working with the Cardano blockchain.
ADA Utilities
Functions for converting between ADA and Lovelace.
import {
adaToLovelace,
lovelaceToAda,
formatAda,
formatLovelace,
parseAda,
meetsMinUtxo,
calculateMinUtxo,
ADA,
} from 'cardano-devkit';
adaToLovelace(ada)
Convert ADA to Lovelace (1 ADA = 1,000,000 Lovelace).
const lovelace = adaToLovelace(5); // 5000000n
const lovelace = adaToLovelace(5.5); // 5500000n
const lovelace = adaToLovelace("5"); // 5000000n
lovelaceToAda(lovelace)
Convert Lovelace to ADA.
const ada = lovelaceToAda(5000000n); // 5
const ada = lovelaceToAda(5500000n); // 5.5
formatAda(ada, decimals?)
Format ADA with symbol.
formatAda(5.5); // "₳5.50"
formatAda(5.5, 0); // "₳6"
formatAda(1234567.89, 2); // "₳1,234,567.89"
formatLovelace(lovelace)
Format Lovelace as ADA with symbol.
formatLovelace(5500000n); // "₳5.50"
ADA Constant
One ADA in Lovelace.
const oneAda = ADA; // 1000000n
const fiveAda = 5n * ADA; // 5000000n
Address Utilities
Functions for validating and working with Cardano addresses.
import {
validateAddress,
isTestnetAddress,
isMainnetAddress,
isScriptAddress,
isStakeAddress,
truncateAddress,
getAddressNetwork,
sameNetwork,
validateAddressForNetwork,
} from 'cardano-devkit';
validateAddress(address)
Check if an address is valid.
validateAddress("addr_test1qz..."); // true
validateAddress("invalid"); // false
isTestnetAddress(address) / isMainnetAddress(address)
Check network type of address.
isTestnetAddress("addr_test1qz..."); // true
isMainnetAddress("addr1qy..."); // true
truncateAddress(address, start?, end?)
Truncate address for display.
truncateAddress("addr_test1qz...", 10, 6); // "addr_test1...abc123"
getAddressNetwork(address)
Get the network ID from an address.
getAddressNetwork("addr_test1qz..."); // "testnet"
getAddressNetwork("addr1qy..."); // "mainnet"
Transaction Utilities
Functions for building and sending transactions.
import {
sendAda,
sendMultiple,
sweepWallet,
sendWithMessage,
getWalletBalance,
waitForConfirmation,
findUtxosWithMinAda,
sumUtxoLovelace,
previewTransaction,
} from 'cardano-devkit';
sendAda(lucid, recipient, amount)
Send ADA to an address.
const result = await sendAda(lucid, "addr_test1...", 5000000n);
console.log("Tx Hash:", result.txHash);
sendMultiple(lucid, payments)
Send to multiple recipients in one transaction.
const result = await sendMultiple(lucid, [
{ address: "addr_test1...", lovelace: 5000000n },
{ address: "addr_test2...", lovelace: 3000000n },
]);
sweepWallet(lucid, recipient)
Send all available ADA to an address.
const result = await sweepWallet(lucid, "addr_test1...");
sendWithMessage(lucid, recipient, amount, message)
Send ADA with a CIP-20 message.
const result = await sendWithMessage(
lucid,
"addr_test1...",
5000000n,
"Hello from Cardano DevKit!"
);
getWalletBalance(lucid)
Get wallet balance in Lovelace.
const balance = await getWalletBalance(lucid);
console.log("Balance:", formatLovelace(balance));
waitForConfirmation(lucid, txHash, timeout?)
Wait for transaction confirmation.
const confirmed = await waitForConfirmation(lucid, txHash, 60000);
previewTransaction(lucid, tx)
Get a comprehensive preview of a transaction before signing.
const preview = await previewTransaction(lucid, unsignedTx);
console.log('Fee:', preview.fee);
console.log('Inputs:', preview.inputs.length);
console.log('Outputs:', preview.outputs.length);
console.log('Total Input:', preview.totalInput);
console.log('Total Output:', preview.totalOutput);
console.log('Net ADA Change:', preview.netAdaChange);
// Detailed input/output breakdown
for (const input of preview.inputs) {
console.log(`Input: ${input.txHash}#${input.outputIndex} - ${input.lovelace} lovelace`);
}
for (const output of preview.outputs) {
console.log(`Output: ${output.address} - ${output.lovelace} lovelace`);
if (output.assets) {
console.log(' Assets:', output.assets);
}
}
// Check for mints/burns
if (preview.mints.length > 0) {
console.log('Minting:', preview.mints);
}
// Check metadata
if (preview.metadata) {
console.log('Metadata:', preview.metadata);
}
// Check scripts
if (preview.scripts.length > 0) {
console.log('Scripts:', preview.scripts);
}
// Warnings and suggestions
for (const warning of preview.warnings) {
console.warn('Warning:', warning);
}
Returns:
interface TransactionPreview {
fee: bigint;
inputs: Array<{
txHash: string;
outputIndex: number;
address: string;
lovelace: bigint;
assets?: Record<string, bigint>;
}>;
outputs: Array<{
address: string;
lovelace: bigint;
assets?: Record<string, bigint>;
datum?: string;
}>;
totalInput: bigint;
totalOutput: bigint;
netAdaChange: bigint;
mints: Array<{ policyId: string; assetName: string; amount: bigint }>;
metadata?: Record<string, unknown>;
scripts: Array<{ hash: string; type: string }>;
validityRange?: { from?: number; to?: number };
warnings: string[];
estimatedSize: number;
}
Validation Utilities
Comprehensive validators for Cardano data types.
import {
validateTxHash,
validatePolicyId,
validateAssetName,
validateLovelaceAmount,
validateBlockHash,
validateDatumHash,
validateScriptHash,
validatePoolId,
validateStakeAddress,
validateMetadataLabel,
validateAssetUnit,
assertValidTxHash,
validateAll,
} from 'cardano-devkit';
validateTxHash(hash)
Validate transaction hash format.
validateTxHash("abc123..."); // ValidationResult
if (validateTxHash(hash).valid) {
// Use the hash
}
validatePolicyId(id)
Validate policy ID format (28 bytes hex).
validatePolicyId("abc123..."); // ValidationResult
validateLovelaceAmount(amount)
Validate Lovelace amount.
validateLovelaceAmount(5000000n); // { valid: true }
validateLovelaceAmount(-1n); // { valid: false, error: "..." }
assertValidTxHash(hash)
Throws if invalid (use in strict contexts).
assertValidTxHash(txHash); // throws ValidationError if invalid
validateAll(validators)
Run multiple validators at once.
const results = validateAll([
() => validateTxHash(txHash),
() => validateAddress(address),
() => validateLovelaceAmount(amount),
]);
// Returns array of ValidationResults
Time/Slot Utilities
Functions for working with Cardano slots and timestamps.
import {
timeToSlot,
slotToTime,
getCurrentSlot,
getSlotAtDate,
getDateAtSlot,
slotsBetween,
addSlots,
getTTLSlot,
timeUntilSlot,
isSlotPast,
createValidityRange,
formatTimeRemaining,
SLOT_CONFIGS,
} from 'cardano-devkit';
timeToSlot(timestamp, network?)
Convert Unix timestamp to slot number.
const slot = timeToSlot(Date.now(), "Preprod");
slotToTime(slot, network?)
Convert slot number to Unix timestamp.
const timestamp = slotToTime(12345678, "Preprod");
const date = new Date(timestamp);
getCurrentSlot(network?)
Get the current slot number.
const currentSlot = getCurrentSlot("Preprod");