Skip to main content
Blueprint provides comprehensive testing capabilities for TON smart contracts using the TON Sandbox emulator and test utilities. This reference covers all available testing APIs, methods, and utilities.

Quick Navigation

Main Sections:

Environment setup

Blueprint testing environment requires proper setup of the TON Sandbox and test utilities.

Installation

Basic test structure

./tests/Sample.spec.ts

Core Testing Classes

Blockchain

The main blockchain emulator class provides an isolated testing environment.

Blockchain.create()

Creates a new blockchain instance for testing. Parameters:
  • opts — optional blockchain configuration
    • executor — custom contract executor (default: Executor)
    • config — blockchain configuration (Cell, 'default', or 'slim')
    • storage — contracts storage (default: LocalBlockchainStorage)
    • meta — optional contracts metadata provider
    • autoDeployLibs — automatically collect and deploy libraries
Returns: promise resolving to blockchain instance Usage example:

treasury()

Creates a treasury wallet contract. This wallet is used as an alternative to the wallet smart contract. Parameters:
  • seed — initial seed for the treasury. If the same seed is used to create a treasury, then these treasuries will be identical
  • params — optional treasury parameters
    • workchain — the workchain ID of the treasury (default: 0)
    • predeploy — if set, the treasury will be deployed at the moment of creation
    • balance — initial balance of the treasury (default: 1_000_000 TON if omitted)
    • resetBalanceIfZero — if set and the treasury balance is zero at the moment of calling the method, it resets the balance to balance
Returns: promise resolving to treasury contract wrapper Usage example:

createWallets()

Bulk variant of treasury() method. Parameters:
  • n — number of wallets to create
  • params — params for treasury creation
Returns: array of opened treasury contracts Usage example:

openContract()

Wraps a contract for testing with additional methods and state tracking. Parameters:
  • contract — contract instance to wrap
Returns: SandboxContract wrapper with testing capabilities Usage example:

provider()

Creates a new ContractProvider for the contract address. Parameters:
  • address — address to create contract provider for
  • init — initial state of contract
Returns: ContractProvider instance Usage example:

sender()

Creates a Sender for the address. Note that this sender pushes internal messages to the Blockchain directly. No value is deducted from the sender address; all the values are set to defaults. Use for test purposes only. Parameters:
  • address — address to create sender for
Returns: Sender instance Usage example:

getContract()

Retrieves SmartContract from BlockchainStorage. Parameters:
  • address — address of the contract to get
Returns: a promise resolving to a SmartContract instance

setShardAccount()

Sets the account state directly for a contract address. Parameters:
  • address — contract Address
  • accountShardAccount state to set

getTransactions()

Retrieves transactions for the specified address. Transactions are ordered from newest to oldest. Parameters:
  • address — the Address to retrieve transactions for
  • opts — options to fetch transactions
    • lt — logical time of the transaction to start from (must be used with hash)
    • hash — hash of the transaction to start from (must be used with lt)
    • limit — maximum number of transactions to return
Returns: promise resolving to an array of transactions involving the given address Usage example:

sendMessage()

Emulates the result of sending a message to this Blockchain. Emulates the whole chain of transactions before returning the result. Each transaction increases lt by 1000000. Parameters:
  • message — message to send (Message object or Cell for external messages)
  • params — optional MessageParams
    • now — override blockchain time for this message
    • randomSeed — random seed for deterministic execution
    • ignoreChksig — whether CHKSIG instructions are set to always succeed. Default: false
Returns: promise resolving to SendMessageResult containing transactions, events, and externals Usage example:

sendMessageIter()

Starts emulating the result of sending a message to this Blockchain. Each iterator call emulates one transaction, so the whole chain is not emulated immediately, unlike in sendMessage. Parameters:
  • message — message to send (Message or Cell)
  • params — optional parameters
    • allowParallel — when true, allows many consequential executions of this method (default: false)
    • other MessageParams (now, randomSeed, ignoreChksig)
Returns: promise resolving to async iterator of BlockchainTransaction Usage example:

runGetMethod()

Runs a get method on the contract. Parameters:
  • address — contract Address
  • method — method ID (number) or method name (string) to run
  • stack — method parameters as TupleItem array
  • params — optional GetMethodParams
    • now — override blockchain time for this call
    • randomSeed — random seed for deterministic execution
    • gasLimit — overrides TVM emulator gas_limit, defaults to 10_000_000
