Documentation
Deep Dives
Emulator

Test and Emulate

The Emulator allows developers to test and validate their transactions in a controlled environment without interacting with a real blockchain. This is essential for debugging, rapid prototyping, and ensuring transaction logic is correct before deploying to a testnet or mainnet.

Basic Usage

Initialize Emulator

Create a mock blockchain state with predefined addresses and asset distributions:

// Create an emulator with a test account
const emulator = new Emulator([
  generateEmulatorAccount({
    lovelace: 80000000000n, // 80,000 ADA
  }),
]);
 
// Initialize Lucid with the emulator
const lucid = await Lucid(emulator, "Custom");

Create Test Accounts

You can generate test accounts with helper functions:

// Generate account with seed phrase (can access wallet features)
const seedAccount = generateEmulatorAccount({
  lovelace: 75000000000n,
});
 
// Generate account from private key
const privateKeyAccount = generateEmulatorAccountFromPrivateKey({
  lovelace: 90000000000n,
});
 
// Use the account with Lucid
lucid.selectWallet.fromSeed(seedAccount.seedPhrase);
// or
lucid.selectWallet.fromPrivateKey(privateKeyAccount.privateKey);

Building and Submitting Transactions

// Create a simple payment transaction
const tx = await lucid
  .newTx()
  .pay.ToAddress("addr_test...", { lovelace: 1000000n })
  .complete();
 
const signedTx = await tx.sign.withWallet().complete();
const txHash = await signedTx.submit();
 
// Simulate the passage of time and block confirmations
await emulator.awaitBlock(10);

Query Blockchain State

You can query the emulator's blockchain state:

// Get UTxOs at an address
const utxos = await emulator.getUtxos(address);
 
// Get UTxOs containing a specific token
const nftUtxos = await emulator.getUtxosWithUnit(address, assetId);
 
// Get UTxOs by reference
const specificUtxos = await emulator.getUtxosByOutRef([
  { txHash: "abc...", outputIndex: 0 },
]);
 
// Find the single UTxO holding a specific token (e.g., NFT)
const nftUtxo = await emulator.getUtxoByUnit(assetId);
 
// Get protocol parameters
const params = await emulator.getProtocolParameters();
 
// Get datum by hash
const datum = await emulator.getDatum(datumHash);

Advanced Features

// Advance time by slots
emulator.awaitSlot(20);
 
// Advance by blocks
emulator.awaitBlock(1);
 
// Check current time
const currentTime = emulator.now();

The emulator is a simplified version of the Cardano network designed for testing. It implements core functionality like UTxO tracking, block advancement, staking operations, and transaction validation.

Limitations

While the emulator is useful for testing, be aware of some limitations:

  • Not all Cardano features are implemented (e.g., complex governance operations)
  • Performance characteristics differ from the real network
  • The emulator uses simplified validation compared to the actual ledger

Always test critical applications on testnet before deploying to mainnet.