models.ts
Overview
The [models.ts](/projects/291/68901) file defines TypeScript classes and interfaces that represent the core data structures used in the Blockchain Data Indexing module. These models provide a strongly-typed, normalized representation of blockchain-related entities such as transactions, addresses, blocks, tokens, and errors. This standardization enables consistent interaction with blockchain data, regardless of underlying chain specifics (e.g., Bitcoin vs Ethereum).
The file also includes an error class (`ApiError`) which wraps and extends Axios errors that occur during HTTP communication with the Blockbook backend. This enhances error handling by providing meaningful messages extracted from API responses.
Overall, [models.ts](/projects/291/68901) serves as the foundational schema for blockchain data throughout the system, facilitating clear data contracts between the Blockbook API client, business logic, and any consumers of blockchain data.
Detailed Descriptions
Class: ApiError
A custom error class extending `AxiosError` to represent failures when interacting with the Blockbook API.
Constructor
constructor(err: AxiosError | Error)
Parameters:
err: The original error caught, which can be an AxiosError (from HTTP requests) or a generic Error.
Behavior:
If
erris an Axios error, attempts to extract a human-readable error message from the response payload.Otherwise, uses the standard error message.
Copies all original error properties onto the new instance to preserve context.
Usage Example:
try {
// axios request that may fail
} catch (error) {
throw new ApiError(error)
}
This class improves error transparency by surfacing API response errors in a consistent message format.
Interfaces
The interfaces define the shape of blockchain-related data objects used throughout the system.
Address
Represents an address with associated balance and transaction details.
Extends:
Paging(pagination info)Properties:
address: string— The blockchain address string.balance: string— Confirmed balance as a string (usually in smallest denomination).totalReceived?: string— Total amount received by this address (optional).totalSent?: string— Total amount sent from this address (optional).unconfirmedBalance: string— Balance from unconfirmed transactions.unconfirmedTxs: number— Count of unconfirmed transactions.txs: number— Total number of transactions.nonTokenTxs?: number— Count of transactions excluding tokens (optional).transactions?: Array<Tx>— Array of transaction objects (optional).txids?: Array<string>— Array of transaction IDs (optional).nonce?: string— Nonce value, relevant for Ethereum-like chains (optional).usedTokens?: number— Count of used tokens (optional).tokens?: Array<Token>— List of tokens associated with this address (optional).erc20Contract?: Erc20Contract— ERC20 contract details if applicable (optional).
BackendInfo
Contains metadata about the connected backend blockchain node.
Properties (all optional):
error?: stringchain?: string— Blockchain network name.blocks?: number— Number of blocks synced.headers?: number— Number of headers synced.bestBlockHash?: stringdifficulty?: stringsizeOnDisk?: numberversion?: stringsubversion?: stringprotocolVersion?: stringtimeOffset?: numberwarnings?: stringconsensus?: unknown— Consensus details, type not fixed.
BalanceHistory
Represents historical balance data at a specific time point.
Properties:
time: number— Timestamp (epoch seconds).txs: number— Number of transactions in this period.received: string— Amount received.sent: string— Amount sent.sentToSelf: string— Amount sent to self.rates?: { [key: string]: number }— Optional map of fiat or token rates.txid?: string— Optional transaction ID related to this data point.
Block
Describes a blockchain block and its transactions.
Extends:
PagingProperties:
hash: string— Block hash.previousBlockHash?: stringnextBlockHash?: stringheight: number— Block height.confirmations: numbersize: number— Block size in bytes.time?: number— Timestamp.version: numbermerkleRoot: stringnonce: stringbits: string— Difficulty bits.difficulty: stringtxCount: number— Number of transactions.tx?: Array<string>— Transaction IDs.txs?: Array<Tx>— Transaction objects.
BlockbookInfo (internal interface)
Information about the Blockbook service instance.
Properties:
coin: string— Coin type.host: string— Host URL.version: string— Blockbook version.gitCommit: stringbuildTime: stringsyncMode: booleaninitialSync: booleaninSync: booleanbestHeight: numberlastBlockTime: stringinSyncMempool: booleanlastMempoolTime: stringmempoolSize: numberdecimals: numberdbSize: numberdbSizeFromColumns?: numberdbColumns?: Array<unknown>about: string
BlockIndex
Minimal info about a block, typically for referencing by hash.
Properties:
hash: string
Info
Aggregates Blockbook and backend node info.
Properties:
blockbook: BlockbookInfobackend: BackendInfo
EthereumSpecific
Ethereum-specific transaction fields.
Properties:
status: number— Transaction status.nonce: numbergasLimit: numbergasUsed: number | nullgasPrice: stringdata?: string— Transaction input data (optional).
Erc20Contract
Details of an ERC20 token contract.
Properties:
contract: string— Contract address.name: stringsymbol: stringdecimals: number
Paging
Pagination parameters common to address, block, and xpub queries.
Optional Properties:
page?: numbertotalPages?: numberitemsOnPage?: number
SendTx
Result object for a transaction submission.
Properties:
result: string— Usually the transaction ID or success message.
Token
Information about tokens held by an address.
Properties:
type: string— Token type (e.g., ERC20).name: stringpath?: string— Derivation path (optional).contract?: string— Contract address (optional).transfers: number— Number of transfers.symbol?: stringdecimals?: numberbalance?: stringtotalReceived?: stringtotalSent?: stringids?: Array<string>— Token IDs (optional).multiTokenValues?: Array<MultiTokenValue>— For multi-token standards (optional).
MultiTokenValue
Represents a single multi-token ID and its value.
Properties:
id: stringvalue: string
TokenTransfer
Details a single token transfer within a transaction.
Properties:
type: stringfrom: stringto: stringcontract: stringname: stringsymbol: stringdecimals: numbervalue: stringmultiTokenValues?: Array<MultiTokenValue>
Tx
Represents a blockchain transaction with normalized fields.
Properties:
txid: stringversion?: numberlockTime?: numbervin: Array<Vin>— Inputs.vout: Array<Vout>— Outputs.blockHash?: stringblockHeight: numberconfirmations: numberblockTime: numbersize?: numbervalue: string— Total value transferred.valueIn?: string— Input value (optional).fees?: stringhex?: string— Raw transaction hex (optional).rbf?: boolean— Replace-By-Fee flag (optional).tokenTransfers?: Array<TokenTransfer>— Token transfers in this Tx (optional).coinSpecificData?: unknown— Coin-specific extensions.ethereumSpecific?: EthereumSpecific— Ethereum-specific data (optional).
Utxo
Data about a single unspent transaction output (UTXO).
Properties:
txid: stringvout: number— Output index.value: stringheight?: number— Block height (optional).confirmations: numberaddress?: string— Address holding this UTXO (optional).path?: string— Derivation path (optional).locktime?: numbercoinbase?: boolean— Whether coinbase UTXO (optional).
Vin
Details about a single transaction input.
Properties:
txid?: stringvout?: numbersequence?: numbern: number— Input index.addresses?: Array<string>isAddress: booleanvalue?: stringhex?: stringasm?: stringcoinbase?: string— Coinbase input data.
Vout
Details about a single transaction output.
Properties:
value?: stringn: numberspent?: boolean— Whether spent.spentTxId?: stringspentIndex?: numberspentHeight?: numberhex?: stringasm?: stringaddresses: Array<string> | null— Null for contract creation transactions.isAddress: booleantype?: string— Output script type.
Xpub
Type alias for `Address` representing extended public keys.
BlockbookArgs
Arguments to configure a Blockbook client instance.
Properties:
apiKey?: string— API key for authentication (optional).httpURL: string— HTTP endpoint for Blockbook API.wsURL: string— WebSocket endpoint.logger: Logger— Logger instance for diagnostics.
Implementation Details and Algorithms
Error Handling via
ApiError: The class intelligently extracts meaningful error messages from Axios HTTP response payloads, helping to propagate backend errors clearly.Normalized Models: The interfaces abstract away blockchain-specific details and provide a unified data format that supports multiple chains (Bitcoin, Ethereum, etc.). For example,
Txincludes optionalethereumSpecificdata to cover Ethereum peculiarities.Pagination Support: The
Paginginterface and its inclusion in entities likeAddressandBlocksupport scalable queries with page-based result sets.Token and Multi-Token Support: Data models support complex token representations, including multi-token standards via
MultiTokenValuearrays, enabling support for ERC1155-like tokens or other multi-asset standards.Optionality and Extensibility: Many fields are optional or use generic
unknowntypes to allow extension for coin-specific data without breaking existing contracts.
Interaction with Other Parts of the System
These models are used primarily by the Blockbook API client module that performs HTTP/WS requests to the Blockbook backend indexer.
The
ApiErrorclass is used throughout the client code to wrap and handle errors from network requests, ensuring consistent error propagation.The typed interfaces are consumed by business logic layers and REST API controllers that expose blockchain data to external clients or UI components.
Logging (
Loggerfrom@shapeshiftoss/logger) is integrated via parameters like inBlockbookArgsto trace and monitor API interactions.These models provide the schema foundation for transforming raw blockchain data from the backend into normalized, consumable formats for wallet services, explorers, or analytics components.
Visual Diagram: Class Diagram of Key Entities
classDiagram
class ApiError {
+constructor(err: AxiosError | Error)
}
class Address {
+address: string
+balance: string
+totalReceived?: string
+totalSent?: string
+unconfirmedBalance: string
+unconfirmedTxs: number
+txs: number
+transactions?: Tx[]
+txids?: string[]
}
class Tx {
+txid: string
+vin: Vin[]
+vout: Vout[]
+blockHeight: number
+confirmations: number
+blockTime: number
+value: string
+tokenTransfers?: TokenTransfer[]
+ethereumSpecific?: EthereumSpecific
}
class Vin {
+n: number
+addresses?: string[]
+isAddress: boolean
}
class Vout {
+n: number
+addresses: string[] | null
+isAddress: boolean
+spent?: boolean
}
class Token {
+type: string
+name: string
+transfers: number
+balance?: string
}
class TokenTransfer {
+type: string
+from: string
+to: string
+contract: string
+value: string
}
class EthereumSpecific {
+status: number
+nonce: number
+gasLimit: number
+gasUsed: number | null
+gasPrice: string
}
class Erc20Contract {
+contract: string
+name: string
+symbol: string
+decimals: number
}
class Utxo {
+txid: string
+vout: number
+value: string
+confirmations: number
}
Address "1" o-- "*" Tx : transactions
Tx "1" o-- "*" Vin : vin
Tx "1" o-- "*" Vout : vout
Tx "1" o-- "*" TokenTransfer : tokenTransfers
Tx "1" o-- "0..1" EthereumSpecific : ethereumSpecific
Address "1" o-- "*" Token : tokens
TokenTransfer "1" o-- "0..1" MultiTokenValue : multiTokenValues
Token "1" o-- "0..1" MultiTokenValue : multiTokenValues
Summary
The [models.ts](/projects/291/68901) file plays a critical role in the Blockchain Data Indexing module by defining the data contracts and error handling mechanisms essential for consistent and reliable blockchain data retrieval. Its well-structured, strongly-typed interfaces enable multi-chain support and token complexity handling, while the custom error class facilitates robust API error management. These models underpin the entire interaction layer with the Blockbook backend and serve as the foundation for blockchain data services in the application.