Skip to main content
The @trezor/blockchain-link package provides a unified client interface for multiple blockchain backend implementations. It abstracts the differences between various blockchain APIs, allowing Trezor Suite to interact with different networks through a consistent interface.

Overview

blockchain-link is the bridge between Trezor Suite and various blockchain backends. It handles:
  • Blockchain connectivity and communication
  • Transaction fetching and broadcasting
  • Account balance and history queries
  • Block and mempool monitoring
  • WebSocket connections for real-time updates

Supported Backends

Blockbook

Maintained by: SatoshiLabsNetworks: Bitcoin-like and Ethereum-likeFeatures: Full history, UTXO tracking, mempool monitoringBlockbook on GitHub

Electrum

Maintained by: Third partiesNetworks: Bitcoin networkFeatures: Lightweight, wide server availabilityElectrum Protocol Docs

Ripple

Maintained by: Ripple/XRP Ledger FoundationNetworks: Ripple (XRP)Features: Native XRP Ledger supportXRP Ledger Docs

Blockfrost

Maintained by: Blockfrost.ioNetworks: Cardano (ADA)Features: Cardano-specific functionalityBlockfrost Docs

Installation

Install the package in your project:
yarn add @trezor/blockchain-link

Basic Usage

Initializing a Connection

import BlockchainLink from '@trezor/blockchain-link';
import Blockbook from '@trezor/blockchain-link/lib/workers/blockbook';

const link = new BlockchainLink({
    name: 'Bitcoin',                    // Name used in logs
    worker: Blockbook,                  // Worker implementation
    server: [
        'https://btc1.trezor.io',       // Primary server
        'https://btc2.trezor.io',       // Fallback server
    ],
    debug: true,                        // Enable debug logging
});

Fetching Blockchain Info

try {
    const info = await link.getInfo();
    console.log('Block height:', info.blockHeight);
    console.log('Block hash:', info.blockHash);
} catch (error) {
    console.error('Failed to get blockchain info:', error);
}

Getting Account Information

const account = await link.getAccountInfo({
    descriptor: 'xpub6D...',  // Account descriptor (xpub, address, etc.)
    details: 'txs',           // Include transaction details
});

console.log('Balance:', account.balance);
console.log('Transactions:', account.history.total);

Subscribing to Block Updates

// Subscribe to new blocks
await link.subscribe({
    type: 'block',
});

// Listen for block events
link.on('block', (block) => {
    console.log('New block:', block.height);
});

Architecture

Worker-Based Design

Blockchain-link uses Web Workers to handle network communication without blocking the main thread:

Key Components

Each backend has a dedicated worker implementation:
  • workers/blockbook/index.ts - Blockbook backend
  • workers/electrum/index.ts - Electrum backend
  • workers/ripple/index.ts - Ripple backend
  • workers/blockfrost/index.ts - Blockfrost backend
Workers handle:
  • Network communication
  • Response parsing
  • WebSocket management
  • Error handling
Shared types in @trezor/blockchain-link-types:
  • Request/response types
  • Event types
  • Backend-specific types
  • Error definitions
Helper functions in @trezor/blockchain-link-utils:
  • Response transformers
  • Data validators
  • Common utilities

Worker Implementation

Using Workers in Different Environments

Web (with Webpack)

import BlockbookWorker from 'worker-loader?filename=workers/blockbook-worker.[hash].js!@trezor/blockchain-link/lib/workers/blockbook/index.js';

const link = new BlockchainLink({
    worker: BlockbookWorker,
    // ... other options
});

Web (with URL)

const link = new BlockchainLink({
    worker: './workers/blockbook-worker.js',
    // ... other options
});

Node.js (without Workers)

const link = new BlockchainLink({
    worker: () => import('@trezor/blockchain-link/lib/workers/blockbook'),
    // ... other options
});

API Reference

Methods

