Skip to content

CardanoTools/cardano-devkit

Repository files navigation

🃏 Cardano DevKit

npm version License: MIT TypeScript Tests

One solution fits all - The most comprehensive development kit for Cardano blockchain

Cardano DevKit is an all-in-one development toolkit that wraps Lucid Evolution and provides unified APIs for JavaScript, TypeScript, and React development. Build Cardano dApps with ease!

✨ Features

🎯 Core Development

  • Network Switching - Seamlessly switch between local devnet, testnets (Preprod/Preview), and mainnet
  • Local Devnet - Sub-second block times (100-200ms) with Docker-based blockchain
  • Transaction Building - Simplified transaction creation, signing, and submission
  • Wallet Integration - Full support for seed phrases, private keys, and browser wallets
  • Multiple Providers - Blockfrost, Koios, and Maestro support out of the box

📜 Smart Contracts

  • Aiken Support - First-class support for Aiken smart contract development
  • Smart Contract Debugging - Built-in Plutus debugger for local development
  • Contract Templates - Pre-built templates for common use cases:
    • Escrow contracts
    • Vesting schedules
    • Time-locked assets
    • Multi-party agreements
    • Token sales
    • Auctions (English/Dutch)
    • Royalty distribution
    • Rewards distribution

🪙 Token & NFT

  • NFT Minting - CIP-25 compliant NFT creation and batch minting
  • Token Management - Fungible token minting, burning, and transfers
  • Metadata Standards - Full support for CIP-20, CIP-25, CIP-68
  • Royalties - CIP-27 royalty implementation

🏛️ Governance (Conway Era)

  • DRep Registration - CIP-119 compliant DRep metadata and registration
  • Voting - Cast votes on governance actions
  • Delegation - Delegate voting power to DReps
  • Proposal Building - Create treasury withdrawals, parameter changes, and more

📦 Advanced Features

  • Batch Transactions - Optimized batching with automatic chunking
  • Multi-Signature - Complete multi-sig transaction workflow
  • Real-time Subscriptions - WebSocket and polling-based event subscriptions
  • Staking - Delegation, rewards withdrawal, and pool queries
  • Enhanced Error Handling - Descriptive errors with recovery suggestions and code examples
  • React Integration - Ready-to-use hooks and context providers
  • UTxO Management - Smart coin selection with multiple strategies
  • Transaction History - Track and search transaction history with labels
  • Transaction Simulation - Validate transactions before submission
  • Address Book - Manage named addresses with labels and notes
  • Multi-Provider Failover - Automatic provider switching on failures
  • Project Scaffolding - Quick-start templates for common project types
  • Interactive Console - REPL for rapid Cardano development
  • File Watching - Auto-rebuild TypeScript and Aiken projects

🛠️ Developer Experience

  • Namespace Imports - Organized grouped imports for cleaner code (ADA, Transaction, NFT, etc.)
  • Debug Utilities - Transaction tracing, performance timing, and structured logging
  • Diagnostics - Runtime health checks and system diagnostics
  • CLI Wizard - Interactive project initialization and code generation
  • Health Monitoring - Built-in healthCheck() and getStatus() methods

📦 Installation

# Using pnpm (recommended)
pnpm install cardano-devkit

# Using npm
npm install cardano-devkit

# Using yarn
yarn add cardano-devkit

🚀 Quick Start

JavaScript

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

// Enable debug mode for development
Debug.enable({ level: "debug" });

// Initialize on Preprod testnet
const devKit = createDevKit({ network: "Preprod" });
const lucid = await devKit.init();

// Check system health
const health = await devKit.healthCheck();
console.log("System healthy:", health.healthy);

// Generate a new wallet
const seed = WalletHelper.generateSeed();
lucid.selectWallet.fromSeed(seed);

const address = await lucid.wallet().address();
console.log("Wallet address:", address);

TypeScript

