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

Clone the aptos-core repo:

git clone https://github.com/aptos-labs/aptos-core.git
  • Typescript

  • Python

  • Rust

Navigate to the Typescript SDK examples directory:

cd ~/aptos-core/ecosystem/typescript/sdk/examples/typescript

Install the necessary dependencies:

yarn install

Run the transfer_coin example:

yarn run transfer_coin

Step 3: Understand the output

An output very similar to the following will appear after executing the above command:

=== Addresses ===Alice: 0xbd20517751571ba3fd06326c23761bc0bc69cf450898ffb43412fbe670c28806Bob: 0x8705f98a74f5efe17740276ed75031927402c3a965e10f2ee16cda46d99d8f7f=== Initial Balances ===Alice: 100000000Bob: 0=== Intermediate Balances ===Alice: 99944900Bob: 1000=== Final Balances ===Alice: 99889800Bob: 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 FULL CODE

See the TypeScript transfer-coin for the complete code as you follow the below steps.

Step 4.1: Initializing the clients

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.

  • Typescript

  • Python

  • Rust

const client = new AptosClient(NODE_URL);const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL); 

Using the API client we can create a CoinClient that we use for common coin operations such as transferring coins and checking balances.

const coinClient = new CoinClient(client); 

common.ts initializes the URL values as such:

export const NODE_URL = process.env.APTOS_NODE_URL || "https://fullnode.devnet.aptoslabs.com";export const FAUCET_URL = process.env.APTOS_FAUCET_URL || "https://faucet.devnet.aptoslabs.com";

TIP

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 = new AptosAccount();const bob = new AptosAccount(); 

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 faucetClient.fundAccount(alice.address(), 100_000_000);await faucetClient.fundAccount(bob.address(), 0); 

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

console.log(`Alice: ${await coinClient.checkBalance(alice)}`);console.log(`Bob: ${await coinClient.checkBalance(bob)}`); 

Behind the scenes, the checkBalance function in CoinClient in the SDK queries the CoinStore resource for the AptosCoin and reads the current stored value:

async checkBalance(  account: AptosAccount,  extraArgs?: {    // The coin type to use, defaults to 0x1::aptos_coin::AptosCoin    coinType?: string;  },): Promise<bigint> {  const coinType = extraArgs?.coinType ?? APTOS_COIN;  const typeTag = `0x1::coin::CoinStore<${coinType}>`;  const resources = await this.aptosClient.getAccountResources(account.address());  const accountResource = resources.find((r) => r.type === typeTag);  return BigInt((accountResource!.data as any).coin.value);} 

Step 4.5: Transferring

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.

  • Typescript

  • Python

  • Rust

let txnHash = await coinClient.transfer(alice, bob, 1_000, { gasUnitPrice: BigInt(100) }); 

Behind the scenes, the transfer function generates a transaction payload and has the client sign, send, and wait for it:

async transfer(  from: AptosAccount,  to: AptosAccount,  amount: number | bigint,  extraArgs?: OptionalTransactionArgs & {    // The coin type to use, defaults to 0x1::aptos_coin::AptosCoin    coinType?: string;  },): Promise<string> {  const coinTypeToTransfer = extraArgs?.coinType ?? APTOS_COIN;  const payload = this.transactionBuilder.buildTransactionPayload(    "0x1::coin::transfer",    [coinTypeToTransfer],    [to.address(), amount],  );  return this.aptosClient.generateSignSubmitTransaction(from, payload, extraArgs);} 

Within the client, generateSignSubmitTransaction is doing this:

const rawTransaction = await this.generateRawTransaction(sender.address(), payload, extraArgs);const bcsTxn = AptosClient.generateBCSTransaction(sender, rawTransaction);const pendingTransaction = await this.submitSignedBCSTransaction(bcsTxn);return pendingTransaction.hash;

Breaking the above down into pieces:

  1. transfer internally is a EntryFunction in the Coin Move module, i.e. an entry function in Move that is directly callable.

  2. The Move function is stored on the coin module: 0x1::coin.

  3. Because the Coin module can be used by other coins, the transfer must explicitly specify which coin type to transfer. If not specified with coinType it defaults to 0x1::aptos_coin::AptosCoin.


Step 4.6: Waiting for transaction resolution

  • Typescript

  • Python

  • Rust

In TypeScript, just calling coinClient.transfer 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.

You can set checkSuccess to true when calling transfer if you'd like it to throw an error if the transaction was not committed successfully:

await client.waitForTransaction(txnHash); 

Supporting documentation

Last updated