Skip to main content

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

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: 0x0baec07bfc42f8018ea304ddc307a359c1c6ab20fbce598065b6cb19acff7043
Bob: 0xc98ceafadaa32e50d06d181842406dbbf518b6586ab67cfa2b736aaddeb7c74f

=== Initial Balances ===
Alice: 20000
Bob: 0

=== Intermediate Balances ===
Alice: 18996
Bob: 1000

=== Final Balances ===
Alice: 17992
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 4 coins of gas paid for by Alice to make that transfer.
  • Another transfer of 1000 coins from Alice to Bob.
  • The additional 4 coins of gas paid for by Alice to make that transfer.

Next, see below a walk-through of the SDK functions that are 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.

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, and
  • The faucet client interacts with the devnet Faucet service for creating and funding accounts.
const client = new AptosClient(NODE_URL);
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);

Using the API client we can create a CoinClient, which 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.

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 support receive tokens and coins as well as interacting in 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 only create Bob's account:

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.

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 which transfers 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 include the transaction signature, unused sequence number, and submitting the transaction to the appropriate chain.

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

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 if the transaction was not committed successfully:

await client.waitForTransaction(txnHash);