Establishes connection to the blockchain backend.
await link.connect();
Closes the connection and cleans up resources.
await link.disconnect();
Gets current blockchain info (block height, hash, etc.).
const info = await link.getInfo();
// { blockHeight: 750000, blockHash: '0x...', ... }
Fetches account information including balance and history.
const account = await link.getAccountInfo({
    descriptor: 'xpub6D...',
    details: 'txs',
    page: 1,
    pageSize: 25,
});
Gets details of a specific transaction.
const tx = await link.getTransaction('abc123...');
Broadcasts a signed transaction to the network.
const result = await link.pushTransaction('0100000...');
// Returns transaction ID
Estimates transaction fee for confirmation within N blocks.
const fees = await link.estimateFee({ blocks: [1, 3, 6] });
// { 1: 20, 3: 15, 6: 10 } // sat/byte
Subscribes to blockchain events (blocks, addresses, etc.).
await link.subscribe({
    type: 'block',
});

await link.subscribe({
    type: 'addresses',
    addresses: ['1A1zP1...', '3J98t1...'],
});
Unsubscribes from blockchain events.
await link.unsubscribe({ type: 'block' });

Events

Listen to events using the EventEmitter pattern:
// New block mined
link.on('block', (block) => {
    console.log('Block:', block.height, block.hash);
});

// Transaction affecting subscribed address
link.on('notification', (notification) => {
    console.log('Address activity:', notification);
});

// Connection status changed
link.on('connected', () => {
    console.log('Connected to blockchain backend');
});

link.on('disconnected', () => {
    console.log('Disconnected from blockchain backend');
});

// Error occurred
link.on('error', (error) => {
    console.error('Blockchain-link error:', error);
});

Development

Running the Development UI

Blockchain-link includes a testing UI:
# With Web Workers support
yarn workspace @trezor/blockchain-link dev

# Without Web Workers (bundle mode)
yarn workspace @trezor/blockchain-link dev:module

Running Tests

# Unit tests
yarn workspace @trezor/blockchain-link test:unit

# Type checking
yarn workspace @trezor/blockchain-link type-check

# Linting
yarn workspace @trezor/blockchain-link lint

Integration Tests

# Build first
yarn workspace @trezor/blockchain-link build:lib
yarn workspace @trezor/blockchain-link build:workers

# Run integration tests
yarn workspace @trezor/blockchain-link test:integration

Configuration Options

name
string
required
Name used in debug logs to identify this instance
worker
Worker | string | function
required
Worker implementation or path to worker script
server
string | string[]
required
Backend server URL(s). Multiple URLs provide fallback support
debug
boolean
default:"false"
Enable debug logging
timeout
number
default:"30000"
Connection timeout in milliseconds
throttleBlockEvent
number
default:"500"
Throttle block events to prevent overwhelming the UI (in ms)

blockchain-link-types

TypeScript type definitions

blockchain-link-utils

Utility functions and helpers

websocket-client

WebSocket client implementation

Best Practices

Network requests can fail. Always wrap API calls in try-catch blocks:
try {
    const info = await link.getInfo();
} catch (error) {
    // Handle connection errors, timeouts, etc.
    console.error('Failed to get blockchain info:', error);
}
Provide fallback servers for reliability:
const link = new BlockchainLink({
    server: [
        'https://btc1.trezor.io',
        'https://btc2.trezor.io',
        'https://btc3.trezor.io',
    ],
});
Unsubscribe when no longer needed to prevent memory leaks:
// Subscribe
await link.subscribe({ type: 'block' });

// Later, when component unmounts
await link.unsubscribe({ type: 'block' });
link.removeAllListeners();
Use the throttleBlockEvent option to prevent UI performance issues during rapid block updates:
const link = new BlockchainLink({
    throttleBlockEvent: 1000, // Max 1 event per second
});

Next Steps

Package Overview

Explore all packages in the monorepo

Utilities

Learn about utility packages

Connect Package

Explore the Connect package documentation

Common Tasks

Development workflows and troubleshooting

Build docs developers (and LLMs) love