import { createDevKit, WalletHelper } from "cardano-devkit";
import { ADA, Transaction, Debug } from "cardano-devkit/namespaces";
import type { DevKitConfig } from "cardano-devkit";

const config: DevKitConfig = {
  network: "Preprod",
  debug: true,
};

const devKit = createDevKit(config);
const lucid = await devKit.init();

// Use namespace imports for cleaner code
const amount = ADA.toLovelace(5);  // 5_000_000n

// Send ADA
const tx = await lucid
  .newTx()
  .pay.ToAddress("addr_test1...", { lovelace: amount })
  .complete();

// Preview transaction before signing
const preview = await Transaction.preview(lucid, tx);
console.log("Fee:", ADA.format(preview.fee));

const signedTx = await tx.sign.withWallet().complete();
const txHash = await signedTx.submit();
console.log("Transaction:", txHash);

React

import { useCardanoDevKit, useWallet } from "cardano-devkit";

function App() {
  const { lucid, isLoading, switchNetwork } = useCardanoDevKit({
    network: "Preprod",
  });
  const { walletAddress, connectWallet, isConnected } = useWallet(lucid);

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>My Cardano dApp</h1>
      {isConnected ? (
        <p>Connected: {walletAddress}</p>
      ) : (
        <button onClick={() => connectWallet("nami")}>Connect Nami</button>
      )}
    </div>
  );
}

🔌 Network Switching

Cardano DevKit makes it easy to switch between networks:

const devKit = createDevKit({ network: "Preprod" });
await devKit.init();

// Convenient helper methods
await devKit.useLocalDevnet();     // Switch to local devnet
await devKit.usePreprod();         // Switch to Preprod testnet
await devKit.usePreview();         // Switch to Preview testnet
await devKit.useMainnet({          // Switch to Mainnet (requires confirmation)
  confirmMainnet: true,
});

// Environment checks
devKit.getEnvironment();     // 'local' | 'testnet' | 'mainnet'
devKit.isLocalDevnet();      // boolean
devKit.isTestnet();          // boolean
devKit.isSafeForTesting();   // boolean (true if not mainnet)

// Health monitoring
const health = await devKit.healthCheck();
const status = devKit.getStatus();

🏗️ Namespace Imports

Cardano DevKit provides organized namespace imports for cleaner, more discoverable code:

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

// ADA/Lovelace conversion
const lovelace = ADA.toLovelace(100);     // 100_000_000n
const ada = ADA.toAda(5_000_000n);        // 5
const formatted = ADA.format(2_500_000n); // "2.5 ₳"

// Address utilities
const isValid = Address.validate(addr);
const network = Address.getNetwork(addr);

// Transaction utilities
const preview = await Transaction.preview(lucid, tx);
await Transaction.awaitConfirmation(lucid, txHash);

// NFT operations
const { policyId } = await NFT.createPolicy(lucid, { type: "sig" });
const metadata = NFT.buildMetadata(policyId, "MyNFT", { name: "My NFT", image: "ipfs://..." });

// Debug mode
Debug.enable({ level: "debug", timestamps: true });
const logger = Debug.createLogger("MyApp");
logger.info("Transaction submitted", { txHash });

Available namespaces: DevKit, ADA, Address, Transaction, NFT, Token, Governance, Wallet, Validation, Script, Batch, Staking, Time, Metadata, Debug

🔍 Diagnostics & Debugging

Runtime Diagnostics

import { diagnose, isHealthy, quickBalance } from "cardano-devkit";

// Quick health check
if (await isHealthy(devKit)) {
  console.log("All systems go!");
}

// Full diagnostics
const diag = await diagnose(devKit);
console.log("Network:", diag.network.status);
console.log("Wallet:", diag.wallet.balanceAda, "ADA");
console.log("Suggestions:", diag.suggestions);

// Quick balance
const balance = await quickBalance(devKit);
console.log(`${balance.ada} ADA in ${balance.utxoCount} UTxOs`);

Transaction Tracing

import { traceTransaction, formatTrace, createDebugLogger } from "cardano-devkit";