Returns: promise resolving to GetMethodResult with stackReader and other execution details Usage example:

runTickTock()

Runs tick or tock transaction. Parameters:
  • onAddress or Address array to run tick-tock
  • which — type of transaction ('tick' or 'tock')
  • paramsMessageParams (now, randomSeed, ignoreChksig)
Returns: promise resolving to SendMessageResult Usage example:

snapshot()

Saves a snapshot of the current blockchain. Returns: BlockchainSnapshot object Usage example:

loadFrom()

Restores blockchain state from the snapshot. Parameters: Usage example:

enableCoverage()

Enable coverage collection. Parameters:
  • enable — if false, disable coverage collection (default: true)
Usage example:

coverage()

Returns coverage analysis for the specified contract. Coverage is collected at the TVM assembly instruction level from all executed transactions and get method calls. Parameters:
  • contract — contract to analyze coverage for
Returns: Coverage object with detailed coverage data or undefined Throws: Error if the contract has no code or if verbose VM logs are not enabled Usage example:

coverageForCell()

Returns coverage analysis for the specified code cell. This method allows analyzing coverage for code cells directly, with optional address filtering. Parameters:
  • code — Cell containing contract code to analyze
  • address — optional contract address to filter transactions by
Returns: Coverage object with detailed coverage data Usage example:

getDebuggerExecutor()

Gets the debugger executor instance for debugging purposes. Returns: promise resolving to Executor instance for debugging Usage example:

debug

Gets or sets debug mode for the blockchain.

setVerbosityForAddress()

Update the logs’ verbosity level for the address. Parameters:
  • address — contract Address
  • verbosityLogsVerbosity configuration or undefined to reset
Usage example:

setConfig()

Updates blockchain config. Parameters:
  • config — custom config in Cell format, or predefined 'default' | 'slim'
Usage example:

randomize()

Generates and sets a new random seed using secure random bytes. Returns: promise resolving to the generated random seed Buffer Usage example:

now

Gets or sets the current time in the blockchain (UNIX timestamp). Usage example:

lt

Gets the current logical time in the blockchain. Returns: current logical time as bigint

config

Gets the configuration used in the blockchain. Returns: configuration as Cell

configBase64

Gets the configuration used in the blockchain in base64 format. Returns: configuration as base64 string

verbosity

Gets or sets the logs verbosity level. Usage example:

libs

Gets or sets the global blockchain libraries. Usage example:

random

Gets or sets the random seed. Usage example:

recordStorage

If set to true, BlockchainTransaction will have oldStorage and newStorage fields. Note that enabling this flag will disable a certain optimization, which will slow down contract emulation.

autoDeployLibraries

Gets or sets whether libraries should be automatically deployed.

prevBlocks

Gets or sets the PrevBlocksInfo for the blockchain.

Treasury

A test treasury wallet for sending transactions and managing test funds. Treasury is created by blockchain.treasury() and provides a convenient wallet interface for testing.

code

Static property containing the compiled treasury contract code. Returns: Cell with treasury contract bytecode

create()

Creates a new treasury contract instance. Parameters:
  • workchain — workchain ID (typically 0)
  • subwalletId — unique subwallet identifier
Returns: new TreasuryContract instance

address

The address of the treasury contract. Returns: Address of the treasury

init

The initial state of the treasury contract. Returns: StateInit for contract deployment

subwalletId

Unique subwallet identifier generated from the treasury seed using SHA-256. Returns: bigint subwallet ID

sendMessages()

Sends multiple messages via the treasury contract. Parameters:
  • providerContractProvider
  • messages — array of MessageRelaxed to send
  • sendMode — optional SendMode (default: pay gas fees separately)

send()

Sends a single message via the treasury contract. Parameters:
  • providerContractProvider
  • argsSenderArguments including value, body, and send mode

getSender()

Returns a sender interface for this treasury that automatically handles sending transactions. Returns: Sender object for transaction signing Usage example:

getBalance()

Returns the current TON balance of the treasury. Parameters:
  • providerContractProvider
Returns: promise resolving to balance in nanoTON Usage example:

