Your First Transaction
This tutorial describes how to generate and submit transactions to the Aptos blockchain, and verify these submitted transactions. The transfer-coin
example used in this tutorial is built with the Aptos SDKs.
Step 1: Pick an SDK​
Install your preferred SDK from the below list:
Step 2: Run the example​
- Typescript
- Python
- Rust
Clone the aptos-ts-sdk
repo and build it:
git clone https://github.com/aptos-labs/aptos-ts-sdk.git
cd aptos-ts-sdk
pnpm install
pnpm build
Navigate to the Typescript examples directory:
cd examples/typescript
Install the necessary dependencies:
pnpm install
Run the transfer_coin
example:
pnpm run transfer_coin
Clone the aptos-core
repo:
git clone https://github.com/aptos-labs/aptos-core.git
Navigate to the Python SDK directory:
cd aptos-core/ecosystem/python/sdk
Install the necessary dependencies:
curl -sSL https://install.python-poetry.org | python3
poetry install
Run the transfer-coin
example:
poetry run python -m examples.transfer_coin
Clone the aptos-core
repo:
git clone https://github.com/aptos-labs/aptos-core.git
Navigate to the Rust SDK directory:
cd aptos-core/sdk
Run the transfer-coin
example:
cargo run --example transfer-coin
Step 3: Understand the output​
- Typescript
- Python
- Rust
An output very similar to the following will appear after executing the above command:
=== Addresses ===
Alice's address is: 0xbd20517751571ba3fd06326c23761bc0bc69cf450898ffb43412fbe670c28806
Bob's address is: 0x8705f98a74f5efe17740276ed75031927402c3a965e10f2ee16cda46d99d8f7f
=== Initial Balances ===
Alice's balance is: 100000000
Bob's balance is: 0
=== Transfer 1000000 from Alice to Bob ===
Committed transaction: 0xc0d348afdfc34ae2c48971b253ece727cc9980dde182e2f2c42834552cbbf04c
=== Balances after transfer ===
Alice's balance is: 98899100
Bob's balance is: 1000000
The above output demonstrates that the transfer-coin
example executes the following steps:
- Initializing the Aptos client.
- The creation of two accounts: Alice and Bob.
- The funding and creation of Alice's account from a faucet.
- The transferring of 1000000 coins from Alice to Bob.
- The 1100900 coins of gas paid for by Alice to make that transfer.
An output very similar to the following will appear after executing the above command:
=== Addresses ===
Alice: 0xbd20517751571ba3fd06326c23761bc0bc69cf450898ffb43412fbe670c28806
Bob: 0x8705f98a74f5efe17740276ed75031927402c3a965e10f2ee16cda46d99d8f7f
=== Initial Balances ===
Alice: 100000000
Bob: 0
=== Intermediate Balances ===
Alice: 99944900
Bob: 1000
=== Final Balances ===
Alice: 99889800
Bob: 2000
The above output demonstrates that the transfer-coin
example executes the following steps:
- Initializing the REST and faucet clients.
- The creation of two accounts: Alice and Bob.
- The funding and creation of Alice's account from a faucet.
- The creation of Bob's account from a faucet.
- The transferring of 1000 coins from Alice to Bob.
- The 54100 coins of gas paid for by Alice to make that transfer.
- Another transfer of 1000 coins from Alice to Bob.
- The additional 54100 coins of gas paid for by Alice to make that transfer.
Now see the below walkthrough of the SDK functions used to accomplish the above steps.
An output very similar to the following will appear after executing the above command:
=== Addresses ===
Alice: 0xbd20517751571ba3fd06326c23761bc0bc69cf450898ffb43412fbe670c28806
Bob: 0x8705f98a74f5efe17740276ed75031927402c3a965e10f2ee16cda46d99d8f7f
=== Initial Balances ===
Alice: 100000000
Bob: 0
=== Intermediate Balances ===
Alice: 99944900
Bob: 1000
=== Final Balances ===
Alice: 99889800
Bob: 2000
The above output demonstrates that the transfer-coin
example executes the following steps:
- Initializing the REST and faucet clients.
- The creation of two accounts: Alice and Bob.
- The funding and creation of Alice's account from a faucet.
- The creation of Bob's account from a faucet.
- The transferring of 1000 coins from Alice to Bob.
- The 54100 coins of gas paid for by Alice to make that transfer.
- Another transfer of 1000 coins from Alice to Bob.
- The additional 54100 coins of gas paid for by Alice to make that transfer.
Now see the below walkthrough of the SDK functions used to accomplish the above steps.
Step 4: The SDK in depth​
The transfer-coin
example code uses helper functions to interact with the REST API. This section reviews each of the calls and gives insights into functionality.
- Typescript
- Python
- Rust
See the TypeScript transfer_coin
for the complete code as you follow the below steps.
See the Python transfer_coin
for the complete code as you follow the below steps.
See the Rust transfer-coin
for the complete code as you follow the below steps.
Step 4.1: Initializing the clients​
- Typescript
- Python
- Rust
In the first step, the transfer_coin
example initializes the Aptos client:
const APTOS_NETWORK: Network =
NetworkToNetworkName[process.env.APTOS_NETWORK] || Network.DEVNET;
const config = new AptosConfig({ network: APTOS_NETWORK });
const aptos = new Aptos(config);
By default, the Aptos client points to Aptos devnet services. However, it can be configured with the network
input argument
In the first step, the transfer-coin
example initializes both the REST and faucet clients:
- The REST client interacts with the REST API.
- The faucet client interacts with the devnet Faucet service for creating and funding accounts.
rest_client = RestClient(NODE_URL)
faucet_client = FaucetClient(FAUCET_URL, rest_client)
common.py
initializes these values as follows:
NODE_URL = os.getenv("APTOS_NODE_URL", "https://api.devnet.aptoslabs.com/v1")
FAUCET_URL = os.getenv(
"APTOS_FAUCET_URL",
"https://faucet.devnet.aptoslabs.com",
)
By default, the URLs for both the services point to Aptos devnet services. However, they can be configured with the following environment variables:
APTOS_NODE_URL
APTOS_FAUCET_URL
In the first step, the transfer-coin
example initializes both the REST and faucet clients:
- The REST client interacts with the REST API.
- The faucet client interacts with the devnet Faucet service for creating and funding accounts.
let rest_client = Client::new(NODE_URL.clone());
let faucet_client = FaucetClient::new(FAUCET_URL.clone(), NODE_URL.clone());
Using the API client we can create a CoinClient
, which we use for common coin operations such as transferring coins and checking balances.
let coin_client = CoinClient::new(&rest_client);
In the example we initialize the URL values as such:
static NODE_URL: Lazy<Url> = Lazy::new(|| {
Url::from_str(
std::env::var("APTOS_NODE_URL")
.as_ref()
.map(|s| s.as_str())
.unwrap_or("https://api.devnet.aptoslabs.com"),
)
.unwrap()
});
static FAUCET_URL: Lazy<Url> = Lazy::new(|| {
Url::from_str(
std::env::var("APTOS_FAUCET_URL")
.as_ref()
.map(|s| s.as_str())
.unwrap_or("https://faucet.devnet.aptoslabs.com"),
)
.unwrap()
});
By default, the URLs for both the services point to Aptos devnet services. However, they can be configured with the following environment variables:
APTOS_NODE_URL
APTOS_FAUCET_URL
Step 4.2: Creating local accounts​
The next step is to create two accounts locally. Accounts represent both on and off-chain state. Off-chain state consists of an address and the public/private key pair used to authenticate ownership. This step demonstrates how to generate that off-chain state.
- Typescript
- Python
- Rust
const alice = Account.generate();
const bob = Account.generate();
alice = Account.generate()
bob = Account.generate()
let mut alice = LocalAccount::generate(&mut rand::rngs::OsRng);
let bob = LocalAccount::generate(&mut rand::rngs::OsRng);
Step 4.3: Creating blockchain accounts​
In Aptos, each account must have an on-chain representation in order to receive tokens and coins and interact with other dapps. An account represents a medium for storing assets; hence, it must be explicitly created. This example leverages the Faucet to create and fund Alice's account and to create but not fund Bob's account:
- Typescript
- Python
- Rust
await aptos.fundAccount({
accountAddress: alice.accountAddress,
amount: 100_000_000,
});
alice_fund = faucet_client.fund_account(alice.address(), 100_000_000)
bob_fund = faucet_client.fund_account(bob.address(), 0)
faucet_client
.fund(alice.address(), 100_000_000)
.await
.context("Failed to fund Alice's account")?;
faucet_client
.create_account(bob.address())
.await
.context("Failed to fund Bob's account")?;
Step 4.4: Reading balances​
In this step, the SDK translates a single call into the process of querying a resource and reading a field from that resource.
- Typescript
- Python
- Rust
const aliceBalance = await balance("Alice", alice.accountAddress);
const bobBalance = await balance("Bob", bob.accountAddress);
Behind the scenes, the balance
function uses the SDK getAccountAPTAmount
function that queries the Indexer service and reads the current stored value:
const balance = async (
name: string,
accountAddress: AccountAddress,
): Promise<number> => {
const amount = await aptos.getAccountAPTAmount({
accountAddress,
});
console.log(`${name}'s balance is: ${amount}`);
return amount;
};
alice_balance = rest_client.account_balance(alice.address())
bob_balance = rest_client.account_balance(bob.address())
[alice_balance, bob_balance] = await asyncio.gather(*[alice_balance, bob_balance])
print(f"Alice: {alice_balance}")
print(f"Bob: {bob_balance}")
Behind the scenes, the SDK queries the CoinStore resource for the AptosCoin and reads the current stored value:
def account_balance(self, account_address: str) -> int:
"""Returns the test coin balance associated with the account"""
return self.account_resource(
account_address, "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>"
)["data"]["coin"]["value"]
println!(
"Alice: {:?}",
coin_client
.get_account_balance(&alice.address())
.await
.context("Failed to get Alice's account balance the second time")?
);
println!(
"Bob: {:?}",
coin_client
.get_account_balance(&bob.address())
.await
.context("Failed to get Bob's account balance the second time")?
);
Behind the scenes, the SDK queries the CoinStore resource for the AptosCoin and reads the current stored value:
let balance = self
.get_account_resource(address, "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>")
.await?;
Step 4.5: Transferring​
Like the previous step, this is another helper step that constructs a transaction transferring the coins from Alice to Bob. The SDK provides a helper function to generate a transferCoinTransaction
transaction that can be simulated or submitted to chain. Once a transaction has been submitted to chain, the API will return a transaction hash that can be used in the subsequent step to check on the transaction status. The Aptos blockchain does perform a handful of validation checks on submission; and if any of those fail, the user will instead be given an error. These validations use the transaction signature and unused sequence number, and submitting the transaction to the appropriate chain.
- Typescript
- Python
- Rust
const transaction = await aptos.transferCoinTransaction({
sender: alice,
recipient: bob.accountAddress,
amount: TRANSFER_AMOUNT,
});
const pendingTxn = await aptos.signAndSubmitTransaction({
signer: alice,
transaction,
});
Behind the scenes, the transferCoinTransaction
function generates a transaction payload that can be simulated or submitted to chain:
export async function transferCoinTransaction(args: {
aptosConfig: AptosConfig;
sender: Account;
recipient: AccountAddressInput;
amount: AnyNumber;
coinType?: MoveStructId;
options?: InputGenerateTransactionOptions;
}): Promise<SingleSignerTransaction> {
const { aptosConfig, sender, recipient, amount, coinType, options } = args;
const coinStructType = coinType ?? APTOS_COIN;
const transaction = await generateTransaction({
aptosConfig,
sender: sender.accountAddress,
data: {
function: "0x1::aptos_account::transfer_coins",
typeArguments: [coinStructType],
functionArguments: [recipient, amount],
},
options,
});
return transaction;
}
Breaking the above down into pieces:
transfer_coins
internally is aEntryFunction
in the Aptos Account Move module, i.e. an entry function in Move that is directly callable.- The Move function is stored on the aptos_account module:
0x1::aptos_account
. - The
transfer_coins
functions uses the Coin Move module - Because the Coin module can be used by other coins, the
transferCoinTransaction
must explicitly specify which coin type to transfer. If not specified withcoinType
it defaults to0x1::aptos_coin::AptosCoin
.
Like the previous step, this is another helper step that constructs a transaction transferring the coins from Alice to Bob. For correctly generated transactions, the API will return a transaction hash that can be used in the subsequent step to check on the transaction status. The Aptos blockchain does perform a handful of validation checks on submission; and if any of those fail, the user will instead be given an error. These validations use the transaction signature and unused sequence number, and submitting the transaction to the appropriate chain.
txn_hash = await rest_client.transfer(alice, bob.address(), 1_000)
Behind the scenes the Python SDK generates, signs, and submits a transaction:
async def bcs_transfer(
self,
sender: Account,
recipient: AccountAddress,
amount: int,
sequence_number: Optional[int] = None,
) -> str:
transaction_arguments = [
TransactionArgument(recipient, Serializer.struct),
TransactionArgument(amount, Serializer.u64),
]
payload = EntryFunction.natural(
"0x1::aptos_account",
"transfer",
[],
transaction_arguments,
)
signed_transaction = await self.create_bcs_signed_transaction(
sender, TransactionPayload(payload), sequence_number=sequence_number
)
return await self.submit_bcs_transaction(signed_transaction)
Breaking the above down into pieces:
transfer
internally is aEntryFunction
in the Coin Move module, i.e. an entry function in Move that is directly callable.- The Move function is stored on the coin module:
0x1::coin
. - Because the Coin module can be used by other coins, the transfer must explicitly use a
TypeTag
to define which coin to transfer. - The transaction arguments must be placed into
TransactionArgument
s with type specifiers (Serializer.{type}
), that will serialize the value into the appropriate type at transaction generation time.
Like the previous step, this is another helper step that constructs a transaction transferring the coins from Alice to Bob. For correctly generated transactions, the API will return a transaction hash that can be used in the subsequent step to check on the transaction status. The Aptos blockchain does perform a handful of validation checks on submission; and if any of those fail, the user will instead be given an error. These validations use the transaction signature and unused sequence number, and submitting the transaction to the appropriate chain.
let txn_hash = coin_client
.transfer(&mut alice, bob.address(), 1_000, None)
.await
.context("Failed to submit transaction to transfer coins")?;
Behind the scenes the Rust SDK generates, signs, and submits a transaction:
let chain_id = self
.api_client
.get_index()
.await
.context("Failed to get chain ID")?
.inner()
.chain_id;
let transaction_builder = TransactionBuilder::new(
TransactionPayload::EntryFunction(EntryFunction::new(
ModuleId::new(AccountAddress::ONE, Identifier::new("coin").unwrap()),
Identifier::new("transfer").unwrap(),
vec![TypeTag::from_str(options.coin_type).unwrap()],
vec![
bcs::to_bytes(&to_account).unwrap(),
bcs::to_bytes(&amount).unwrap(),
],
)),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
+ options.timeout_secs,
ChainId::new(chain_id),
)
.sender(from_account.address())
.sequence_number(from_account.sequence_number())
.max_gas_amount(options.max_gas_amount)
.gas_unit_price(options.gas_unit_price);
let signed_txn = from_account.sign_with_transaction_builder(transaction_builder);
Ok(self
.api_client
.submit(&signed_txn)
.await
.context("Failed to submit transfer transaction")?
.into_inner())
Breaking the above down into pieces:
- First, we fetch the chain ID, necessary for building the transaction payload.
transfer
internally is aEntryFunction
in the Coin Move module, i.e. an entry function in Move that is directly callable.- The Move function is stored on the coin module:
0x1::coin
. - Because the Coin module can be used by other coins, the transfer must explicitly use a
TypeTag
to define which coin to transfer. - The transaction arguments, such as
to_account
andamount
, must be encoded as BCS to use with theTransactionBuilder
.
Step 4.6: Waiting for transaction resolution​
- Typescript
- Python
- Rust
In the TypeScript SDK, just calling waitForTransaction
is sufficient to wait for the transaction to complete. The function will return the Transaction
returned by the API once it is processed (either successfully or unsuccessfully) or throw an error if processing time exceeds the timeout.
const response = await aptos.waitForTransaction({
transactionHash: pendingTxn.hash,
});
The transaction hash can be used to query the status of a transaction:
await rest_client.wait_for_transaction(txn_hash)
The transaction hash can be used to query the status of a transaction:
rest_client
.wait_for_transaction(&txn_hash)
.await
.context("Failed when waiting for the transfer transaction")?;