Skip to content

Latest commit

 

History

History
192 lines (150 loc) · 8.31 KB

File metadata and controls

192 lines (150 loc) · 8.31 KB

retracer-core

retracer-core is a core library for deep analysis, emulation, and tracing transactions on the TON blockchain. The library allows you to reproduce transaction execution in a local sandbox, obtain detailed reports on computation, actions, and money flow, and collect low-level information about blocks, accounts, and messages.

Features

  • Detailed transaction tracing: Emulate transaction execution in an environment identical to TON blockchain's mainnet.
  • Full trace replay: Reproduce every transaction in a trace while preserving the canonical transaction order and per-account state.
  • Raw-message emulation: Execute a serialized inbound message and its internal-message cascade without an existing on-chain transaction.
  • Block and account data collection: Obtain account state snapshots, block configuration, and transaction history.
  • Work with libraries and contracts: Automatic loading and handling of exotic library cells.
  • Analysis of incoming/outgoing messages, balance calculations, and VM log collection.
  • Supports mainnet, testnet, and custom Toncenter-compatible endpoints.

Installation

yarn add @ton/retracer-core
# or
npm install @ton/retracer-core

Quick Start

import {RETRACE_MAINNET_NETWORK, retrace} from "@ton/retracer-core"

// Example: trace a transaction by its hash
const result = await retrace(RETRACE_MAINNET_NETWORK, "YOUR_TX_HASH")
console.log(result)

Main API

Transaction Tracing

import {
  RETRACE_MAINNET_NETWORK,
  RETRACE_TESTNET_NETWORK,
  findBaseTxByHash,
  retrace,
  retraceBaseTx,
} from "@ton/retracer-core"
import type {RetraceNetworkConfig} from "@ton/retracer-core"

/**
 * @param network - Toncenter-compatible network configuration
 * @param txHash - hex transaction hash
 * @returns Detailed execution report (TraceResult)
 */
const result1 = await retrace(RETRACE_MAINNET_NETWORK, txHash)
const result2 = await retrace(RETRACE_TESTNET_NETWORK, txHash)

const customNetwork: RetraceNetworkConfig = {
  testnet: true,
  v2BaseUrl: "https://example.com/api/v2",
  v3BaseUrl: "https://example.com/api/v3",
  toncenterApiKey: "optional-api-key",
}
const result3 = await retrace(customNetwork, txHash)

/**
 * Retrace a transaction described by base transaction information.
 * Base transaction info should be resolved through the same network first,
 * because it carries the Toncenter v3 shard block reference.
 */
const baseTx = await findBaseTxByHash(RETRACE_MAINNET_NETWORK, txHash)
if (baseTx === undefined) {
  throw new Error("Transaction not found")
}
const result4 = await retraceBaseTx(RETRACE_MAINNET_NETWORK, baseTx)

Full Trace Replay

Use retraceTrace when a single transaction is not enough and you need the result of every transaction in its complete message trace. The input may be the hash of any transaction in the trace; rootTxHash identifies the actual trace root and can therefore differ from the input.

import {RETRACE_MAINNET_NETWORK, retraceTrace} from "@ton/retracer-core"

const replay = await retraceTrace(RETRACE_MAINNET_NETWORK, txHash)

if (!replay.stateUpdateHashOk) {
    throw new Error("At least one transaction diverged from the on-chain state update")
}

const rootTransaction = replay.transactions[replay.rootTxHash]
console.log("root", rootTransaction)
for (const [hash, transaction] of Object.entries(replay.transactions)) {
    console.log(hash, transaction.inMsg, transaction.money, transaction.emulatedTx)
}

retraceTrace returns a TraceReplayResult:

  • rootTxHash — normalized lowercase hex hash of the trace root, without a 0x prefix.
  • transactionsTraceResult values keyed by normalized transaction hash. Entries are populated in Toncenter's transactions_order when it is available, with logical-time and trace tree fallbacks for compatible endpoints that omit it.
  • stateUpdateHashOktrue only when every replayed transaction produced the same state update as the on-chain transaction. Do not use replayed state changes as authoritative when this value is false.
  • emulatorVersion — TON Sandbox executor version used for the replay.