const logger = createDebugLogger("PaymentService");

const { txHash, trace } = await traceTransaction(lucid, async (l) => {
  logger.info("Building transaction...");
  const tx = await l.newTx()
    .pay.ToAddress(recipient, { lovelace: 10_000_000n })
    .complete();
  return await tx.sign.withWallet().complete().then(s => s.submit());
});

console.log(formatTrace(trace));
// Shows timing for: build (145ms), sign (52ms), submit (1203ms)

🖥️ Local Devnet

Start a local Cardano blockchain with sub-second block times:

Using CLI

# Start local devnet (100ms blocks by default)
npx cardano-devkit start

# Start with custom block time (200ms)
npx cardano-devkit start --block-time 200

# Check status
npx cardano-devkit status

# Get current tip
npx cardano-devkit tip

# Fund an address with test ADA
npx cardano-devkit topup addr_test1... --amount 1000000000

# List available test wallets
npx cardano-devkit wallets

# Reset blockchain state
npx cardano-devkit reset

# Stop devnet
npx cardano-devkit stop

Programmatic Usage

import { createDevnetManager, createDevKit } from "cardano-devkit";

// Start local devnet
const devnet = createDevnetManager({
  port: 10080,
  blockTimeMs: 200,  // 200ms blocks
});
await devnet.start();

// Connect DevKit to local devnet
const devKit = createDevKit({ network: "LocalDevnet" });
await devKit.useLocalDevnet(10080);

// Fund addresses for testing
await devnet.topup("addr_test1...", 100_000_000n); // 100 ADA

// Get blockchain tip
const tip = await devnet.getTip();
console.log("Current slot:", tip.slot);

// Create fork for rollback testing
const forkId = await devnet.createFork();
// ... do operations ...
await devnet.joinFork(forkId); // Rollback to fork point

Service Ports

Default ports use 10XXX range to avoid conflicts with common dev tools:

Service Port Description
Indexer API 10080 Blockfrost-compatible API
WebSocket 10180 Real-time subscriptions
Node N2N 10301 Direct cardano-node connection
Explorer 10173 Block explorer UI
Submit API 10090 Transaction submission
Ogmios 10337 WebSocket JSON-RPC bridge
Kupo 10442 Chain indexer

Note: These ports avoid conflicts with Next.js (3000), Vite (5173), and other frameworks.

📦 Batch Transactions

Efficiently batch multiple operations into optimal transactions:

import {
  createBatchBuilder,
  batchAdaPayments,
  batchMintNFTs,
  analyzeBatch
} from "cardano-devkit";

// Simple batch ADA payments
const payments = [
  { address: "addr_test1...", lovelace: 5_000_000n },
  { address: "addr_test2...", lovelace: 10_000_000n },
  { address: "addr_test3...", lovelace: 3_000_000n },
];
const txHashes = await batchAdaPayments(lucid, payments);

// Using BatchBuilder for complex operations
const builder = createBatchBuilder(lucid);
const batch = builder
  .addPayment("addr_test1...", 5_000_000n)
  .addPayment("addr_test2...", 10_000_000n)
  .addMint(policyId, "MyNFT", 1n, metadata)
  .addBurn(policyId, "OldToken", 100n)
  .addMetadata(674, { msg: ["Batch transaction"] })
  .build();

// Analyze batch before execution
const analysis = analyzeBatch(batch);
console.log("Operations:", analysis.operationCount);
console.log("Estimated transactions:", analysis.estimatedTxCount);
console.log("Estimated fees:", analysis.estimatedFees);

// Execute batch
const results = await builder.execute();
console.log("Transaction hashes:", results.map(r => r.txHash));

📜 Smart Contract Templates

Pre-built templates for common smart contract patterns:

Escrow

import { createEscrowTemplate, EscrowState } from "cardano-devkit";