createTransfer()

Creates a transfer message cell for sending multiple messages via the treasury. Parameters:
  • args — transfer arguments
    • messages — array of MessageRelaxed to include in transfer
    • sendMode — optional SendMode (default: pay gas fees separately)
Returns: Cell containing the transfer message body

Treasury usage

Treasury contracts are pre-funded wallets that work like regular wallet contracts: Usage example:

RemoteBlockchainStorage

Storage implementation that fetches contract states from a real TON network.
Parameters:
  • client — wrapped TON client for network access
  • blockSeqno — optional block number to fetch state from
Usage example:

Type Definitions

SandboxContract

Enhanced contract wrapper that transforms contract methods for sandbox testing. SandboxContract automatically wraps get methods and send methods to work with the sandbox environment.
Key transformations:
  • Get methods (get*) — Remove the ContractProvider parameter, return the same result
  • Send methods (send*) — Remove ContractProvider parameter, return Promise<SendMessageResult & { result: R }>
  • Other properties — Remain unchanged
Usage example:

SendMessageResult

Result of sending a message to the blockchain emulator.
Properties:
  • transactions — array of BlockchainTransaction objects that resulted from the message
  • events — array of Event objects emitted during execution
  • externals — array of ExternalOut messages generated during execution

BlockchainTransaction

Enhanced transaction type with additional sandbox-specific properties.
Properties:
  • eventsEvent objects emitted during transaction execution
  • parent — parent BlockchainTransaction that triggered this one
  • children — child BlockchainTransaction objects triggered by this transaction
  • externalsExternalOut messages generated during execution
  • mode — transaction execution mode

MessageParams

Optional parameters for message sending operations.
Properties:
  • now — override blockchain time for this message (UNIX timestamp)
  • randomSeed — random seed for deterministic execution
  • ignoreChksig — whether CHKSIG instructions are set to always succeed

GetMethodParams

Optional parameters for a get method execution.
Properties:
  • now — override blockchain time for this call (UNIX timestamp)
  • randomSeed — random seed for deterministic execution
  • gasLimit — override TVM emulator gas limit (default: 10,000,000)

GetMethodResult

Result of executing a get method on a contract.
Properties:
  • stack — raw TupleItem array returned by the method
  • stackReader — convenient TupleReader for parsing stack items
  • exitCode — TVM exit code (0 for success, see ExitCodes)
  • gasUsed — amount of gas consumed during execution
  • blockchainLogs — blockchain-level execution logs
  • vmLogs — TVM execution logs
  • debugLogs — debug-level execution logs

Verbosity

Verbosity levels for TVM execution logging.
Values:
  • 'none' — no VM logs
  • 'vm_logs' — basic VM execution logs
  • 'vm_logs_location' — VM logs with code location information
  • 'vm_logs_gas' — VM logs with gas consumption details
  • 'vm_logs_full' — comprehensive VM logs
  • 'vm_logs_verbose' — maximum verbosity VM logs

LogsVerbosity

Configuration for different types of logging output.
Properties:
  • print — enable console output
  • blockchainLogs — enable blockchain-level logs
  • vmLogs — TVM execution Verbosity level
  • debugLogs — enable debug-level logs

SmartContractTransaction

Enhanced transaction type with execution logs and storage information.
Properties:
  • blockchainLogs — blockchain execution logs
  • vmLogs — TVM execution logs
  • debugLogs — debug execution logs
  • oldStorage — contract storage before transaction (if recordStorage enabled)
  • newStorage — contract storage after transaction (if recordStorage enabled)
  • outActions — output actions generated during execution

BlockchainSnapshot

Snapshot of blockchain state for persistence and restoration.
Properties:
  • contracts — snapshots of all contract states
  • networkConfig — blockchain configuration
  • lt — current logical time
  • time — current blockchain time
  • verbosity — logging configuration
  • libs — shared libraries
  • nextCreateWalletIndex — next treasury wallet index
  • prevBlocksInfo — previous blocks information
  • randomSeed — random seed for execution
  • autoDeployLibs — auto-deploy libraries flag
  • transactions — transaction history

GetMethodResultSuccess

Successful get method execution result from the remote API.
Properties:
  • success — always true for successful results
  • stack — serialized result stack
  • gas_used — gas consumption as string
  • vm_exit_code — TVM exit code
  • vm_log — TVM execution log
  • missing_library — missing library hash if any

GetMethodResultError

A failed get method execution result from the remote API.
Properties:
  • success — always false for error results
  • error — error description

Event Types

Blockchain events that were emitted during transaction execution.
Event Types:
  • EventAccountCreated — account was created during execution
  • EventAccountDestroyed — account was destroyed during execution
  • EventMessageSent — message was sent during execution

BlockId

An identifier for a blockchain block.
Properties:
  • workchain — workchain number
  • shard — shard identifier
  • seqno — sequence number
  • rootHash — block root hash
  • fileHash — block file hash

PrevBlocksInfo

Information about previous blocks in the blockchain.
Properties:
  • lastMcBlocks — last masterchain blocks
  • prevKeyBlock — previous key block
  • lastMcBlocks100 — last 100 masterchain blocks (optional)

SerializableSnapshot

JSON-serializable format for blockchain snapshots.

ExtraCurrency

Type for extra currencies in transactions.
Properties:
  • [key: number] — currency ID mapped to amount in basic units

Utility functions

loadConfig()

Loads and parses blockchain configuration from Cell or base64 string.
Parameters:
  • configCellOrBase64 — configuration as Cell or base64 string
Returns: parsed BlockchainConfig object

updateConfig()

Updates blockchain configuration with new parameters.
Parameters:
  • config — existing configuration Cell
  • ...paramsConfigParam array to update
Returns: updated configuration Cell

prettyLogTransaction()

Creates a formatted log string for a transaction.
Parameters:
  • txTransaction to create a log string for
  • mapFunc — optional AddressMapFunc to map addresses to human-readable strings
Returns: formatted transaction log string

prettyLogTransactions()

Logs multiple transactions to the console using formatted output.
Parameters:
  • txsTransaction array to log
  • mapFunc — optional AddressMapFunc to map addresses to a human-readable format
Example Output:

internal() (Utility Function)

Creates an internal message from parameters. This is a utility function used internally and in message builders.
Parameters:
  • from — sender Address
  • to — recipient Address
  • value — message value in nanoTON
  • body — optional message body Cell
  • stateInit — optional StateInit for contract deployment
  • bounce — bounce flag (default: true for bounceable messages)
  • bounced — indicates if this is a bounced message (default: false)
  • ihrDisabled — disable Instant Hypercube Routing (default: true)
  • ihrFee — IHR fee amount
  • forwardFee — forward fee amount
  • createdAt — message creation timestamp
  • createdLt — logical time when message was created
  • ec — extra currencies Dictionary or ExtraCurrency
Returns: Message object for blockchain processing Usage examples:

printTransactionFees()

Prints transaction fees in a formatted table to the console.
Parameters:
  • transactions — list of Transaction to analyze and print fees for
  • mapFunc — optional OpMapFunc to map operation codes to a human-readable format
Returns: void (outputs formatted table to console)

snapshotToSerializable()

Parameters: Returns: SerializableSnapshot — JSON-serializable snapshot object

snapshotFromSerializable()

Parameters: Returns: BlockchainSnapshot — restored blockchain snapshot Usage example:

setGlobalVersion()

Sets the global version in the blockchain configuration.
Parameters:
  • config — blockchain configuration Cell
  • version — global version number to set
  • capabilites — optional capabilities flags
Returns: Cell — updated configuration Cell

fetchConfig()

Fetches blockchain configuration from TON network.
Parameters:
  • network — network to fetch config from ('mainnet' or 'testnet')
  • maxRetries — maximum number of retry attempts (default: 5)
Returns: Promise<Cell> — blockchain configuration Cell

registerCompiledContract()

Registers compiled contract for debugging support.
Parameters:
  • code — compiled contract code Cell
  • debugInfoFuncDebugInfo debug information
  • marks — debug marks Cell
Returns: Cell — the same code Cell (for chaining)

Test utilities and matchers

Comprehensive testing utilities for TON blockchain transactions and state. Import from @ton/test-utils to use these utilities and matchers.

FlatTransaction

