Quick Navigation
Main Sections:- Environment setup — installation and basic test structure
- Core Testing Classes —
Blockchain
,Treasury
,RemoteBlockchainStorage
- Type Definitions —
SandboxContract
,SendMessageResult
,FlatTransaction
,FlatTransactionComparable
- Utility functions — helper functions for testing
- Test utilities and matchers — Jest/Chai assertion extensions and testing utilities
- Network configuration — custom blockchain configs
- Blueprint testing overview — getting started with testing
- Testing guidelines — best practices and patterns
- Testing on real network — mainnet/testnet testing
- Blueprint benchmarks — performance testing and optimization
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
Main blockchain emulator class that provides isolated testing environment.
Blockchain.create()
opts
— optional blockchain configurationexecutor
— custom contract executor (default:Executor
)config
— blockchain configuration (Cell
,'default'
, or'slim'
)storage
— contracts storage (default:LocalBlockchainStorage
)meta
— optional contracts metadata providerautoDeployLibs
— automatically collect and deploy libraries
treasury()
seed
— initial seed for treasury. If the same seed is used to create a treasury, then these treasuries will be identicalparams
— optional treasury parametersworkchain
— the workchain ID of the treasury (default: 0)predeploy
— if set the treasury will be deployed on the moment of creationbalance
— initial balance of the treasury (default: 1_000_000 TON if omitted)resetBalanceIfZero
— if set and treasury balance is zero on moment of calling method it reset balance tobalance
createWallets()
treasury()
method.
Parameters:
n
— number of wallets to createparams
— params for treasury creation
openContract()
contract
— contract instance to wrap
SandboxContract
wrapper with testing capabilities
Usage example:
provider()
ContractProvider
for contract address.
Parameters:
address
— address to create contract provider forinit
— initial state of contract
sender()
address
— address to create sender for
Sender
instance
Usage example:
getContract()
SmartContract
from BlockchainStorage
.
Parameters:
address
— address of contract to get
SmartContract
instance
setShardAccount()
address
— contractAddress
account
—ShardAccount
state to set
getTransactions()
address
— theAddress
to retrieve transactions foropts
— options to fetch transactionslt
— logical time of the transaction to start from (must be used withhash
)hash
— hash of the transaction to start from (must be used withlt
)limit
— maximum number of transactions to return
sendMessage()
Blockchain
. Emulates the whole chain of transactions before returning the result. Each transaction increases lt by 1000000.
Parameters:
message
— message to send (Message
object orCell
for external messages)params
— optionalMessageParams
now
— override blockchain time for this messagerandomSeed
— random seed for deterministic executionignoreChksig
— whetherCHKSIG
instructions are set to always succeed. Default:false
SendMessageResult
containing transactions, events, and externals
Usage example:
sendMessageIter()
sendMessage
.
Parameters:
message
— message to send (Message
orCell
)params
— optional parametersallowParallel
— whentrue
, allows many consequential executions of this method (default:false
)- other
MessageParams
(now, randomSeed, ignoreChksig)
BlockchainTransaction
Usage example:
runGetMethod()
address
— contractAddress
method
— method ID (number) or method name (string) to runstack
— method parameters asTupleItem
arrayparams
— optionalGetMethodParams
now
— override blockchain time for this callrandomSeed
— random seed for deterministic executiongasLimit
— overrides TVM emulatorgas_limit
, defaults to 10_000_000
GetMethodResult
with stackReader and other execution details
Usage example:
runTickTock()
on
—Address
orAddress
array to run tick-tockwhich
— type of transaction ('tick'
or'tock'
)params
—MessageParams
(now, randomSeed, ignoreChksig)
SendMessageResult
Usage example:
snapshot()
BlockchainSnapshot
object
Usage example:
loadFrom()
snapshot
—BlockchainSnapshot
to restore from
enableCoverage()
enable
— iffalse
, disable coverage collection (default:true
)
coverage()
contract
— contract to analyze coverage for
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()
code
— Cell containing contract code to analyzeaddress
— optional contract address to filter transactions by
Coverage
object with detailed coverage data
Usage example:
getDebuggerExecutor()
debug
setVerbosityForAddress()
address
— contractAddress
verbosity
—LogsVerbosity
configuration or undefined to reset
setConfig()
config
— custom config inCell
format, or predefined'default'
|'slim'
randomize()
Buffer
Usage example:
now
lt
bigint
config
Cell
configBase64
verbosity
libs
random
recordStorage
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
prevBlocks
PrevBlocksInfo
for the blockchain.
Treasury
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
create()
workchain
— workchain ID (typically 0)subwalletId
— unique subwallet identifier
address
Address
of the treasury
init
StateInit
for contract deployment
subwalletId
bigint
subwallet ID
sendMessages()
provider
—ContractProvider
messages
— array ofMessageRelaxed
to sendsendMode
— optionalSendMode
(default: pay gas fees separately)
send()
provider
—ContractProvider
args
—SenderArguments
including value, body, and send mode
getSender()
Sender
object for transaction signing
Usage example:
getBalance()
provider
—ContractProvider
createTransfer()
args
— transfer argumentsmessages
— array ofMessageRelaxed
to include in transfersendMode
— optionalSendMode
(default: pay gas fees separately)
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.
client
— wrapped TON client for network accessblockSeqno
— optional block number to fetch state from
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.
- Get methods (
get*
) — Remove the ContractProvider parameter, return the same result - Send methods (
send*
) — Remove ContractProvider parameter, returnPromise<SendMessageResult & { result: R }>
- Other properties — Remain unchanged
SendMessageResult
Result of sending a message to the blockchain emulator.
transactions
— array ofBlockchainTransaction
objects that resulted from the messageevents
— array ofEvent
objects emitted during executionexternals
— array ofExternalOut
messages generated during execution
BlockchainTransaction
Enhanced transaction type with additional sandbox-specific properties.
events
—Event
objects emitted during transaction executionparent
— parentBlockchainTransaction
that triggered this onechildren
— childBlockchainTransaction
objects triggered by this transactionexternals
—ExternalOut
messages generated during executionmode
— transaction execution mode
MessageParams
Optional parameters for message sending operations.
now
— override blockchain time for this message (UNIX timestamp)randomSeed
— random seed for deterministic executionignoreChksig
— whetherCHKSIG
instructions are set to always succeed
GetMethodParams
Optional parameters for get method execution.
now
— override blockchain time for this call (UNIX timestamp)randomSeed
— random seed for deterministic executiongasLimit
— override TVM emulator gas limit (default: 10,000,000)
GetMethodResult
Result of executing a get method on a contract.
stack
— rawTupleItem
array returned by the methodstackReader
— convenientTupleReader
for parsing stack itemsexitCode
— TVM exit code (0 for success, see ExitCodes)gasUsed
— amount of gas consumed during executionblockchainLogs
— blockchain-level execution logsvmLogs
— TVM execution logsdebugLogs
— debug-level execution logs
Verbosity
Verbosity levels for TVM execution logging.
'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.
print
— enable console outputblockchainLogs
— enable blockchain-level logsvmLogs
— TVM executionVerbosity
leveldebugLogs
— enable debug-level logs
SmartContractTransaction
Enhanced transaction type with execution logs and storage information.
blockchainLogs
— blockchain execution logsvmLogs
— TVM execution logsdebugLogs
— debug execution logsoldStorage
— contract storage before transaction (ifrecordStorage
enabled)newStorage
— contract storage after transaction (ifrecordStorage
enabled)outActions
— output actions generated during execution
BlockchainSnapshot
Snapshot of blockchain state for persistence and restoration.
contracts
— snapshots of all contract statesnetworkConfig
— blockchain configurationlt
— current logical timetime
— current blockchain timeverbosity
— logging configurationlibs
— shared librariesnextCreateWalletIndex
— next treasury wallet indexprevBlocksInfo
— previous blocks informationrandomSeed
— random seed for executionautoDeployLibs
— auto-deploy libraries flagtransactions
— transaction history
GetMethodResultSuccess
Successful get method execution result from remote API.
success
— always true for successful resultsstack
— serialized result stackgas_used
— gas consumption as stringvm_exit_code
— TVM exit codevm_log
— TVM execution logmissing_library
— missing library hash if any
GetMethodResultError
Failed get method execution result from remote API.
success
— always false for error resultserror
— error description
Event
Types
Blockchain events emitted during transaction execution.
EventAccountCreated
— account was created during executionEventAccountDestroyed
— account was destroyed during executionEventMessageSent
— message was sent during execution
BlockId
Identifier for a blockchain block.
workchain
— workchain numbershard
— shard identifierseqno
— sequence numberrootHash
— block root hashfileHash
— block file hash
PrevBlocksInfo
Information about previous blocks in the blockchain.
lastMcBlocks
— last masterchain blocksprevKeyBlock
— previous key blocklastMcBlocks100
— last 100 masterchain blocks (optional)
SerializableSnapshot
JSON-serializable format for blockchain snapshots.
ExtraCurrency
Type for extra currencies in transactions.
[key: number]
— currency ID mapped to amount in basic units
Utility functions
loadConfig()
Loads and parses blockchain configuration from Cell or base64 string.
configCellOrBase64
— configuration asCell
or base64 string
BlockchainConfig
object
updateConfig()
Updates blockchain configuration with new parameters.
config
— existing configurationCell
...params
—ConfigParam
array to update
Cell
prettyLogTransaction()
Creates a formatted log string for a transaction.
tx
—Transaction
to create log string formapFunc
— optionalAddressMapFunc
to map addresses to human-readable strings
prettyLogTransactions()
Logs multiple transactions to console using formatted output.
txs
—Transaction
array to logmapFunc
— optionalAddressMapFunc
to map addresses to human-readable format
internal()
(Utility Function)
Creates an internal message from parameters. This is a utility function used internally and in message builders.
from
— senderAddress
to
— recipientAddress
value
— message value in nanoTONbody
— optional message bodyCell
stateInit
— optionalStateInit
for contract deploymentbounce
— 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 amountforwardFee
— forward fee amountcreatedAt
— message creation timestampcreatedLt
— logical time when message was createdec
— extra currenciesDictionary
orExtraCurrency
Message
object for blockchain processing
Usage examples:
printTransactionFees()
Prints transaction fees in a formatted table to console.
transactions
— list ofTransaction
to analyze and print fees formapFunc
— optionalOpMapFunc
to map operation codes to human-readable format
void
(outputs formatted table to console)
snapshotToSerializable()
snapshot
—BlockchainSnapshot
to serialize
SerializableSnapshot
— JSON-serializable snapshot object
snapshotFromSerializable()
serialized
—SerializableSnapshot
object
BlockchainSnapshot
— restored blockchain snapshot
Usage example:
setGlobalVersion()
Sets global version in blockchain configuration.
config
— blockchain configurationCell
version
— global version number to setcapabilites
— optional capabilities flags
Cell
— updated configuration Cell
fetchConfig()
Fetches blockchain configuration from TON network.
network
— network to fetch config from ('mainnet'
or'testnet'
)maxRetries
— maximum number of retry attempts (default: 5)
Promise<Cell>
— blockchain configuration Cell
registerCompiledContract()
Registers compiled contract for debugging support.
code
— compiled contract codeCell
debugInfo
—FuncDebugInfo
debug informationmarks
— debug marksCell
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.
from
— sender address (if internal message)to
— recipient addresson
— contract address being calledvalue
— message value in nanoTONec
— extra currencies as[currencyId, amount]
pairsbody
— message body cellinMessageBounced
— whether incoming message was bouncedinMessageBounceable
— whether incoming message is bounceableop
— operation code extracted from message bodyinitData
— contract initialization datainitCode
— contract initialization codedeploy
— whether this transaction deployed a contractlt
— logical time of transactionnow
— timestamp of transactionoutMessagesCount
— number of outbound messagesoldStatus
— account status before transactionendStatus
— account status after transactiontotalFees
— total fees paid for transactionaborted
— whether transaction was aborteddestroyed
— whether account was destroyedexitCode
— TVM exit codeactionResultCode
— action phase result codesuccess
— whether transaction was successfulmode
— transaction execution mode
FlatTransactionComparable
Pattern for matching transactions with optional fields and functions.
FlatTransaction
where each field can be either:
- The exact value to match
- A function that returns
true
if the value matches the criteria
PrettyTransaction
Human-readable transaction format for debugging and logging.
failReason
— human-readable failure reason (if transaction failed)from
— readable sender address or nameto
— readable recipient address or nameon
— readable contract address or nameop
— readable operation name or code
FailReason
Describes why a transaction failed with human-readable information.
message
— human-readable failure description
ContractsMeta
Registry for contract metadata to enhance debugging and logging.
get()
— retrieve metadata for contract addressupsert()
— add or update metadata for contract addressclear()
— remove all metadatadelete()
— remove metadata for specific address
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()
cmp
—FlatTransactionComparable
pattern with optional fields to match
toEqualCell()
cell
— Cell to compare against
toEqualAddress()
address
— Address to compare against
toEqualSlice()
slice
— Slice to compare against
toThrowExitCode()
exitCode
— expected TVM exit code
Transaction utilities
Utilities for finding, filtering, and working with transactions in tests.findTransaction()
txs
— single transaction or array of transactions to searchmatch
—FlatTransactionComparable
pattern to match
undefined
if not found
Usage example:
findTransactionRequired()
txs
— single transaction or array of transactions to searchmatch
—FlatTransactionComparable
pattern to match
Error
if no matching transaction is found
Usage example:
filterTransactions()
txs
— array of transactions to filtermatch
—FlatTransactionComparable
pattern to match
Async execution utilities
Utilities for working with transaction iterators and step-by-step execution.executeTill()
txs
— async iterator of transactions fromsendMessageIter()
match
—FlatTransactionComparable
pattern to match
Error
if no matching transaction is found
Usage example:
executeFrom()
txs
— async iterator of transactions
Formatting and debugging utilities
Utilities for making transactions and debugging information more readable.prettifyTransaction()
transaction
— transaction to prettify
PrettyTransaction
object with readable formatting
Usage example:
contractsMeta
Global registry for contract metadata to enhance debugging and logging.
Testing constants and utilities
ExitCodes
Comprehensive collection of TVM exit codes for error testing and analysis.
randomAddress()
workchain
— workchain ID (default: 0)
Address
Usage example: