Skip to main content

Simulating a Transaction with a Contract Instance

Simulating transactions on OP_NET helps predict the outcome of smart contract interactions without broadcasting them to the network. This crucial step ensures accuracy in returned values, gas estimation, and transaction behavior, enabling developers to debug effectively and avoid unnecessary failures.


Using Simulation and Accessing Returned Values

When you simulate a transaction, the result contains detailed information, including returned values, gas requirements, and metadata. This data is essential for validating the interaction before executing it.

Accessing Returned Values

The simulation result includes a properties object that maps the contract's returned values based on its ABI. You can access these values directly using their defined names.

Example:

const result = await op20Contract.balanceOf(addressPublicKey);
console.log("Balance:", result.properties.balance);
  • properties.balance: The balance returned by the balanceOf function.
  • Mapped to ABI: The properties field ensures that outputs match the contract’s ABI structure, reducing ambiguity.

Gas Calculation

Estimating gas usage is a core feature of OP_NET simulations. Simulations provide a field called estimatedGas that represents the amount of gas required for a transaction.

Adding a Buffer

Gas requirements may fluctuate due to network conditions. It’s recommended to add a 15% buffer to the estimatedGas value to ensure transaction success.

Example:

const estimatedGasWithBuffer = result.estimatedGas * 1.15n;
console.log("Estimated Gas with Buffer:", estimatedGasWithBuffer);

Simulation Example

Below is an example of a simulation result for the balanceOf method:

{
"result": {
"currentOffset": 32,
"buffer": {
"byteLength": 32,
"byteOffset": 0,
"buffer": [ArrayBuffer]
}
},
"accessList": {},
"revert": undefined,
"calldata": "<Buffer 82 d6 2f 3d ...>",
"estimatedGas": 120566118n,
"properties": {
"balance": 866000n
},
"estimatedSatGas": 330n,
"events": [],
"to": "bcrt1p7x7cgs70..."
}

Key Fields

  • properties: The returned values, such as balance in this example.
  • estimatedGas: The estimated gas needed for the transaction.
  • calldata: Encoded transaction data sent to the contract.
  • estimatedSatGas: The cost of gas in satoshis.

Best Practices

  • Simulating allows you to verify the transaction's behavior and ensures accurate gas estimation, minimizing risks.
  • Use the properties object to directly read data returned by the contract, as defined in its ABI.
  • Include a 15% buffer to the estimatedGas value to account for unexpected fluctuations.
  • The sendTransaction method simplifies gas estimation and broadcasting. It’s a reliable option for production transactions.

What’s Next?

Once you've simulated and verified your transaction, the next step is sending it to the network. Learn how to build and send transactions in the next section: