Skip to main content

Namespace Imports

Cardano DevKit provides organized namespace imports that group related functionality together. This makes code more readable and reduces the number of individual imports you need.

Overview

Instead of importing many individual functions:

// ❌ Traditional imports - many lines
import {
adaToLovelace,
lovelaceToAda,
formatAda,
validateAddress,
getAddressDetails,
createBatchBuilder,
// ... many more
} from "cardano-devkit";

Use namespace imports for cleaner code:

// ✅ Namespace imports - organized and clear
import { ADA, Address, Batch, Transaction } from "cardano-devkit/namespaces";

// Use with clear context
const lovelace = ADA.toLovelace(100);
const isValid = Address.validate(addr);
const builder = Batch.createBuilder(lucid);

Available Namespaces

DevKit

Core DevKit functionality for network and provider management.

import { DevKit } from "cardano-devkit/namespaces";

const devkit = DevKit.create({ network: "Preprod" });
await devkit.init();
const lucid = devkit.getLucid();
const status = devkit.getStatus();
const health = await devkit.healthCheck();

Contents:

  • create() - Create a new DevKit instance
  • CardanoDevKit - The main DevKit class

ADA

ADA and Lovelace conversion utilities.

import { ADA } from "cardano-devkit/namespaces";

const lovelace = ADA.toLovelace(100); // 100 ADA → 100_000_000n lovelace
const ada = ADA.toAda(5_000_000n); // 5_000_000n lovelace → 5 ADA
const formatted = ADA.format(2_500_000n); // "2.5 ₳"
const parsed = ADA.parse("10.5"); // 10_500_000n

Contents:

  • toLovelace() - Convert ADA to lovelace
  • toAda() - Convert lovelace to ADA
  • format() - Format lovelace as readable ADA string
  • parse() - Parse ADA string to lovelace
  • LOVELACE_PER_ADA - Constant (1_000_000n)

Address

Address validation and utilities.

import { Address } from "cardano-devkit/namespaces";

const isValid = Address.validate(addr);
const details = Address.getDetails(addr);
const network = Address.getNetwork(addr);
const type = Address.getType(addr);

Contents:

  • validate() - Check if address is valid
  • getDetails() - Get address components
  • getNetwork() - Get network from address
  • getType() - Get address type (base, enterprise, etc.)

Transaction

Transaction building and preview utilities.

import { Transaction } from "cardano-devkit/namespaces";

// Build a simple payment
const txHash = await Transaction.sendLovelace(lucid, recipient, amount);

// Preview before signing
const preview = await Transaction.preview(lucid, unsignedTx);
console.log(preview.estimatedFee);
console.log(preview.inputs);
console.log(preview.outputs);

// Wait for confirmation
await Transaction.awaitConfirmation(lucid, txHash);

Contents:

  • sendLovelace() - Simple ADA transfer
  • sendAssets() - Send multiple assets
  • preview() - Detailed transaction preview
  • awaitConfirmation() - Wait for tx confirmation
  • getMetadata() - Extract transaction metadata

NFT

NFT minting and management.

import { NFT } from "cardano-devkit/namespaces";

// Create minting policy
const { policyId, policy } = await NFT.createPolicy(lucid, { type: "sig" });

// Mint NFT
const txHash = await NFT.mint(lucid, {
policyId,
assetName: "MyNFT",
metadata: {
name: "My NFT",
image: "ipfs://...",
description: "An awesome NFT"
}
});

// Build CIP-25 metadata
const metadata = NFT.buildMetadata(policyId, "MyNFT", {
name: "My NFT",
image: "ipfs://...",
});

Contents:

  • createPolicy() - Create minting policy
  • mint() - Mint an NFT
  • burn() - Burn an NFT
  • buildMetadata() - Build CIP-25 metadata
  • parseMetadata() - Parse NFT metadata

Token

Native token utilities.

import { Token } from "cardano-devkit/namespaces";

// Parse asset unit
const { policyId, assetName } = Token.parseUnit(unit);

// Create asset unit
const unit = Token.createUnit(policyId, assetName);

// Mint tokens
const txHash = await Token.mint(lucid, policyId, assetName, amount);

Contents:

  • parseUnit() - Parse policy ID and asset name from unit
  • createUnit() - Create unit from policy ID and asset name
  • mint() - Mint native tokens
  • burn() - Burn native tokens
  • getBalance() - Get token balance

Governance

Conway-era governance functions.

import { Governance } from "cardano-devkit/namespaces";

// Register as DRep
await Governance.registerDRep(lucid, {
credential,
anchor: { url: "https://...", dataHash }
});

// Cast a vote
await Governance.vote(lucid, {
actionId: { txHash, index: 0 },
vote: "Yes"
});

// Delegate voting power
await Governance.delegateVotingPower(lucid, {
type: "KeyHash",
credential: drepCred
});

Contents:

  • registerDRep() - Register as DRep
  • updateDRep() - Update DRep registration
  • unregisterDRep() - Retire as DRep
  • vote() - Cast a vote
  • delegateVotingPower() - Delegate to DRep

Wallet

Wallet connection and management.

import { Wallet } from "cardano-devkit/namespaces";

// Connect wallet
await Wallet.connect(lucid, "nami");

// Get available wallets
const wallets = Wallet.getAvailable();

// Check if connected
const connected = Wallet.isConnected(lucid);