const escrow = createEscrowTemplate({
  seller: "addr_test1seller...",
  buyer: "addr_test1buyer...",
  arbiter: "addr_test1arbiter...",
  amount: 100_000_000n,
  deadline: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days
  requireArbiter: true,
});

// Build the escrow contract
const contract = escrow.build();
console.log("Script address:", contract.scriptAddress);

// Generate datum for initial state
const datum = escrow.getDatum(EscrowState.Pending);

// Create release/refund transactions
const releaseTx = escrow.createReleaseTransaction(lucid, utxo);
const refundTx = escrow.createRefundTransaction(lucid, utxo);

Vesting

import { createVestingTemplate } from "cardano-devkit";

const vesting = createVestingTemplate({
  beneficiary: "addr_test1beneficiary...",
  totalAmount: 1_000_000_000n, // 1000 ADA
  schedule: [
    { unlockTime: Date.now() + 30 * 24 * 60 * 60 * 1000, amount: 250_000_000n },
    { unlockTime: Date.now() + 60 * 24 * 60 * 60 * 1000, amount: 250_000_000n },
    { unlockTime: Date.now() + 90 * 24 * 60 * 60 * 1000, amount: 500_000_000n },
  ],
});

const contract = vesting.build();
const currentlyVested = vesting.getVestedAmount();
const nextUnlock = vesting.getNextUnlockTime();

Auction

import { createAuctionTemplate } from "cardano-devkit";

const auction = createAuctionTemplate({
  seller: "addr_test1seller...",
  startingBid: 10_000_000n,
  minBidIncrement: 1_000_000n,
  startTime: Date.now(),
  endTime: Date.now() + 24 * 60 * 60 * 1000, // 24 hours
  auctionType: "english", // or "dutch"
});

const isActive = auction.isAuctionActive();
const minBid = auction.getMinimumBid(currentBid);
const bidTx = auction.createBidTransaction(lucid, utxo, bidAmount);

Token Sale

import { createTokenSaleTemplate } from "cardano-devkit";

const sale = createTokenSaleTemplate({
  seller: "addr_test1seller...",
  tokenPolicyId: "abc123...",
  tokenAssetName: "MyToken",
  pricePerToken: 1_000_000n, // 1 ADA per token
  totalTokens: 10000n,
  startTime: Date.now(),
  endTime: Date.now() + 7 * 24 * 60 * 60 * 1000,
  minPurchase: 10n,
  maxPurchase: 1000n,
});

const remaining = sale.getRemainingTokens();
const cost = sale.calculateCost(100n); // Cost for 100 tokens

🏛️ Governance (Conway Era)

Full support for Conway-era governance features:

DRep Registration

import {
  createDRepMetadata,
  registerDRep,
  delegateVotingPower
} from "cardano-devkit";

// Create CIP-119 compliant metadata
const metadata = createDRepMetadata({
  givenName: "Alice",
  bio: "Passionate about Cardano governance",
  motivations: "To help guide Cardano development",
  qualifications: ["Software engineer", "Active community member"],
  paymentAddress: "addr_test1...",
});

// Register as DRep
const regTx = await registerDRep(lucid, {
  anchorUrl: "https://example.com/drep-metadata.json",
  anchorHash: "...",
});

// Delegate voting power
await delegateVotingPower(lucid, {
  type: "drep",
  drepId: "drep1...",
});

Voting

import { castVote, ProposalBuilder } from "cardano-devkit";

// Cast vote on governance action
await castVote(lucid, {
  actionId: { txHash: "abc...", index: 0 },
  vote: "yes", // "yes" | "no" | "abstain"
  anchor: {
    url: "https://example.com/vote-rationale.json",
    hash: "...",
  },
});

// Build governance proposals
const proposal = new ProposalBuilder()
  .setProposer("addr_test1...")
  .addTreasuryWithdrawal("addr_test1...", 1_000_000_000n)
  .setAnchor("https://example.com/proposal.json", "...")
  .build();

🎨 NFT & Token Management

Minting NFTs

