pub struct Aptos { /* private fields */ }Expand description
The main entry point for the Aptos SDK.
This struct provides a unified interface for interacting with the Aptos blockchain, including account management, transaction building and submission, and queries.
§Example
use aptos_sdk::{Aptos, AptosConfig};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create client for testnet
let aptos = Aptos::new(AptosConfig::testnet())?;
// Get ledger info
let ledger = aptos.ledger_info().await?;
println!("Ledger version: {:?}", ledger.version());
Ok(())
}Implementations§
Source§impl Aptos
impl Aptos
Sourcepub fn new(config: AptosConfig) -> AptosResult<Self>
pub fn new(config: AptosConfig) -> AptosResult<Self>
Creates a new Aptos client with the given configuration.
§Errors
Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
Sourcepub fn testnet() -> AptosResult<Self>
pub fn testnet() -> AptosResult<Self>
Creates a client for testnet with default settings.
§Errors
Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
Sourcepub fn devnet() -> AptosResult<Self>
pub fn devnet() -> AptosResult<Self>
Creates a client for devnet with default settings.
§Errors
Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
Sourcepub fn mainnet() -> AptosResult<Self>
pub fn mainnet() -> AptosResult<Self>
Creates a client for mainnet with default settings.
§Errors
Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
Sourcepub fn local() -> AptosResult<Self>
pub fn local() -> AptosResult<Self>
Creates a client for local development network.
§Errors
Returns an error if the HTTP client fails to build (e.g., invalid TLS configuration).
Sourcepub fn config(&self) -> &AptosConfig
pub fn config(&self) -> &AptosConfig
Returns the configuration.
Sourcepub fn fullnode(&self) -> &FullnodeClient
pub fn fullnode(&self) -> &FullnodeClient
Returns the fullnode client.
Sourcepub fn faucet(&self) -> Option<&FaucetClient>
Available on crate feature faucet only.
pub fn faucet(&self) -> Option<&FaucetClient>
faucet only.Returns the faucet client, if available.
Sourcepub fn indexer(&self) -> Option<&IndexerClient>
Available on crate feature indexer only.
pub fn indexer(&self) -> Option<&IndexerClient>
indexer only.Returns the indexer client, if available.
Sourcepub async fn ledger_info(&self) -> AptosResult<LedgerInfo>
pub async fn ledger_info(&self) -> AptosResult<LedgerInfo>
Gets the current ledger information.
As a side effect, this also resolves the chain ID if it was unknown (e.g., for custom network configurations).
§Errors
Returns an error if the HTTP request fails, the API returns an error status code, or the response cannot be parsed.
§Panics
Panics if the internal chain_id lock is poisoned (only possible if another thread
panicked while holding the lock).
Sourcepub fn chain_id(&self) -> ChainId
pub fn chain_id(&self) -> ChainId
Returns the current chain ID.
For known networks (mainnet, testnet, devnet, local), this returns the
well-known chain ID immediately. For custom networks, this returns
ChainId(0) until the chain ID is resolved via ensure_chain_id
or any method that makes a request to the node (e.g., build_transaction,
ledger_info).
§Panics
Panics if the internal chain_id lock is poisoned.
Sourcepub async fn ensure_chain_id(&self) -> AptosResult<ChainId>
pub async fn ensure_chain_id(&self) -> AptosResult<ChainId>
Resolves the chain ID from the node if it is unknown.
For known networks, this returns the chain ID immediately without making a network request. For custom networks (chain ID 0), this fetches the ledger info from the node to discover the actual chain ID and caches it for future use.
This is called automatically by build_transaction
and other transaction methods, so you typically don’t need to call it
directly unless you need the chain ID before building a transaction.
§Errors
Returns an error if the HTTP request to fetch ledger info fails.
§Panics
Panics if the internal chain_id lock is poisoned.
Sourcepub async fn get_sequence_number(
&self,
address: AccountAddress,
) -> AptosResult<u64>
pub async fn get_sequence_number( &self, address: AccountAddress, ) -> AptosResult<u64>
Gets the sequence number for an account.
§Errors
Returns an error if the HTTP request fails, the API returns an error status code (e.g., account not found 404), or the response cannot be parsed.
Sourcepub async fn get_balance(&self, address: AccountAddress) -> AptosResult<u64>
pub async fn get_balance(&self, address: AccountAddress) -> AptosResult<u64>
Gets the APT balance for an account.
§Errors
Returns an error if the HTTP request fails, the API returns an error status code, or the response cannot be parsed.
Sourcepub async fn account_exists(&self, address: AccountAddress) -> AptosResult<bool>
pub async fn account_exists(&self, address: AccountAddress) -> AptosResult<bool>
Checks if an account exists.
§Errors
Returns an error if the HTTP request fails or the API returns an error status code
other than 404 (not found). A 404 error is handled gracefully and returns Ok(false).
Sourcepub async fn build_transaction<A: Account>(
&self,
sender: &A,
payload: TransactionPayload,
) -> AptosResult<RawTransaction>
pub async fn build_transaction<A: Account>( &self, sender: &A, payload: TransactionPayload, ) -> AptosResult<RawTransaction>
Builds a transaction for the given account.
This automatically fetches the sequence number and gas price.
§Errors
Returns an error if fetching the sequence number fails, fetching the gas price fails, or if the transaction builder fails to construct a valid transaction (e.g., missing required fields).
Sourcepub async fn sign_and_submit<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
) -> AptosResult<AptosResponse<PendingTransaction>>
Available on crate feature ed25519 only.
pub async fn sign_and_submit<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<AptosResponse<PendingTransaction>>
ed25519 only.Signs and submits a transaction.
§Errors
Returns an error if building the transaction fails, signing fails (e.g., invalid key), the transaction cannot be serialized to BCS, the HTTP request fails, or the API returns an error status code.
Sourcepub async fn sign_submit_and_wait<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
timeout: Option<Duration>,
) -> AptosResult<AptosResponse<Value>>
Available on crate feature ed25519 only.
pub async fn sign_submit_and_wait<A: Account>( &self, account: &A, payload: TransactionPayload, timeout: Option<Duration>, ) -> AptosResult<AptosResponse<Value>>
ed25519 only.Signs, submits, and waits for a transaction to complete.
§Errors
Returns an error if building the transaction fails, signing fails, submission fails, the transaction times out waiting for commitment, the transaction execution fails, or any HTTP/API errors occur.
Sourcepub async fn submit_transaction(
&self,
signed_txn: &SignedTransaction,
) -> AptosResult<AptosResponse<PendingTransaction>>
pub async fn submit_transaction( &self, signed_txn: &SignedTransaction, ) -> AptosResult<AptosResponse<PendingTransaction>>
Submits a pre-signed transaction.
§Errors
Returns an error if the transaction cannot be serialized to BCS, the HTTP request fails, or the API returns an error status code.
Sourcepub async fn submit_and_wait(
&self,
signed_txn: &SignedTransaction,
timeout: Option<Duration>,
) -> AptosResult<AptosResponse<Value>>
pub async fn submit_and_wait( &self, signed_txn: &SignedTransaction, timeout: Option<Duration>, ) -> AptosResult<AptosResponse<Value>>
Submits and waits for a pre-signed transaction.
§Errors
Returns an error if transaction submission fails, the transaction times out waiting
for commitment, the transaction execution fails (vm_status indicates failure),
or any HTTP/API errors occur.
Sourcepub async fn simulate_transaction(
&self,
signed_txn: &SignedTransaction,
) -> AptosResult<AptosResponse<Vec<Value>>>
pub async fn simulate_transaction( &self, signed_txn: &SignedTransaction, ) -> AptosResult<AptosResponse<Vec<Value>>>
Simulates a transaction.
§Errors
Returns an error if the transaction cannot be serialized to BCS, the HTTP request fails, the API returns an error status code, or the response cannot be parsed as JSON.
Sourcepub async fn simulate<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
) -> AptosResult<SimulationResult>
Available on crate feature ed25519 only.
pub async fn simulate<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<SimulationResult>
ed25519 only.Simulates a transaction and returns a parsed result.
This method provides a more ergonomic way to simulate transactions with detailed result parsing.
§Example
let result = aptos.simulate(&account, payload).await?;
if result.success() {
println!("Gas estimate: {}", result.gas_used());
} else {
println!("Would fail: {}", result.error_message().unwrap_or_default());
}§Errors
Returns an error if building the transaction fails, signing fails, simulation fails, or the simulation response cannot be parsed.
Sourcepub async fn simulate_signed(
&self,
signed_txn: &SignedTransaction,
) -> AptosResult<SimulationResult>
pub async fn simulate_signed( &self, signed_txn: &SignedTransaction, ) -> AptosResult<SimulationResult>
Simulates a transaction with a pre-built signed transaction.
§Errors
Returns an error if simulation fails or the simulation response cannot be parsed.
Sourcepub async fn estimate_gas<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
) -> AptosResult<u64>
Available on crate feature ed25519 only.
pub async fn estimate_gas<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<u64>
ed25519 only.Estimates gas for a transaction by simulating it.
Returns the estimated gas usage with a 20% safety margin.
§Example
let gas = aptos.estimate_gas(&account, payload).await?;
println!("Estimated gas: {}", gas);§Errors
Returns an error if simulation fails or if the simulation indicates the transaction
would fail (returns AptosError::SimulationFailed).
Sourcepub async fn simulate_and_submit<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
) -> AptosResult<AptosResponse<PendingTransaction>>
Available on crate feature ed25519 only.
pub async fn simulate_and_submit<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<AptosResponse<PendingTransaction>>
ed25519 only.Simulates and submits a transaction if successful.
This is a “dry run” approach that first simulates the transaction to verify it will succeed before actually submitting it.
§Example
let result = aptos.simulate_and_submit(&account, payload).await?;
println!("Transaction submitted: {}", result.hash);§Errors
Returns an error if building the transaction fails, signing fails, simulation fails,
the simulation indicates the transaction would fail (returns AptosError::SimulationFailed),
or transaction submission fails.
Sourcepub async fn simulate_submit_and_wait<A: Account>(
&self,
account: &A,
payload: TransactionPayload,
timeout: Option<Duration>,
) -> AptosResult<AptosResponse<Value>>
Available on crate feature ed25519 only.
pub async fn simulate_submit_and_wait<A: Account>( &self, account: &A, payload: TransactionPayload, timeout: Option<Duration>, ) -> AptosResult<AptosResponse<Value>>
ed25519 only.Simulates, submits, and waits for a transaction.
Like simulate_and_submit but also waits for the transaction to complete.
§Errors
Returns an error if building the transaction fails, signing fails, simulation fails,
the simulation indicates the transaction would fail (returns AptosError::SimulationFailed),
submission fails, the transaction times out waiting for commitment, or the transaction
execution fails.
Sourcepub async fn transfer_apt<A: Account>(
&self,
sender: &A,
recipient: AccountAddress,
amount: u64,
) -> AptosResult<AptosResponse<Value>>
Available on crate feature ed25519 only.
pub async fn transfer_apt<A: Account>( &self, sender: &A, recipient: AccountAddress, amount: u64, ) -> AptosResult<AptosResponse<Value>>
ed25519 only.Transfers APT from one account to another.
§Errors
Returns an error if building the transfer payload fails (e.g., invalid address), signing fails, submission fails, the transaction times out, or the transaction execution fails.
Sourcepub async fn transfer_coin<A: Account>(
&self,
sender: &A,
recipient: AccountAddress,
coin_type: TypeTag,
amount: u64,
) -> AptosResult<AptosResponse<Value>>
Available on crate feature ed25519 only.
pub async fn transfer_coin<A: Account>( &self, sender: &A, recipient: AccountAddress, coin_type: TypeTag, amount: u64, ) -> AptosResult<AptosResponse<Value>>
ed25519 only.Transfers a coin from one account to another.
§Errors
Returns an error if building the transfer payload fails (e.g., invalid type tag or address), signing fails, submission fails, the transaction times out, or the transaction execution fails.
Sourcepub async fn view(
&self,
function: &str,
type_args: Vec<String>,
args: Vec<Value>,
) -> AptosResult<Vec<Value>>
pub async fn view( &self, function: &str, type_args: Vec<String>, args: Vec<Value>, ) -> AptosResult<Vec<Value>>
Sourcepub async fn view_bcs<T: DeserializeOwned>(
&self,
function: &str,
type_args: Vec<String>,
args: Vec<Vec<u8>>,
) -> AptosResult<T>
pub async fn view_bcs<T: DeserializeOwned>( &self, function: &str, type_args: Vec<String>, args: Vec<Vec<u8>>, ) -> AptosResult<T>
Calls a view function using BCS encoding for both inputs and outputs.
This method provides lossless serialization by using BCS (Binary Canonical Serialization) instead of JSON, which is important for large integers (u128, u256) and other types where JSON can lose precision.
§Type Parameter
T- The expected return type. Must implementserde::de::DeserializeOwned.
§Arguments
function- The fully qualified function name (e.g.,0x1::coin::balance)type_args- Type arguments as strings (e.g.,0x1::aptos_coin::AptosCoin)args- Pre-serialized BCS arguments as byte vectors
§Example
use aptos_sdk::{Aptos, AptosConfig, AccountAddress};
let aptos = Aptos::new(AptosConfig::testnet())?;
let owner = AccountAddress::from_hex("0x1")?;
// BCS-encode the argument
let args = vec![aptos_bcs::to_bytes(&owner)?];
// Call view function with typed return
let balance: u64 = aptos.view_bcs(
"0x1::coin::balance",
vec!["0x1::aptos_coin::AptosCoin".to_string()],
args,
).await?;§Errors
Returns an error if the HTTP request fails, the API returns an error status code, or the BCS deserialization fails.
Sourcepub async fn view_bcs_raw(
&self,
function: &str,
type_args: Vec<String>,
args: Vec<Vec<u8>>,
) -> AptosResult<Vec<u8>>
pub async fn view_bcs_raw( &self, function: &str, type_args: Vec<String>, args: Vec<Vec<u8>>, ) -> AptosResult<Vec<u8>>
Calls a view function with BCS inputs and returns raw BCS bytes.
Use this when you need to manually deserialize the response or when the return type is complex or dynamic.
§Errors
Returns an error if the HTTP request fails or the API returns an error status code.
Sourcepub async fn fund_account(
&self,
address: AccountAddress,
amount: u64,
) -> AptosResult<Vec<String>>
Available on crate feature faucet only.
pub async fn fund_account( &self, address: AccountAddress, amount: u64, ) -> AptosResult<Vec<String>>
faucet only.Funds an account using the faucet.
This method waits for the faucet transactions to be confirmed before returning.
§Errors
Returns an error if the faucet feature is not enabled, the faucet request fails (e.g., rate limiting 429, server error 500), waiting for transaction confirmation times out, or any HTTP/API errors occur.
Sourcepub async fn create_funded_account(
&self,
amount: u64,
) -> AptosResult<Ed25519Account>
Available on crate features faucet and ed25519 only.
pub async fn create_funded_account( &self, amount: u64, ) -> AptosResult<Ed25519Account>
faucet and ed25519 only.Creates a funded account.
§Errors
Returns an error if funding the account fails (see Self::fund_account for details).
Sourcepub fn batch(&self) -> BatchOperations<'_>
pub fn batch(&self) -> BatchOperations<'_>
Returns a batch operations helper for submitting multiple transactions.
§Example
let aptos = Aptos::testnet()?;
// Build and submit batch of transfers
let payloads = vec![
EntryFunction::apt_transfer(addr1, 1000)?.into(),
EntryFunction::apt_transfer(addr2, 2000)?.into(),
EntryFunction::apt_transfer(addr3, 3000)?.into(),
];
let results = aptos.batch().submit_and_wait(&sender, payloads, None).await?;Sourcepub async fn submit_batch<A: Account>(
&self,
account: &A,
payloads: Vec<TransactionPayload>,
) -> AptosResult<Vec<BatchTransactionResult>>
Available on crate feature ed25519 only.
pub async fn submit_batch<A: Account>( &self, account: &A, payloads: Vec<TransactionPayload>, ) -> AptosResult<Vec<BatchTransactionResult>>
ed25519 only.Submits multiple transactions in parallel.
This is a convenience method that builds, signs, and submits multiple transactions at once.
§Arguments
account- The account to sign withpayloads- The transaction payloads to submit
§Returns
Results for each transaction in the batch.
§Errors
Returns an error if building any transaction fails, signing fails, or submission fails for any transaction in the batch.
Sourcepub async fn submit_batch_and_wait<A: Account>(
&self,
account: &A,
payloads: Vec<TransactionPayload>,
timeout: Option<Duration>,
) -> AptosResult<Vec<BatchTransactionResult>>
Available on crate feature ed25519 only.
pub async fn submit_batch_and_wait<A: Account>( &self, account: &A, payloads: Vec<TransactionPayload>, timeout: Option<Duration>, ) -> AptosResult<Vec<BatchTransactionResult>>
ed25519 only.Submits multiple transactions and waits for all to complete.
§Arguments
account- The account to sign withpayloads- The transaction payloads to submittimeout- Optional timeout for waiting
§Returns
Results for each transaction in the batch.
§Errors
Returns an error if building any transaction fails, signing fails, submission fails, any transaction times out waiting for commitment, or any transaction execution fails.
Sourcepub async fn batch_transfer_apt<A: Account>(
&self,
sender: &A,
transfers: Vec<(AccountAddress, u64)>,
) -> AptosResult<Vec<BatchTransactionResult>>
Available on crate feature ed25519 only.
pub async fn batch_transfer_apt<A: Account>( &self, sender: &A, transfers: Vec<(AccountAddress, u64)>, ) -> AptosResult<Vec<BatchTransactionResult>>
ed25519 only.Transfers APT to multiple recipients in a batch.
§Arguments
sender- The sending accounttransfers- List of (recipient, amount) pairs
§Example
let results = aptos.batch_transfer_apt(&sender, vec![
(addr1, 1_000_000), // 0.01 APT
(addr2, 2_000_000), // 0.02 APT
(addr3, 3_000_000), // 0.03 APT
]).await?;§Errors
Returns an error if building any transfer payload fails, signing fails, submission fails, any transaction times out, or any transaction execution fails.