Skip to main content

Aptos

Struct Aptos 

Source
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

Source

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).

Source

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).

Source

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).

Source

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).

Source

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).

Source

pub fn config(&self) -> &AptosConfig

Returns the configuration.

Source

pub fn fullnode(&self) -> &FullnodeClient

Returns the fullnode client.

Source

pub fn faucet(&self) -> Option<&FaucetClient>

Available on crate feature faucet only.

Returns the faucet client, if available.

Source

pub fn indexer(&self) -> Option<&IndexerClient>

Available on crate feature indexer only.

Returns the indexer client, if available.

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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).

Source

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).

Source

pub async fn sign_and_submit<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<AptosResponse<PendingTransaction>>

Available on crate feature 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.

Source

pub 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.

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.

Source

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.

Source

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.

Source

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.

Source

pub async fn simulate<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<SimulationResult>

Available on crate feature 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.

Source

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.

Source

pub async fn estimate_gas<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<u64>

Available on crate feature 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).

Source

pub async fn simulate_and_submit<A: Account>( &self, account: &A, payload: TransactionPayload, ) -> AptosResult<AptosResponse<PendingTransaction>>

Available on crate feature 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.

Source

pub 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.

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.

Source

pub async fn transfer_apt<A: Account>( &self, sender: &A, recipient: AccountAddress, amount: u64, ) -> AptosResult<AptosResponse<Value>>

Available on crate feature 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.

Source

pub 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.

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.

Source

pub async fn view( &self, function: &str, type_args: Vec<String>, args: Vec<Value>, ) -> AptosResult<Vec<Value>>

Calls a view function using JSON encoding.

For lossless serialization of large integers, use view_bcs instead.

§Errors

Returns an error if the HTTP request fails, the API returns an error status code, or the response cannot be parsed as JSON.

Source

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 implement serde::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.

Source

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.

Source

pub async fn fund_account( &self, address: AccountAddress, amount: u64, ) -> AptosResult<Vec<String>>

Available on crate feature 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.

Source

pub async fn create_funded_account( &self, amount: u64, ) -> AptosResult<Ed25519Account>

Available on crate features faucet and ed25519 only.

Creates a funded account.

§Errors

Returns an error if funding the account fails (see Self::fund_account for details).

Source

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?;
Source

pub async fn submit_batch<A: Account>( &self, account: &A, payloads: Vec<TransactionPayload>, ) -> AptosResult<Vec<BatchTransactionResult>>

Available on crate feature 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 with
  • payloads - 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.

Source

pub 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.

Submits multiple transactions and waits for all to complete.

§Arguments
  • account - The account to sign with
  • payloads - The transaction payloads to submit
  • timeout - 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.

Source

pub async fn batch_transfer_apt<A: Account>( &self, sender: &A, transfers: Vec<(AccountAddress, u64)>, ) -> AptosResult<Vec<BatchTransactionResult>>

Available on crate feature ed25519 only.

Transfers APT to multiple recipients in a batch.

§Arguments
  • sender - The sending account
  • transfers - 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.

Trait Implementations§

Source§

impl Debug for Aptos

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Aptos

§

impl !RefUnwindSafe for Aptos

§

impl Send for Aptos

§

impl Sync for Aptos

§

impl Unpin for Aptos

§

impl !UnwindSafe for Aptos

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more