import { mintNFT, mintBatchNFTs, createNFTMetadata } from "cardano-devkit";

// Single NFT
const result = await mintNFT(lucid, {
  name: "My NFT #1",
  image: "ipfs://Qm...",
  description: "A unique digital collectible",
  attributes: { rarity: "legendary" },
});

// Batch minting
const nfts = [
  { name: "Collection #1", image: "ipfs://Qm1..." },
  { name: "Collection #2", image: "ipfs://Qm2..." },
  { name: "Collection #3", image: "ipfs://Qm3..." },
];
const results = await mintBatchNFTs(lucid, nfts);

Fungible Tokens

import { mintTokens, transferTokens, getWalletTokens } from "cardano-devkit";

// Mint tokens
const mintResult = await mintTokens(lucid, {
  name: "MyToken",
  amount: 1_000_000n,
  metadata: {
    name: "My Token",
    ticker: "MTK",
    decimals: 6,
  },
});

// Transfer tokens
await transferTokens(lucid, {
  policyId: mintResult.policyId,
  assetName: "MyToken",
  amount: 100n,
  to: "addr_test1...",
});

// Query token balances
const tokens = await getWalletTokens(lucid);

🔐 Multi-Signature Transactions

import {
  createMultiSigScript,
  MultiSigTransactionBuilder,
  serializeForSigning,
  assembleMultiSigTx,
} from "cardano-devkit";

// Create 2-of-3 multisig
const multiSig = createMultiSigScript({
  type: "atLeast",
  required: 2,
  participants: [
    { name: "Alice", keyHash: "abc..." },
    { name: "Bob", keyHash: "def..." },
    { name: "Carol", keyHash: "ghi..." },
  ],
});

// Build transaction
const builder = new MultiSigTransactionBuilder(lucid, multiSig);
const tx = await builder
  .addPayment("addr_test1...", 5_000_000n)
  .build();

// Serialize for offline signing
const serialized = serializeForSigning(tx);

// Collect signatures (from each participant)
const aliceSignature = await signSerializedTx(serialized, alicePrivateKey);
const bobSignature = await signSerializedTx(serialized, bobPrivateKey);

// Assemble and submit
const finalTx = assembleMultiSigTx(serialized, [aliceSignature, bobSignature]);
const txHash = await finalTx.submit();

📡 Real-time Subscriptions

import {
  createSubscriptionManager,
  watchTxConfirmation,
} from "cardano-devkit";

// WebSocket subscriptions (local devnet)
const manager = createSubscriptionManager({
  url: "ws://localhost:8081",
});

// Subscribe to new blocks
const blockSub = manager.subscribeToBlocks((block) => {
  console.log("New block:", block.slot, block.hash);
});

// Subscribe to address activity
const addrSub = manager.subscribeToAddress("addr_test1...", (event) => {
  console.log("Address activity:", event.type, event.txHash);
});

// Watch transaction confirmation
await watchTxConfirmation(lucid, txHash, {
  confirmations: 3,
  timeout: 60000,
  onConfirmation: (count) => console.log(`${count} confirmations`),
});

// Cleanup
blockSub.unsubscribe();
addrSub.unsubscribe();
manager.disconnect();

💰 Staking

import {
  delegateToPool,
  withdrawRewards,
  getDelegationStatus,
  getAvailableRewards,
} from "cardano-devkit";

// Delegate to a stake pool
await delegateToPool(lucid, "pool1...");

// Check delegation status
const status = await getDelegationStatus(lucid);
console.log("Delegated to:", status.poolId);
console.log("Active stake:", status.activeStake);

// Get available rewards
const rewards = await getAvailableRewards(lucid);
console.log("Pending rewards:", rewards.lovelace);

// Withdraw rewards
await withdrawRewards(lucid);

💾 UTxO Management

Smart UTxO selection and management:

import {
  createUTxOManager,
  selectCoins,
  formatUTxOStats,
} from "cardano-devkit";