Contents:

  • connect() - Connect browser wallet
  • getAvailable() - List available wallets
  • isConnected() - Check connection status
  • disconnect() - Disconnect wallet

Validation

Input validation utilities.

import { Validation } from "cardano-devkit/namespaces";

// Validate inputs
Validation.assertAddress(addr); // throws if invalid
Validation.assertTxHash(hash); // throws if invalid
Validation.assertPolicyId(policyId); // throws if invalid

// Check without throwing
const isValid = Validation.isValidAddress(addr);
const isValidHash = Validation.isValidTxHash(hash);

Contents:

  • assertAddress() - Assert valid address
  • assertTxHash() - Assert valid transaction hash
  • assertPolicyId() - Assert valid policy ID
  • isValidAddress() - Check if address is valid
  • isValidTxHash() - Check if tx hash is valid
  • isValidPolicyId() - Check if policy ID is valid

Script

Smart contract script utilities.

import { Script } from "cardano-devkit/namespaces";

// Load Aiken contracts
const contracts = Script.loadAiken("./plutus.json");

// Apply parameters
const validator = Script.applyParams(contracts["my_validator"], [param1]);

// Get script address
const scriptAddr = Script.getAddress(lucid, validator);

Contents:

  • loadAiken() - Load Aiken plutus.json
  • applyParams() - Apply parameters to script
  • getAddress() - Get script address
  • getHash() - Get script hash

Batch

Batch transaction building.

import { Batch } from "cardano-devkit/namespaces";

const builder = Batch.createBuilder(lucid)
.addPayment(addr1, { lovelace: 5_000_000n })
.addPayment(addr2, { lovelace: 10_000_000n })
.addMint(policyId, "Token", 100n);

const txs = await builder.build();

Contents:

  • createBuilder() - Create batch builder
  • BatchBuilder - Batch builder class

Staking

Stake delegation and rewards.

import { Staking } from "cardano-devkit/namespaces";

// Delegate to pool
await Staking.delegate(lucid, poolId);

// Get rewards
const rewards = await Staking.getRewards(lucid);

// Withdraw rewards
await Staking.withdrawRewards(lucid);

Contents:

  • delegate() - Delegate to stake pool
  • getRewards() - Get pending rewards
  • withdrawRewards() - Withdraw rewards
  • getPoolInfo() - Get pool information

Time

Slot and time conversion utilities.

import { Time } from "cardano-devkit/namespaces";

// Convert between slots and time
const slot = Time.dateToSlot(lucid, new Date());
const date = Time.slotToDate(lucid, slot);

// Get current slot
const currentSlot = Time.getCurrentSlot(lucid);

Contents:

  • dateToSlot() - Convert date to slot
  • slotToDate() - Convert slot to date
  • getCurrentSlot() - Get current slot
  • getSlotDuration() - Get slot duration

Metadata

Transaction metadata utilities.

import { Metadata } from "cardano-devkit/namespaces";

// Build metadata
const meta = Metadata.build(674, { msg: ["Hello Cardano!"] });

// Parse metadata from transaction
const parsed = Metadata.parse(tx);

Contents:

  • build() - Build transaction metadata
  • parse() - Parse metadata from tx
  • validate() - Validate metadata structure

Debug

Debugging and tracing utilities.

import { Debug } from "cardano-devkit/namespaces";

// Enable debug mode
Debug.enable({ level: "debug", timestamps: true });

// Create logger
const logger = Debug.createLogger("MyApp");
logger.debug("Processing transaction");
logger.info("Transaction submitted");

// Trace transaction lifecycle
const tracer = Debug.createTracer();
tracer.startPhase("build");
// ... build transaction
tracer.endPhase("build");
const trace = tracer.getTrace();
Debug.formatTrace(trace);

// Wrap async function with timing
const result = await Debug.withTiming("fetchUTxOs", async () => {
return await lucid.wallet().getUtxos();
});

Contents:

  • enable() - Enable debug mode
  • disable() - Disable debug mode
  • createLogger() - Create debug logger
  • createTracer() - Create transaction tracer
  • withTiming() - Wrap function with timing
  • formatTrace() - Format trace for display
  • logger - Default logger instance

Import Patterns

Individual Namespaces

Import only what you need:

import { ADA, Transaction } from "cardano-devkit/namespaces";

All Namespaces

Import everything for exploration:

import * as Cardano from "cardano-devkit/namespaces";

Cardano.ADA.toLovelace(100);
Cardano.Transaction.preview(lucid, tx);

Mixed with Direct Imports

Combine namespaces with direct imports:

import { createDevKit } from "cardano-devkit";
import { ADA, Transaction } from "cardano-devkit/namespaces";

const devkit = createDevKit({ network: "Preprod" });
const amount = ADA.toLovelace(10);

Benefits

  1. Discoverability - See all related functions via autocomplete
  2. Organization - Logical grouping of functionality
  3. Readability - Clear context in code (ADA.toLovelace vs adaToLovelace)
  4. Tree-shaking - Only import namespaces you use
  5. IDE Support - Better autocomplete and documentation

Migration Guide

If you're migrating from individual imports:

// Before
import { adaToLovelace, lovelaceToAda } from "cardano-devkit";
const amount = adaToLovelace(100);

// After
import { ADA } from "cardano-devkit/namespaces";
const amount = ADA.toLovelace(100);

Both patterns work - use whichever you prefer!