Acton
Acton standard libraryEmulation

network

network.tolk standard library file

Module for sending messages to a real or emulated blockchain.

It provides capabilities to send messages to contracts, calling their getters, and performing other network-level operations.

Note: while writing tests, also use testing.xxx methods. While writing scripts, also use scripts.xxx methods.

Examples:

// Setup
val deployer = scripts.wallet("deployer");
val contract = build("MyContract");

// Interact
val msg = createMessage({ ... });
val txs = net.send(deployer.address, msg);

// Check state
val balance = scripts.fetchAccountBalance(contract.address);
val seqno = net.runGetMethod<int>(contract.address, "seqno");

Definitions

net

struct net

Root module for sending messages to a real or emulated blockchain.

Source code

CANNOT_RUN_GET_METHOD_OF_UNDEPLOYED_CONTRACT

const CANNOT_RUN_GET_METHOD_OF_UNDEPLOYED_CONTRACT = 678
Source code

CANNOT_RUN_GET_METHOD_OF_CONTRACT_WITHOUT_CODE

const CANNOT_RUN_GET_METHOD_OF_CONTRACT_WITHOUT_CODE = 679
Source code

SendParams

struct SendParams {
    /// Value to send with the message.
    value: coins = ton("0.1")
    /// Whether to bounce the message if the contract does not exist or fails (default: false)
    bounce: bool = false
}

Represents a set of parameters for creating a message.

Source code

ChildTxsIds

type ChildTxsIds = array<int>

Represents a list of child transactions IDs (LT) for single send result.

Source code

OutMessages

type OutMessages = array<cell>

Represents a list of out messages for single send result.

Source code

ExtOutList

type ExtOutList = array<cell>

Represents a list of external outgoing messages for single send result.

Source code

ExtOutList.at

fun ExtOutList.at<Msg>(self, index: int): TlbExtMessageRelaxed<Msg>

Returns the external outgoing message at the given index with given type.

If the message is not of the requested type, loading fails with exit code 63. Use ExtOutList.atOrNull to handle this case without throwing.

Source code

ExtOutList.atOrNull

fun ExtOutList.atOrNull<Msg>(self, index: int): TlbExtMessageRelaxed<Msg>?

Returns the external outgoing message at the given index with given type or null if message is not of the requested type.

If message is not of the requested type, index < 0, or index >= self.size(), this method returns null instead of throwing. Use ExtOutList.at if you do not want to handle the null case.

Source code

OutMessages.atCell

fun OutMessages.atCell(self, index: int): cell

Returns the out message at the given index as a raw cell.

To get parsed message, use OutMessages.at method.

Source code

OutMessages.at

fun OutMessages.at<Msg>(self, index: int): TlbMessageRelaxed<Msg>

Returns the out message at the given index as a parsed message of given type.

To get raw cell, use OutMessages.atCell method.

If actual message body has a different type, loading will fail.

Source code

SendResult

struct SendResult {
    /// Raw cell with encoded transaction.
    tx: Cell<TlbTransaction>
    /// Logical time of the transaction.
    lt: int
    /// List of child transactions IDs.
    /// This transactions are directly produced by this transaction.
    childTxs: ChildTxsIds
    /// Parent transaction LT that produced this transaction or null if this transaction is the root one.
    parentLt: int?
    /// Raw cell with encoded out actions.
    /// Use [SendResult.allOutActions] to load all actions.
    outActions: Cell<TlbOutList>
    /// All out messages produced by this transaction.
    outMessages: OutMessages
    /// Amount of gas used by this transaction.
    gasUsed: int
    /// All external outgoing messages produced by this transaction.
    externals: ExtOutList
}

Represents a single send result obtained from net.send method.

Source code

SendResult.allOutActions

fun SendResult.allOutActions(self): OutActionList

Returns all out actions produced by this transaction as a list.

Source code

SendResultList

type SendResultList = BigArray<SendResult>

Represents a list of send results obtained from net.send method.

This list represent all transactions produced by a net.send call.

To get a single send result, use SendResultList.at method.

Source code

SendResultList.at

fun SendResultList.at(self, index: int): SendResult

Returns the send result at the given index.

Source code

SendResultList.giveName

fun SendResultList.giveName(self, nameForUI: string): void

Give a custom name for a trace chain produced by net.send.

The custom name is used in the Test UI and gas/fee profiling reports instead of "trace N".