Replay is sequential because each transaction may provide the account state required by a later transaction. Missing public libraries are loaded automatically and the trace is restarted with the expanded library set. options.additionalLibs can be used to provide libraries that are not available from the configured endpoint.

The method rejects incomplete traces rather than returning partial state changes. It also rejects when the trace is missing, empty, references unavailable transactions, cannot load required block context or libraries, or when transaction emulation fails. Network and Toncenter errors are passed through to the caller.

Raw Message Emulation

Use emulateRawMessage to execute a serialized inbound message from a chosen masterchain state. The message may be passed as a Cell, a hex BoC, or a base64 BoC. Internal messages emitted by a transaction are executed in order against an in-memory account-state cache. ignoreChksig applies only to the root transaction; signature checks remain enabled for the rest of the cascade.

import {emulateRawMessage, RETRACE_TESTNET_NETWORK} from "@ton/retracer-core"

const emulation = await emulateRawMessage(RETRACE_TESTNET_NETWORK, rawMessageBoc, {
  mcSeqno: 42_000_000,
  ignoreChksig: true,
  maxTransactions: 64,
  accountStateOverrides: {
    [contractAddress.toString()]: {
      balance: 10_000_000_000n,
      state: {
        type: "active",
        codeBoc: compiledCode.toBoc().toString("base64"),
        dataBoc: initialData.toBoc().toString("base64"),
      },
    },
  },
})

console.log(emulation.rootTxHash)
console.log(emulation.trace.trace)
console.log(emulation.transactions[emulation.rootTxHash])

When mcSeqno is omitted, the latest masterchain block is used. now and lt can override the execution timestamp and initial logical time. Account overrides can start from a complete shardAccountBoc and then replace its balance, state, or last-transaction metadata.

The returned EmulateRawMessageResult contains detailed TraceResult values and a synthetic Toncenter-shaped EmulatedTrace. Its stateUpdateHashOk value is always true for compatibility; raw-message emulation has no on-chain state update to compare against, so it must not be interpreted as an on-chain verification result. maxTransactions bounds the cascade and defaults to 128.

Helper Methods

All methods are exported from retracer-core and can be used independently:

  • findBaseTxByHash(network, txHash) — Find base transaction info by hash.
  • findRawTxByHash(network, baseTxInfo) — Get the raw transaction BoC and shard reference.
  • findShardBlockForTx(network, rawTx) — Find the shard block containing the transaction.
  • findMinLtInShardBlock(network, address, block, targetLt) — Find the earliest account transaction lt in the same shard block.
  • findAllTransactionsBetween(network, baseTx, minLt) — Get all account transactions in a given range.
  • getBlockConfig(network, mcSeqno) — Get global config for a masterchain block.
  • getBlockAccount(network, address, mcSeqno) — Get account snapshot before a masterchain block.
  • getShardAccountAtBlock(network, address, mcSeqno) — Get the exact account snapshot produced by a masterchain block.
  • collectUsedLibraries(network, account, tx) — Collect used library cells.
  • prepareEmulator(blockConfig, libs, randSeed) — Prepare the emulator for transaction execution.
  • emulatePreviousTransactions(...) — Emulate a chain of previous transactions to restore the state.
  • computeFinalData(...) — Gather final data from emulation result.
  • findFinalActions(logs) — Extract final actions from VM logs.
  • shardAccountToBase64(shardAccount) — Serialize an account to base64 for the emulator.

Types

All main types (transactions, blocks, messages, tracing results) are exported from retracer-core and are fully typed (see src/types.ts).

Projects based on retracer-core

  • TxTracer — Web application for tracing and debugging any TON blockchain transactions

License

MIT © TON Core, TON Studio

Links