Flattened transaction structure for easier testing and comparison.
Properties:
  • from — sender address (if internal message)
  • to — recipient address
  • on — contract address being called
  • value — message value in nanoTON
  • ec — extra currencies as [currencyId, amount] pairs
  • body — message body cell
  • inMessageBounced — whether the incoming message was bounced
  • inMessageBounceable — whether the incoming message is bounceable
  • op — operation code extracted from message body
  • initData — contract initialization data
  • initCode — contract initialization code
  • deploy — whether this transaction deployed a contract
  • lt — logical time of transaction
  • now — timestamp of transaction
  • outMessagesCount — number of outbound messages
  • oldStatus — account status before transaction
  • endStatus — account status after transaction
  • totalFees — total fees paid for the transaction
  • aborted — whether the transaction was aborted
  • destroyed — whether the account was destroyed
  • exitCode — TVM exit code
  • actionResultCode — action phase result code
  • success — whether the transaction was successful
  • mode — transaction execution mode

FlatTransactionComparable

Pattern for matching transactions with optional fields and functions.
A partial FlatTransaction where each field can be either:
  • The exact value to match
  • A function that returns true if the value matches the criteria
Usage examples:

PrettyTransaction

Human-readable transaction format for debugging and logging.
Properties:
  • failReason — human-readable failure reason (if transaction failed)
  • from — readable sender address or name
  • to — readable recipient address or name
  • on — readable contract address or name
  • op — readable operation name or code

FailReason

Describes why a transaction failed with human-readable information.
Properties:
  • message — human-readable failure description

ContractsMeta

Registry for contract metadata to enhance debugging and logging.
Methods:
  • get() — retrieve metadata for contract address
  • upsert() — add or update metadata for contract address
  • clear() — remove all metadata
  • delete() — remove metadata for specific address
Usage example:

Jest/Chai matchers

Test utils provides custom Jest/Chai matchers for testing TON blockchain transactions and data structures. These matchers are automatically available when you import @ton/test-utils.

toHaveTransaction()

Asserts that a transaction array or result contains a transaction matching the specified pattern. Parameters: Usage examples:

toEqualCell()

Asserts that a Cell equals another Cell by comparing their hash and content. Parameters:
  • cell — Cell to compare against
Usage example:

toEqualAddress()

Asserts that an Address equals another Address. Parameters:
  • address — Address to compare against
Usage example:

toEqualSlice()

Asserts that a Slice equals another Slice by comparing their underlying Cell data. Parameters:
  • slice — Slice to compare against
Usage example:

toThrowExitCode()

Asserts that a function throws an error with a specific TVM exit code. Parameters:
  • exitCode — expected TVM exit code
Usage examples:

Transaction utilities

Utilities for finding, filtering, and working with transactions in tests.

findTransaction()

Finds the first transaction matching the specified pattern. Parameters: Returns: matching transaction or undefined if not found Usage example:

findTransactionRequired()

Finds the first transaction matching the specified pattern, throwing an error if not found. Parameters: Returns: matching transaction Throws: Error if no matching transaction is found Usage example:

filterTransactions()

Filters the transactions array to only include transactions matching the specified pattern. Parameters: Returns: array of matching transactions Usage example:

Async execution utilities

Utilities for working with transaction iterators and step-by-step execution.

executeTill()

Executes transactions from an async iterator until finding a transaction matching the pattern. Parameters: Returns: a Promise resolving to an array of executed transactions up to and including the match Throws: Error if no matching transaction is found Usage example:

executeFrom()

Executes all remaining transactions from an async iterator. Parameters:
  • txs — async iterator of transactions
Returns: promise resolving to array of all executed transactions Usage example:

Formatting and debugging utilities

Utilities for making transactions and debugging information more readable.

prettifyTransaction()

Converts a transaction to a human-readable format for debugging and logging. Parameters:
  • transaction — transaction to prettify
Returns: PrettyTransaction object with readable formatting Usage example:

contractsMeta

Global registry for contract metadata to enhance debugging and logging.
Usage example:

Testing constants and utilities

ExitCodes

Comprehensive collection of TVM exit codes for error testing and analysis.

randomAddress()

Generates a random TON address for testing purposes. Parameters:
  • workchain — workchain ID (default: 0)
Returns: randomly generated Address Usage example:

Network configuration

Custom network configuration