Example:

val txs = net.send(deployer.address, msg);
txs.giveName("deploy-counter");
expect(txs).toHaveAllSuccessfulTxs();
Source code

SendResultList.waitForFirstTransaction

fun SendResultList.waitForFirstTransaction(
    self,
    quiet: bool = false,
    attempts: int = 20,
    sleepDuration: int = 1000,
): SendResult?

Wait for the first (root) message of the send result to be applied on the blockchain.

This method is useful when broadcasting transactions to the real network. It polls the network until the transaction is applied or the maximum number of attempts is reached.

The lookup follows the TON docs message-lookup reference (https://docs.ton.org/ecosystem/ton-connect/message-lookup): the external-in message actually delivered to the network is identified by its TEP-467 normalized hash (returned by sendBocReturnHash at send time), and the destination account's recent transactions are scanned until one with a matching inMessage shows up.

Returns the matched SendResult rebuilt from the on-chain transaction if found, or null otherwise. Fields that cannot be reconstructed from a single on-chain transaction (childTxs, parentLt, outActions) are left empty/null; outMessages, externals, and gasUsed are derived from the transaction itself.

In emulation mode (without --net), this method returns the first SendResult immediately (or null if the list is empty), because the trace is already fully processed locally.

Example:

val result = net.send(wallet.address, message);
val applied = result.waitForFirstTransaction();
if (applied != null) {
    println("Transaction applied successfully at lt {}", applied.lt);
}

Example with custom parameters:

val result = net.send(wallet.address, message);
result.waitForFirstTransaction(true, 30, 3000); // quiet mode, 30 attempts, 3 seconds delay
Source code

SendResultList.waitForTrace

fun SendResultList.waitForTrace(
    self,
    quiet: bool = false,
    attempts: int = 20,
    sleepDuration: int = 1000,
): SendResultList?

Wait for the full message chain originating from the first message to settle on-chain.

Unlike SendResultList.waitForFirstTransaction, this method follows all descendant transactions (children, grandchildren, ...) using toncenter's traces API and returns them as a fresh SendResultList.

In emulation mode (without --net), the trace is already fully processed locally, so the method returns self as-is (or null if the list is empty).

Returns null if the chain cannot be fetched within the given attempt budget.

Source code

SearchParams

struct SearchParams {
    /// Destination address of the transaction.
    to: (address -> bool) | address | null = null
    /// Source address of the transaction.
    from: (address -> bool) | address | null = null
    /// Value of the message in nanotons.
    value: (coins -> bool) | coins | null = null
    /// Exit code of the transaction.
    exitCode: (int32 -> bool) | int32 | null = null
    /// Whether the transaction is successful (both compute and action phase).
    success: (bool -> bool) | bool | null = null
    /// Whether the compute phase of transaction was aborted and transaction was reverted.
    aborted: (bool -> bool) | bool | null = null
    /// Whether it's a deploy transaction (that changes the account status from "NonExisting" to "Active").
    deploy: (bool -> bool) | bool | null = null
    /// Whether the transaction message is bounceable.
    bounce: (bool -> bool) | bool | null = null
    /// Whether the transaction is a bounced transaction.
    bounced: (bool -> bool) | bool | null = null
    /// Opcode of the in message.
    opcode: (uint32 -> bool) | uint32 | null = null
    /// Action exit code of the transaction.
    actionExitCode: (int32 -> bool) | int32 | null = null
    /// Whether the compute phase was skipped.
    computePhaseSkipped: (bool -> bool) | bool | null = null
    /// Body of the in message (compared by hash).
    body: (cell -> bool) | cell | null = null
    /// StateInit of the in message, encoded as Cell<StateInit?>.
    ///
    /// Exact match example:
    /// ```
    /// val expected = (init as StateInit?).toCell();
    /// expect(txs).toHaveTx({ state_init: expected });
    /// ```
    /// Predicate example:
    /// ```
    /// expect(txs).toHaveTx({
    ///     state_init: fun(rawStateInit: Cell<StateInit?>): bool {
    ///         val actual = rawStateInit.load();
    ///         // ...
    ///     },
    /// });
    /// ```
    state_init: (Cell<StateInit?> -> bool) | Cell<StateInit?> | null = null
}

Represents a set of parameters to search for a transaction in the transaction list.

Source code

SearchParams.hasPredicates

fun SearchParams.hasPredicates(self): bool

Check if user-provided SearchParams has any lambdas. If not (most common), fast FFI path will be used.

Source code

SearchParams.toScalarFFITuple

fun SearchParams.toScalarFFITuple(self): tuple

Convert SearchParams to a tuple of plain nullable scalar values for the fast FFI path.

Source code

SearchParams.toPredicateFFITuple

fun SearchParams.toPredicateFFITuple(self): tuple

Convert SearchParams to a tuple of [tag, predicate] pairs for FFI.

Source code

ExternalOutSearchParams

struct ExternalOutSearchParams {
    /// Source address of the external-out message.
    from: address? = null
    /// Destination address of the external-out message.
    to: any_address? = null
}

Represents a set of parameters to search for an external-out message.

Source code

TlbMessage<RemainingBitsAndRefs, TlbExternalOutMessageInfo>.matches

fun TlbMessage<RemainingBitsAndRefs, TlbExternalOutMessageInfo>.matches<TBody>(
    self,
    params: ExternalOutSearchParams,
): bool
Source code

SendResultList.findExternalOutMessage

fun SendResultList.findExternalOutMessage<TBody = unknown>(
    self,
    params: ExternalOutSearchParams = {},
): TlbMessage<TBody, TlbExternalOutMessageInfo>?

Find a external-out message in the send result list by specified parameters.

Example:

val txs = net.send(deployer.address, message);
val result = txs.findExternalOutMessage({ from: counter.address });
expect(result).toBeNotNull();
val tx = result!;

You can specify an optional type argument, specifying the message type to search for; the function will also check that the opcode of the tx message matches the opcode of the given message.

Example:

tx.findExternalOutMessage<IncrementEvent>({ from: counter.address });
//                        ^^^^^^^^^^^^^^ search for message with IncrementEvent opcode

If the message is not found, returns null.

Source code

SendResultList.findTransaction

fun SendResultList.findTransaction<Msg = unknown>(
    self,
    params: SearchParams = {},
): TlbTransaction?

Find a transaction in the send result list by specified parameters.

Example:

val txs = net.send(deployer.address, message);
val result = txs.findTransaction({ to: counter.address });
expect(result).toBeNotNull();
val tx = result!;
Source code

net.send

fun net.send(from: address, message: OutMessage): SendResultList

Send a message from a specified address.

In broadcast mode (with --net), sending to the real network is attempted only when from matches one of the wallets opened at script startup. If from is not an opened wallet address, this method falls back to normal emulator execution, even when net.isBroadcasting is true.

Example:

get fun `test send message`() {
    // ...
    val message = createMessage({
        bounce: false,
        dest: counter.address,
        value: ton("1"),
    });
    net.send(deployer.address, message);
}

In local emulation mode, returns a list of send results representing the full recursively processed transaction chain produced by this send call.

Unlike testing.processSingleTraceStep, the emulation path keeps draining out messages until the whole trace queue is exhausted. Use it for normal end-to-end emulation where children, grandchildren, and other follow-up transactions should all be executed.

When from resolves to a real opened wallet and the call is routed to a broadcast network instead of the local emulator, Acton sends the message to that network and returns a single pseudo transaction placeholder rather than recursively executing descendants locally.

See testing.processSingleTraceStep if you need to send a single message without out message processing.

Source code

ExternalInMessage

struct ExternalInMessage {
    messageCell: cell
}

The response from net.createExternalMessage. It's an already composed message cell, ready to be sent by net.sendExternal.

Source code

net.createExternalMessage

fun net.createExternalMessage<TBody>(
    dest: address,
    body: TBody,
    stateInit: StateInit? = null,
    src: any_address? = null,
): ExternalInMessage

Creates an external-in message. Body is always packed into the Either Right (in the reference). If StateInit is present it is also packed in the Either Right (in the reference). Full TL-B scheme of the message is.

ext_in_msg_info$10 src:MsgAddressExt dest:MsgAddressInt
  import_fee:Grams = CommonMsgInfo;
message$_ {X:Type} info:CommonMsgInfo
  init:(Maybe (Either StateInit ^StateInit))
  body:(Either X ^X) = Message X;
Source code

net.sendExternal

fun net.sendExternal(msg: ExternalInMessage): SendResultList?

Sends an external-in message to the specified destination address. Read more about external incoming messages: https://docs.ton.org/foundations/messages/external-in#incoming-external-messages

This helper recursively processes the resulting trace in local emulation just like net.send, but it starts from an already composed external-in message instead of an internal message sent from a wallet-like address.

Returns null if the external message was not accepted or the destination account does not exist.

Source code

OutMessage.bounced

fun OutMessage.bounced(self): OutMessage

Transform the out message to a bounced message. Essentially, it sets the bounced flag to true.

Example:

val msg = createMessage({
    bounce: false,
    value: ton("1"),
    dest: counter.address,
});
val bouncedMsg = msg.bounced();

This is useful for testing single messages with testing.processSingleTraceStep.

Example:

val bouncedMsg = createMessage({
    bounce: false,
    value: ton("0.95"),
    dest: deployer.address,
    body: beginCell().storeUint(0xFFFFFFFF, 32).storeSlice(body.toCell().beginParse()).endCell(),
}).bounced();

testing.processSingleTraceStep(notDeployer.address, bouncedMsg);
Source code

net.isBroadcasting

fun net.isBroadcasting(): bool

Returns true if the script is running in broadcasting mode (with --net), false otherwise.

This is useful for writing scripts that behave differently in emulation and broadcasting modes.

Example:

if (net.isBroadcasting()) {
    println("Running on real network");
} else {
    println("Running in emulation mode");
}
Source code

net.enableBroadcast

fun net.enableBroadcast(): void

Enable broadcasting mode.

This function allows scripts to manually enable broadcasting behavior. Useful for testing broadcasting logic in emulation mode. It toggles only the runtime broadcast flag.

Wallets are loaded once at startup (when the script is launched with CLI --net). Calling net.enableBroadcast later does not load wallets, so scripts.wallet can still fail and wallet-backed real sends can remain unavailable.

Example:

// Force broadcasting behavior even in emulation mode
net.enableBroadcast();
if (net.isBroadcasting()) {
    println("Broadcasting mode enabled");
}
Source code

net.disableBroadcast

fun net.disableBroadcast(): void

Disable broadcasting mode.

This function allows scripts to manually disable broadcasting behavior. It does not reload or rebuild the startup wallet map.

Example:

// Disable broadcasting behavior
net.disableBroadcast();
if (!net.isBroadcasting()) {
    println("Broadcasting mode disabled");
}
Source code

net.runGetMethod

fun net.runGetMethod<Ret>(addr: address, idOrName: int | string, args: array<unknown> = []): Ret

Run a get method of a contract by its name or id.

Imagine you have the following get method in the contract:

get fun get_balance(): coins { ... }

To call it, you can use the following code:

val balance = net.runGetMethod<coins>(wallet.address, "get_balance");

Since this get method doesn't accept any arguments, third argument can be omitted.

With arguments

If the get method accepts single argument, you can pass it as a third argument.

get fun get_wallet_address(ownerAddress: address): address { ... }
val address = net.runGetMethod<address>(wallet.address, "get_wallet_address", [address("...")]);

If the get method accepts several arguments, you can pass them as a third argument as an array.

get fun do_smth(owner: address, id: int): address { ... }
val address = net.runGetMethod<address>(wallet.address, "do_smth", [deployer.address, 10]);

Specify the method's return type as a type parameter

Specify the return type as a generic parameter:

get fun get_jetton_data(): JettonDataReply { ... }
val data = net.runGetMethod<JettonDataReply>(wallet.address, "get_jetton_data");
Source code

randomAddress

fun randomAddress(name: string? = null, wc: int = BASECHAIN): address

Generate a random address.

If a name is provided, the address will be registered with the given name. This allows test runner to show the name instead of the address in the test output.

Example:

val address = randomAddress("random_user");
val masterchainAddress = randomAddress("random_user", -1);
Source code

net.registerAddress

fun net.registerAddress(addr: address, name: string): void

Register an address with a name.

This allows test runner to show the name instead of the address in the test output.

For example, if your contract is not deployed yet, without calling this method, the test runner will show raw address in the test output. In this case, you likely want to call this method to register the address with a name.

Example:

net.registerAddress(address, "my_address");
Source code

net.registerCodeCell

fun net.registerCodeCell(code: cell, name: string): void

Register a code cell with a name.

This allows test runner to show the name instead of the address in the test output if the actual code of the contract is match to previously registered code.

Example:

net.registerCodeCell(code, "my_code");
Source code

net.loadLibrary

fun net.loadLibrary(hash: string): cell?

Load library by hash, first from the current emulated blockchain and then from the configured network.

In forked tests this means locally registered libraries win over the remote fork network for the same hash.

Returns null if library is not found.

Source code

tuple.fromTuple

fun tuple.fromTuple(data: tuple): tuple
Source code

Expectation<SendResultList>.toHaveSuccessfulDeploy

fun Expectation<SendResultList>.toHaveSuccessfulDeploy<Msg = unknown>(
    self,
    params: SearchParams = {},
): void

Expect the transaction list to have a successful deploy transaction.

Transaction is considered as "deploy" if previous status was "NonExisting" and end status was "Active". If generic Msg is provided and has declared prefix, matcher also filters by params.opcode.

Example:

expect(txs).toHaveSuccessfulDeploy({
    to: counter.address,
});
Source code

Expectation<SendResultList>.toHaveSuccessfulTx

fun Expectation<SendResultList>.toHaveSuccessfulTx<Msg = unknown>(
    self,
    params: SearchParams = {},
): void

Expect the transaction list to have a successful transaction.

Matcher sets params.success = true. Runtime "success" means both compute phase and action phase are successful.

By default matcher also requires params.exitCode = 0 when exitCode is not provided. This default can be overridden with explicit params.exitCode.

If generic Msg is provided and has declared prefix, matcher also filters by params.opcode.

Example:

expect(txs).toHaveSuccessfulTx({
    from: deployer.address,
    to: counter.address,
});
Source code

Expectation<SendResultList>.toHaveTx

fun Expectation<SendResultList>.toHaveTx<Msg = unknown>(self, params: SearchParams = {}): void

Expect the transaction list to have a transaction with specified parameters.

All non-null SearchParams fields are applied as filters.

If generic Msg is provided and has declared prefix, matcher also filters by params.opcode.

Example:

expect(txs).toHaveTx({
    from: deployer.address,
    to: counter.address,
    actionExitCode: 37,
});
Source code

Expectation<SendResultList>.toNotHaveTx

fun Expectation<SendResultList>.toNotHaveTx<Msg = unknown>(self, params: SearchParams = {}): void

Expect the transaction list to NOT have a transaction with specified parameters.

Example:

expect(txs).toNotHaveTx({
    from: deployer.address,
    to: counter.address,
});
Source code

Expectation<SendResultList>.toHaveBouncedTx

fun Expectation<SendResultList>.toHaveBouncedTx<Msg = unknown>(
    self,
    params: SearchParams = {},
): void

Expect the transaction list to have a bounced transaction.

Example:

expect(txs).toHaveBouncedTx({
    from: deployer.address,
    to: counter.address,
});
Source code

Expectation<SendResultList>.toHaveFailedTx

fun Expectation<SendResultList>.toHaveFailedTx<Msg = unknown>(
    self,
    params: SearchParams = {},
): void

Expect the transaction list to have a failed transaction.

This matcher sets params.success = false. params.exitCode is required and must be non-zero. If exitCode is null or 0, matcher fails immediately before transaction search.

Any additional non-null SearchParams fields further narrow the search. If generic Msg is provided and has declared prefix, matcher also filters by params.opcode.

Example:

expect(txs).toHaveFailedTx({
    from: deployer.address,
    to: counter.address,
    exitCode: 123,
});
Source code

Expectation<SendResultList>.toHaveAllSuccessfulTxs

fun Expectation<SendResultList>.toHaveAllSuccessfulTxs(self): void

Expect all transactions in the list to be successful.

Example:

val txs = net.send(wallet.address, msg);
expect(txs).toHaveAllSuccessfulTxs();
Source code

Expectation<SendResultList>.toEmitExternalMessage

fun Expectation<SendResultList>.toEmitExternalMessage<Msg>(self): void

Expect the transaction to emit an external message of given type.

Example:

expect(txs).toEmitExternalMessage<IncreaseCounter>();
Source code

Expectation<SendResult>.toConsumeLessThan

fun Expectation<SendResult>.toConsumeLessThan(self, amount: int): void

Expect the transaction to consume less than the expected amount of gas.

Example:

val txs = net.send(deployer.address, message);
expect(txs.at(0)).toConsumeLessThan(1000);
Source code

Last updated on

On this page