Skip to main content

Your First Transaction

This tutorial describes, in the following step-by-step approach, how to generate, submit, and verify transactions submitted to the Aptos Blockchain:

  1. Create a representation of an account.

Each Aptos account has a unique account address. The owner of that account holds the public, private key-pair that maps to the Aptos account address and, in turn, the authentication key stored in that account.

note

See more about Aptos accounts in Accounts.

  1. Prepare a wrapper around the REST interfaces.

Aptos provides a REST API for interacting with the blockchain. This step prepares wrappers around this API, for retrieving account information, and for constructing a transaction, signing it and submitting the transaction. Alternatively, Typescript SDK can be used to interreact with the blockchain. In this tutorial, we use Typescript SDK for the Typescript example and custom wrappers for Python and Rust.

note

Aptos SDK is preferred when available.

  1. Prepare a wrapper around the Faucet interface.

Using the Faucet interface at the Aptos devnet, this tutorial code automatically creates an account with the account address 0x1 and funds the account.

  1. Combine the above wrappers into an application, execute and verify.

Before you start

Make sure you follow the below steps first so you can run the tutorial.

  1. Clone the Aptos repo.

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

  2. cd into aptos-core directory.

    cd aptos-core
  3. Checkout the devnet branch using git checkout --track origin/devnet.

  4. Run the scripts/dev_setup.sh Bash script as shown below. This will prepare your developer environment.

    ./scripts/dev_setup.sh
  5. Update your current shell environment.

    source ~/.cargo/env

With your development environment ready, now you are ready to run this tutorial.

GitHub source

Follow the below links to access the source code for the tutorial:

See the first_transaction.ts code in the Typescript project of the tutorial.

Step 1: Create a representation of an account

This step creates the representation of an account. See also Aptos accounts and Creating a Signed Transaction.

/** AptosAccount provides methods around addresses, key-pairs */
import { AptosAccount, TxnBuilderTypes, BCS, MaybeHexString } from "aptos";

Step 2: REST interface

While the data from the REST interface can be read directly, the following code examples demonstrate a more ergonomic approach, while still using the REST interface, for:

  • Retrieving the ledger data from the FullNode, including account and account resource data.
  • Constructing signed transactions, represented by JSON format.
/** Wrappers around the Aptos Node and Faucet API */
import { AptosClient, FaucetClient } from "aptos";

Step 2.1: Reading an account

The following are wrappers for querying account data.

const client = new AptosClient(NODE_URL);
/**
* https://aptos-labs.github.io/ts-sdk-doc/classes/AptosClient.html#getAccount
* returns the sequence number and authentication key for an account
*
* https://aptos-labs.github.io/ts-sdk-doc/classes/AptosClient.html#getAccountResource
* returns all resources associated with the account
*/

Step 2.2: Submitting a transaction

The following demonstrates the core functionality for constructing, signing, and waiting on a transaction.

/**
* https://aptos-labs.github.io/ts-sdk-doc/classes/AptosClient.html#generateBCSTransaction
* signs a raw transaction, which can be submitted to the blockchain.
*/

/**
* https://aptos-labs.github.io/ts-sdk-doc/classes/AptosClient.html#submitSignedBCSTransaction
* submits a signed transaction to the blockchain.
*/

Step 2.3: Application-specific logic

The following demonstrates how to read data from the blockchain and how to submit a specific transaction.

/** Helper method returns the coin balance associated with the account */
export async function accountBalance(accountAddress: MaybeHexString): Promise<number | null> {
const resource = await client.getAccountResource(accountAddress, "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>");
if (resource == null) {
return null;
}

return parseInt((resource.data as any)["coin"]["value"]);
}

/**
* Transfers a given coin amount from a given accountFrom to the recipient's account address.
* Returns the transaction hash of the transaction used to transfer.
*/
async function transfer(accountFrom: AptosAccount, recipient: MaybeHexString, amount: number): Promise<string> {
const token = new TxnBuilderTypes.TypeTagStruct(TxnBuilderTypes.StructTag.fromString("0x1::aptos_coin::AptosCoin"));

const scriptFunctionPayload = new TxnBuilderTypes.TransactionPayloadScriptFunction(
TxnBuilderTypes.ScriptFunction.natural(
"0x1::coin",
"transfer",
[token],
[BCS.bcsToBytes(TxnBuilderTypes.AccountAddress.fromHex(recipient)), BCS.bcsSerializeUint64(amount)],
),
);

const [{ sequence_number: sequenceNumber }, chainId] = await Promise.all([
client.getAccount(accountFrom.address()),
client.getChainId(),
]);

const rawTxn = new TxnBuilderTypes.RawTransaction(
TxnBuilderTypes.AccountAddress.fromHex(accountFrom.address()),
BigInt(sequenceNumber),
scriptFunctionPayload,
1000n,
1n,
BigInt(Math.floor(Date.now() / 1000) + 10),
new TxnBuilderTypes.ChainId(chainId),
);

const bcsTxn = AptosClient.generateBCSTransaction(accountFrom, rawTxn);
const pendingTxn = await client.submitSignedBCSTransaction(bcsTxn);

return pendingTxn.hash;
}

Step 3: Faucet interface

Aptos Blockchain faucets issue test tokens to accounts. These test tokens can be used for testing, e.g., paying gas fees or transferring tokens between users. The Aptos Faucet can also create accounts if they do not exist. The Aptos Faucet interface requires a public key represented in a hex-encoded string.

/** Faucet creates and funds accounts. */
const faucetClient = new FaucetClient(NODE_URL, FAUCET_URL);

Step 4: Run the application

Finally, we can run the application and verify the output.

For Typescript:
  1. Make sure you followed the prerequisites described in Before you start.
  2. cd into aptos-core/developer-docs-site/static/examples/typescript directory.
  3. Install the required libraries: yarn install.
  4. Execute the example: yarn first_transaction.

Output

The output after executing:

=== Addresses ===
Alice: e26d69b8d3ff12874358da6a4082a2ac
Bob: c8585f009c8a90f22c6b603f28b9ed8c

=== Initial Balances ===
Alice: 5000
Bob: 0

=== Final Balances ===
Alice: 3927
Bob: 1000

The output shows that Bob received 1000 coins from Alice. Alice paid 73 coins for gas.

Verify

The data can be verified by visiting either a REST interface or the explorer:

note

The Aptos devnet is reset from time to time, so the above links may not work. Try the tutorial yourself and check the accounts in the Aptos Explorer then.