// Create UTxO manager from wallet UTxOs
const utxos = await lucid.wallet().getUtxos();
const manager = createUTxOManager(utxos);

// Select UTxOs for a target amount
const result = manager.select(10_000_000n, {
  strategy: "optimal", // "largest-first" | "smallest-first" | "optimal"
  maxInputs: 10,
});

if (result.success) {
  console.log("Selected:", result.selected.length, "UTxOs");
  console.log("Total:", result.totalValue, "lovelace");
  console.log("Change:", result.change, "lovelace");
}

// Get UTxO statistics
const stats = manager.getStats();
console.log(formatUTxOStats(stats));

// Find UTxOs containing specific assets
const nftUtxos = manager.findByAsset(policyId, assetName);

// Lock UTxOs to prevent double-spending
manager.lock(selectedUtxos);

// Find consolidation candidates (small UTxOs)
const dustUtxos = manager.findConsolidationCandidates(5_000_000n);

📜 Transaction History

Track and search your transaction history:

import {
  createTxHistory,
  formatTxRecord,
  formatTxHistoryStats,
} from "cardano-devkit";

// Create transaction history manager
const history = createTxHistory();

// Add a transaction record
history.add({
  txHash: "abc123...",
  status: "submitted",
  direction: "outgoing",
  amount: 5_000_000n,
  fee: 200_000n,
  addresses: {
    from: ["addr_test1..."],
    to: ["addr_test2..."],
  },
  network: "Preprod",
});

// Update status when confirmed
history.updateStatus("abc123...", "confirmed", {
  block: 12345,
  slot: 67890,
});

// Search transactions
const results = history.search("addr_test2");

// Filter by status or direction
const pending = history.getPending();
const incoming = history.getByDirection("incoming");

// Add labels and notes
history.addLabel("abc123...", "important");
history.setNote("abc123...", "Payment for services");

// Get statistics
const stats = history.getStats();
console.log(formatTxHistoryStats(stats));

🔮 Transaction Simulation

Validate transactions before submitting:

import {
  simulateTransaction,
  formatSimulationResult,
} from "cardano-devkit";

// Simulate a transaction
const result = simulateTransaction({
  inputs: utxos,
  outputs: [
    { address: "addr_test1...", value: { lovelace: 5_000_000n } },
    { address: "addr_test2...", value: { lovelace: 10_000_000n } },
  ],
});

// Check if valid
if (result.valid) {
  console.log("Transaction is valid!");
  console.log("Estimated fee:", result.estimatedFee);
  console.log("Change:", result.change);
} else {
  console.log("Errors:", result.errors);
}

// Show warnings
for (const warning of result.warnings) {
  console.log("Warning:", warning.message);
}

console.log(formatSimulationResult(result));

📒 Address Book

Manage named addresses:

import {
  createAddressBook,
  resolveAddress,
  addWellKnownAddresses,
} from "cardano-devkit";

// Create address book (persisted to file)
const book = createAddressBook();

// Add addresses with labels
book.add({
  label: "alice",
  address: "addr_test1...",
  network: "Preprod",
  tags: ["team", "developer"],
  note: "Alice's test wallet",
});

// Resolve label to address
const address = resolveAddress("alice", book);

// Use in transactions (supports both labels and addresses)
const recipient = resolveAddress("alice", book); // Returns address

// Add well-known addresses (faucets, etc.)
addWellKnownAddresses(book);

// List all addresses
const entries = book.list();

🚀 Project Scaffolding

Quickly create new Cardano projects:

# Create a new project with templates
npx cardano-devkit new my-dapp --template react-dapp
npx cardano-devkit new my-contract --template aiken-contract
npx cardano-devkit new my-api --template express-api

# Available templates:
# - basic         - Minimal TypeScript setup
# - react-dapp    - React dApp with wallet integration
# - next-dapp     - Next.js dApp with SSR
# - node-backend  - Node.js backend service
# - aiken-contract- Aiken smart contract project
# - fullstack     - Full-stack dApp template
# - library       - Reusable library package
import { scaffold, listTemplates, listFeatures } from "cardano-devkit";

