account.rs
Overview
The account.rs file defines the Account struct and its associated asynchronous and synchronous methods to manage blockchain account representations, primarily focusing on smart contract interaction. It facilitates loading contract ABI files, optionally handling contract TVC (compiled contract code) files, calculating contract addresses, encoding and running local contract calls, and updating contract images with cryptographic keys. This file integrates with external modules and libraries to perform operations related to contract deployment and interaction.
Account Struct
The Account struct models a blockchain account with the following fields:
address: String
The blockchain address of the account.dapp_id: Option<String>
An optional identifier for the decentralized application (DApp) associated with the account.keys: Option<KeyPair>
Optional cryptographic key pair (public/private) used for signing transactions or messages.abi: Abi
The Application Binary Interface representing the contract's callable functions and data structures._tvc: Option<Vec<u8>>
Optional TVC (TVC = TON Virtual Machine contract code) bytes representing the compiled contract binary.
Display Trait Implementation
Implements std::fmt::Display for Account to provide a formatted string representation displaying the address, DApp ID, and keys while omitting ABI details for brevity.
Account { address: <address>, dapp_id: <dapp_id>, keys: <keys>, abi: <Abi> }
Account Methods
try_new
pub async fn try_new(
abi_path: &str,
tvc_path: Option<&str>,
keys: Option<KeyPair>,
address: Option<&str>,
) -> anyhow::Result<Self>
Creates a new Account instance by loading the ABI from a file and optionally the TVC from a file. If the TVC is provided, it updates the TVC with the keys and calculates the account address from the TVC. If no TVC is given, it requires an explicit address string.
Parameters:
abi_path: Path to the ABI JSON file.tvc_path: Optional path to the TVC file.keys: Optional cryptographic keys for the account.address: Optional pre-calculated address string (required if no TVC).
Returns:
A Result containing the newAccountinstance or an error.Usage example:
let account = Account::try_new("contract.abi.json", Some("contract.tvc"), Some(keys), None).await?;
try_new_with_abi
pub async fn try_new_with_abi(
abi: Abi,
tvc_path: Option<&str>,
keys: Option<KeyPair>,
address: Option<&str>,
) -> anyhow::Result<Self>
Similar to try_new, but receives an Abi instance directly instead of loading from a file.
Parameters:
abi: ABI instance.tvc_path: Optional path to the TVC file.keys: Optional cryptographic keys.address: Optional account address string.
Returns:
A Result with the newAccountor an error.
address
pub fn address(&self) -> String
Returns the account's address as a String.
run_local
pub async fn run_local(
&self,
context: &Arc<ClientContext>,
method: &str,
params: Option<serde_json::Value>,
boc: Option<String>,
) -> anyhow::Result<Value>
Executes a local call on the account's smart contract method without sending a transaction on-chain. It uses the TON Virtual Machine (TVM) to simulate the method call and returns the decoded output.
Parameters:
context: Shared client context used for network and TVM calls.method: The smart contract method name to call.params: Optional JSON parameters to pass to the method.boc: Optional serialized account state (Boc format); if not provided, it queries blockchain state.
Returns:
A Result containing the method's JSON output or an error.Implementation details:
Queries the blockchain for the account's BOC if not provided.
Encodes the call message using ABI and method parameters.
Runs the TVM with the encoded message and account state.
Extracts and returns the decoded output.
Usage example:
let result = account.run_local(&context, "getBalance", None, None).await?; println!("Balance: {:?}", result);
calc_address
pub async fn calc_address(tvc: &[u8]) -> anyhow::Result<String>
Calculates the blockchain address from the TVC contract binary.
Parameters:
tvc: Byte slice of the TVC file.
Returns:
The calculated address as aString.Implementation details:
Usestvm_types::boc::read_single_root_bocto read the TVC's BOC representation, computes the root hash, and formats it into an address string prefixed with0:.
update_tvc
pub fn update_tvc(tvc_bytes: &mut [u8], abi: Abi, keys: Option<KeyPair>) -> anyhow::Result<()>
Updates the TVC binary by injecting the public key and ABI data into the contract image's initialization data.
Parameters:
tvc_bytes: Mutable byte slice of the TVC file to modify.abi: ABI instance.keys: Optional cryptographic keys to insert the public key.
Returns:
Unit type on success or an error.Implementation details:
Loads the contract image from the TVC bytes.
Inserts the public key into the contract's initial data.
Updates the contract image with the ABI JSON string.
Serializes and writes back the updated contract image into the TVC bytes.
insert_pubkey_to_init_data
pub fn insert_pubkey_to_init_data(
pubkey: &str,
opt_init_data: Option<&str>,
) -> anyhow::Result<String>
Inserts the public key into the JSON-formatted initialization data for the contract.
Parameters:
pubkey: Hex string of the public key.opt_init_data: Optional JSON string of initial data; defaults to empty JSON{}.
Returns:
Updated initialization data as a JSON string.Implementation details:
Parses the input JSON, inserts a_pubkeyfield with the public key prefixed by0x, then serializes back to string.
load_abi
pub fn load_abi(path: &str) -> anyhow::Result<Abi>
Loads an ABI JSON file from the filesystem and returns an Abi object.
Parameters:
path: Path to the ABI JSON file.
Returns:
ABI instance or an error if the file cannot be read or parsed.
Important Implementation Details
The file extensively uses asynchronous Rust with Tokio or async-std runtime for network and TVM calls.
The TVC update logic involves deserializing the contract image, modifying its state initialization data, and reserializing it. This process is critical for binding the contract to the keys used for signing.
The
run_localmethod simulates a smart contract call locally using the TVM client, combining encoded message building and TVM execution.Error handling is performed via the
anyhowcrate to provide context-rich errors.
System Interaction
Uses the
tvm_clientcrate modules for ABI encoding, cryptographic key management, network queries to collections, and TVM execution.Depends on the
tvm_sdkfor contract image manipulation.Interacts with blockchain nodes via the
query_collectionmethod to fetch account state.Reads contract ABI and TVC files from the local filesystem using utilities like
read_file.The
Accountstruct serves as a bridge between raw contract files and runtime interaction with deployed contracts.
Visual Diagram
classDiagram
class Account {
-address: String
-dapp_id: Option<String>
-keys: Option<KeyPair>
-abi: Abi
-_tvc: Option<Vec<u8>>
+try_new()
+try_new_with_abi()
+address()
+run_local()
+calc_address()
+update_tvc()
+insert_pubkey_to_init_data()
+load_abi()
}
Account ..> Abi : uses
Account ..> KeyPair : uses
Account ..> ClientContext : requires
Account ..> ContractImage : manipulates
Account ..> serde_json::Value : processes
Account ..> "tvm_client::net" : queries collection
Account ..> "tvm_client::tvm" : runs TVM