Skip to main content

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");

getTTLSlot(network?, ttlMinutes?)

Get recommended TTL slot for transactions.

const ttl = getTTLSlot("Preprod", 30); // 30 minutes from now

createValidityRange(network?, options?)

Create a validity range for transactions.

const { from, to } = createValidityRange("Preprod", {
validFromMinutes: 0,
validToMinutes: 30,
});

Metadata Utilities

Functions for creating CIP-20, CIP-25, and CIP-68 metadata.

import {
createCIP20Message,
createCIP25Metadata,
createCIP68Metadata,
generateCIP68AssetNames,
splitMetadataString,
estimateMetadataSize,
CIP20_LABEL,
CIP25_LABEL,
} from 'cardano-devkit';

createCIP20Message(message)

Create CIP-20 transaction message metadata.

const metadata = createCIP20Message("Hello, Cardano!");
// Use with tx.attachMetadata(CIP20_LABEL, metadata);

createCIP25Metadata(policyId, assetName, metadata)

Create CIP-25 NFT metadata.

const nftMetadata = createCIP25Metadata(
"abc123...",
"MyNFT",
{
name: "My Amazing NFT",
image: "ipfs://Qm...",
description: "An awesome NFT",
attributes: [
{ trait_type: "Rarity", value: "Legendary" }
],
}
);

createCIP68Metadata(referenceData, userData?)

Create CIP-68 reference token metadata.

const { referenceMetadata, userMetadata } = createCIP68Metadata({
name: "My Token",
image: "ipfs://...",
}, {
owner: "addr_test1..."
});

generateCIP68AssetNames(baseName)

Generate CIP-68 asset names (reference and user tokens).

const { referenceAssetName, userAssetName } = generateCIP68AssetNames("MyToken");
// referenceAssetName: (000643b0)MyToken
// userAssetName: (000de140)MyToken

Script Utilities

Functions for working with Plutus scripts.

import {
getScriptHash,
getScriptAddress,
getPolicyId,
buildAssetUnit,
parseAssetUnit,
isNativeAsset,
mergeAssets,
findUtxoWithAsset,
} from 'cardano-devkit';

buildAssetUnit(policyId, assetName?)

Build asset unit from policy ID and asset name.

const unit = buildAssetUnit("abc123...", "MyToken");
// "abc123...4d79546f6b656e"

parseAssetUnit(unit)

Parse asset unit into components.

const { policyId, assetName, assetNameHex } = parseAssetUnit(unit);

mergeAssets(assets1, assets2)

Merge two asset maps.

const merged = mergeAssets(
{ "abc.token1": 100n },
{ "abc.token2": 50n }
);

Error Types

Typed errors for better error handling.

import {
CardanoDevKitError,
NetworkError,
TransactionError,
WalletError,
ValidationError,
InsufficientFundsError,
isTransactionError,
isWalletError,
} from 'cardano-devkit';

Error Handling Example

try {
await sendAda(lucid, recipient, amount);
} catch (error) {
if (isTransactionError(error)) {
console.error("Transaction failed:", error.message);
} else if (isWalletError(error)) {
console.error("Wallet error:", error.message);
} else {
throw error;
}
}

Error Recovery Utilities

Enhanced error handling with recovery suggestions and code examples.

import {
formatErrorWithRecovery,
formatErrorForUser,
tryAsync,
trySync,
getRecoverySuggestions,
CardanoDevKitError,
} from 'cardano-devkit';

Error with Recovery Suggestions

All Cardano DevKit errors include recovery suggestions:

try {
await sendAda(lucid, recipient, amount);
} catch (error) {
if (error instanceof CardanoDevKitError) {
console.error('Error:', error.message);

// Recovery suggestions
for (const suggestion of error.suggestions) {
console.log('Suggestion:', suggestion.action);
console.log('Description:', suggestion.description);
console.log('Requires user action:', suggestion.requiresUserAction);
}

// Code example for recovery
if (error.codeExample) {
console.log('Example fix:');
console.log(error.codeExample);
}
}
}

formatErrorWithRecovery(error)

Format error with full recovery information.

const formatted = formatErrorWithRecovery(error);
console.log(formatted);
// Output:
// ❌ TransactionError: Insufficient funds
//
// Context:
// • operation: payment
// • network: Preprod
// • required: 100 ADA
// • available: 50 ADA
//
// Recovery Suggestions:
// 1. [User Action] Fund wallet with more ADA
// Use a faucet for testnet or transfer from another wallet.
// 2. [Auto] Reduce transaction amount
// Lower the amount to fit within available balance.
//
// Example:
// const faucet = createDevnetFaucet();
// await faucet.fundAddress(walletAddress, 100_000_000n);

formatErrorForUser(error)

Format error for end-user display (no technical details).

const userMessage = formatErrorForUser(error);
// "Unable to complete transaction. Please ensure you have enough ADA in your wallet."

tryAsync / trySync

Safe execution wrappers that return Result types.

import { tryAsync, trySync } from 'cardano-devkit';

// Async operations
const result = await tryAsync(async () => {
return await sendAda(lucid, recipient, amount);
});

if (result.success) {
console.log('Transaction hash:', result.value.txHash);
} else {
console.error('Failed:', result.error.message);
console.log('Suggestions:', result.error.suggestions);
}

// Sync operations
const syncResult = trySync(() => {
return validateAddress(address);
});

if (!syncResult.success) {
console.error('Validation failed:', syncResult.error);
}

getRecoverySuggestions(error)

Extract recovery suggestions from any error.

const suggestions = getRecoverySuggestions(error);
for (const s of suggestions) {
if (s.requiresUserAction) {
showUserPrompt(s.action, s.description);
} else {
await attemptAutoRecovery(s);
}
}

Creating Errors with Recovery Info

When throwing errors, include recovery information:

import { TransactionError, InsufficientFundsError } from 'cardano-devkit';

throw new TransactionError('Failed to build transaction', {
code: 'TX_BUILD_FAILED',
context: {
operation: 'payment',
network: 'Preprod',
},
suggestions: [
{
action: 'Check UTxO balance',
description: 'Ensure wallet has sufficient UTxOs',
requiresUserAction: true,
},
{
action: 'Split large UTxOs',
description: 'Transaction may need smaller UTxOs',
requiresUserAction: false,
},
],
codeExample: `
// Check balance first
const balance = await quickBalance(devKit);
if (balance.ada < requiredAmount) {
await faucet.fundAddress(address, neededLovelace);
}
`.trim(),
});