// List available templates
const templates = listTemplates();
console.log(templates);

// Scaffold a new project
const result = await scaffold({
  name: "my-dapp",
  template: "react-dapp",
  features: ["wallet", "transactions", "nft"],
  directory: "./my-dapp",
});

🖥️ Interactive Console

REPL for rapid development:

# Start interactive console
npx cardano-devkit console

# Or with specific network
npx cardano-devkit console --network Preprod
import { startConsole, executeCommand } from "cardano-devkit";

// Start console programmatically
await startConsole({
  network: "Preprod",
  welcomeMessage: "Welcome to Cardano Console!",
});

// Execute commands
await executeCommand("balance addr_test1...");
await executeCommand("tip");

🔒 Error Handling

Cardano DevKit provides descriptive errors with recovery suggestions:

import {
  CardanoDevKitError,
  InsufficientFundsError,
  TransactionError,
  isInsufficientFundsError,
  getRecoverySuggestions,
} from "cardano-devkit";

try {
  const tx = await lucid.newTx()
    .pay.ToAddress("addr_test1...", { lovelace: 1_000_000_000_000n })
    .complete();
} catch (error) {
  if (isInsufficientFundsError(error)) {
    console.log("Required:", error.required);
    console.log("Available:", error.available);
    console.log("Suggestions:", getRecoverySuggestions(error));
    // Suggestions: [
    //   "Add more ADA to your wallet",
    //   "Request test ADA from a faucet",
    //   "Reduce the transaction amount"
    // ]
  }
}

🌐 Provider Configuration

Blockfrost

const devKit = createDevKit({
  network: "Preprod",
  provider: {
    type: "blockfrost",
    url: "https://cardano-preprod.blockfrost.io/api/v0",
    projectId: "your-project-id",
  },
});

Koios (Default)

const devKit = createDevKit({
  network: "Preprod",
  provider: {
    type: "koios",
    url: "https://preprod.koios.rest/api/v1",
  },
});

Maestro

const devKit = createDevKit({
  network: "Mainnet",
  provider: {
    type: "maestro",
    url: "https://mainnet.gomaestro-api.org/v1",
    apiKey: "your-api-key",
  },
});

⚛️ React Integration

Hooks

import {
  useCardanoDevKit,
  useWallet,
  useTransaction,
  useAssets,
  useUTxOs,
  useNetworkStatus,
} from "cardano-devkit";

function MyComponent() {
  // DevKit hook
  const { lucid, isLoading, error, switchNetwork } = useCardanoDevKit();

  // Wallet hook
  const { walletAddress, connectWallet, disconnectWallet } = useWallet(lucid);

  // Transaction hook
  const { send, isSubmitting, lastTxHash } = useTransaction(lucid);

  // Assets hook
  const { tokens, nfts, isLoading: assetsLoading } = useAssets(lucid);

  // UTxOs hook
  const { utxos, refresh } = useUTxOs(lucid);

  // Network status
  const { tip, isOnline, latency } = useNetworkStatus(lucid);
}

Context Provider

import { CardanoProvider, useCardano } from "cardano-devkit";

function App() {
  return (
    <CardanoProvider network="Preprod" debug={true}>
      <WalletView />
    </CardanoProvider>
  );
}

function WalletView() {
  const { lucid, wallet, network, actions } = useCardano();

  return (
    <div>
      <p>Network: {network.current}</p>
      <p>Address: {wallet.address}</p>
      <button onClick={() => actions.connect("nami")}>
        Connect Wallet
      </button>
    </div>
  );
}

📋 CLI Reference

Core Commands

Command Description
start [--port] [--block-time] Start local devnet
stop Stop local devnet
status Check devnet status
tip Get current blockchain tip
topup <address> [--amount] Fund an address with test ADA
wallets List available test wallets
reset Reset devnet to initial state
switch <network> Switch active network
info Display devkit information
urls Show service URLs

Project & Development

Command Description
new <name> Create new Cardano project (7 templates available)
init <name> Initialize a Cardano project in current directory
generate <type> <name> Generate code scaffolds
console / repl Start interactive Cardano console
watch [--ts] [--aiken] Watch files and auto-rebuild
doctor Check development environment
config Generate configuration file

Transaction Tools

Command Description
simulate Simulate transaction before submitting
decode-tx <cbor> Decode and inspect transaction

Wallet & Address

Command Description
wallet balance <address> Get wallet balance
wallet utxos <address> List UTxOs for address
wallet send Send ADA from wallet
wallet new Generate new wallet
wallet assets <address> List native assets
address-book list List saved addresses
address-book add <label> <addr> Add address to book
address-book resolve <label> Resolve label to address

UTxO Management

Command Description
utxo analyze <file> Analyze UTxOs from JSON file
utxo select <file> <amount> Select UTxOs for target amount

Transaction History

Command Description
history list List transaction history
history stats Show history statistics
history search <query> Search transactions
history pending List pending transactions
history clear Clear transaction history

📚 API Reference

Core Classes

Class Description
CardanoDevKit Main entry point for DevKit
DevnetManager Local devnet lifecycle management
DevnetFaucet Test ADA distribution
SmartContractDebugger Plutus script debugging
BatchBuilder Batch transaction builder
MultiSigTransactionBuilder Multi-signature transactions
SubscriptionManager Real-time event subscriptions
ProposalBuilder Governance proposal builder

Template Classes

Class Description
EscrowTemplate Two-party escrow contracts
VestingTemplate Token vesting schedules
TimeLockTemplate Time-locked assets
MultiPartyTemplate Multi-party agreements
TokenSaleTemplate Token sale/ICO contracts
AuctionTemplate English/Dutch auctions
RoyaltyTemplate CIP-27 royalty distribution
RewardsDistributionTemplate Staking rewards distribution

Utility Modules

Module Functions
ada adaToLovelace, lovelaceToAda, formatAda, parseAda
address validateAddress, isTestnetAddress, truncateAddress
validation validateTxHash, validatePolicyId, validateAmount
time timeToSlot, slotToTime, createValidityRange
metadata createCIP25Metadata, createCIP68Metadata
nft mintNFT, mintBatchNFTs, transferNFT
token mintTokens, burnTokens, transferTokens
staking delegateToPool, withdrawRewards
governance registerDRep, castVote, delegateVotingPower
batch createBatchBuilder, batchAdaPayments
multisig createMultiSigScript, serializeForSigning
subscriptions createSubscriptionManager, watchTxConfirmation
errors CardanoDevKitError, getRecoverySuggestions
utxo-manager createUTxOManager, selectCoins, formatUTxOStats
tx-history createTxHistory, formatTxRecord, formatTxHistoryStats
simulator simulateTransaction, formatSimulationResult
addressbook createAddressBook, resolveAddress
scaffold scaffold, listTemplates, listFeatures
console startConsole, executeCommand
watch createWatcher, createTsWatcher, createAikenWatcher
multi-provider createMultiProvider, createFailoverProvider
fees estimateSimpleFee, estimateScriptFee, estimateMinUtxo
chaining createTxChain, TxChainBuilder
cache createProviderCache, DEFAULT_TTL

🎓 Learning Resources

Cardano Development

Smart Contracts

Community

🛠️ Development

# Clone the repository
git clone https://github.com/CardanoTools/cardano-devkit.git
cd cardano-devkit

# Install dependencies
pnpm install

# Build the project
pnpm build

# Run tests (1145 tests)
pnpm test

# Format code
pnpm format

# Lint code
pnpm lint

🤝 Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

📄 License

MIT License - see the LICENSE file for details.

🙏 Acknowledgments

This project builds upon:

💬 Support


Made with ❤️ for the Cardano community

Releases

No releases published

Packages

 
 
 

Contributors