Aptos Agent Skills (https://github.com/aptos-labs/aptos-agent-skills) cover common workflows: write-contracts, generate-tests, security-audit, deploy-contracts, use-ts-sdk, ts-sdk-transactions, create-aptos-project, analyze-gas-optimization, modernize-move. Install the skill that matches the task before deep work. This is the curated low-token Aptos developer documentation set for AI agents and IDE assistants. # Build the Future of Web3 on Aptos > Everything you need to build a best-in-class Web3 experience. Getting Started * [Deploy Your First Move Smart Contract](/build/guides/first-move-module) Compile & publish Move modules to devnet in minutes. * [Your First Transaction](/build/guides/first-transaction) Write and read on-chain data using the TypeScript SDK. * [Code with AI (MCP)](/build/ai/aptos-mcp) Give Cursor, Claude Code, and Codex direct access to Aptos APIs. * [Agent Skills](/build/ai/aptos-agent-skills) Move and TS SDK skills for Claude Code, Cursor, Copilot. Tools * [Testnet Faucet](/network/faucet) Fund your testnet account with APT to start building. * [Official SDKs](/build/sdks) TypeScript, Python, Go, Rust, and more. * [Aptos CLI](/build/cli) Compile, test, publish contracts; accounts & keys; localnet. Smart Contracts * [NEW! Move on Aptos (VS Code Extension)](/build/smart-contracts/move-vscode-extension) Aptos Labs’ official extension for Move development. * [Objects](/build/smart-contracts/objects) Composable on-chain primitives for flexible asset ownership, addressing, & programmability. * [The Move Book](https://aptos-labs.github.io/move-book/) Understand Move syntax, types, resources, & best practices. * [Vibe Code a full-stack dApp on Learn](https://learn.aptoslabs.com/en/hackathon/vibe-coder-to-aptos-guide/introduction) Interactive AI workshop to quickly build a full-stack dApp. On-Chain Features * [Sponsored Transactions](/build/guides/sponsored-transactions) Pay for users’ gas so they can use your dApp with zero APT. * [Keyless Accounts](/build/guides/aptos-keyless) Onboard users and sign without wallets or seed phrases. * [NEW! Orderless Transactions](/build/guides/orderless-transactions) High-volume apps can be safer by sending transactions out of order with replay-protection nonce. * [On-chain Randomness](/build/smart-contracts/randomness) Verifiable random number = fair games, lotteries, & drops. Resources * [LLMs.txt Integration](/llms-txt) AI-optimized documentation feeds for coding assistants and chat tools. * [Query, Index, or Stream On-Chain Data](/build/indexer) Query Indexer API, index contracts, stream raw transactions. * [Apply for a Grant](https://aptosnetwork.com/grants) Connect * [GitHub Developer Discussions](https://github.com/aptos-labs/aptos-developer-discussions/discussions) * [Ecosystem Directory](https://aptosnetwork.com/ecosystem/directory) * [Discord](https://discord.gg/aptosnetwork) * [Telegram](https://t.me/aptos) # Get Started Building on Aptos > Learn how to build on Aptos with smart contracts, indexer queries, SDKs, APIs, and comprehensive developer resources ## What would you like to learn? [](#what-would-you-like-to-learn) [Smart Contracts](/build/smart-contracts) Learn how to write smart contracts on Aptos with the Move programming language. [Query Data](/build/indexer) Use the Aptos Indexer to query for on-chain data efficiently. [Blockchain Infrastructure](/network/blockchain/blockchain-deep-dive) Learn the different components of the Aptos blockchain's infrastructure. ## What developer tools should I use? [](#what-developer-tools-should-i-use) [SDKs](/build/sdks) Use the TypeScript, Python, Go, and Rust SDKs to submit transactions and read on-chain data. [Indexer](/build/indexer) Query for on-chain data like account balances, historical transactions, NFTs by account, and more. [CLI](/build/cli) Compile and profile Move smart contracts, run a local network, and more with the Aptos CLI. Here’s an interactive example of our [Indexer](/build/indexer) and how you can query for the Current Fungible Asset Balances of an account. More usage examples can be found in [example queries](/build/indexer/indexer-api/fungible-asset-balances). ## Coming from another ecosystem? [](#coming-from-another-ecosystem) Quickly ramp up on some of the differences and similarities between Aptos and other ecosystems. [Ethereum / EVM to Aptos Cheatsheet](/build/get-started/ethereum-cheatsheet) [Solana / SVM to Aptos Cheatsheet](/build/get-started/solana-cheatsheet) [VM Comparison](/network/blockchain/move#comparison-to-other-vms) ## Do you have any examples? [](#do-you-have-any-examples) We’ve got all kinds of examples and guides, catered to what you’re looking for. ### End-to-end guides [](#end-to-end-guides) [Your First Transaction](/build/guides/first-transaction) This tutorial describes how to generate and submit transactions to the Aptos blockchain, and verify these submitted transactions. [Payments](/build/guides/payments) Latency, fees, sponsored and orderless options, and two-party (multi-agent) payments. [Your First NFT](/build/guides/your-first-nft) This tutorial describes how to create and transfer non-fungible assets on the Aptos blockchain. [Your First Fungible Asset](/build/guides/first-fungible-asset) This tutorial introduces how you can compile, deploy, and mint your own fungible asset (FA), named FACoin. ### Smart Contract guides [](#smart-contract-guides) See the [Smart Contract](/build/smart-contracts) section for more info [Create a Smart Contract](/build/guides/build-e2e-dapp/1-create-smart-contract) This is the first chapter of the tutorial on building an end-to-end dapp on Aptos. [Aptos Move Examples](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples) 30+ examples on how to develop Move on Aptos [Move Tutorial](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples/move-tutorial) Covers the basics of programming with Move ### Interactive guides [](#interactive-guides) [Aptos Learn](https://learn.aptoslabs.com/en/workshops) Basic and advanced guides [Move Spiders](https://movespiders.com) Learn about Move with a friendly spider mascot by Move Spiders [Aptos Shores](https://www.aptosshores.com) Learn about Move with Aptos Shores ## How do I setup a full node or validator? [](#how-do-i-setup-a-full-node-or-validator) [Setup a full node](/network/nodes/full-node) [Setup a validator](/network/nodes/validator-node) # Learn from Guides > Step-by-step tutorials for building on Aptos, from first transactions and Move modules to orderless transactions, keyless accounts, and exchange integration. Welcome to Aptos guides. These tutorials walk through specific tasks on the Aptos blockchain, from your first transaction through production integration. ## Beginner Guides [](#beginner-guides) Start with these foundational tutorials. They match the Beginner group in the sidebar. [Your First Transaction](/build/guides/first-transaction) Create, submit, and verify a basic APT transfer with the TypeScript and Python SDKs. [Your First Move Module](/build/guides/first-move-module) Write a simple Move module and publish it to the Aptos blockchain. [Your First Fungible Asset](/build/guides/first-fungible-asset) Create and manage a fungible asset that can be transferred between accounts. [Your First NFT](/build/guides/your-first-nft) Create, mint, and transfer digital assets (NFTs) using the Aptos TypeScript SDK. [Your First Multisig](/build/guides/first-multisig) Set up a multi-signature account that requires approval from multiple key holders. [Your First Dapp](/build/guides/build-e2e-dapp) Build a complete todo list dapp with a Move contract and a React frontend. ## Ethereum to Aptos [](#ethereum-to-aptos) Coming from Solidity and Ethers? This migration path maps EVM patterns to Move, Objects, and the current TypeScript SDK. [Ethereum to Aptos Guide](/build/guides/ethereum-to-aptos) Port Solidity mental models to Move, then walk through a billboard contract and a Dutch auction. ## Advanced Guides [](#advanced-guides) These guides cover transaction types, account security, and passwordless login. [Sponsored Transactions](/build/guides/sponsored-transactions) Let your application pay gas so users can transact without holding APT. [Transaction Management](/build/guides/transaction-management) Sequence-number orchestration, failure recovery, and worker accounts for high-volume submission. [Orderless Transactions](/build/guides/orderless-transactions) Submit transactions in parallel with a replay-protection nonce instead of a sequence number. [Encrypted Pending Transactions](/build/guides/encrypted-pending-transactions) Encrypt the Move payload while a transaction is pending, then decrypt it at execution. [Multisig Managed Assets](/build/guides/multisig-managed-fungible-asset) Control minting, freezing, and burning of a fungible asset with a framework multisig account. [Key Rotation](/build/guides/key-rotation) Rotate an account's authentication key without changing its address. [Aptos Keyless](/build/guides/aptos-keyless) Create blockchain accounts from existing Google or Apple logins, without seed phrases. ## Integration Guides [](#integration-guides) For payments, exchanges, existing applications, and oracle feeds. [Payments](/build/guides/payments) Latency, fees, sponsored and orderless options, and two-party (multi-agent) payments. [Exchange Integration](/build/guides/exchanges) Infrastructure, address standards, asset management, balances, and transaction processing for exchanges. [Application Integration](/build/guides/application-integration) Map an existing blockchain app onto Aptos accounts, signing, balances, and the TypeScript SDK. [Oracles](/build/guides/oracles) Use Chainlink Data Feeds and CCIP, or Pyth Network price feeds, from Aptos Move contracts. # Ethereum to Aptos Migration Guide > Comprehensive comparison and migration guide for Ethereum developers transitioning to Aptos blockchain development Aptos is built to allow you to quickly prototype and scale secure production applications. It combines a fast, cost-efficient, and stable blockchain layer with Move’s compile-time safety that catches exploits before deployment, comprehensive tooling for rapid development, and a strong ecosystem of exchanges and bridges for seamless integration. ### High Level Overview [](#high-level-overview)
FeatureEthereumAptos
Account Addresses160-bit256-bit
Storage MindsetContract-based storageAccount centric mindset for code and data
Caller IDmsg.sender&signer reference
Smart ContractsSolidity, EVMMove, MoveVM
BenefitsMature, wide adoptionScalability, low latency, predictable fees
Transaction FeesVariable, can be highLower and more predictable
Sponsored TransactionsRequires third-party services or EIP-7702 wallet support (2025+)Natively supported via fee payer field. Geomi Gas Stations provides production infrastructure
Account StructureBalance in a single field, uses nonceModules and resources, uses sequence number
Data StoragePatricia Merkle TreesGlobal storage with resources and modules
UpgradeabilityProxy patternsDirect module upgrades
Safety & SecurityVulnerable to attacks like reentrancyMitigates common vulnerabilities
Dispatch TypeDynamic dispatchStatic dispatch
Frontend SDKEthers.js libraryAptos Typescript SDK
NFT StandardsERC-721, ERC-1155Digital Asset
FT StandardERC-20, factory patternSee Fungible Asset, copy paste in your module: use aptos_framework::fungible_asset...
Example CodeERC-20 (new contract per deploy)Fungible Asset (single reusable module)
Legacy [`Coin`](/build/smart-contracts/aptos-coin) documentation still covers the original standard; most new deployments should prefer the Fungible Asset module referenced above. ### Comparing Token Standards in Detail [](#comparing-token-standards-in-detail)
SolidityMove (Aptos)
Token StructureEach token is its own contract.Every token is a typed FungibleAsset instantiation that reuses the same published module.
Token StandardMust conform to standards like ERC-20; implementations can vary per deploy.Uniform interface and implementation enforced by the shared module; new tokens simply register a new type rather than redeploying code.
Balance StorageBalances stored in contract using a mapping structure.Resource-Oriented Balance: balances live in an extensible object owned by the user’s account.
Transfer MechanismTokens can be transferred without receiver’s explicit permission.Transfers can skip receiver permission, but only when the FA explicitly enables primary-store auto creation (visible in the token’s creation code).
### Comparing EVM and Move VM in Detail [](#comparing-evm-and-move-vm-in-detail) * **EVM**: Known for its flexibility and dynamic dispatch, which allows a wide range of smart contract behaviors. This flexibility, however, can lead to complexities in parallel execution and network operations. * **Move VM**: Focuses on safety and efficiency with a more integrated approach between the VM and the programming language. Its data storage model allows for better parallelization, and its static dispatch method enhances security and predictability.
EVM (Ethereum Virtual Machine)Move VM (Move Virtual Machine)
Data StorageData is stored in the smart contract’s storage space.Data is stored across smart contracts, user accounts, and objects.
ParallelizationParallel execution is limited due to shared storage space.More parallel execution enabled due to flexible split storage design.
VM and Language IntegrationSeparate layers for EVM and smart contract languages (e.g., Solidity).Seamless integration between VM layer and Move language, with native functions written in Rust executable in Move.
Critical Network OperationsImplementation of network operations can be complex and less direct.Critical operations like validator set management natively implemented in Move, allowing for direct execution.
Function CallingDynamic dispatch allows for arbitrary smart contract calls.Static dispatch aligns with a focus on security and predictable behavior.
Type SafetyContract types provide a level of type safety.Module structs and generics in Move offer robust type safety.
Transaction SafetyUses nonces for transaction ordering and safety.Uses sequence numbers for transaction ordering and safety.
Authenticated StorageYes, with smart contract storage.Yes, leveraging Move’s resource model.
Object AccessibilityObjects are not globally accessible; bound to smart contract scope.Guaranteed global accessibility of objects.
## Migration Tips for Ethereum Developers [](#migration-tips-for-ethereum-developers) * [Storage](#tab-panel-0-0) * [Authentication](#tab-panel-0-1) * [Resources & Abilities](#tab-panel-0-2) * [Upgradability](#tab-panel-0-3) * [Deploying Modules](#tab-panel-0-4) Ethereum stores all data in contract storage using mappings. Aptos uses an account-centric model where each account stores their own resources. Instead of a contract maintaining a `mapping(address => T)`, each user stores their own `T` resource at their address. ``` module my_hackathon_account::prototype { use std::string; use std::signer; // Unlike Solidity's mapping(address => string), each account stores their own resource struct MessageHolder has key, store, drop { message: string::String, } entry fun set_message(account: &signer, message: string::String) acquires MessageHolder { let addr = signer::address_of(account); // Check if resource exists at this account (like checking mapping[addr]) if (exists(addr)) { move_from(addr); // Remove old resource }; // Store resource at the user's address (in their account, not in contract storage!) move_to(account, MessageHolder { message }); } #[view] public fun get_message(addr: address): string::String acquires MessageHolder { assert!(exists(addr), 0); // Read message stored at the user's address borrow_global(addr).message }} ``` By default, modules deploy to your account address. For production apps, consider deploying to [Objects](/build/smart-contracts/objects), which creates a unique address per deployment and enables transferable code ownership. See [Using Objects](/build/smart-contracts/object/using-objects) for implementation details. Learn more: [`global storage operators`](https://aptos-labs.github.io/move-book/global-storage.html), [`structs and resources`](https://aptos-labs.github.io/move-book/structs-and-enums.html) On Ethereum, `msg.sender` is set by the EVM, but many bugs come from using `tx.origin` for auth or trusting user-supplied addresses. Aptos’ `&signer` goes further: it’s an unforgeable capability created only by the VM for actual transaction signers, so any function that requires `&signer` can’t be called with a spoofed identity. In dapps, wallets plus the [Aptos TypeScript SDK](/build/sdks/ts-sdk) and [wallet adapter](/build/sdks/wallet-adapter/wallets) bridge this signer identity from frontend to on-chain. ``` module my_hackathon_account::prototype { use std::string; use std::signer; struct MessageHolder has key, store, drop { message: string::String, } // Only the account owner can provide their &signer (unforgeable authentication) entry fun set_message(account: &signer, message: string::String) acquires MessageHolder { // Extract address from authenticated signer (no spoofing possible!) let addr = signer::address_of(account); if (exists(addr)) { move_from(addr); }; // account is guaranteed to be authentic move_to(account, MessageHolder { message }); } #[view] public fun get_message(addr: address): string::String acquires MessageHolder { assert!(exists(addr), 0); // Read message stored at the user's address borrow_global(addr).message }} ``` Create and fund an account using the [Aptos CLI](/build/cli): ``` aptos init ``` Learn more: [`signer`](https://aptos-labs.github.io/move-book/primitive-types.html) type, [`functions`](https://aptos-labs.github.io/move-book/functions.html) Move has four abilities: `copy`, `drop`, `store`, and `key`, which control how values can be used. In this example, MessageHolder deliberately omits `copy` so messages stored as resources can’t be duplicated; you generally avoid `copy` on any type that represents on-chain state or assets. `key` + `store` allow it to live in global storage at an address, and `drop` lets you destroy the old resource safely when overwriting it. ``` module my_hackathon_account::prototype { use std::string; use std::signer; // Resources: structs with 'key' ability that live in global storage // key = can be stored at account addresses (makes it a "resource") // store = can be stored inside other structs // drop = can be destroyed/discarded implicitly struct MessageHolder has key, store, drop { message: string::String, } entry fun set_message(account: &signer, message: string::String) acquires MessageHolder { let addr = signer::address_of(account); // The 'drop' ability allows implicit destruction if (exists(addr)) { move_from(addr); // Old resource is destroyed (requires 'drop') }; move_to(account, MessageHolder { message }); } #[view] public fun get_message(addr: address): string::String acquires MessageHolder { assert!(exists(addr), 0); // Read message stored at the user's address borrow_global(addr).message }} ``` Learn more: [`abilities`](https://aptos-labs.github.io/move-book/generics-and-abilities.html), [`structs and resources`](https://aptos-labs.github.io/move-book/structs-and-enums.html) Aptos packages support two upgrade policies: `compatible` (default; only backward-compatible changes allowed) and `immutable` (no upgrades allowed). By default, packages published with the [Aptos CLI](/build/cli) using `aptos move publish` use the **compatible** policy, which lets you push new versions as long as you don’t break struct layouts or public function signatures. To prevent all future upgrades, set the immutable policy: ``` aptos move publish --upgrade-policy immutable ``` Or configure in your `Move.toml`: ``` [package]name = "MyPackage"version = "1.0.0"upgrade_policy = "immutable" ``` See [Package Upgrades](https://aptos-labs.github.io/move-book/cli-deploy.html) for the exact compatibility rules. On Ethereum you “deploy a contract to a new address.” On Aptos you **publish a package** of Move modules to an account (or object) address using the [Aptos CLI](/build/cli). Publish your package: ``` aptos move publish ``` Call an `entry` function after deployment: ``` aptos move run --function-id 'your_address::module_name::function_name' ``` Both account-based publishing and object-based deployment (via `aptos move deploy-object`) respect the package’s upgrade policy. See [Your First Move Module](/build/guides/first-move-module) for a complete walkthrough and [Objects](/build/smart-contracts/objects) for object-centric patterns. # Your First Transaction > Create and submit your first transaction on Aptos blockchain - transfer coins between accounts with TypeScript, Python, Go, and Rust examples. Transactions are the fundamental way to change data on the Aptos blockchain. Think of them like sending a package: you need to specify what you’re sending, who it’s going to, and then track it until delivery is confirmed. In blockchain terms, transactions allow you to transfer APT, call smart contract functions, and update on-chain state. This tutorial will guide you through creating and submitting your first transaction on the Aptos blockchain. You’ll learn how to: 1. Set up your development environment 2. Create test accounts and fund them 3. Build a transaction to transfer APT 4. Simulate the transaction to estimate costs 5. Sign and submit the transaction 6. Verify the transaction was executed successfully ## 1\. Setting Up Your Environment [](#1-setting-up-your-environment) * [TypeScript](#tab-panel-4-0) * [Python](#tab-panel-4-1) Before we can create transactions, we need to set up our development environment with the necessary tools and SDKs. 1. Install the TypeScript SDK Install the TypeScript SDK using your preferred package manager: * [npm](#tab-panel-1-0) * [yarn](#tab-panel-1-1) * [pnpm](#tab-panel-1-2) ``` npm install @aptos-labs/ts-sdk ``` ``` yarn add @aptos-labs/ts-sdk ``` ``` pnpm add @aptos-labs/ts-sdk ``` 2. Create a project directory Create a new directory for your project: ``` mkdir my-first-transactioncd my-first-transaction ``` 3. Create a new file Create a new file named `transaction.ts`: * [Mac/Linux](#tab-panel-2-0) * [Windows](#tab-panel-2-1) ``` touch transaction.ts ``` ``` type nul > transaction.ts ``` Before we can create transactions, we need to set up our development environment with the necessary tools and SDKs. 1. Install the Python SDK Install the Python SDK using pip: ``` pip install aptos-sdk ``` 2. Create a project directory Create a new directory for your project: ``` mkdir my-first-transactioncd my-first-transaction ``` 3. Create a new file Create a new file named `transaction.py`: * [Mac/Linux](#tab-panel-3-0) * [Windows](#tab-panel-3-1) ``` touch transaction.py ``` ``` type nul > transaction.py ``` ## 2\. Creating Test Accounts [](#2-creating-test-accounts) * [TypeScript](#tab-panel-5-0) * [Python](#tab-panel-5-1) In blockchain, all transactions must come from an account. Let’s create two test accounts: one to send coins (Alice) and one to receive them (Bob). 1. Set up the client First, we need to initialize the Aptos client that will connect to the blockchain. Open `transaction.ts` in your editor and add: ``` import { Account, Aptos, AptosConfig, Network,} from "@aptos-labs/ts-sdk"; async function main() { // Initialize the Aptos client const config = new AptosConfig({ network: Network.DEVNET }); const aptos = new Aptos(config); console.log("Connected to Aptos devnet"); // More code will go here} main().catch(console.error); ``` 2. Generate accounts Add this code inside your `main()` function to create two accounts - Alice (sender) and Bob (receiver): ``` // Generate two accountsconst alice = Account.generate();const bob = Account.generate(); console.log("=== Addresses ===");console.log(`Alice's address: ${alice.accountAddress}`);console.log(`Bob's address: ${bob.accountAddress}`); ``` 3. Fund the accounts Add this code after generating the accounts to get test coins from the faucet: ``` // Fund the accounts with test APT from the devnet faucetconsole.log("\n=== Funding accounts ===");await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100_000_000, // 1 APT = 100,000,000 octas});console.log("Accounts funded successfully"); // Check initial balancesconst aliceBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress,});const bobBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress,}); console.log("\n=== Initial Balances ===");console.log(`Alice: ${aliceBalance} octas`);console.log(`Bob: ${bobBalance} octas`); ``` 4. Run the code Let’s test our code so far: ``` npx ts-node transaction.ts ``` You should see output similar to: ``` Connected to Aptos devnet=== Addresses ===Alice's address: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaBob's address: 0x7af2d6c93a2feafc9b69b5e8ad9d6b513b260f62f23f3a384a3a2e4a84694a9b === Funding accounts ===Accounts funded successfully === Initial Balances ===Alice: 100000000 octasBob: 0 octas ``` In blockchain, all transactions must come from an account. Let’s create two test accounts: one to send APT (Alice) and one to receive them (Bob). 1. Set up the client First, we need to initialize the Aptos client that will connect to the blockchain. Open `transaction.py` in your editor and add: ``` import asynciofrom aptos_sdk.account import Accountfrom aptos_sdk.async_client import FaucetClient, RestClientfrom aptos_sdk.transactions import EntryFunction, TransactionPayload, TransactionArgument, RawTransactionfrom aptos_sdk.bcs import Serializerimport time # Network configurationNODE_URL = "https://fullnode.devnet.aptoslabs.com/v1"FAUCET_URL = "https://faucet.devnet.aptoslabs.com" async def main(): # Initialize the clients rest_client = RestClient(NODE_URL) faucet_client = FaucetClient(FAUCET_URL, rest_client) print("Connected to Aptos devnet") # More code will go here if __name__ == "__main__": asyncio.run(main()) ``` 2. Generate accounts Add this code inside your `main()` function to create two accounts - Alice (sender) and Bob (receiver): ``` # Generate two accountsalice = Account.generate()bob = Account.generate() print("=== Addresses ===")print(f"Alice's address: {alice.address()}")print(f"Bob's address: {bob.address()}") ``` 3. Fund the accounts Add this code after generating the accounts to get test coins from the faucet: ``` # Fund the accounts with test APT from the devnet faucetprint("\n=== Funding accounts ===")alice_amount = 100_000_000 # 1 APT = 100,000,000 octasbob_amount = 0 # Bob starts with 0 APT await faucet_client.fund_account(alice.address(), alice_amount)print("Account funded successfully") # Check initial balancesalice_balance = await rest_client.account_balance(alice.address())bob_balance = await rest_client.account_balance(bob.address()) print("\n=== Initial Balances ===")print(f"Alice: {alice_balance} octas")print(f"Bob: {bob_balance} octas") ``` 4. Run the code Let’s test our code so far: ``` python transaction.py ``` You should see output similar to: ``` Connected to Aptos devnet=== Addresses ===Alice's address: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaBob's address: 0x7af2d6c93a2feafc9b69b5e8ad9d6b513b260f62f23f3a384a3a2e4a84694a9b === Funding accounts ===Accounts funded successfully === Initial Balances ===Alice: 100000000 octasBob: 0 octas ``` ## 3\. Building a Transaction [](#3-building-a-transaction) * [TypeScript](#tab-panel-6-0) * [Python](#tab-panel-6-1) Now that we have funded accounts, let’s create a transaction to transfer APT from Alice to Bob. This is like filling out a form specifying what you want to send and to whom. 1. Understand transaction structure A transaction in Aptos has several key components: 1. **Sender**: The account initiating the transaction (Alice) 2. **Function**: The on-chain function to call (in this case, an APT transfer) 3. **Arguments**: Data needed by the function (recipient address and amount) 4. **Gas parameters**: Maximum gas amount and gas unit price 5. **Expiration time**: When the transaction is no longer valid if not executed 6. **Sequence number**: A counter that prevents replay attacks. For parallel submission from multiple machines, Aptos also supports [orderless transactions](/build/guides/orderless-transactions) that use a nonce instead. 2. Build the transaction Let’s add code to build a transaction that transfers 1000 octas from Alice to Bob: Add this code to your `main()` function: ``` // 1. Build the transactionconsole.log("\n=== 1. Building the transaction ===");const transaction = await aptos.transaction.build.simple({ sender: alice.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [bob.accountAddress, 1000], // Transfer 1000 octas },});console.log("Transaction built successfully"); // Access transaction details from the raw transactionconst rawTxn = transaction.rawTransaction;console.log(`Sender: ${rawTxn.sender}`);console.log(`Sequence Number: ${rawTxn.sequence_number}`);console.log(`Max Gas Amount: ${rawTxn.max_gas_amount}`);console.log(`Gas Unit Price: ${rawTxn.gas_unit_price}`);console.log(`Expiration Timestamp: ${new Date(Number(rawTxn.expiration_timestamp_secs) * 1000).toISOString()}`); ``` Now that we have funded accounts, let’s create a transaction to transfer APT from Alice to Bob. This is like filling out a form specifying what you want to send and to whom. 1. Understand transaction structure A transaction in Aptos has several key components: 1. **Sender**: The account initiating the transaction (Alice) 2. **Function**: The on-chain function to call (in this case, an APT transfer) 3. **Arguments**: Data needed by the function (recipient address and amount) 4. **Gas parameters**: Maximum gas amount and gas unit price 5. **Expiration time**: When the transaction is no longer valid if not executed 6. **Sequence number**: A counter that prevents replay attacks. For parallel submission from multiple machines, Aptos also supports [orderless transactions](/build/guides/orderless-transactions) that use a nonce instead. 2. Build the transaction Add the following code to your `main()` function to build a transaction that transfers 1000 octas from Alice to Bob: ``` # 1. Build the transactionprint("\n=== 1. Building the transaction ===") # Create the entry function payload# This specifies which function to call and with what argumentsentry_function = EntryFunction.natural( "0x1::aptos_account", # Module address and name "transfer", # Function name [], # Type arguments (empty for this function) [ # Function arguments with their serialization type TransactionArgument(bob.address(), Serializer.struct), # Recipient address TransactionArgument(1000, Serializer.u64), # Amount to transfer (1000 octas) ],) # Get the chain ID for the transactionchain_id = await rest_client.chain_id() # Get the sender's current sequence numberaccount_data = await rest_client.account(alice.address())sequence_number = int(account_data["sequence_number"]) # Create the raw transaction with all required fieldsraw_transaction = RawTransaction( sender=alice.address(), # Sender's address sequence_number=sequence_number, # Sequence number to prevent replay attacks payload=TransactionPayload(entry_function), # The function to call max_gas_amount=2000, # Maximum gas units to use gas_unit_price=100, # Price per gas unit in octas expiration_timestamps_secs=int(time.time()) + 600, # Expires in 10 minutes chain_id=chain_id, # Chain ID to ensure correct network) print("Transaction built successfully")print(f"Sender: {raw_transaction.sender}")print(f"Sequence Number: {raw_transaction.sequence_number}")print(f"Max Gas Amount: {raw_transaction.max_gas_amount}")print(f"Gas Unit Price: {raw_transaction.gas_unit_price}")print(f"Expiration Timestamp: {time.ctime(raw_transaction.expiration_timestamps_secs)}") ``` ## 4\. Simulating the Transaction [](#4-simulating-the-transaction) * [TypeScript](#tab-panel-7-0) * [Python](#tab-panel-7-1) Before submitting a transaction, it’s wise to simulate it first to estimate the gas cost. This is like checking shipping costs before sending a package. 1. Simulate the transaction Add this code after building the transaction: ``` // 2. Simulate the transactionconsole.log("\n=== 2. Simulating the transaction ===");const [simulationResult] = await aptos.transaction.simulate.simple({ signerPublicKey: alice.publicKey, transaction,}); const gasUsed = parseInt(simulationResult.gas_used);const gasUnitPrice = parseInt(simulationResult.gas_unit_price);console.log(`Estimated gas units: ${gasUsed}`);console.log(`Estimated gas cost: ${gasUsed * gasUnitPrice} octas`);console.log(`Transaction would ${simulationResult.success ? "succeed" : "fail"}`); ``` Before submitting a transaction, it’s wise to simulate it first to estimate the gas cost. This is like checking shipping costs before sending a package. 1. Simulate the transaction Add this code after building the transaction: ``` # 2. Simulate the transactionprint("\n=== 2. Simulating the transaction ===") # Create a BCS transaction for simulation# This doesn't actually submit the transaction to the blockchainsimulation_transaction = await rest_client.create_bcs_transaction(alice, TransactionPayload(entry_function)) # Simulate the transaction to estimate gas costs and check for errorssimulation_result = await rest_client.simulate_transaction(simulation_transaction, alice) # Extract and display the simulation resultsgas_used = int(simulation_result[0]['gas_used'])gas_unit_price = int(simulation_result[0]['gas_unit_price'])success = simulation_result[0]['success'] print(f"Estimated gas units: {gas_used}")print(f"Estimated gas cost: {gas_used * gas_unit_price} octas")print(f"Transaction would {'succeed' if success else 'fail'}") ``` ## 5\. Signing and Submitting the Transaction [](#5-signing-and-submitting-the-transaction) * [TypeScript](#tab-panel-8-0) * [Python](#tab-panel-8-1) Now that we’ve built and simulated the transaction, we need to sign it with Alice’s private key and submit it to the blockchain. 1. Sign the transaction Signing proves that Alice authorized this transaction: Add this code after simulating the transaction: ``` // 3. Sign the transactionconsole.log("\n=== 3. Signing the transaction ===");const senderAuthenticator = aptos.transaction.sign({ signer: alice, transaction,});console.log("Transaction signed successfully"); ``` 2. Submit the transaction Add this code after signing the transaction to submit the signed transaction to the blockchain: ``` // 4. Submit the transactionconsole.log("\n=== 4. Submitting the transaction ===");const pendingTransaction = await aptos.transaction.submit.simple({ transaction, senderAuthenticator,});console.log(`Transaction submitted with hash: ${pendingTransaction.hash}`); ``` Now that we’ve built and simulated the transaction, we need to sign it with Alice’s private key and submit it to the blockchain. 1. Sign the transaction Signing proves that Alice authorized this transaction: Add this code after simulating the transaction: ``` # 3. Sign the transactionprint("\n=== 3. Signing the transaction ===") # Sign the raw transaction with the sender's private key# This creates a cryptographic signature that proves the sender authorized this transactionsigned_transaction = await rest_client.create_bcs_signed_transaction( alice, # Account with the private key TransactionPayload(entry_function), # The payload from our transaction sequence_number=sequence_number # Use the same sequence number as before) print("Transaction signed successfully")# We can't easily extract the signature from the signed transaction object,# but we can confirm it was created ``` 2. Submit the transaction Add this code after signing the transaction to submit the signed transaction to the blockchain: ``` # 4. Submit the transactionprint("\n=== 4. Submitting the transaction ===") # Submit the signed transaction to the blockchain# This broadcasts the transaction to the network for processingtx_hash = await rest_client.submit_bcs_transaction(signed_transaction) print(f"Transaction submitted with hash: {tx_hash}") ``` ## 6\. Waiting for Confirmation [](#6-waiting-for-confirmation) * [TypeScript](#tab-panel-9-0) * [Python](#tab-panel-9-1) After submitting a transaction, we need to wait for it to be processed by the blockchain. This is like waiting for a package to be delivered. 1. Wait for transaction completion Add this code after submitting the transaction: ``` // 5. Wait for the transaction to completeconsole.log("\n=== 5. Waiting for transaction completion ===");const txnResult = await aptos.waitForTransaction({ transactionHash: pendingTransaction.hash,});console.log(`Transaction completed with status: ${txnResult.success ? "SUCCESS" : "FAILURE"}`); // If you want to see more details about the transaction:console.log(`VM Status: ${txnResult.vm_status}`);console.log(`Gas used: ${txnResult.gas_used}`); ``` 2. Verify the results Add this code after waiting for the transaction to check the balances and confirm the transfer worked: ``` // Check final balancesconst aliceFinalBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress,});const bobFinalBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress,}); console.log("\n=== Final Balances ===");console.log(`Alice: ${aliceFinalBalance} octas (spent ${aliceBalance - aliceFinalBalance} octas on transfer and gas)`);console.log(`Bob: ${bobFinalBalance} octas (received 1000 octas)`); ``` 3. Run the complete code ``` npx ts-node transaction.ts ``` You should see output similar to: ``` Connected to Aptos devnet=== Addresses ===Alice's address: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaBob's address: 0x7af2d6c93a2feafc9b69b5e8ad9d6b513b260f62f23f3a384a3a2e4a84694a9b === Funding accounts ===Accounts funded successfully === Initial Balances ===Alice: 100000000 octasBob: 0 octas === 1. Building the transaction ===Transaction built successfullySender: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaSequence Number: 0Max Gas Amount: 20000Gas Unit Price: 100Expiration Timestamp: 2025-03-05T22:59:21.000Z === 2. Simulating the transaction ===Estimated gas units: 146Estimated gas cost: 14600 octasTransaction would succeed === 3. Signing the transaction ===Transaction signed successfully === 4. Submitting the transaction ===Transaction submitted with hash: 0x3a8a3e34a1c64ad9d7636a3a827b7ec3bb12d73825b36fa06d425c5a3b42cccc === 5. Waiting for transaction completion ===Transaction completed with status: SUCCESSVM Status: Executed successfullyGas used: 146 === Final Balances ===Alice: 99984400 octas (spent 15600 octas on transfer and gas)Bob: 1000 octas (received 1000 octas) ``` After submitting a transaction, we need to wait for it to be processed by the blockchain. This is like waiting for a package to be delivered. 1. Wait for transaction completion Add this code after submitting the transaction: ``` # 5. Wait for the transaction to completeprint("\n=== 5. Waiting for transaction completion ===") # Wait for the transaction to be processed by the blockchain# This polls the blockchain until the transaction is confirmedawait rest_client.wait_for_transaction(tx_hash) # Get the transaction details to check its statustransaction_details = await rest_client.transaction_by_hash(tx_hash)success = transaction_details["success"]vm_status = transaction_details["vm_status"]gas_used = transaction_details["gas_used"] print(f"Transaction completed with status: {'SUCCESS' if success else 'FAILURE'}")print(f"VM Status: {vm_status}")print(f"Gas used: {gas_used}") ``` 2. Verify the results Add this code after waiting for the transaction to check the balances and confirm the transfer worked: ``` # Check final balancesalice_final_balance = await rest_client.account_balance(alice.address())bob_final_balance = await rest_client.account_balance(bob.address()) print("\n=== Final Balances ===")print(f"Alice: {alice_final_balance} octas (spent {alice_balance - alice_final_balance} octas on transfer and gas)")print(f"Bob: {bob_final_balance} octas (received 1000 octas)") ``` 3. Run the complete code ``` python transaction.py ``` You should see output similar to: ``` Connected to Aptos devnet=== Addresses ===Alice's address: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaBob's address: 0x7af2d6c93a2feafc9b69b5e8ad9d6b513b260f62f23f3a384a3a2e4a84694a9b === Funding accounts ===Accounts funded successfully === Initial Balances ===Alice: 100000000 octasBob: 0 octas === 1. Building the transaction ===Transaction built successfullySender: 0x978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aaSequence Number: 0Max Gas Amount: 2000Gas Unit Price: 100Expiration Timestamp: Wed Mar 05 22:59:21 2025 === 2. Simulating the transaction ===Estimated gas units: 146Estimated gas cost: 14600 octasTransaction would succeed === 3. Signing the transaction ===Transaction signed successfully === 4. Submitting the transaction ====== 3. Signing the transaction ===Transaction signed successfully === 4. Submitting the transaction ===Transaction submitted with hash: 0x3a8a3e34a1c64ad9d7636a3a827b7ec3bb12d73825b36fa06d425c5a3b42cccc === 5. Waiting for transaction completion ===Transaction completed with status: SUCCESSVM Status: Executed successfullyGas used: 146 === Final Balances ===Alice: 99984400 octas (spent 15600 octas on transfer and gas)Bob: 1000 octas (received 1000 octas) ``` ## 7\. (Optional) Explore Your Transaction On-Chain [](#7-optional-explore-your-transaction-on-chain) Now that you’ve successfully executed a transaction, you can explore it on the Aptos Explorer. This will help you understand how transactions are recorded on the blockchain and what information is publicly available. 1. Copy your transaction hash From your terminal output, copy the transaction hash that was printed after submission. It looks something like this: ``` Transaction submitted with hash: 0x3a8a3e34a1c64ad9d7636a3a827b7ec3bb12d73825b36fa06d425c5a3b42cccc ``` 2. Open the Aptos Explorer Go to the [Aptos Explorer](https://explorer.aptoslabs.com/?network=devnet). 3. Ensure you are on Devnet network Look for “Devnet” in the top right corner, or switch networks by clicking the dropdown and selecting Devnet. ![Switching to Devnet network in Aptos Explorer](/_vercel/image?url=_astro%2Fexplorer_devnet.D3PWblc6.png&w=320&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) 4. Search for your transaction Paste your transaction hash into the search bar in the middle of the page. Caution Do not press enter! There is a known bug where searching with Enter does not work. 5. View the transaction details Wait for the results to appear, then click on the transaction hash to view its details. You should see information about your transaction, including: * Status (should be “Success”) * Timestamp * Gas used * Sender and recipient addresses * Amount transferred 6. Explore further From the transaction details page, you can: * Click on the sender or recipient addresses to view their account details * See the exact changes made to the blockchain state * View the transaction payload and arguments ## 8\. Next Steps [](#8-next-steps) Congratulations! You’ve successfully created and executed your first transaction on the Aptos blockchain. Here are some suggestions for what to explore next: **Learn about more complex transactions**: * [TypeScript SDK](/build/sdks/ts-sdk/building-transactions) — [multi-agent](/build/sdks/ts-sdk/building-transactions/multi-agent-transactions), [sponsored](/build/sdks/ts-sdk/building-transactions/sponsoring-transactions), [batching](/build/sdks/ts-sdk/building-transactions/batching-transactions) * [Python SDK](/build/sdks/python-sdk/building-transactions) — [multi-agent](/build/sdks/python-sdk/building-transactions/multi-agent-transactions), [sponsored](/build/sdks/python-sdk/building-transactions/sponsoring-transactions), [batching](/build/sdks/python-sdk/building-transactions/batching-transactions) * [Go SDK](/build/sdks/go-sdk/building-transactions) — [multi-agent](/build/sdks/go-sdk/building-transactions/multi-agent-transactions), [sponsored](/build/sdks/go-sdk/building-transactions/sponsoring-transactions), [batching](/build/sdks/go-sdk/building-transactions/batching-transactions) * [Rust SDK](/build/sdks/rust-sdk/building-transactions) — [multi-agent](/build/sdks/rust-sdk/building-transactions/multi-agent-transactions), [sponsored](/build/sdks/rust-sdk/building-transactions/sponsoring-transactions), [batching](/build/sdks/rust-sdk/building-transactions/batching-transactions) **Explore smart contracts or account basics**: * [Your First Move Module](/build/guides/first-move-module) - Create your own smart contract * [Account Basics](/network/blockchain/accounts) [Join the Aptos Discord](https://discord.gg/aptoslabs) and share what you’re building! ## Full Code Sample [](#full-code-sample) The complete code samples below combine all the snippets we’ve covered in this tutorial: * [TypeScript](#tab-panel-10-0) * [Python](#tab-panel-10-1) ``` import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; async function main() { // Initialize the Aptos client const config = new AptosConfig({ network: Network.DEVNET }); const aptos = new Aptos(config); console.log("Connected to Aptos devnet"); // More code will go here // Generate two accounts const alice = Account.generate(); const bob = Account.generate(); console.log("=== Addresses ==="); console.log(`Alice's address: ${alice.accountAddress}`); console.log(`Bob's address: ${bob.accountAddress}`); // Fund the accounts with test APT from the devnet faucet console.log("\n=== Funding accounts ==="); await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100_000_000, // 1 APT = 100,000,000 octas }); await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 0, // Bob starts with 0 APT }); console.log("Accounts funded successfully"); // Check initial balances const aliceBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress, }); const bobBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress, }); console.log("\n=== Initial Balances ==="); console.log(`Alice: ${aliceBalance} octas`); console.log(`Bob: ${bobBalance} octas`); // 1. Build the transaction console.log("\n=== 1. Building the transaction ==="); const transaction = await aptos.transaction.build.simple({ sender: alice.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [bob.accountAddress, 1000], // Transfer 1000 octas }, }); console.log("Transaction built successfully"); // Use type assertion to bypass TypeScript's type checking const txnAny = transaction as any; console.log(`Sender: ${alice.accountAddress}`); // Use the known sender address console.log(`Sequence Number: ${txnAny.sequenceNumber || "N/A"}`); console.log(`Max Gas Amount: ${txnAny.maxGasAmount || "N/A"}`); console.log(`Gas Unit Price: ${txnAny.gasUnitPrice || "N/A"}`); console.log( `Expiration Timestamp: ${new Date( Number(txnAny.expirationTimestampSecs || 0) * 1000 ).toISOString()}` ); // 2. Simulate the transaction console.log("\n=== 2. Simulating the transaction ==="); const [simulationResult] = await aptos.transaction.simulate.simple({ signerPublicKey: alice.publicKey, transaction, }); console.log(`Estimated gas units: ${simulationResult.gas_used}`); console.log( `Estimated gas cost: ${ Number(simulationResult.gas_used) * Number(simulationResult.gas_unit_price) } octas` ); console.log( `Transaction would ${simulationResult.success ? "succeed" : "fail"}` ); // 3. Sign the transaction console.log("\n=== 3. Signing the transaction ==="); const senderAuthenticator = aptos.transaction.sign({ signer: alice, transaction, }); console.log("Transaction signed successfully"); // Use type assertion to bypass TypeScript's type checking const authAny = senderAuthenticator as any; const signatureStr = typeof authAny.signature === 'string' ? authAny.signature : JSON.stringify(authAny.signature || ''); console.log(`Signature: ${signatureStr.slice(0, 20)}...`); // 4. Submit the transaction console.log("\n=== 4. Submitting the transaction ==="); const pendingTransaction = await aptos.transaction.submit.simple({ transaction, senderAuthenticator, }); console.log(`Transaction submitted with hash: ${pendingTransaction.hash}`); // 5. Wait for the transaction to complete console.log("\n=== 5. Waiting for transaction completion ==="); const txnResult = await aptos.waitForTransaction({ transactionHash: pendingTransaction.hash, }); console.log( `Transaction completed with status: ${ txnResult.success ? "SUCCESS" : "FAILURE" }` ); // If you want to see more details about the transaction: console.log(`VM Status: ${txnResult.vm_status}`); console.log(`Gas used: ${txnResult.gas_used}`); // Check final balances const aliceFinalBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress, }); const bobFinalBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress, }); console.log("\n=== Final Balances ==="); console.log( `Alice: ${aliceFinalBalance} octas (spent ${ aliceBalance - aliceFinalBalance } octas on transfer and gas)` ); console.log(`Bob: ${bobFinalBalance} octas (received 1000 octas)`);} main().catch(console.error); ``` ``` import asynciofrom aptos_sdk.account import Accountfrom aptos_sdk.async_client import FaucetClient, RestClientfrom aptos_sdk.transactions import EntryFunction, TransactionPayload, TransactionArgument, RawTransactionfrom aptos_sdk.bcs import Serializerimport time # Network configurationNODE_URL = "https://fullnode.devnet.aptoslabs.com/v1"FAUCET_URL = "https://faucet.devnet.aptoslabs.com" async def main(): # Initialize the clients rest_client = RestClient(NODE_URL) faucet_client = FaucetClient(FAUCET_URL, rest_client) print("Connected to Aptos devnet") # Generate two accounts alice = Account.generate() bob = Account.generate() print("=== Addresses ===") print(f"Alice's address: {alice.address()}") print(f"Bob's address: {bob.address()}") # More code will go here # Fund the accounts with test APT from the devnet faucet print("\n=== Funding accounts ===") alice_amount = 100_000_000 # 1 APT = 100,000,000 octas bob_amount = 0 # Bob starts with 0 APT await faucet_client.fund_account(alice.address(), alice_amount) await faucet_client.fund_account(bob.address(), bob_amount) print("Accounts funded successfully") # Check initial balances alice_balance = await rest_client.account_balance(alice.address()) bob_balance = await rest_client.account_balance(bob.address()) print("\n=== Initial Balances ===") print(f"Alice: {alice_balance} octas") print(f"Bob: {bob_balance} octas") # 1. Build the transaction print("\n=== 1. Building the transaction ===") # Create the entry function payload # This specifies which function to call and with what arguments entry_function = EntryFunction.natural( "0x1::aptos_account", # Module address and name "transfer", # Function name [], # Type arguments (empty for this function) [ # Function arguments with their serialization type TransactionArgument(bob.address(), Serializer.struct), # Recipient address TransactionArgument(1000, Serializer.u64), # Amount to transfer (1000 octas) ], ) # Get the chain ID for the transaction chain_id = await rest_client.chain_id() # Get the sender's current sequence number account_data = await rest_client.account(alice.address()) sequence_number = int(account_data["sequence_number"]) # Create the raw transaction with all required fields raw_transaction = RawTransaction( sender=alice.address(), # Sender's address sequence_number=sequence_number, # Sequence number to prevent replay attacks payload=TransactionPayload(entry_function), # The function to call max_gas_amount=2000, # Maximum gas units to use gas_unit_price=100, # Price per gas unit in octas expiration_timestamps_secs=int(time.time()) + 600, # Expires in 10 minutes chain_id=chain_id, # Chain ID to ensure correct network ) print("Transaction built successfully") print(f"Sender: {raw_transaction.sender}") print(f"Sequence Number: {raw_transaction.sequence_number}") print(f"Max Gas Amount: {raw_transaction.max_gas_amount}") print(f"Gas Unit Price: {raw_transaction.gas_unit_price}") print(f"Expiration Timestamp: {time.ctime(raw_transaction.expiration_timestamps_secs)}") # 2. Simulate the transaction print("\n=== 2. Simulating the transaction ===") # Create a BCS transaction for simulation # This doesn't actually submit the transaction to the blockchain simulation_transaction = await rest_client.create_bcs_transaction(alice, TransactionPayload(entry_function)) # Simulate the transaction to estimate gas costs and check for errors simulation_result = await rest_client.simulate_transaction(simulation_transaction, alice) # Extract and display the simulation results gas_used = int(simulation_result[0]['gas_used']) gas_unit_price = int(simulation_result[0]['gas_unit_price']) success = simulation_result[0]['success'] print(f"Estimated gas units: {gas_used}") print(f"Estimated gas cost: {gas_used * gas_unit_price} octas") print(f"Transaction would {'succeed' if success else 'fail'}") # 3. Sign the transaction print("\n=== 3. Signing the transaction ===") # Sign the raw transaction with the sender's private key # This creates a cryptographic signature that proves the sender authorized this transaction signed_transaction = await rest_client.create_bcs_signed_transaction( alice, # Account with the private key TransactionPayload(entry_function), # The payload from our transaction sequence_number=sequence_number # Use the same sequence number as before ) print("Transaction signed successfully") # We can't easily extract the signature from the signed transaction object, # but we can confirm it was created # 4. Submit the transaction print("\n=== 4. Submitting the transaction ===") # Submit the signed transaction to the blockchain # This broadcasts the transaction to the network for processing tx_hash = await rest_client.submit_bcs_transaction(signed_transaction) print(f"Transaction submitted with hash: {tx_hash}") # 5. Wait for the transaction to complete print("\n=== 5. Waiting for transaction completion ===") # Wait for the transaction to be processed by the blockchain # This polls the blockchain until the transaction is confirmed await rest_client.wait_for_transaction(tx_hash) # Get the transaction details to check its status transaction_details = await rest_client.transaction_by_hash(tx_hash) success = transaction_details["success"] vm_status = transaction_details["vm_status"] gas_used = transaction_details["gas_used"] print(f"Transaction completed with status: {'SUCCESS' if success else 'FAILURE'}") print(f"VM Status: {vm_status}") print(f"Gas used: {gas_used}") # Check final balances alice_final_balance = await rest_client.account_balance(alice.address()) bob_final_balance = await rest_client.account_balance(bob.address()) print("\n=== Final Balances ===") print(f"Alice: {alice_final_balance} octas (spent {alice_balance - alice_final_balance} octas on transfer and gas)") print(f"Bob: {bob_final_balance} octas (received 1000 octas)")if __name__ == "__main__": asyncio.run(main()) ``` # Payments on Aptos > Build payments on Aptos: latency, fees, transfers, confidential transfers, sponsored and orderless options, and multi-agent two-party agreement. Aptos is a Layer 1 settlement rail for moving APT, [stablecoins](/build/guides/exchanges#stablecoin-addresses), and other [fungible assets](/build/smart-contracts/fungible-asset). A successful payment is **final as soon as the transaction commits** (BFT consensus, no extra block confirmations). This page separates block time, end-to-end latency, finality, and fees, then maps those onto ordinary transfers, confidential transfers, and other payment flows. A payment can be a **one-sided send** (the payer signs; the recipient does not) or a **[multi-agent](#two-party-agreement-multi-agent) transaction** that both parties sign so they agree in one atomic commit. [Sponsored](/build/guides/sponsored-transactions) (another account pays gas) and [orderless](/build/guides/orderless-transactions) (nonce instead of a sequence number, parallel submit) options compose with either shape. ## Latency, block time, and fees [](#latency-block-time-and-fees) These four numbers answer different questions. Do not treat block time as the time a user waits for a payment. graph LR submit\["1. Client submits"\] --> mempool\["2. Mempool"\] mempool --> block\["3. Block proposed"\] block --> exec\["4. Execute"\] exec --> commit\["5. Commit"\] commit --> wait\["6. Client observes"\]
MetricWhat it measuresTypical mainnet valueWhere to verify
Block timeInterval between consecutive blocksTens of milliseconds. Aptos does not use a fixed slot clock; live timestamps are often under 50 msBlocks, Explorer
FinalityWhen a committed result cannot be reversedImmediate on commit. No confirmation depth, no reorg window. A failed transaction is still final; it did not move fundsTransactions and States
End-to-end (E2E) latencyClient submit → committed and returned by waitForTransactionTypically sub-second under normal load. Includes client RTT to a fullnode, mempool, consensus, execution, and polling. Build, sign, and proof generation happen before submit and are not in this numberAlways call waitForTransaction after submit
Transaction feeAPT charged to the fee payerNet charge is gas_used × gas_unit_price − storage_refund in octas. Storage is already folded into gas_used. Independent of the amount transferredGas and Storage Fees, simulate
### Block time [](#block-time) Validators propose the next block as soon as network delay allows. Mainnet block times are typically tens of milliseconds. That is how fast the chain packages transactions, not how long a wallet should wait before showing “paid.” See [Blocks](/network/blockchain/blocks) and [Execution](/network/blockchain/execution) (Block-STM). ### End-to-end latency [](#end-to-end-latency) On this page, **E2E latency** is the clock from **submit** to `waitForTransaction` returning a committed transaction. That wait is typically under a second for a simple payment. Work that happens **before** submit is separate and can dominate the user’s clock: * Build, optional simulation, and sign. * Confidential-asset proof generation, collecting multisig signatures, or encrypting a pending payload. Submit is not settlement. A 202 and a hash mean the node **accepted** the transaction. Poll with `waitForTransaction`, then check `success === true` before treating the payment as completed. A committed failed transaction is still [final](#finality) (it will not reverse), but the transfer did not happen. ### Finality [](#finality) Aptos uses BFT consensus. A committed transaction is final, whether it succeeded or aborted. You do not wait for additional blocks the way you would on a probabilistic-finality chain. See the [exchange FAQ on finality](/build/guides/exchanges#what-is-the-finality-of-a-transaction) and the [transaction lifecycle](/network/blockchain/blockchain-deep-dive). ### Transaction fees [](#transaction-fees) Fees have two parts, both documented in [Gas and Storage Fees](/network/blockchain/gas-txn-fee). Today the client still sees them combined in `gas_used`: 1. **Execution and IO** — gas units × `gas_unit_price` (octas). The unit price can rise under load; a higher price only helps the transaction **enter** the next block, not its order inside the block. 2. **Storage** — fixed APT for new or grown state slots (for example, the first time a recipient holds a given fungible asset). That amount is converted into gas units at the transaction’s `gas_unit_price` and included in `gas_used`. A deletion can later credit a `storage_refund` that is **not** inside `gas_used`. Net APT moved from the payer is `gas_used × gas_unit_price − storage_refund`. A 1 APT transfer and a 1,000,000 APT transfer with the same payload cost about the same in gas. Average mainnet fees sit at a **fraction of a US cent** (on the order of 0.0005 USD in public network figures; treat USD as order-of-magnitude only). Simple APT and fungible-asset transfers are among the cheapest transactions. Always [simulate](/network/blockchain/gas-txn-fee#estimating-gas-consumption-via-simulation) for the exact payload you will submit. To hide APT from end users, use a [sponsored transaction](/build/guides/sponsored-transactions) or a [Geomi Gas Station](https://geomi.dev/docs/gas-stations). ## Payments by usage [](#payments-by-usage) Use this table to pick an API and to see how latency and fees change. Confidential transfers are summarized here only; the protocol details live on the Confidential Asset pages. Sponsored, orderless, and multi-agent are transaction-layer options that compose with every row — see [Compose every payment](#compose-every-payment).
UsageTypical on-chain E2EExtra client workFee profileImplement
APT transferSub-second after submitSign, submit, waitLowest. Amount-independent0x1::aptos_account::transfer
Fungible asset / stablecoin transferSame as APTSign, submit, waitSimilar to APT. Storage if the recipient has no primary store yet0x1::primary_fungible_store::transfer
Confidential transferSame commit path; more execution and a larger payloadGenerate ZK proofs before submitHigher than a plaintext transferConfidential Asset (do not implement from this page)
Encrypted pending payloadSame once committedEncrypt at build timeMinimum gas_unit_price of 200 octas (twice the usual floor)Encrypted Pending Transactions
Treasury / policyExtra round-trips for approvalsCollect N-of-M signaturesOne execution fee after approvalYour First Multisig
Passwordless onboardingSame as the inner transferOIDC / Keyless flowSame as the inner transferAptos Keyless
Two-party agreementSame as the inner transfer after all signaturesCollect a signature from each agentSame on-chain cost as the inner callMulti-agent transactions
Peer-to-peer swapSame after both signaturesBoth parties sign the same payloadGas of both legs in one transactionP2P swap
Batch payouts (payroll, disbursements) can use `0x1::aptos_account::batch_transfer` / `batch_transfer_coins` so one transaction pays many recipients. That raises gas with the number of outputs but still keeps a single E2E wait. ## Compose every payment [](#compose-every-payment) A payment is the Move call (APT, FA, confidential, NFT, …). These three options attach at the transaction layer and can be combined with each other: 1. **[Sponsored](/build/guides/sponsored-transactions)** — another account pays gas. Build with `withFeePayer: true`; the sender calls `.sign` and the sponsor calls `.signAsFeePayer`. Same on-chain cost; the fee payer is charged instead of the sender. [Geomi Gas Station](https://geomi.dev/docs/gas-stations) is a hosted fee payer. 2. **[Orderless](/build/guides/orderless-transactions)** (AIP-123) — pass a unique `replayProtectionNonce` instead of a sequence number so one account can submit many payments in parallel (payroll, hot wallets). Orderless transactions expire after at most 60 seconds. Sequence-number workers remain the default; see [Transaction Management](/build/guides/transaction-management). 3. **[Multi-agent](#two-party-agreement-multi-agent)** — every listed account signs **one** transaction so both parties agree, rather than one side sending to the other. Requires a Move entry function with multiple `&signer` arguments. Distinct from **multisig** (N-of-M control of a single account).
PaymentSponsoredOrderlessMulti-agent (both parties agree)
APTFee payer covers gas so transferred APT is not reducedParallel sends from one hot walletCustom two-signer swap, not aptos_account::transfer
FA / stablecoinUser holds the FA; the app pays APT gasSame parallel submitP2P swap: both sign one entry that moves both assets
ConfidentialCA client withFeePayer: true (global or per call)Nonce if you build the CA payload yourselfStandard CA transfer is one-sided; two-party needs a custom contract
Encrypted pendingCombinable (withFeePayer: true)Combinable (replayProtectionNonce)Combinable (build.multiAgent)
NFT / objectSame fee-payer pattern as APT or FASame parallel submitBoth parties sign an object-for-token transfer
Treasury / multisigSponsor can pay gas after N-of-M approvalParallel treasury operationsDifferent tool: two accounts, not several keys on one account
KeylessSponsor gas so a new user never holds APTSame nonce option as any other senderKeyless account can be sender or secondary signer
Sponsored and orderless flags on a one-sided APT (or FA) transfer: ``` const transaction = await aptos.transaction.build.simple({ sender: sender.accountAddress, withFeePayer: true, data: { function: "0x1::aptos_account::transfer", functionArguments: [recipientAddress, amountInOctas], }, options: { replayProtectionNonce: nonce, // unique u64; omit this field to use a sequence number },}); const senderAuthenticator = aptos.transaction.sign({ signer: sender, transaction });const feePayerAuthenticator = aptos.transaction.signAsFeePayer({ signer: feePayer, transaction });const committed = await aptos.transaction.submit.simple({ transaction, senderAuthenticator, feePayerAuthenticator,}); ``` Swap the `function` (and arguments) for an FA transfer. For a two-party payment, use `build.multiAgent` / `submit.multiAgent` and keep `withFeePayer` and `replayProtectionNonce` as above. Full walkthroughs: [sponsoring](/build/sdks/ts-sdk/building-transactions/sponsoring-transactions), [orderless](/build/sdks/ts-sdk/building-transactions/orderless-transactions), [multi-agent](/build/sdks/ts-sdk/building-transactions/multi-agent-transactions). ## APT transfers [](#apt-transfers) Transfer native APT with `0x1::aptos_account::transfer`. The function creates the recipient account resource when needed. ``` const transaction = await aptos.transaction.build.simple({ sender: sender.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [recipientAddress, amountInOctas], },}); const committed = await aptos.signAndSubmitTransaction({ signer: sender, transaction });const executed = await aptos.waitForTransaction({ transactionHash: committed.hash });if (!executed.success) { throw new Error(executed.vm_status);} ``` Walk through the full flow (fund, simulate, sign, wait) in [Your First Transaction](/build/guides/first-transaction). SDK quickstarts repeat the same pattern: [TypeScript](/build/sdks/ts-sdk/quickstart), [Python](/build/sdks/python-sdk/quickstart), [Go](/build/sdks/go-sdk/quickstart), [Rust](/build/sdks/rust-sdk/quickstart). For Coin-typed assets (including migrated coins), prefer `0x1::aptos_account::transfer_coins` over `0x1::coin::transfer` so the recipient store is registered automatically. See [Transferring Assets](/build/guides/exchanges#transferring-assets) on the exchange guide. How the compose options apply to APT: * **Sponsored.** The fee payer pays gas, so the sender’s transferred APT is not reduced by the fee. Use this when a treasury or app should absorb gas, or when you want the recipient to receive an exact octa amount while the sender spends only that amount. * **Orderless.** Give each payout a unique `replayProtectionNonce` so one hot wallet can submit many APT transfers at once (payroll, disbursements). Expiry is at most 60 seconds. * **Multi-agent.** A one-sided `aptos_account::transfer` only needs the sender. If both parties must agree — especially a [peer-to-peer swap](#peer-to-peer-swap) — use a custom entry function with two `&signer` arguments. Adding a secondary signer to `0x1::aptos_account::transfer` fails (`NUMBER_OF_SIGNER_ARGUMENTS_MISMATCH`). See [Two-party agreement](#two-party-agreement-multi-agent). ## Fungible asset and stablecoin transfers [](#fungible-asset-and-stablecoin-transfers) USDC, USDT, and other current tokens use the [Fungible Asset](/build/smart-contracts/fungible-asset) standard. Transfer with `0x1::primary_fungible_store::transfer`. It creates the recipient’s primary store when missing. ``` const transaction = await aptos.transaction.build.simple({ sender: sender.accountAddress, data: { function: "0x1::primary_fungible_store::transfer", typeArguments: ["0x1::object::ObjectCore"], functionArguments: [metadataAddress, recipientAddress, amount], },}); const committed = await aptos.signAndSubmitTransaction({ signer: sender, transaction });const executed = await aptos.waitForTransaction({ transactionHash: committed.hash });if (!executed.success) { throw new Error(executed.vm_status);} ``` Mainnet stablecoin metadata addresses are listed under [Stablecoin Addresses](/build/guides/exchanges#stablecoin-addresses). For a broader token registry, see the [Panora Token List](https://github.com/PanoraExchange/Aptos-Tokens). To issue your own asset, start with [Your First Fungible Asset](/build/guides/first-fungible-asset). Caution A first-time FA credit can allocate a storage slot. That storage fee is converted into gas units and included in `gas_used` (see [Calculating Storage Fees](/network/blockchain/gas-txn-fee#calculating-storage-fees)). Simulate the exact sender/recipient pair rather than assuming a repeat-transfer cost. Read balances with `aptos.getBalance({ accountAddress, asset })` or the `0x1::primary_fungible_store::balance` view function. Indexing and product tables are covered in the [Indexer](/build/indexer) and [fungible asset balance queries](/build/indexer/indexer-api/fungible-asset-balances). How the compose options apply to FA and stablecoins: * **Sponsored.** This is the usual gasless checkout: the user holds USDC (or another FA) and never needs APT. The application or [Geomi Gas Station](https://geomi.dev/docs/gas-stations) pays gas. Same `withFeePayer: true` pattern as APT; only the entry function changes. * **Orderless.** Same nonce as APT. Use it for parallel stablecoin payouts from one treasury account. * **Multi-agent.** A one-sided `primary_fungible_store::transfer` is a push from payer to recipient. For a [peer-to-peer swap](#peer-to-peer-swap) (USDC vs APT, two FAs, or delivery-versus-payment), both accounts sign one custom entry function so neither side can claim the other already paid. ## Confidential transfers [](#confidential-transfers) [Confidential Asset (CA)](/build/smart-contracts/confidential-asset) wraps a fungible asset so **amounts and confidential balances stay hidden**, including from validators, using zero-knowledge proofs. Sender and recipient **addresses remain visible**. Incoming funds land in a pending confidential balance and must be rolled over before they are spendable. Do not hand-build CA transactions. Use the TypeScript client documented in [Confidential Assets (SDK)](/build/sdks/ts-sdk/confidential-asset). That package generates proofs, decrypts balances, and constructs entry-function payloads. Relative to a plaintext FA transfer: * **E2E latency:** on-chain E2E is still typically sub-second after submit. Proof generation on the client happens before submit and is the usual extra delay. * **Fees:** higher execution and IO because of proof verification and a larger payload. Simulate. There is no separate “confidential gas schedule” beyond ordinary metering. * **Not the same as encrypted pending transactions.** CA hides committed amounts. [Encrypted pending transactions](/build/guides/encrypted-pending-transactions) hide the Move payload only while the transaction is in mempool. How the compose options apply to confidential transfers: * **Sponsored.** The CA TypeScript client supports fee payer first-class: `new ConfidentialAsset({ config, withFeePayer: true })` or `withFeePayer: true` on a single call (`deposit`, `transfer`, `withdraw`, rollover). See [Fee Payer](/build/sdks/ts-sdk/confidential-asset#fee-payer). * **Orderless.** Orderless is a transaction-layer nonce, not a CA protocol feature. The high-level CA client documents fee payer, not `replayProtectionNonce`. If you construct the CA entry-function payload yourself (still using the SDK to generate proofs), you can pass `options.replayProtectionNonce` on `build.simple` the same way as any other call. Prefer sequence numbers unless you are submitting many CA operations from one account in parallel. * **Multi-agent.** `ca.transfer` is a one-sided send: the sender proves and signs; the recipient does not. Incoming funds still land in the recipient’s pending confidential balance and must be rolled over. Two-party confidential settlement (both must agree before amounts move) needs a custom module with two `&signer` arguments that both call into CA — do not treat a standard CA transfer as a jointly signed payment. ## Two-party agreement (multi-agent) [](#two-party-agreement-multi-agent) A one-sided payment is: Alice signs, Bob receives. Bob never agreed on-chain. That is the right shape for a checkout, a withdrawal, or a payroll push. A **[multi-agent transaction](/build/sdks/ts-sdk/building-transactions/multi-agent-transactions)** is the other shape: Alice and Bob both sign **one** transaction. The Move function runs only if every listed account authorizes it, so either both legs happen or neither does. Use this when you need both parties to agree — a [peer-to-peer swap](#peer-to-peer-swap), an escrow release, a refund that the merchant must accept, or any payment that should not be a unilateral send. flowchart TB subgraph onesided \[One-sided send\] A\[Payer signs\] --> T1\[Recipient is credited\] end subgraph twoparty \[Multi-agent\] B\[Payer signs\] --> T2\[One committed transaction\] C\[Counterparty signs\] --> T2 end This is **not** multisig. Multisig is N-of-M keys controlling **one** account ([Your First Multisig](/build/guides/first-multisig)). Multi-agent is several **distinct accounts** on one transaction. There is no built-in `0x1` payment function that already takes two signers. You publish (or reuse) an entry function with multiple `&signer` arguments. The usual payment shape for that is a swap. ### Peer-to-peer swap [](#peer-to-peer-swap) Two one-sided sends cannot implement a swap. If Alice transfers USDC first, Bob can refuse to send APT. If they submit two separate transactions, one can commit and the other abort. A **multi-agent swap** puts both transfers in **one** Move function that both accounts sign: 1. Alice and Bob agree off-chain on assets and amounts. Those values are arguments of the transaction they both sign, so neither party can change the deal after the other has signed. 2. The entry function pulls Alice’s asset to Bob **and** Bob’s asset to Alice. 3. Block-STM executes the function atomically. If either signer is missing, the transaction is invalid. If the function aborts (for example, insufficient balance), **neither** transfer commits. flowchart LR subgraph agents \[Both must sign\] A\[Alice\] B\[Bob\] end agents --> S\["swap entry: both transfers"\] S --> A2\[Alice receives Bob asset\] S --> B2\[Bob receives Alice asset\] This is not an AMM or DEX swap. A pool swap is usually **one** signer against a contract. Multi-agent is two accounts swapping **with each other** (OTC, delivery-versus-payment, NFT-for-stablecoin). Publish a module whose first two parameters are `&signer` and that calls the ordinary transfer APIs. Signer order in the transaction must match the Move parameter order: the **sender** is `alice`; the first secondary signer is `bob`. ``` module example::p2p_swap { use std::signer; use aptos_framework::object::Object; use aptos_framework::fungible_asset::Metadata; use aptos_framework::primary_fungible_store; /// Alice sends `alice_amount` of `alice_asset` to Bob. /// Bob sends `bob_amount` of `bob_asset` to Alice. /// Both happen, or neither does. public entry fun swap( alice: &signer, bob: &signer, alice_asset: Object, bob_asset: Object, alice_amount: u64, bob_amount: u64, ) { let alice_addr = signer::address_of(alice); let bob_addr = signer::address_of(bob); primary_fungible_store::transfer(alice, alice_asset, bob_addr, alice_amount); primary_fungible_store::transfer(bob, bob_asset, alice_addr, bob_amount); }} ``` The same pattern works for APT vs a stablecoin (`0x1::aptos_account::transfer` in one leg), or an object vs an FA (NFT checkout). Swap APT for APT by using two APT legs; the teaching script [`two_by_two_transfer`](https://github.com/aptos-labs/aptos-ts-sdk/blob/main/tests/move/transfer/sources/script_two_by_two.move#L5) is that coin-only analog. ``` const transaction = await aptos.transaction.build.multiAgent({ sender: alice.accountAddress, // first &signer (alice) secondarySignerAddresses: [bob.accountAddress], // second &signer (bob) withFeePayer: true, // optional: app pays gas data: { function: "0xYOUR_MODULE::p2p_swap::swap", functionArguments: [aliceAssetMetadata, bobAssetMetadata, aliceAmount, bobAmount], }, options: { replayProtectionNonce: nonce, // optional; omit for a sequence number },}); const aliceAuth = aptos.transaction.sign({ signer: alice, transaction });const bobAuth = aptos.transaction.sign({ signer: bob, transaction });const feePayerAuth = aptos.transaction.signAsFeePayer({ signer: feePayer, transaction }); const committed = await aptos.transaction.submit.multiAgent({ transaction, senderAuthenticator: aliceAuth, additionalSignersAuthenticators: [bobAuth], feePayerAuthenticator: feePayerAuth,}); ``` Compose options on a swap: * **Sponsored.** Useful when both legs are FAs and neither party should hold APT for gas. The fee payer is not a swap party unless you also pass them as a signer. * **Orderless.** Use a nonce if the same sender account runs many independent OTC swaps in parallel. Sequence numbers are enough for occasional swaps. * **Encrypted pending.** Combine `encrypted: true` with `build.multiAgent` if the agreed amounts should stay hidden in mempool. Other SDKs use the same `multiAgent` flow: [Python](/build/sdks/python-sdk/building-transactions/multi-agent-transactions), [Go](/build/sdks/go-sdk/building-transactions/multi-agent-transactions), [Rust](/build/sdks/rust-sdk/building-transactions/multi-agent-transactions). ## Other payment usages [](#other-payment-usages) ### Encrypted pending payload [](#encrypted-pending-payload) Encrypt the Move arguments until execution ([Encrypted Pending Transactions](/build/guides/encrypted-pending-transactions), AIP-144). Currently on devnet and testnet; minimum gas unit price 200 octas. * **Sponsored.** Pass `withFeePayer: true` on the encrypted build. The SDK documents `feePayerAuthenticationKey` as optional. * **Orderless.** Pass `replayProtectionNonce` together with `encrypted: true` so parallel submitters keep the payload hidden. * **Multi-agent.** `build.multiAgent` accepts `encrypted: true` and optional `secondarySignerAuthenticationKeys`. Use it when both parties must agree **and** the pending payload should stay hidden. ### Treasury and policy (multisig) [](#treasury-and-policy-multisig) N-of-M controls for mint, freeze, or large payouts: [Your First Multisig](/build/guides/first-multisig), [Multisig Managed Assets](/build/guides/multisig-managed-fungible-asset). * **Sponsored.** After the owners approve, a fee payer can still cover gas for the executing transaction. * **Orderless.** Use a nonce when the treasury account submits many independent payouts in parallel. * **Multi-agent.** Do not substitute multi-agent for multisig. If the treasury must settle against another party in one shot, collect the multisig signatures **and** the counterparty’s signature (multi-agent secondary signer), or have the approved multisig account be one agent in a two-signer module. ### NFT or object checkout [](#nft-or-object-checkout) [Digital Asset](/build/smart-contracts/digital-asset) and [Your First NFT](/build/guides/your-first-nft). Settlement still uses the same block time, finality, and fee model; the payload is an object transfer rather than an FA transfer. * **Sponsored.** Same `withFeePayer` pattern so the buyer need not hold APT. * **Orderless.** Same nonce if a marketplace hot wallet mints or delivers many objects in parallel. * **Multi-agent.** One-sided object transfer is a push. For an [NFT-for-stablecoin swap](#peer-to-peer-swap) where neither side should move first, both the buyer and the seller sign one entry function. ### Passwordless onboarding (Keyless) [](#passwordless-onboarding-keyless) [Aptos Keyless](/build/guides/aptos-keyless) accounts are ordinary senders once created. * **Sponsored.** Cover gas so a new user can pay in a stablecoin without ever holding APT. * **Orderless.** Same nonce option as any other account. * **Multi-agent.** The Keyless account can be the sender or a secondary signer when the user must agree with a merchant or another wallet in one transaction. ### Exchanges and custody [](#exchanges-and-custody) Deposits, withdrawals, and finality rules: [Exchange Integration](/build/guides/exchanges). * **Sponsored.** Uncommon on a CEX hot wallet (the venue already holds APT). Useful for user-facing deposit helpers or gasless withdrawal claims. * **Orderless.** The usual tool for parallel withdrawals from one hot wallet; sequence-number workers are the alternative in [Transaction Management](/build/guides/transaction-management). * **Multi-agent.** CEX deposit and withdrawal are one-sided. OTC or on-chain delivery-versus-payment between the venue and a client can use multi-agent so both sides agree rather than one sending to the other. ## Next steps [](#next-steps) [Your First Transaction](/build/guides/first-transaction) Fund accounts and send a verified APT transfer. [Fungible Asset](/build/smart-contracts/fungible-asset) The token standard used by USDC, USDT, and new payment assets. [Confidential Asset](/build/smart-contracts/confidential-asset) Hide transfer amounts and confidential balances with ZK proofs. [Gas and Storage Fees](/network/blockchain/gas-txn-fee) How execution, IO, and storage fees are charged and refunded. [Sponsored Transactions](/build/guides/sponsored-transactions) Let the application pay gas so users transact without APT. [Orderless Transactions](/build/guides/orderless-transactions) Submit many payments in parallel from one account with a replay-protection nonce. [Multi-Agent Transactions](/build/sdks/ts-sdk/building-transactions/multi-agent-transactions) Both parties sign one transaction instead of one side sending to the other. [Application Integration](/build/guides/application-integration) Accounts, signing, balances, and the submit-then-wait lifecycle. # Your First Move Module > Learn to compile, test, publish, and interact with Move smart contracts on Aptos blockchain from setup to deployment. The Aptos blockchain allows developers to write Turing complete smart contracts (called “modules”) with the secure-by-design Move language. Smart contracts enable users to send money with the blockchain, but also write arbitrary code, even games! It all starts with the Aptos CLI creating an account which will store the deployed (”published”) Move module. This tutorial will help you understand Move Modules by guiding you through setting up a minimal Aptos environment, then how to compile, test, publish and interact with Move modules on the Aptos Blockchain. You will learn how to: 1. Setup your environment, install the CLI 2. Create a devnet account and fund it 3. Compile and test a Move module 4. Publish (or “deploy”) a Move module to the Aptos blockchain 5. Interact with the module 6. Keep building with Aptos (next steps) ## 1\. Setup [](#1-setup) Changes to the blockchain are called “transactions”, and they require an account to pay the network fee (”gas fee”). We will need to create an account with some APT to pay that fee and own the published contract. In order to do that, we will need to use the Aptos CLI. 1. Install the Aptos CLI [Install the Aptos CLI](/build/cli) (if you haven’t already). 2. Open a new terminal Open a new terminal window or tab. 3. Verify the installation Run `aptos --version` to verify you have it installed. ``` aptos --version ``` You should see a response like `aptos 4.6.1`. 4. Create a project folder Create a new folder for this tutorial by running: ``` mkdir my-first-module ``` 5. Navigate to the project folder Run `cd my-first-module` to go into your new folder. 6. Initialize your account Run `aptos init` and press ‘enter’ for each step of setup to create a test account on `devnet`. You should see a success message like this: ``` ---Aptos CLI is now set up for account 0x9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba as profile default!{ "Result": "Success"} ``` ## 2\. (Optional) Explore What You Just Did On-Chain [](#2-optional-explore-what-you-just-did-on-chain) 1. Copy your account address Copy the address from the command line for your new account. The address looks like this `0x9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba` and you can find it in the line: ``` Aptos CLI is now set up for account 0x9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba as profile default! ``` 2. Open the Aptos Explorer Go to the [Aptos Explorer](https://explorer.aptoslabs.com/?network=devnet). This is the primary way to quickly check what is happening on devnet, testnet, or mainnet. We will use it later on to view our deployed contracts. 3. Ensure you are on Devnet network. Look for “Devnet” in the top right corner, or switch networks by clicking the “Mainnet” dropdown and selecting Devnet ![Switching to Devnet network in Aptos Explorer](/_vercel/image?url=_astro%2Fexplorer_devnet.D3PWblc6.png&w=320&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) 4. Search for your account Paste your newly created address into the search bar. Caution Do not press enter! There is a known bug where searching with Enter does not work. 5. View the search results Wait for the results to appear, then click the top result. 6. Check the transaction You should see your newly created account and a transaction with the faucet function, funding it with devnet tokens. ![Viewing Account in Aptos Explorer](/_vercel/image?url=_astro%2Fexplorer_account.DlK3EDU1.png&w=1280&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) 7. Verify your balance Click the “Coins” tab to see that you have 1 APT of the Aptos Coin. This will allow you to publish and interact with smart contracts on the aptos devnet. ## 3\. Writing and Compiling Your First Module [](#3-writing-and-compiling-your-first-module) Now that we have our environment set up and an account created, let’s write and compile our first Move module. Unlike Ethereum where contracts exist independently, Move ties everything to accounts - both modules and their resources. Let’s start with a simple example to understand the core concepts. ![Move Blockchain Diagram](/_vercel/image?url=_astro%2Fmove_blockchain.US8AdnUd.png&w=640&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) This diagram illustrates the relationship between module ownership, token ownership, and the Move blockchain state. It helps visualize how modules and resources are tied to accounts, emphasizing the unique aspects of Move’s design compared to other blockchain platforms. ### What is a Move Module? [](#what-is-a-move-module) Move modules are similar to smart contracts in other blockchains, with some key differences: * **Resources:** Unlike Solidity where state is stored in contract variables, Move uses “resources” - special data types that can only exist in one place at a time and are always tied to an account * **Module-based**: Rather than deploying entire contracts as independent units like in Solidity, Move code is organized into reusable modules that can share and handle resources across boundaries. Modules are more like standard library packages that can be published together or separately, offering finer-grained control over code organization. * **Safety by design:** Move’s type system and resource semantics help prevent common smart contract vulnerabilities ### Your First Move Module [](#your-first-move-module) Before we start, go to your VSCode (or Cursor) and install the [Move On Aptos](/build/smart-contracts/move-vscode-extension) VSCode extension. 1. Open VSCode (or Cursor) and navigate to the Extensions tab. 2. Search for `Move On Aptos` published by `aptoslabs` and install the extension. This extension will help us with the syntax highlighting, auto-completion, and other features that will make our development experience easier. Our first module will be a simple message storage system that allows accounts to store and retrieve messages. Let’s create a new move project within our `my-first-module` folder: 1. Initialize the project Initialize a new move project with `aptos move init --name my_first_module` This creates a project structure with a `sources` directory and a `Move.toml` file. 2. Create the module file Create a new file `sources/message.move` with our module code: ``` module my_first_module::message { use std::string; use std::signer; struct MessageHolder has key, store, drop { message: string::String, } public entry fun set_message(account: &signer, message: string::String) acquires MessageHolder { let account_addr = signer::address_of(account); if (exists(account_addr)) { move_from(account_addr); }; move_to(account, MessageHolder { message }); } public fun get_message(account_addr: address): string::String acquires MessageHolder { assert!(exists(account_addr), 0); let message_holder = borrow_global(account_addr); message_holder.message }} ``` Let’s break down this module: * We define a `MessageHolder` resource type that can store a string message * `set_message` allows an account to store a message * `get_message` allows anyone to retrieve a stored message * The `acquires` keyword indicates which resources the functions need access to (MessageHolder, in this case) * `move_to` and `move_from` handle the storage of resources under accounts 3. Compile the module Compile the Move module we just created with `aptos move compile --named-addresses my_first_module=default` You should see a message like this if it succeeded: ``` ❯ aptos move compile --named-addresses my_first_module=defaultCompiling, may take a little while to download git dependencies...UPDATING GIT DEPENDENCY https://github.com/aptos-labs/aptos-framework.gitINCLUDING DEPENDENCY AptosFrameworkINCLUDING DEPENDENCY AptosStdlibINCLUDING DEPENDENCY MoveStdlibBUILDING my_first_module{ "Result": [ "9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba::message" ]} ``` Great job! We are now ready to test and debug. ## 4\. Testing and Debugging [](#4-testing-and-debugging) Testing and debugging are crucial parts of Move module development. Move has built-in support for unit testing and debug printing. 1. Add debug prints First, let’s modify our message module to add some debug prints. Update your `sources/message.move`: ``` module my_first_module::message { use std::string; use std::signer; use std::debug; // Add this for debug prints struct MessageHolder has key, store, drop { message: string::String, } public entry fun set_message(account: &signer, message: string::String) acquires MessageHolder { let account_addr = signer::address_of(account); debug::print(&message); // Print the message being set if (exists(account_addr)) { debug::print(&string::utf8(b"Updating existing message")); // Print debug info move_from(account_addr); } else { debug::print(&string::utf8(b"Creating new message")); // Print when creating new }; move_to(account, MessageHolder { message }); } public fun get_message(account_addr: address): string::String acquires MessageHolder { assert!(exists(account_addr), 0); let message_holder = borrow_global(account_addr); debug::print(&message_holder.message); // Print the retrieved message message_holder.message }} ``` 2. Create test file Create our tests: a new file `sources/message_tests.move` with: ``` #[test_only] module my_first_module::message_tests { use std::string; use std::signer; use my_first_module::message; #[test(sender= @my_first_module)] fun test_set_and_get_message(sender: &signer) { // Test setting a message message::set_message(sender, string::utf8(b"Hello World")); // Verify the message was set correctly let stored_message = message::get_message(signer::address_of(sender)); assert!(stored_message == string::utf8(b"Hello World"), 0) } #[test(sender=@my_first_module)] fun test_update_message(sender: &signer) { // Test setting a message message::set_message(sender, string::utf8(b"Hello World")); // Test updating the message message::set_message(sender, string::utf8(b"Hello Aptos")); // Verify the message was updated correctly let stored_message = message::get_message(signer::address_of(sender)); assert!(stored_message == string::utf8(b"Hello Aptos"), 0) } } ``` 3. Run the tests Now run the tests with `aptos move test --named-addresses my_first_module=default` You should see output if the tests pass: (See below for how to handle errors) ``` INCLUDING DEPENDENCY AptosFramework INCLUDING DEPENDENCY AptosStdlib INCLUDING DEPENDENCY MoveStdlib BUILDING my_first_module Running Move unit tests [debug] "Hello World" [debug] "Creating new message" [debug] "Hello World" [ PASS ] 0x852a264419a80b27771f072b5cae8c8b358d4450e135e134e065247376a4357a::message_tests::test_set_and_get_message [debug] "Hello World" [debug] "Creating new message" [debug] "Hello Aptos" [debug] "Updating existing message" [debug] "Hello Aptos" [ PASS ] 0x852a264419a80b27771f072b5cae8c8b358d4450e135e134e065247376a4357a::message_tests::test_update_message Test result: OK. Total tests: 2; passed: 2; failed: 0 { "Result": "Success" } ``` **If you encounter errors while testing, here are some common issues and solutions:** * Make sure all module dependencies are properly imported * Check that your account address matches in the `-named-addresses` parameter * Verify that test functions have the `#[test]` attribute * Ensure string literals are properly encoded ## 5\. Publishing Your Module [](#5-publishing-your-module) After successfully compiling and testing your module, you can publish it to the Aptos blockchain. This process deploys your code so that it’s accessible on-chain. 1. Publish the module Publish your module with `aptos move publish --named-addresses my_first_module=default` You’ll see output showing the compilation process and then a prompt asking about gas fees: ``` Compiling, may take a little while to download git dependencies...UPDATING GIT DEPENDENCY https://github.com/aptos-labs/aptos-framework.gitINCLUDING DEPENDENCY AptosFrameworkINCLUDING DEPENDENCY AptosStdlibINCLUDING DEPENDENCY MoveStdlibBUILDING my_first_modulepackage size 1271 bytesDo you want to submit a transaction for a range of [141300 - 211900] Octas at a gas unit price of 100 Octas? [yes/no] > ``` 2. Confirm the transaction Type `y` and press Enter to confirm the transaction. After confirmation, you’ll receive a response showing the transaction details: ``` { "Result": { "transaction_hash": "0x95fce7344b066abda10c07dbf1ffa83e0d9c7bd400e2b143682a6c8a5f179dc2", "gas_used": 1413, "gas_unit_price": 100, "sender": "9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba", "sequence_number": 0, "success": true, "timestamp_us": 1735351260227638, "version": 273029731, "vm_status": "Executed successfully" }} ``` ### (Optional) Seeing Your Contract On-Chain [](#optional-seeing-your-contract-on-chain) After successful publication, you can verify your module is on-chain by following these steps: 1. Open the Explorer Go to the [Aptos Explorer](https://explorer.aptoslabs.com/?network=devnet) 2. Check the transaction Search for your account address. You should notice that there is a new transaction in your account, the `code::publish_package_txn` function. 3. View your balance Click the “Coins” tab to see that you now have less than 1 APT of the Aptos Coin. ![Explorer Coins View](/_vercel/image?url=_astro%2Fexplorer_coins.BHJq95xO.png&w=1280&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) You have spent a small amount on gas to deploy the contract so should have around `0.99855 APT` remaining. 4. Find your module Look under the “Modules” tab ![Exporer Modules View](/_vercel/image?url=_astro%2Fexplorer_modules.BhR9Jwde.png&w=1280&q=100&dpl=dpl_4VCU8B8pAouLiDVrt4Y39M1DTCWg) 5. Verify the module You should see your “message” module listed ## 6\. Interacting with Your Module [](#6-interacting-with-your-module) Now that your module is published, you can interact with it through the Aptos CLI: 1. Set a message Set a message using the CLI: ``` aptos move run --function-id 'default::message::set_message' --args 'string:Hello, Aptos!' ``` You’ll see a gas fee prompt similar to what you saw during publishing. 2. Confirm the transaction After confirming with `y`, you should get a success response like: ``` Transaction submitted: https://explorer.aptoslabs.com/txn/0x0c0b1e56a31d037280278327eb8fdfcc469a20213e5e65accf6e7c56af574449?network=devnet{ "Result": { "transaction_hash": "0x0c0b1e56a31d037280278327eb8fdfcc469a20213e5e65accf6e7c56af574449", "gas_used": 445, "gas_unit_price": 100, "sender": "9ec1cfa30b885a5c9d595f32f3381ec16d208734913b587be9e210f60be9f9ba", "sequence_number": 1, "success": true, "timestamp_us": 1735351754495208, "version": 273137362, "vm_status": "Executed successfully" }} ``` 3. View your message View your stored message by checking under Resources on the Explorer. 4. Celebrate! We did it! ## Next Steps [](#next-steps) Congratulations! You’ve successfully: 1. Compiled your first Move module 2. Added tests to help debug 3. Published your module on-chain 4. Used your contract through the CLI Now your published Move module can be connected to just like an API via one of our [many Official SDKs](/build/sdks)! Here are some **suggested next steps to get a deeper understanding of Move modules**: 1. Try modifying the module to add a new feature. You can use the [Move Book](https://aptos-labs.github.io/move-book/) to build your understanding of writing Move modules. 2. To understand how Move works on-chain, you can learn about Move’s [resource system](/network/blockchain/resources). 3. If you’re building an application to interact with contracts or look up data from on-chain, learn how to use the SDKs [here](/build/sdks). 4. Join the [Aptos Discord](https://discord.gg/aptoslabs) to connect with other developers. ## Supporting documentation [](#supporting-documentation) * [Account basics](/network/blockchain/accounts) * [TypeScript SDK](/build/sdks/ts-sdk) * [Python SDK](/build/sdks/python-sdk) * [Go SDK](/build/sdks/go-sdk) * [Rust SDK](/build/sdks/rust-sdk) * [REST API specification](/rest-api) # Accounts > Understand Aptos accounts, their addresses, authentication schemes, key rotation, sequence numbers, and how they control assets and resources on-chain. An account on Aptos controls a set of on-chain assets, including [fungible assets](/build/smart-contracts/fungible-asset), coins, and digital assets (NFTs). Those assets are **resources**: a Move primitive that enforces access control and scarcity. Each account is identified by a 32-byte address. You can use the [Aptos Name Service](https://www.aptosnames.com/) to register human-readable `.apt` domains for key accounts. Unlike blockchains where accounts are implicit (just an address with a balance), Aptos accounts are explicit and backed by on-chain resources that enable features like key rotation and native multisig. However, with [Stateless Accounts (AIP-115)](/build/aips/aip-115), you no longer need to set up an account before using it. Any valid address is treated as an account by default, and you can send transactions as long as you hold the private key. The on-chain `Account` resource is created automatically only when first needed (for example, when rotating keys). See [Creating an account](#creating-an-account) for how addresses are derived. Aptos accounts offer features not available on most other networks: * **Key rotation.** The account’s authentication key can be changed to use a different private key, similar to changing a password. * **Native multisig.** Accounts support k-of-n multisig using Ed25519 and Secp256k1 ECDSA signature schemes. There are three types of accounts on Aptos: * _Standard account_ — an address controlled by a public/private key pair. That pair can be Ed25519, Secp256k1, [Keyless](/build/guides/aptos-keyless), WebAuthn, or a k-of-n combination. * [_Resource account_](/build/smart-contracts/resource-accounts) — an autonomous account without an interactive private key, used to store resources or publish modules. * [_Object_](/build/smart-contracts/objects) — a dedicated address that groups resources into one entity. ``` Alice: 0xeeff357ea5c1a4e7bc11b2b17ff2dc2dcca69750bfef1e1ebcaccf8c8018175bBob: 0x19aadeca9388e009d136245b9a67423f3eee242b03142849eb4f81a4a409e59c ``` ## Account address [](#account-address) Aptos uses a single identifier for an account: a 32-byte hex string. A hex string shorter than 32-bytes is also valid; in those scenarios, the hex string can be padded with leading zeroes, e.g., `0x1` => `0x0000000000000...01`. While Aptos standards indicate leading zeroes may be removed from an Address, most applications attempt to eschew that legacy behavior and only support the removal of zeros for special addresses ranging from `0x0` to `0xa`. ## Creating an account [](#creating-an-account) When a user requests to create an account, for example, by using the [Aptos SDK](/build/sdks/ts-sdk/account), the following steps are executed: * Select the authentication scheme for managing the user’s account, e.g., Ed25519 or Secp256k1 ECDSA. * Generate a new private key, public key pair. * Combine the public key with the public key’s authentication scheme to generate a 32-byte authentication key and the account address. The user should use the private key for signing the transactions associated with this account. ## Account sequence number [](#account-sequence-number) The sequence number for an account indicates the number of transactions that have been submitted and committed on-chain from that account. Committed transactions either execute with the resulting state changes committed to the blockchain or abort wherein state changes are discarded and only the transaction is stored. Every **sequenced** transaction must carry the sender’s next sequence number. The node compares that number with the on-chain account. Mempool forwards a transaction only when it can form a contiguous series from the current sequence number. Execution rejects gaps, which prevents replay of old transactions and orders later ones. [Orderless transactions](/build/guides/orderless-transactions) skip this counter. They use a unique nonce instead, set `sequence_number` to `u64::MAX`, and expire within 60 seconds. That lets several machines submit from the same account without coordinating sequence numbers. See [AIP-123](/build/aips/aip-123). ## Authentication key [](#authentication-key) The initial account address is set to the authentication key derived during account creation. The authentication key can change later, for example when you rotate to a new key pair. The account address never changes. The Aptos blockchain supports the following authentication schemes: 1. [Ed25519](https://ed25519.cr.yp.to/) 2. [Secp256k1 ECDSA](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-049-secp256k1-ecdsa-for-transaction-authentication.md) 3. [K-of-N multi-signatures](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-055-multikey-accounts.md) 4. A dedicated, now legacy, MultiEd25519 scheme ### Ed25519 authentication [](#ed25519-authentication) To generate an authentication key and the account address for an Ed25519 signature: 1. **Generate a key-pair**: Generate a fresh key-pair (`privkey_A`, `pubkey_A`). The Aptos blockchain uses the PureEdDSA scheme over the Ed25519 curve, as defined in RFC 8032. 2. **Derive a 32-byte authentication key**: Derive a 32-byte authentication key from the `pubkey_A`: ``` auth_key = sha3-256(pubkey_A | 0x00) ``` where `|` denotes concatenation. The `0x00` is the 1-byte single-signature scheme identifier. 3. Use this initial authentication key as the permanent account address. ### MultiEd25519 authentication [](#multied25519-authentication) With K-of-N multisig authentication, there are a total of N signers for the account, and at least K of those N signatures must be used to authenticate a transaction. To generate a K-of-N multisig account’s authentication key and the account address: 1. **Generate key-pairs**: Generate `N` ed25519 public keys `p_1`, …, `p_n`. 2. Decide on the value of `K`, the threshold number of signatures needed for authenticating the transaction. 3. **Derive a 32-byte authentication key**: Compute the authentication key as described below: ``` auth_key = sha3-256(p_1 | . . . | p_n | K | 0x01) ``` The `0x01` is the 1-byte multisig scheme identifier. 4. Use this initial authentication key as the permanent account address. ### Generalized authentication [](#generalized-authentication) Generalized authentication supports both Ed25519 and Secp256k1 ECDSA. Like the previous authentication schemes, these schemes contain a scheme value, `0x02` and `0x03` for single and multikey respectively, but also each key contains a prefix value to indicate its key type:
Key typePrefix byte
Ed25519 generalized scheme0x00
Secp256k1Ecdsa generalized scheme0x01
Secp256r1Ecdsa WebAuthn scheme0x02
Keyless0x03
For a single key Secp256k1 ECDSA account, using public key `pubkey`, the authentication key would be derived as follows: ``` auth_key = sha3-256(0x01 | pubkey | 0x02) ``` Where * the first entry, `0x01`, represents the use of a Secp256k1 ECDSA key; * the last entry, `0x02`, represents the authentication scheme. For a 1-of-2 multi-key account containing, a single Secp256k1 ECDSA public key, `pubkey_0`, and a single Ed25519 public key, `pubkey_1`, where one signature suffices, the authentication key would be derived as follows: ``` auth_key = sha3-256(0x02 | 0x01 | pubkey_0 | 0x00 | pubkey_1 | 0x01 | 0x03) ``` Where * the first entry, `0x02`, represents the total number of keys as a single byte; * the second-to-last entry, `0x01`, represents the required number of signatures as a single byte; * the last entry, `0x03`, represents the authentication scheme. ## Rotating the keys [](#rotating-the-keys) An Account on Aptos can rotate keys so that potentially compromised keys cannot be used to access the accounts. Keys can be rotated via the `account::rotate_authentication_key` function. Refreshing the keys is generally regarded as good hygiene in the security field. However, this presents a challenge for system integrators who are used to using a mnemonic to represent both a private key and its associated account. To simplify this for system integrators, Aptos provides an on-chain mapping via `aptos account lookup-address`. The on-chain data maps an effective account address as defined by the current mnemonic to the actual account address. For more information, see [`account.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/account/account.move). ## State of an account [](#state-of-an-account) The state of each account comprises both the code (Move modules) and the data (Move resources). An account may contain an arbitrary number of Move modules and Move resources: * **Move modules**: Move modules contain code, for example, type and procedure declarations; but they do not contain data. A Move module encodes the rules for updating the Aptos blockchain’s global state. * **Move resources**: Move resources contain data but no code. Every resource value has a type declared in a module published on the Aptos blockchain. ## Access control with signers [](#access-control-with-signers) The sender of a transaction is represented by a signer. When a function in a Move module takes `signer` as an argument, the Aptos Move VM translates the identity of the account that signed the transaction into a signer in a Move module entry point. See the below Move example code with `signer` in the `initialize` and `withdraw` functions. When a `signer` is not specified in a function, for example, the below `deposit` function, then no signer-based access controls will be provided for this function: ``` module Test::Coin { struct Coin has key { amount: u64 } public fun initialize(account: &signer) { move_to(account, Coin { amount: 1000 }); } public fun withdraw(account: &signer, amount: u64): Coin acquires Coin { let balance = &mut borrow_global_mut(Signer::address_of(account)).amount; *balance = *balance - amount; Coin { amount } } public fun deposit(account: address, coin: Coin) acquires Coin { let balance = &mut borrow_global_mut(account).amount; *balance = *balance + coin.amount; Coin { amount: _ } = coin; }} ``` # Transactions and States > Understand how transactions modify the blockchain state on Aptos, including transaction types, execution states, and the versioned database model. The Aptos blockchain stores three types of data: * **Transactions**: Transactions represent an intended operation being performed by an account on the blockchain (e.g., transferring assets). * **States**: The (blockchain ledger) state represents the accumulation of the output of execution of transactions, the values stored within all [resources](/network/blockchain/resources). * [**Events**](/network/blockchain/events): Ancillary data published by the execution of a transaction. ## Transactions [](#transactions) Aptos transactions contain information such as the sender’s account address, authentication from the sender, the desired operation to be performed on the Aptos blockchain, and the amount of gas the sender is willing to pay to execute the transaction. ### Transaction states [](#transaction-states) A transaction may end in one of the following states: * Committed on the blockchain and executed. This is considered as a successful transaction. * Committed on the blockchain and aborted. The abort code indicates why the transaction failed to execute. * Discarded during transaction submission due to a validation check such as insufficient gas, invalid transaction format, or incorrect key. * Discarded after transaction submission but before attempted execution. This could be caused by timeouts or insufficient gas due to other transactions affecting the account. The sender’s account will be charged gas for any committed transactions. During transaction submission, the submitter is notified of successful submission or a reason for failing validations otherwise. A transaction that is successfully submitted but ultimately discarded may have no visible state in any accessible Aptos node or within the Aptos network. A user can attempt to resubmit the same transaction to re-validate the transaction. If the submitting node believes that this transaction is still valid, it will return an error stating that an identical transaction has been submitted. The submitter can try to increase the gas cost by a trivial amount to help make progress and adjust for whatever may have been causing the discarding of the transaction further downstream. ### Contents of a Transaction [](#contents-of-a-transaction) A signed transaction on the blockchain contains the following information: * **Signature**: The sender’s digital signature authenticates the transaction. Multi-agent and fee-payer transactions include additional signatures. * **Sender address**: The sender’s [account address](/network/blockchain/accounts#account-address). * **Sender public key**: The public key that corresponds to the private key used to sign the transaction. The derived authentication key must match the account. * **Payload**: The operation to run. Commonly this is an entry function in published Move bytecode. It can also be a [transaction script](/network/glossary#transaction-script), a [multisig payload](/network/blockchain/transaction-payloads#multisig-payload), or (on supporting networks) an [encrypted payload](/network/blockchain/transaction-payloads#encrypted-payload). The payload includes type arguments and inputs. A typical example is transferring APT from the sender to another address. * [**Gas unit price**](/network/glossary#gas-unit-price): What the sender pays per unit of gas, in [Octas](/network/glossary#octa). Higher prices raise the chance the next block includes the transaction. * [**Maximum gas amount**](/network/glossary#maximum-gas-amount): The [maximum gas units](/network/blockchain/gas-txn-fee#specifying-gas-fees-within-a-transaction) the sender will spend. Execution aborts if computation, IO, and converted storage fees exceed this cap. * **Replay protection**: Either a [sequence number](/network/blockchain/accounts#account-sequence-number) that must match the sender’s on-chain sequence number at execution, or an [orderless nonce](/build/guides/orderless-transactions) (AIP-123). Orderless transactions set `sequence_number` to `u64::MAX` and expire within 60 seconds. * **Expiration time**: A timestamp after which the transaction is no longer valid. * **Chain ID**: Distinguishes Mainnet, Testnet, Devnet, and local networks so a signed transaction cannot be replayed on another chain. ### Types of transaction payloads [](#types-of-transaction-payloads) Within a given transaction, the two most common types of payloads include: * An entry point * [A script (payload)](/build/smart-contracts/scripts) The official [TypeScript](/build/sdks/ts-sdk), [Python](/build/sdks/python-sdk), [Go](/build/sdks/go-sdk), and [Rust](/build/sdks/rust-sdk) SDKs support both. Examples in this documentation often call `0x1::aptos_account::transfer`. All operations on the Aptos blockchain should be available via entry point calls. While one could submit multiple transactions calling entry points in series, many such operations may benefit from being called atomically from a single transaction. A script payload transaction can call any entry point or public function defined within any module. ## States [](#states) The Aptos blockchain’s ledger state, or global state, represents the state of all accounts in the Aptos blockchain. Each validator node in the blockchain must know the latest version of the global state to execute any transaction. Anyone can submit a transaction to the Aptos blockchain to modify the ledger state. Upon execution of a transaction, a transaction output is generated. A transaction output contains zero or more operations to manipulate the ledger state called **write sets** emitting a vector of resulting events, the amount of gas consumed, and the executed transaction status. ### Proofs [](#proofs) The Aptos blockchain uses proofs to verify the authenticity and correctness of the blockchain data. Data within the Aptos blockchain is replicated across the network. Each validator and fullnode’s [storage](/network/blockchain/validator-nodes#storage) is responsible for persisting the agreed upon blocks of transactions and their execution results to the database. The blockchain is represented as an ever-growing [Merkle tree](/network/glossary#merkle-trees), where each leaf appended to the tree represents a single transaction executed by the blockchain. All operations executed by the blockchain and all account states can be verified cryptographically. These cryptographic proofs ensure that: * The validator nodes agree on the state. * The client does not need to trust the entity from which it is receiving data. For example, if a client fetches the last **n** transactions from an account, a proof can attest that no transactions were added, omitted or modified in the response. The client may also query for the state of an account, ask whether a specific transaction was processed, and so on. ### Versioned database [](#versioned-database) The ledger state is versioned using an unsigned 64-bit integer corresponding to the number of transactions the system has executed. This versioned database allows the validator nodes to: * Execute a transaction against the ledger state at the latest version. * Respond to client queries about ledger history at both current and previous versions. ## Transactions change ledger state [](#transactions-change-ledger-state) ![Signed Transaction Flow](/_astro/transactions-and-state.DnHxozEu.svg) ![Signed Transaction Flow](/_astro/transactions-and-state-dark.ffwcWBtN.svg) The above figure shows how executing transaction T_i_ changes the state of the Aptos blockchain from S_i-1_ to S_i_. In the figure: * Accounts **A** and **B**: Represent Alice’s and Bob’s accounts on the Aptos blockchain. * **S_i-1_** : Represents the (_i-1_)th state of the blockchain. In this state, Alice’s account **A** has a balance of 110 APT, and Bob’s account **B** has a balance of 52 APT. * **T_i_** : This is the _i_\-th transaction executed on the blockchain. In this example, it represents Alice sending 10 APT to Bob. * **Apply()**: This is a deterministic function that always returns the same final state for a specific initial state and a specific transaction. If the current state of the blockchain is **S_i-1_**, and transaction **T_i_** is executed on the state **S_i-1_**, then the new state of the blockchain is always **S_i_**. The Aptos blockchain uses the [Move language](https://aptos-labs.github.io/move-book/) to implement the deterministic execution function **Apply()**. * **S_i_** : This is the \_i\_th state of the blockchain. Applying **T_i_** produces **S_i_** = **Apply(S_i-1_, T_i_)**. Alice’s balance drops by 10 to 100 APT and Bob’s balance rises by 10 to 62 APT. ## Size limits [](#size-limits) The gas schedule publishes on-chain limits for [transaction size](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/aptos-gas-schedule/src/gas_schedule/transaction.rs) and execution output. Current genesis defaults:
Limit TypeCurrent Per Transaction Limit
transaction64KB
governance transaction1MB
a single write op1MB
all write ops combined10MB
number of write ops8192
a single event1MB
all events combined10MB
# SDKs Overview > Official Aptos software development kits for TypeScript, Python, Go, and Rust, plus wallet adapter tooling ## Official SDKs [](#official-sdks) Use these Aptos software development kits (SDKs), in combination with the [Aptos CLI](/build/cli), to build on the Aptos blockchain. [TypeScript SDK](/build/sdks/ts-sdk) Aptos TypeScript SDK (recommended) [Python SDK](/build/sdks/python-sdk) Aptos Python SDK [Go SDK](/build/sdks/go-sdk) Aptos Go SDK [Rust SDK](/build/sdks/rust-sdk) Aptos Rust SDK [Wallet Adapter](/build/sdks/wallet-adapter) Aptos Wallet Adapter [Forklift](/build/sdks/forklift) Testing & scripting framework for Move contracts with Network Forking support ## [Community SDKs](/build/sdks/community-sdks) [](#community-sdks) SDKs provided by the community for Aptos. These may not be fully vetted by the Aptos team, and may still be in development. They are still provided as a resource for all developers. [Kotlin SDK](/build/sdks/community-sdks/kotlin-sdk) Aptos Kotlin Multiplatform SDK by Kaptos ## Deprecated SDKs [](#deprecated-sdks) Deprecated The following SDKs are deprecated and are no longer maintained. Do not use them for new projects. Prefer the TypeScript, Python, Go, or Rust SDKs. [C#/.NET SDK (deprecated)](/build/sdks/dotnet-sdk) Deprecated Aptos .NET SDK [C++ / Unreal SDK (deprecated)](/build/sdks/cpp-sdk) Deprecated C++ / Unreal SDK [Unity SDK (deprecated)](/build/sdks/unity-sdk) Deprecated Aptos Unity SDK [Swift SDK (deprecated)](/build/sdks/community-sdks/swift-sdk) Deprecated community Swift SDK [Unity SDK (legacy, deprecated)](/build/sdks/community-sdks/unity-opendive-sdk) Deprecated legacy Unity SDK # Aptos CLI – Install, Setup, and Use the Command-Line Interface > Learn how to install, configure, and use the Aptos CLI to compile Move contracts, interact with the blockchain, run a local network, and manage nodes. The Aptos command line interface (CLI) is a tool to help you compile and test Move contracts. It can also help you quickly play with Aptos features on-chain. For more advanced users, the CLI can also be used to run a private Aptos network (to help test code locally) and can be helpful managing a network node. ## 📥 Install the Aptos CLI [](#-install-the-aptos-cli) [Mac](/build/cli/install-cli/install-cli-mac) Install Aptos CLI via homebrew [Windows](/build/cli/install-cli/install-cli-windows) Install Aptos CLI on Windows via powershell script or pre-compiled binary [Linux](/build/cli/install-cli/install-cli-linux) Install Aptos CLI on Linux via shell script or pre-compiled binary [Advanced (Install Specific Versions)](/build/cli/install-cli/install-cli-specific-version) Build a specific version of the Aptos CLI from source ## ⚙️ Setup the Aptos CLI [](#️-setup-the-aptos-cli) [Setup the CLI](/build/cli/setup-cli) Setup and configure the Aptos CLI [Advanced (Move Prover)](/build/cli/setup-cli/install-move-prover) Setup and install the Move Prover ## 🛠️ Using the Aptos CLI [](#️-using-the-aptos-cli) [Move Contracts](/build/cli/working-with-move-contracts) Compile, Publish, Simulate, and Benchmark Move Contracts [Trying things On-chain](/build/cli/trying-things-on-chain) Interact with Aptos, create accounts, query accounts, use a hardware device like Ledger [Running a Local Network](/build/cli/running-a-local-network) Run a local node / network # Aptos Blockchain > Core concepts of the Aptos blockchain, including accounts, transactions, Move, execution, staking, and how nodes reach consensus. These pages explain how Aptos works: accounts and resources, how transactions change state, how Move and Block-STM execute those transactions, and how validators, staking, and governance keep the network running. For implementation details, read the [Aptos white paper](/network/blockchain/aptos-white-paper), the [research papers](https://aptoslabs.com/research), and the [aptos-core](https://github.com/aptos-labs/aptos-core) source. For hands-on work, start with [Your First Transaction](/build/guides/first-transaction) and the [Move Book](https://aptos-labs.github.io/move-book/). ## Blockchain fundamentals [](#blockchain-fundamentals) [Aptos White Paper](/network/blockchain/aptos-white-paper) Read the design principles behind Aptos: Move, pipelined execution, and on-chain upgrades. [Blockchain Deep Dive](/network/blockchain/blockchain-deep-dive) Follow a transaction from REST submission through mempool, consensus, execution, and commit. [Blocks](/network/blockchain/blocks) See how Aptos batches transactions into blocks, including system transactions and epochs. [The Move Language](/network/blockchain/move) Learn Move's resource model, Aptos-specific features, and how it compares with other VMs. ## Execution and transactions [](#execution-and-transactions) [Transactions and States](/network/blockchain/txns-states) Understand transaction contents, lifecycle states, proofs, and the versioned ledger. [Transaction Payloads and BCS](/network/blockchain/transaction-payloads) Inspect entry function, script, multisig, orderless, and encrypted payload encodings. [Execution](/network/blockchain/execution) See how Block-STM executes transactions in parallel without declared access lists. [Gas and Storage Fees](/network/blockchain/gas-txn-fee) Learn how execution, IO, and storage fees are charged and refunded. [Computing Transaction Gas](/network/blockchain/base-gas) Break down instruction, IO, storage, and payload gas parameters. [Events](/network/blockchain/events) Emit and query module events, and migrate off deprecated EventHandle streams. ## Accounts and resources [](#accounts-and-resources) [Accounts](/network/blockchain/accounts) Cover addresses, authentication keys, key rotation, sequence numbers, and orderless nonces. [Resources](/network/blockchain/resources) See how Move resources, objects, and modules store on-chain state. ## Network and nodes [](#network-and-nodes) [Validator Nodes](/network/blockchain/validator-nodes) Learn how validators run consensus, execute blocks, and persist ledger state. [Fullnodes](/network/blockchain/fullnodes) Run a replica of ledger state, serve the REST API, and forward transactions. [Node Networking and Sync](/network/blockchain/node-networks-sync) Map validator, VFN, and PFN topology, and how state sync keeps nodes current. ## Staking and governance [](#staking-and-governance) [Staking](/network/blockchain/staking) Stake APT, join the validator set, and earn epoch rewards in the owner-operator-voter model. [Delegated Staking](/network/blockchain/delegated-staking) Pool stake from many delegators so a validator can meet the minimum stake. [Governance](/network/blockchain/governance) Create, vote on, and resolve on-chain proposals that upgrade Aptos. ## Related guides [](#related-guides) These topics sit next to the core model. Use them when you implement wallets, contracts, or indexers: * [Payments](/build/guides/payments) — end-to-end latency, block times, and fees for transfers and related flows * [Objects](/build/smart-contracts/objects) — globally addressable resources at a dedicated address * [Fungible Asset](/build/smart-contracts/fungible-asset) — the current token standard (Coin is legacy) * [Orderless transactions](/build/guides/orderless-transactions) — nonce-based replay protection (AIP-123) * [Sponsored transactions](/build/guides/sponsored-transactions) — a fee payer covers gas * [Encrypted pending transactions](/build/guides/encrypted-pending-transactions) — encrypted payloads while pending (AIP-144) * [Glossary](/network/glossary) — definitions for consensus, gas, proofs, and related terms # Move - A Web3 Language and Runtime > Explore Move on Aptos: resource safety, comparison with other VMs, and Aptos-specific features such as objects, Block-STM, and fungible assets. The Aptos blockchain consists of validator nodes that run a consensus protocol. Consensus agrees on the order of transactions and on their output when executed on the Move Virtual Machine (MoveVM). Each validator feeds the current ledger state plus the block into the VM. The MoveVM produces a changeset (storage delta). Once consensus commits that output, it becomes public. This page covers core Move concepts and how they apply on Aptos. ## What is Move? [](#what-is-move) Move is a programming language for Web3 that emphasizes **scarcity** and **access control**. Assets are represented by or stored inside _resources_. **Scarcity** is the default: a struct cannot be copied or dropped unless the bytecode explicitly grants the `copy` or `drop` ability. **Access control** comes from accounts and module visibility. A module is a library or program that can create, store, or transfer assets. Only `public` (and `public(friend)`) functions are callable from other modules. Unless a struct has a public constructor, only its defining module can create it. Fields are readable and writable only inside that module, or through public accessors. Structs with `key` can enter global storage only from the module that defines them. Structs with `store` can sit inside another `store` or `key` value, including outside the defining module. The sender of a transaction is a _signer_, a verified owner of an account. The signer has the highest privilege in Move and is the only entity that can publish a resource into an account. Module authors can also require a signer to read or update assets under an account. ## Comparison to other VMs [](#comparison-to-other-vms)
Aptos / MoveSolana / SeaLevelEVMSui / Move
Data storageStored at a global address or within the owner’s accountStored in the owner’s account for a programStored in the contract accountStored at a global address
ParallelizationInferred at runtime with Block-STMRequires specifying all data accessedTypically serialRequires specifying all data accessed
Transaction safetySequence number or orderless nonceTransaction uniquenessNoncesTransaction uniqueness
Type safetyModule structs and genericsProgram structsContract typesModule structs and generics
Function callingStatic dispatch, plus function values (Move 2.2)Static dispatchDynamic dispatchStatic dispatch
Authenticated storageYesNoYesNo
Object global accessibilityYesNot applicableNot applicableNo; objects can nest inside others
## Aptos Move features [](#aptos-move-features) Each MoveVM deployment can extend core Move through an adapter. Aptos also ships a framework of modules, similar to an operating system sitting on a CPU. The Aptos Move adapter includes: * [Move objects](/build/smart-contracts/objects) — an extensible model for a heterogeneous set of resources at one on-chain address ([AIP-10](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-010-move-objects.md)). * [Cryptography primitives](/build/smart-contracts/cryptography) for scalable, privacy-preserving apps. * [Resource accounts](/build/smart-contracts/resource-accounts) — programmable accounts without an interactive private key, used for DAOs, shared accounts, and app-owned modules. * [Tables](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-stdlib/sources/table.move) for large key-value collections under an account. * Parallel execution via [Block-STM](/network/blockchain/execution) without declared access lists. * Multi-agent transactions, so one transaction can carry multiple distinct `signer`s. * [Function values](/build/smart-contracts/move-security-guidelines#function-values) (Move 2.2) for first-class functions, with reentrancy rules you must follow. * [On-chain randomness](/build/smart-contracts/randomness) for unbiasable random values in Move. The Aptos framework includes: * The [Fungible Asset standard](/build/smart-contracts/fungible-asset) ([AIP-21](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-021-fungible-assets.md)) — the current token model. Prefer it for new assets. * The [Coin standard](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/coin.move) — the earlier type-parameter token model. Treat it as legacy. APT is paired with a fungible-asset representation; new accounts typically hold APT in a primary fungible store rather than `CoinStore`. * [Aptos Digital Asset (token objects)](/build/smart-contracts/digital-asset) as defined in [AIP-11](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-011-digital-assets-tokens-as-objects.md) and [AIP-22](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-022-no-code-digital-assets-token-objects.md). * [Staking](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/staking_contract.move) and [delegation](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/delegation_pool.move). * [`type_of`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-stdlib/sources/type_info.move) to inspect a type’s address, module, and struct name at runtime. * A [timestamp service](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/timestamp.move) that exposes a monotonically increasing Unix time. ## More resources [](#more-resources) * [Smart contracts overview](/build/smart-contracts) — Move on Aptos, the compiler, and the framework * [Move Book](https://aptos-labs.github.io/move-book/) — language reference * [Framework Book](https://aptos-labs.github.io/framework-book/) — generated docs for `0x1` modules * [Accounts](/network/blockchain/accounts) and [Resources](/network/blockchain/resources) — how Move state is stored # Execution > Explore transaction execution on Aptos, including deterministic processing, Block-STM parallel execution, and why that keeps block times low. On Aptos, **execution** is the step where validators apply an ordered block of transactions to ledger state. The output must be [deterministic](https://en.wikipedia.org/wiki/Deterministic_algorithm): honest validators that start from the same state and the same block must produce the same write set. A supermajority of voting power (more than two-thirds) must agree on that result before the block commits. See [BFT](/network/glossary#byzantine-fault-tolerance-bft) and [consensus](/network/glossary#consensus). Execution speed shows up as block time. Aptos does not wait on a fixed slot clock; it proposes the next block as soon as the network allows. Mainnet block times are typically tens of milliseconds. See [Blocks](/network/blockchain/blocks). ## Why parallel execution? [](#why-parallel-execution) flowchart TB subgraph sequential \[Sequential\] direction LR S1\[Txn 1\] --> S2\[Txn 2\] --> S3\[Txn 3\] end subgraph staticp \[Static parallelism\] direction LR D1\[Declare access lists\] --> D2\[Schedule non-overlapping txns\] end subgraph dynamicp \[Dynamic parallelism\] direction LR P1\[Execute speculatively\] --> P2\[Detect conflicts\] --> P3\[Re-execute in preset order\] end Executing a block one transaction at a time is simple and does not scale. Long transactions stall everything behind them, so latency and throughput collapse under load. Parallel execution runs many transactions at once. The hard part is conflicts: two transactions that read or write the same resource cannot both commit as if they ran alone in the wrong order. ### Static parallelism [](#static-parallelism) **Static parallelism** asks developers (or the runtime, from annotations) to declare which data each transaction will touch. The scheduler then runs non-overlapping transactions together. That shifts the burden onto application authors. Declared sets are often wider than the data a transaction actually uses, so independent work is forced to run serially. ### Dynamic parallelism [](#dynamic-parallelism) **Dynamic parallelism** finds conflicts at runtime. Transactions execute speculatively; if two of them collide, the engine re-executes the later one. The committed result must still match executing the block in the **preset consensus order**. Developers do not declare access lists. They write ordinary Move, and the engine parallelizes whatever does not conflict. ## Block-STM [](#block-stm) Aptos executes blocks with **Block-STM**, a multi-threaded, in-memory engine that combines software transactional memory with a collaborative scheduler. It uses the consensus order as the serial baseline, executes transactions in parallel, and re-executes only the ones that aborted because of a conflict. Block-STM is the dynamic-parallelism engine originally built by Aptos Labs. [Polygon](https://polygon.technology/blog/innovating-the-main-chain-a-polygon-pos-study-in-parallelization), Sei, [Starknet](https://www.starknet.io/blog/parallel-execution-and-v0-13-2/), and other chains have adopted the same approach. To learn more: * [Block-STM blog post](https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba) * [Block-STM paper](https://arxiv.org/pdf/2203.06871) * [a16z crypto research talk](https://www.youtube.com/watch?v=2SE5tqPzhyw) * [Stark Spaces | Block-STM and Starknet](https://www.youtube.com/watch?v=y1kXOi39RX0) * [Block-STM: Accelerating Smart-Contract Processing](https://blog.chain.link/block-stm/) * [Transactions and States](/network/blockchain/txns-states) — how execution writes versioned ledger state * [Computing Transaction Gas](/network/blockchain/base-gas) — how execution and IO are metered # Blocks > Understand blocks on Aptos, including system transactions, block epilogues, epochs, and how the versioned ledger stores per-transaction state. Aptos versions ledger state **per transaction**, not per block. After execution, each transaction’s resulting state is stored separately, so clients can read and prove a single version. That differs from chains that persist only the post-block state. Blocks are still the unit of consensus and proof. Validators agree on an ordered batch of transactions, execute that batch with [Block-STM](/network/blockchain/execution), and persist the results. Storage [proofs](/network/blockchain/txns-states#proofs) are at block granularity. How many user transactions land in a block depends on network activity and on-chain limits (gas, output size, and maximum block size). Block production is not a fixed slot time. Aptos proposes the next block as soon as network delay allows. Mainnet block times are typically tens of milliseconds; check live timestamps on [Explorer](https://explorer.aptoslabs.com/blocks?network=mainnet). For how block time relates to payment end-to-end latency and fees, see [Payments](/build/guides/payments). See [Aptos Blockchain Deep Dive](/network/blockchain/blockchain-deep-dive) for the full path from submission to commit. ## System transactions [](#system-transactions) A block is more than user transactions. Consensus inserts system transactions that mark the batch and, in some cases, carry protocol data: 1. **`BlockMetadataTransaction`** — first transaction in the block. It records the proposer, timestamp, and round. At an epoch boundary it can also trigger validator-set changes and reward distribution. 2. **`ValidatorTransaction`** — optional protocol payloads from validators, such as JWK updates or randomness (DKG) material. These are not submitted by users. 3. **User transactions** — signed transactions from accounts. See [Transactions and States](/network/blockchain/txns-states). 4. **`BlockEpilogueTransaction`** — last transaction in the block in the common case. It carries `BlockEndInfo` (whether the block hit gas or output limits, plus approximate usage). Introduced in [AIP-88](/build/aips/aip-88), it replaced `StateCheckpointTransaction` as the usual end-of-block marker. The last block of an [epoch](#epochs) has no `BlockEpilogueTransaction`. Indexers and explorers that assumed every block ended with `StateCheckpoint` must handle `block_epilogue_transaction` instead. A typical mainnet block looks like: ``` BlockMetadataTransaction[ValidatorTransaction ...] // optional[user transactions ...]BlockEpilogueTransaction // omitted on the last block of an epoch ``` ## Epochs [](#epochs) An **epoch** is a longer interval used to apply validator-set changes, redistribute voting power, and pay staking rewards. Mainnet, testnet, and devnet epochs are **two hours** (7200 seconds). The number of blocks in an epoch is however many the network produces in that window. Major configuration changes — for example a validator joining or leaving the set — take effect only at the start of the next epoch. See [Staking](/network/blockchain/staking#epoch) for the on-epoch triggers. # Gas and Storage Fees > Learn about gas fees and storage costs on Aptos, including execution costs, storage fees, gas pricing, and optimization strategies for efficient transactions. Any transaction execution on the Aptos blockchain requires a processing fee. That fee has two components: 1. Execution & IO costs * This covers your usage of transient computation resources, such as processing your transactions and propagating the validated record throughout the distributed network of the mainnet. * It is measured in Gas Units whose price may fluctuate according to the load of the network. This allows execution and IO costs to be low when the network is less busy. * This portion of gas is burned permanently upon the execution of a transaction. 2. Storage fees * This covers the cost to persistently store validated record in the distributed blockchain storage. * It is measured in fixed APT prices, so the permanent storage cost stays stable even as the gas unit price fluctuates with the network’s transient load. * The storage fee can be refunded when the allocated storage slot is deleted. Currently, the network is configured to refund the entirety of the storage fee paid over the lifetime of a state storage slot. * To keep system implementation simple, this portion of gas is burned and minted again upon refund. ## Unit of gas [](#unit-of-gas) Transactions can range from simple and inexpensive to complicated based upon what they do. In the Aptos blockchain, a **unit of gas** represents a basic unit of consumption for transient resources, such as doing computation or accessing the storage. The latter should not be conflated with the long-term storage aspect of such operations, as that is covered by the storage fees separately. See [How Base Gas Works](/network/blockchain/base-gas) for a detailed description of gas fee types and available optimizations. For typical payment fees next to block time and end-to-end latency, see [Payments](/build/guides/payments). ## The Fee Statement [](#the-fee-statement) As of Aptos Framework release 1.7, the breakdown of fee charges and refunds is emitted as a module event represented by struct `0x1::transaction_fee::FeeStatement`. ``` #[event]/// Breakdown of fee charge and refund for a transaction./// The structure is:////// - Net charge or refund (not in the statement)/// - total charge: total_charge_gas_units, matches `gas_used` in the on-chain `TransactionInfo`./// This is the sum of the sub-items below. Notice that there's potential precision loss when/// the conversion between internal and external gas units and between native token and gas/// units, so it's possible that the numbers don't add up exactly. -- This number is the final/// charge, while the break down is merely informational./// - gas charge for execution (CPU time): `execution_gas_units`/// - gas charge for IO (storage random access): `io_gas_units`/// - storage fee charge (storage space): `storage_fee_octas`, to be included in/// `total_charge_gas_unit`, this number is converted to gas units according to the user/// specified `gas_unit_price` on the transaction./// - storage deletion refund: `storage_fee_refund_octas`, this is not included in `gas_used` or/// `total_charge_gas_units`, the net charge / refund is calculated by/// `total_charge_gas_units` * `gas_unit_price` - `storage_fee_refund_octas`.////// This is meant to be emitted as a module event.struct FeeStatement has drop, store { /// Total gas charge. total_charge_gas_units: u64, /// Execution gas charge. execution_gas_units: u64, /// IO gas charge. io_gas_units: u64, /// Storage fee charge. storage_fee_octas: u64, /// Storage fee refund. storage_fee_refund_octas: u64,} ``` ## Gas price and prioritizing transactions [](#gas-price-and-prioritizing-transactions) In the Aptos network, the Aptos governance sets the absolute minimum gas unit price. However, the market determines how quickly a transaction with a particular gas unit price is processed. See [Ethereum Gas Tracker](https://etherscan.io/gastracker), for example, which shows the market price movements of Ethereum gas price. By specifying a higher gas unit price than the current market price, you can **increase** the priority level for your transaction on the blockchain by paying a larger processing fee. As part of consensus, when the leader selects transactions from its mempool to propose as part of the next block, it will prioritize selecting transactions with a higher gas unit price. Please note that higher gas fees only prioritize transaction selection for the next block. However, within a block, the order of transaction execution is determined by the system. This order is based on [transaction shuffling](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-027-sender-aware-transaction-shuffling.md), which makes parallel execution more efficient by considering conflict patterns. While in most cases this is unnecessary, if the network is under load this measure can ensure your transaction is processed more quickly. See the `gas_unit_price` entry under [Estimating the gas units via simulation](#estimating-gas-consumption-via-simulation) for details. Caution If you raise `gas_unit_price` while the same account still has in-flight sequenced transactions, resubmit those earlier transactions at the higher price too. Sequenced transactions from one account must commit in sequence-number order, so a high-price transaction waits for the lower-price ones ahead of it. [Orderless transactions](/build/guides/orderless-transactions) do not have this constraint. ## Specifying gas fees within a transaction [](#specifying-gas-fees-within-a-transaction) When a transaction is submitted to the Aptos blockchain, the transaction must contain the following mandatory gas fields: * `max_gas_amount`: The maximum number of gas units that the transaction sender is willing to spend to execute the transaction. This determines the maximum computational and storage resources that can be consumed by the transaction. * `gas_unit_price`: The price per gas unit the transaction sender is willing to pay. It is expressed in [Octas](/network/glossary#octa). During the transaction execution, the total gas amount, expressed as: ``` (total execution gas units consumed) + (total storage gas units consumed) ``` must not exceed `max_gas_amount`, or else the transaction will abort the execution. The transaction fee charged to the client will be at the most `gas_unit_price * max_gas_amount`. ## Gas parameters set by governance [](#gas-parameters-set-by-governance) The following gas parameters are set by Aptos governance. * `txn.maximum_number_of_gas_units`: Maximum number of gas units that can be spent (this is the maximum allowed value for the `max_gas_amount` gas parameter in the transaction). This is to ensure that the dynamic pricing adjustments do not exceed how much you are willing to pay in total. * `txn.min_transaction_gas_units`: Minimum number of gas units that can be spent. The `max_gas_amount` value in the transaction must be set to greater than this parameter’s value. There also exists some global per-category limits: * `txn.max_execution_gas`: The maximum number of gas units a transaction can spend on execution. * `txn.max_io_gas`: The maximum number of gas units a transaction can spend on IO. * `txn.max_storage_fee`: The maximum amount of APT a transaction can spend on persistent storage. These limits help decouple one category from another, allowing us to set `txn.maximum_number_of_gas_units` generously without having to worry about abuses. ## Calculating Storage Fees [](#calculating-storage-fees) The storage fee for a transaction is charged according to the number of new slots allocated in the global state and the size increase in the existing slots. There are some nuances with regard to price changing and legacy slots which didn’t pay for the size of the slot below a historical “free quota”. Refer to [AIP-65](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-065-storage-fee-for-state-bytes-refundable.md#specification) for more details. It should also be noted that due to some backward compatibility reasons, the total storage fee of a transaction is currently presented to the client as part of the total `gas_used`. This means, this amount could vary based on the gas unit price even for the same transaction. Here is an example. Suppose we have a transaction that costs `100` gas units in execution & IO, and `5000` [Octas](/network/glossary#octa) in storage fees. The network will show that you have used * `100 + 5000 / 100 = 150` gas units if the gas unit price is `100`, or * `100 + 5000 / 200 = 125` gas units if the unit price is `200`. We are aware of the confusion this might create, and plan to present these as separate items in the future. However, this will require some changes to the transaction output format and downstream clients, so please be patient while we work hard to make this happen. ## Calculating Storage Deletion Refund [](#calculating-storage-deletion-refund) If a transaction deletes state items, a refund is issued to the transaction payer for the released storage slots. Currently, a full refund is issued — that is, all storage fee paid for the slot and bytes of the item over the lifetime of it. The refund amount is denominated in APT and is not converted to gas units or included in the total `gas_used`. Instead, this refund amount is specifically detailed in the `storage_fee_refund_octas` field of the [`FeeStatement`](#the-fee-statement). As a result, the transaction’s net effect on the payer’s APT balance is determined by `gas_used * gas_unit_price - storage_refund`. If the result is positive, there is a deduction from the account balance; if negative, there is a deposit. ## Examples [](#examples) ### Example 1: Account balance vs transaction fee [](#example-1-account-balance-vs-transaction-fee) **The sender’s account must have sufficient funds to pay for the transaction fee.** If, let’s say, you transfer all the money out of your account so that you have no remaining balance to pay for the transaction fee. In such case the Aptos blockchain would let you know that the transaction will fail, and your transfer wouldn’t succeed either. ### Example 2: Transaction amounts vs transaction fee [](#example-2-transaction-amounts-vs-transaction-fee) **Transaction fee is independent of transfer amounts in the transaction.** In a transaction, for example, transaction A, you are transferring 1000 coins from one account to another account. In a second transaction B, with the same gas field values of transaction A, you now transfer 100,000 coins from one account to another one account. Assuming that both the transactions A and B are sent roughly at the same time, then the gas costs for transactions A and B would be near-identical. ## Estimating gas consumption via simulation [](#estimating-gas-consumption-via-simulation) The gas used for a transaction can be estimated by simulating the transaction on chain as described here or locally via the gas profiling feature of the Aptos CLI. The results of the simulated transaction represent the **exact** amount that is needed at the **exact** state of the blockchain at the time of the simulation. These gas units used may change based on the state of the chain. For this reason, any amount coming out of the simulation is only an estimate, and when setting the max gas amount, it should include an appropriate amount of headroom based upon your comfort-level and historical behaviors. Setting the max gas amount too low will result in the transaction aborting and the account being charged for whatever gas was consumed. To simulate transactions on chain, use the [`SimulateTransaction`](https://api.devnet.aptoslabs.com/v1/spec#/operations/simulate_transaction) API. This API runs the exact transaction you plan to submit. To simulate the transaction locally, use the gas profiler, which is integrated into the Aptos CLI. This will generate a web-based report to help you understand the precise gas usage of your transaction. See [Gas Profiling](/build/cli/working-with-move-contracts/local-simulation-benchmarking-and-gas-profiling#gas-profiling) for more details. To simulate the transaction, there are two flags: 1. `estimate_gas_unit_price`: This flag will estimate the gas unit price in the transaction using the same algorithm as the [`estimate_gas_price`](https://api.devnet.aptoslabs.com/v1/spec#/operations/estimate_gas_price) API. 2. `estimate_max_gas_amount`: This flag will find the maximum possible gas you can use, and it will simulate the transaction to tell you the actual `gas_used`. ### Simulation steps [](#simulation-steps) The simulation steps for finding the correct amount of gas for a transaction are as follows: 1. Estimate the gas via simulation with both `estimate_gas_unit_price` and `estimate_max_gas_amount` set to `true`. 2. Use the `gas_unit_price` in the returned transaction as your new transaction’s `gas_unit_price`. 3. View the `gas_used * gas_unit_price` values in the returned transaction as the **lower bound** for the cost of the transaction. 4. To calculate the upper bound of the cost, take the **minimum** of the `max_gas_amount` in the returned transaction, and the `gas_used * safety factor`. In the CLI a value of `1.5` is used for `safety factor`. Use this value as `max_gas_amount` for the transaction you want to submit. Note that the **upper bound** for the cost of the transaction is `max_gas_amount * gas_unit_price`, i.e., this is the most the sender of the transaction is charged. 5. At this point you now have your `gas_unit_price` and `max_gas_amount` to submit your transaction as follows: 1. `gas_unit_price` from the returned simulated transaction. 2. `max_gas_amount` as the minimum of the `gas_used` \* `a safety factor` or the `max_gas_amount` from the transaction. 6. If you feel the need to prioritize or deprioritize your transaction, adjust the `gas_unit_price` of the transaction. Increase the value for higher priority, and decrease the value for lower priority. # Staking > Understand staking on Aptos blockchain, including validator operations, rewards, lockup periods, and the owner-operator-voter model for network participation. In a distributed system like blockchain, executing a transaction is distinct from updating the state of the ledger and persisting the results in storage. An agreement, i.e., consensus, must be reached by a quorum of validators on the ordering of transactions and their execution results before these results are persisted in storage and the state of the ledger is updated. Anyone can participate in the Aptos consensus process, if they stake sufficient utility coin, i.e., place their utility coin into escrow. To encourage validators to participate in the consensus process, each validator’s vote weight is proportional to the amount of validator’s stake. In exchange, the validator is rewarded proportionally to the amount staked. Hence, the performance of the blockchain is aligned with the validator’s interest, i.e., rewards. The current on-chain data can be found in [`staking_config::StakingConfig`](https://api.mainnet.aptoslabs.com/v1/accounts/0x1/resource/0x1::staking_config::StakingConfig). The configuration set is defined in [`staking_config.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/configs/staking_config.move). The rest of this document presents how staking works on the Aptos blockchain. See [Supporting documentation](#supporting-documentation) at the bottom for related resources. ## Staking on the Aptos blockchain [](#staking-on-the-aptos-blockchain) Below is a summary flow diagram of how staking on the Aptos blockchain works. The sections following the summary describe it in detail. ![Staking Flow](/_astro/staking-light.tXXsfFR-.svg) ![Staking Flow](/_astro/staking-dark.DVUrnYgo.svg) The Aptos staking module defines a capability that represents ownership. The `OwnerCapability` resource can be used to control the stake pool. Three personas are supported: * Owner * Operator * Voter Using this owner-operator-voter model, a custodian can assume the owner persona and stake on the Aptos blockchain and participate in the Aptos governance. This model allows delegations and staking services to be built as it separates the account that is in control of the funds from the other accounts (operator, voter), hence allows secure delegations of responsibilities. This section describes how this works, using Bob and Alice in the example. ### Owner [](#owner) The owner is the owner of the funds. For example, Bob creates an account on the Aptos blockchain. Now Bob has the `OwnerCapability` resource. Bob can assign his account’s operator address to the account of Alice, a trusted node operator, to appoint Alice as a validator. As an owner: * Bob owns the funds that will be used for staking. * Only Bob can add, unlock or withdraw funds. * Only Bob can extend the lockup period. * Bob can change the node operator Alice to some other node operator anytime Bob wishes to do so. * Bob can set the operator commission percentage. * The reward will be deposited into Bob’s (owner’s) account. ### Operator [](#operator) A node operator is assigned by the fund owner to run the validator node and receives commission as set by the owner. The two personas, the owner and the operator, can be two separate entities or the same. For example, Alice (operator) runs the validator node, operating at the behest of Bob, the fund owner. As an operator: * Alice has permissions only to join or leave the validator set. * As a validator, Alice will perform the validating function. * Alice has the permissions to change the consensus key and network addresses. The consensus key is used by Alice to participate in the validator consensus process, i.e., to vote and propose a block. Alice is allowed to change (“rotate”) this key in case this key is compromised. * However, Alice cannot move funds (unless Alice is the owner, i.e., Alice has the `OwnerCapability` resource). * The operator commission is deducted from the staker (owner) rewards and deposited into the operator account. ### Voter [](#voter) An owner can designate a voter. This enables the voter to participate in governance. The voter will use the voter key to sign the governance votes in the transactions. ## Validation on the Aptos blockchain [](#validation-on-the-aptos-blockchain) Throughout the duration of an epoch, the following flow of events occurs several times (thousands of times): * A validator leader is selected by a deterministic formula based on the validator reputation determined by validator’s performance (including whether the validator has voted in the past or not) and stake. **This leader selection is not done by voting.** * The selected leader sends a proposal containing the collected quorum votes of the previous proposal and the leader’s proposed order of transactions for the new block. * All the validators from the validator set will vote on the leader’s proposal for the new block. Once consensus is reached, the block can be finalized. Hence, the actual list of votes to achieve consensus is a subset of all the validators in the validator set. This leader validator is rewarded. **Rewards are given only to the leader validator, not to the voter validators.** * The above flow repeats with the selection of another validator leader and repeating the steps for the next new block. Rewards are given at the end of the epoch. ## Validator state and stake state [](#validator-state-and-stake-state) States are defined for a validator and the stake. * **Validator state:** A validator can be in any one of these four states. Moreover, the validator can go from inactive (not tracked in the validator set anywhere) state to any one of the other three states: * inactive * pending\_active. * active. * pending\_inactive. * **Stake state:** A validator in pending\_inactive or active state, can have their stake in either of these four states: * inactive. * pending\_active. * active. * pending\_inactive. These stake states are applicable for the existing validators in the validator set adding or removing their stake. ### Validator states [](#validator-states) ![Signed Transaction Flow](/_astro/validator-state.D6ztszN1.svg) ![Signed Transaction Flow](/_astro/validator-state-dark.CScBuPOd.svg) There are two edge cases to call out: 1. If a validator’s stake drops below the required [minimum](#minimum-and-maximum-stake), that validator will be moved from active state directly to the inactive state during an epoch change. This happens only during an epoch change. 2. Aptos governance can also directly remove validators from the active set. **Note that governance proposals will always trigger an epoch change.** ### Stake state [](#stake-state) The state of stake has more granularity than that of the validator; additional stake can be added and a portion of stake removed from an active validator. ![Signed Transaction Flow](/_astro/stake-state.D4F03QIl.svg) ![Signed Transaction Flow](/_astro/stake-state-dark.Bnq4nSt9.svg) ### Validator rules [](#validator-rules) The following rules apply during state changes: * Voting power can change (increase or decrease) only on epoch boundary. * A validator’s consensus key and the validator and validator fullnode network addresses can change only on epoch boundary. * Pending inactive stake cannot be moved into inactive (and thus withdrawable) until the lockup expires. * No validators in the active validator set can have their stake below the minimum required stake. ## Validator flow [](#validator-flow) 1. Owner initializes the stake pool with `aptos stake create-staking-contract`. 2. When the owner is ready to deposit the stake (or have funds assigned by a staking service in exchange for ownership capability), owner calls `aptos stake add-stake`. 3. When the validator node is ready, the operator can call `aptos node join-validator-set` to join the active validator set. Changes will be effective in the next epoch. 4. Validator validates (proposes blocks as a leader-validator) and gains rewards. The stake will automatically be locked up for a fixed duration (set by governance) and automatically renewed at expiration. 5. At any point, if the operator wants to update the consensus key or validator network addresses, they can call `aptos node update-consensus-key` or `aptos node update-validator-network-addresses`. Similar to changes to stake, the changes to consensus key or validator network addresses are only effective in the next epoch. 6. Validator can request to unlock their stake at any time. However, their stake will only become withdrawable when their current lockup expires. This can be at most as long as the fixed lockup duration. 7. After exiting, the validator can either explicitly leave the validator set by calling `aptos node leave-validator-set` or if their stake drops below the min required, they would get removed at the end of the epoch. 8. Validator can always rejoin the validator set by going through steps 2-3 again. 9. An owner can always switch operators by calling `aptos stake set-operator`. 10. An owner can always switch designated voter by calling `aptos stake set-delegated-voter`. ## Joining the validator set [](#joining-the-validator-set) Participating as a validator node on the Aptos network works like this: 1. Operator runs a validator node and configures the on-chain validator network addresses and rotates the consensus key. 2. The owner deposits APT as stake, or has funds assigned by a staking service. The stake must be at least the minimum amount required. 3. **The validator node cannot sync until the stake pool becomes active.** 4. Operator validates and gains rewards. 5. The staked pool is automatically locked up for a fixed duration (set by Aptos governance) and is automatically renewed at expiration. You cannot withdraw any of your staked amount until your lockup period expires. See [`stake.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/stake.move). 6. Operator must wait until the new epoch starts before their validator becomes active. ### Minimum and maximum stake [](#minimum-and-maximum-stake) You must stake the required minimum amount to join the validator set. Moreover, you can only stake up to the maximum stake amount. The current required minimum for staking is 1M APT and the maximum is 50M APT. On-chain values are in Octas (`minimum_stake` / `maximum_stake` on [`StakingConfig`](https://api.mainnet.aptoslabs.com/v1/accounts/0x1/resource/0x1::staking_config::StakingConfig)). The recurring lockup on mainnet is currently 14 days (`recurring_lockup_duration_secs`). If at any time after joining the validator set, your current staked amount exceeds the maximum allowed stake (for example as the rewards are added to your staked amount), then your voting power and the rewards will be calculated only using the maximum allowed stake amount, and not your current staked amount. The owner can withdraw part of the stake and leave their balance below the required minimum. In such case, their stake pool will be removed from the validator set when the next epoch starts. ### Automatic lockup duration [](#automatic-lockup-duration) When you join the validator set, your stake will automatically be locked up for a fixed duration that is set by the Aptos governance. ### Automatic lockup renewal [](#automatic-lockup-renewal) When your lockup period expires, it will be automatically renewed, so that you can continue to validate and receive the rewards. ### Unlocking your stake [](#unlocking-your-stake) You can request to unlock your stake at any time. However, your stake will only become withdrawable when your current lockup expires. This can be at most as long as the fixed lockup duration. You will continue earning rewards on your stake until it becomes withdrawable. The principal amount is updated when any of the following actions occur: 1. Operator [requests commission unlock](/network/nodes/validator-node/connect-nodes/staking-pool-operations#requesting-commission) 2. Staker (owner) withdraws funds 3. Staker (owner) switches operators When the staker unlocks stake, this also triggers a commission unlock. The full commission amount for any staking rewards earned is unlocked. This is not proportional to the unlock stake amount. Commission is distributed to the operator after the lockup ends when `request commission` is called a second time or when staker withdraws (distributes) the unlocked stake. ### Resetting the lockup [](#resetting-the-lockup) When the lockup period expires, it is automatically renewed by the network. However, the owner can explicitly reset the lockup. ## Epoch [](#epoch) An epoch in the Aptos blockchain is defined as a duration of time, in seconds, during which a number of blocks are voted on by the validators, the validator set is updated, and the rewards are distributed to the validators. ### Triggers at the epoch start [](#triggers-at-the-epoch-start) At the start of each epoch, the following key events are triggered: * Update the validator set by adding the pending active validators to the active validators set and by removing the pending inactive validators from the active validators set. * Move any pending active stake to active stake, and any pending inactive stake to inactive stake. * The staking pool’s voting power in this new epoch is updated to the total active stake. * Automatically renew a validator’s lockup for the validators who will still be in the validator set in the next epoch. * The voting power of each validator in the validator set is updated to be the corresponding staking pool’s voting power. * Rewards are distributed to the validators that participated in the previous epoch. ## Rewards [](#rewards) Rewards for staking are calculated by using: 1. The `rewards_rate`, an annual percentage yield (APY), i.e., rewards accrue as a compound interest on your current staked amount. 2. Your staked amount. 3. Your proposer performance in the Aptos governance. ### Rewards formula [](#rewards-formula) See below the formula used to calculate rewards to the validator: ``` Reward = staked_amount * rewards_rate per epoch * (Number of successful proposals by the validator / Total number of proposals made by the validator) ``` ### Rewards paid every epoch [](#rewards-paid-every-epoch) Rewards are paid every epoch. Any reward you (i.e., validator) earned at the end of current epoch is added to your staked amount. The reward at the end of the next epoch is calculated based on your increased staked amount (i.e., original staked amount plus the added reward), and so on. ### Rewards based on the proposer performance [](#rewards-based-on-the-proposer-performance) The validator rewards calculation uses the validator’s proposer performance. Once you are in the validator set, you can propose in every epoch. The more successfully you propose, i.e., your proposals pass, the more rewards you will receive. Note that rewards are given only to the **leader-validators**, i.e., validators who propose the new block, and not to the **voter-validators** who vote on the leader’s proposal for the new block. See [Validation on the Aptos blockchain](#validation-on-the-aptos-blockchain). ## Leaving the validator set [](#leaving-the-validator-set) * At any time you can call the following sequence of functions to leave the validator set: * Call `Stake::unlock` to unlock your stake amount, and * Either call `Stake::withdraw` to withdraw your staked amount at the next epoch, or call `Stake::leave_validator_set`. ## Rejoining the validator set [](#rejoining-the-validator-set) When you leave a validator set, you can rejoin by depositing the minimum required stake amount. ## Supporting documentation [](#supporting-documentation) * [Current on-chain data](https://api.mainnet.aptoslabs.com/v1/accounts/0x1/resource/0x1::staking_config::StakingConfig) * [Staking Pool Operations](/network/nodes/validator-node/connect-nodes/staking-pool-operations) * [Delegation Pool Operations](/network/nodes/validator-node/connect-nodes/delegation-pool-operations) * [Configuration file `staking_config.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/configs/staking_config.move) * [Contract file `staking_contract.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/staking_contract.move) covering requesting commissions * [All staking-related `.move` files](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/framework/aptos-framework/sources) # Smart Contracts > Learn to write secure, efficient smart contracts on Aptos using the Move programming language with examples, tutorials, and developer resources Aptos contracts are written using Move, a next generation language for secure, sandboxed, and formally verified programming which is used for multiple chains. Move allows developers to write programs that flexibly manage and transfer assets while providing security and protections against attacks on those assets. ## 📖 Learn Move [](#-learn-move) [Why Move?](/build/smart-contracts/why-move) Learn why Aptos uses the Move Language [Create Package](/build/smart-contracts/create-package) Get started by learning how to create a Move package [Objects](/build/smart-contracts/objects) Learn how to use the Object standard on Aptos to create composable and flexible primitives on chain ## 👨‍💻 Move Examples [](#-move-examples) [Aptos Move Examples](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples) 30+ examples on how to develop Move on Aptos [Move Tutorial](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples/move-tutorial) Covers the basics of programming with Move [Your first Move Module](/build/guides/first-move-module) A example of how to publish your first move module Here is a `hello_blockchain` example of move hello\_blockchain.move ``` module hello_blockchain::message { use std::error; use std::signer; use std::string; use aptos_framework::event; //:!:>resource struct MessageHolder has key { message: string::String, } //<:!:resource #[event] struct MessageChange has drop, store { account: address, from_message: string::String, to_message: string::String, } /// There is no message present const ENO_MESSAGE: u64 = 0; #[view] public fun get_message(addr: address): string::String acquires MessageHolder { assert!(exists(addr), error::not_found(ENO_MESSAGE)); borrow_global(addr).message } public entry fun set_message(account: signer, message: string::String) acquires MessageHolder { let account_addr = signer::address_of(&account); if (!exists(account_addr)) { move_to(&account, MessageHolder { message, }) } else { let old_message_holder = borrow_global_mut(account_addr); let from_message = old_message_holder.message; event::emit(MessageChange { account: account_addr, from_message, to_message: copy message, }); old_message_holder.message = message; } } #[test(account = @0x1)] public entry fun sender_can_set_message(account: signer) acquires MessageHolder { let addr = signer::address_of(&account); aptos_framework::account::create_account_for_test(addr); set_message(account, string::utf8(b"Hello, Blockchain")); assert!( get_message(addr) == string::utf8(b"Hello, Blockchain"), ENO_MESSAGE ); }} ``` ## ⚒️ Developer Resources [](#️-developer-resources) ### FAQ and Discussions [](#faq-and-discussions) * [Aptos Dev Discussions](https://github.com/aptos-labs/aptos-developer-discussions/discussions) for Q&A about Move. ### Move IDE plugins [](#move-ide-plugins) * Move on Aptos extension for [VSCode](https://marketplace.visualstudio.com/items?itemName=AptosLabs.move-on-aptos) and [OpenVSX](https://open-vsx.org/extension/aptoslabs/move-on-aptos). * [Move language plugin for JetBrains IDEs](https://plugins.jetbrains.com/plugin/14721-move-language) ### External Resources [](#external-resources) * [Aptos Move by Example](https://move-developers-dao.gitbook.io/aptos-move-by-example) * [Teach yourself Move on Aptos](https://github.com/econia-labs/teach-yourself-move). * [Formal Verification, the Move Language, and the Move Prover](https://www.certik.com/resources/blog/2wSOZ3mC55AB6CYol6Q2rP-formal-verification-the-move-language-and-the-move-prover) * [Collection of nestable Move resources](https://github.com/taoheorg/taohe) We have a new Move on Aptos compiler that supports Move 2. See [this page](/build/smart-contracts/compiler_v2) for more information. # Building with Objects > Learn about objects for Aptos Objects in smart contract development. In Move, Objects group resources together so they can be treated as a single entity on chain. Objects have their own address and can own resources similar to an account. They are useful for representing more complicated data types on-chain as Objects can be used in entry functions directly, and can be transferred as complete packages instead of one resource at a time. Here’s an example of creating an Object and transferring it: ``` module my_addr::object_playground { use std::signer; use std::string::{Self, String}; use aptos_framework::object::{Self, ObjectCore}; struct MyStruct1 has key { message: String, } struct MyStruct2 has key { message: String, } entry fun create_and_transfer(caller: &signer, destination: address) { // Create object let caller_address = signer::address_of(caller); let constructor_ref = object::create_object(caller_address); let object_signer = object::generate_signer(&constructor_ref); // Set up the object by creating 2 resources in it move_to(&object_signer, MyStruct1 { message: string::utf8(b"hello") }); move_to(&object_signer, MyStruct2 { message: string::utf8(b"world") }); // Transfer to destination let object = object::object_from_constructor_ref( &constructor_ref ); object::transfer(caller, object, destination); }} ``` During construction, Objects can be configured to be transferrable and extensible. For example, you could use an Object to represent a soulbound NFT by making it only transferrable once, and have it own resources for an image link and metadata. Objects can also own other Objects, so you could implement your own NFT collection Object by transferring several of the soulbound NFTs to it. ## Learn how to [](#learn-how-to) * [Create and configure a new Object.](/build/smart-contracts/object/creating-objects) * [Use Objects you created.](/build/smart-contracts/object/using-objects) ## Examples with Object contracts [](#examples-with-object-contracts) * [Digital Asset Marketplace Example](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples/marketplace) * [Digital Assets Examples](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples/token_objects) * [Fungible Asset Examples](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples/fungible_asset) # Randomness API > Learn about randomness for Move smart contract development on Aptos blockchain. ## What does it do: a quick example [](#what-does-it-do-a-quick-example) ### How random numbers have been obtained, insecurely/awkwardly [](#how-random-numbers-have-been-obtained-insecurelyawkwardly) Building a lottery system and pick a random winner from `n` participants is trivial, at least in the centralized world with a trusted server: the backend simply calls a random integer sampling function (`random.randint(0, n-1)` in python, or `Math.floor(Math.random() * n)` in JS). Unfortunately, without an equivalent of `random.randint()` in Aptos Move, building a dApp version of it was actually much harder. One may have written a contract where the random numbers are sampled insecurely (e.g., from the blockchain timestamp): ``` module module_owner::lottery { // ... struct LotteryState { players: vector
, winner_idx: std::option::Option, } fun load_lottery_state_mut(): &mut LotteryState { // ... } entry fun decide_winner() { let lottery_state = load_lottery_state_mut(); let n = std::vector::length(&lottery_state.players); let winner_idx = aptos_framework::timestamp::now_microseconds() % n; lottery_state.winner_idx = std::option::some(winner_idx); }} ``` The implementation above is insecure in multiple ways: * a malicious user may bias the result by picking the transaction submission time; * a malicious validator can bias the result easily by selecting which block the `decide_winner` transaction goes to. Other dApps may have chosen to use an external secure randomness source (e.g., [drand](https://drand.love/)), which is typically a complicated flow: 1. The participants agree on using a future randomness seed promised by the randomness source to determine the winner. 2. Once the randomness seed is revealed, the clients fetch it and derive the winner locally. 3. One of the participants submits the seed and the winner on chain. ``` module module_owner::lottery { // ... struct LotteryState { players: vector
, /// public info about the "future randomness", tyipcally a VRF public key and an input. seed_verifier: vector, winner_idx: std::option::Option, } fun load_lottery_state_mut(): &mut LotteryState { // ... } fun is_valid_seed(seed_verifier: vector, seed: vector): bool { // ... } fun derive_winner(n: u64, seed: vector): u64 { // ... } entry fun update_winner(winner_idx: u64, seed: vector) { let lottery_state = load_lottery_state_mut(); assert!(is_valid_seed(lottery_state.seed_verifier, seed), ERR_INVALID_SEED); let n = std::vector::length(players); let expected_winner_idx = derive_winner(n, seed); assert!(expected_winner_idx == winner_idx, ERR_INCORRECT_DERIVATION); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` ### Achieve simplicity + security with Aptos randomness API [](#achieve-simplicity--security-with-aptos-randomness-api) Using Aptos randomness API, the implementation will look like this: ``` module module_owner::lottery { // ... use aptos_framework::randomness; struct LotteryState { players: vector
, winner_idx: std::option::Option, } fun load_lottery_state_mut(): &mut Lottery { // ... } #[randomness] entry fun decide_winner() { let lottery_state = load_lottery_state_mut(); let n = vector::length(&lottery_state.players); let winner_idx = aptos_framework::randomness::u64_range(0, n); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` where: * `let winner_idx = aptos_framework::randomness::u64_range(0, n);` is the randomness API call that returns an u64 integer in range `[0, n)` uniformly at random. * `#[randomness]` is a required attribute to enable the API call at runtime. ## How to use Aptos randomness API [](#how-to-use-aptos-randomness-api) ### Prerequisites [](#prerequisites) Ensure you have the latest [aptos-cli](/build/cli) installed. ### Keep undergasing attacks in mind [](#keep-undergasing-attacks-in-mind) Caution **The randomness API currently does not prevent undergasing attacks.** Carefully read the undergasing section to understand about undergasing attacks and how to prevent them. As a dApp developer, you will need to design applications using randomness with safety in mind. ### Identify randomness-dependent entry functions and make them compliant [](#identify-randomness-dependent-entry-functions-and-make-them-compliant) For safety (discussed with more details later), randomness API calls are only allowed from an entry function that is: * private, and * annotated with `#[randomness]`. It’s now a good time to think about what user actions need randomness API, write them down, and make sure they are private and have the right attribute, as shown in the example below. ``` module module_owner::lottery { // ... #[randomness] entry fun decide_winner() { // ... }} ``` At runtime, when randomness API is called, the VM checks whether the outermost of the callstack is a private entry function with `#[randomness]` attribute. **If not, the entire transaction is aborted.** ### Call the API [](#call-the-api) The APIs are public functions under `0x1::randomness` and can be referenced directly, as demonstrated in the lottery example above. ``` module module_owner::lottery { // ... use aptos_framework::randomness; #[randomness] entry fun decide_winner() { // ... let winner_idx = aptos_framework::randomness::u64_range(0, n); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` The above example uses function `u64_range()` but many other basic types are also supported. Here’s a quick overview of all the API, where `T` can be one of `u8, u16, u32, u64, u128, u256`. ``` module aptos_framework::randomness { /// Generates an number uniformly at random. fun u8_integer(): u8 {} /// Generates an number uniformly at random. fun u16_integer(): u16 {} // fun u32_integer(), fun u64_integer() ... /// Generates a number `[min_incl, max_excl)` uniformly at random. fun u8_range(min_incl: u8, max_excl: u8): u8 {} /// Generates a number `[min_incl, max_excl)` uniformly at random. fun u16_range(min_incl: u16, max_excl: u16): u16 {} // fun u32_range(), fun u64_range() ... /// Generates a sequence of bytes uniformly at random /// n is the number of bytes /// If n is 0, returns the empty vector. fun bytes(n: u64): vector {} /// Generate a permutation of `[0, 1, ..., n-1]` uniformly at random. /// n is the number of bytes /// If n is 0, returns the empty vector. fun permutation(n: u64): vector {}} ``` The full API function list and documentation can be found [here](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/doc/randomness.md). ## Security considerations [](#security-considerations-1) Randomness API is powerful in many ways: it unlocks new dApp designs; but if used incorrectly, it may leave your dApps open to attacks! Below are some common mistakes you should avoid. ### Randomness API calls in public functions [](#randomness-api-calls-in-public-functions) As your dApp gets more complicated, you may have multiple entry functions that need to share the same randomness-dependent logic, and want to pull the logic out as a separate helper function. While this is supported as shown below, extra care must be taken. ``` module module_owner::lottery { // ... use aptos_framework::randomness; #[randomness] entry fun decide_winner_v0() { // ... decide_winner_internal(lottery_state); } #[randomness] entry fun decide_winner_v1() { // ... decide_winner_internal(lottery_state); } // A private helper function fun decide_winner_internal(lottery_state: &mut lottery_state) { let n = std::vector::length(&lottery_state.players); let winner_idx = aptos_framework::randomness::u64_range(0, n); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` If `decide_winner_internal()` were accidentally marked public, malicious players can deploy their own contract to: 1. call`decide_winner_internal()`; 2. read the lottery result (assuming the `lottery` module has some getter functions for the result); 3. abort if the result is not in their favor. By repeatedly calling their own contract until a txn succeeds, malicious users can bias the uniform distribution of the winner (dApp developer’s initial design). This is referred to as a [test-and-abort attack](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-41.md#test-and-abort-attacks). The Aptos Move compiler has been updated to prevent this attack for your contract safety: a randomness-dependent public function is treated as a compile error. If you have finished the steps in the [“build Aptos CLI”](/build/cli) section, then your Aptos CLI are equipped with the updated compiler. ``` module module_owner::lottery { // Compile error! public fun decide_winner_internal(lottery_state: &mut lottery_state) { let n = std::vector::length(&lottery_state.players); let winner_idx = aptos_framework::randomness::u64_range(0, n); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` Not recommended, but if you intend to expose such a randomness-dependent function to the public, you can bypass the compiler check by annotating your function with `#[lint::allow_unsafe_randomness]`. ``` module module_owner::lottery { // Can compile, but use it at your own risk! #[lint::allow_unsafe_randomness] public fun decide_winner_internal(lottery_state: &mut lottery_state) { let n = std::vector::length(&lottery_state.players); let winner_idx = aptos_framework::randomness::u64_range(0, n); lottery_state.winner_idx = std::option::some(winner_idx); }} ``` ### Undergasing attacks, and how to prevent [](#undergasing-attacks-and-how-to-prevent) Imagine such a dApp. It defines a private entry function for a user to: 1. toss a coin (gas cost: 9), then 2. get a reward (gas cost: 10) if coin=1, or do some cleanup (gas cost: 100) otherwise. A malicious user can control its account balance, so it covers at most 108 gas units (or set transaction parameter `max_gas=108`), and the cleanup branch (total gas cost: 110) will always abort with an out-of-gas error. The user then repeatedly call the entry function until it gets the reward. Formally, this is referred to as an [undergasing attack](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-41.md#undergasing-attacks), where an attacker can control how much gas is left for the entry function to execute, and so can arbitrarily decide to abort paths that cost more gas, biasing the outcome (i.e., effectively changing the distribution of random numbers). Caution **WARNING: randomness API currently does not prevent undergasing attacks.** As a dApp developer, you need to be very careful in your design to avoid this type of attack. Here are some ideas of how to prevent undergasing attack generally. * Make your entry function gas independent from the randomness outcome. The simplest example is to not “act” on the randomness outcome, i.e., read it and store it for later. Note that calling any other functions can have variable gas costs. For example, when calling randomness to decide which player should win, and then depositing the winnings to the winner might seem like a fixed gas cost. But, `0x1::coin::transfer` / `0x1::fungible_asset::transfer` can have a variable cost based on the user’s on-chain state. * If your dApp involves a trusted admin/admin group, only allow the trusted to execute randomness transaction (i.e., require an admin signer). * Make the path that is most beneficial have the highest gas (as attacker can only abort paths with gas above a threshold he chooses. NOTE: that this can be tricky to get right, and gas schedule can change, and is even harder to get right when there are more than 2 possible outcomes. Note that everything that does not fall in above categories can be susceptible to undergasing attack in a subtle ways. Reach out if you need help. We will be providing more functionality in the future, to allow for more complex code to be able to be safe against undergasing attacks. ### It’s random, but not a secret [](#its-random-but-not-a-secret) While the randomness API mimics the standard libraries you use to implement a private centralized server, keep in mind that **the seed is public, and so is your transaction execution**, and not every randomness-dependent logic in your private centralized server can be transferred on chain safely, **especially when it involves a secret that only the server should see**. For example, in your contract, DO NOT try to do the following. * Use randomness API to generate an asymmetric key pair, discard the private key, then think the public key is safe. * Use randomness API to shuffle some opened cards, veil them, and think no one knows the permutation. ## Read more [](#read-more) [Aptogotchi Random Mint](https://github.com/aptos-labs/aptogotchi-random-mint/tree/main) is an official demo dApp built to demonstrate the use of randomness API. The full API function list and documentation can be found [here](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/doc/randomness.md). You can also find the partial implementation of the API functions and example unit tests [here](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/randomness.move). See [AIP-41](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-41.md) for the API design, and [AIP-79](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-79.md) if you are interested in system-level/cryptography details. # Aptos APIs > Access the Aptos blockchain through the Fullnode REST API, Indexer GraphQL, Transaction Stream gRPC, faucet, and Geomi-hosted endpoints Use these APIs to read chain state, submit transactions, index historical data, and fund test accounts. Most application code should go through an [official SDK](/build/sdks); the HTTP, GraphQL, and gRPC endpoints below are the underlying services those SDKs call. ## Choose an API [](#choose-an-api)
You needUse
Latest on-chain state, transaction submission, or simulationFullnode REST API
NFTs, objects, historical activity, or aggregated tablesIndexer GraphQL API
A real-time or historical transaction feed for a custom indexerTransaction Stream (gRPC)
Test APT on Devnet or TestnetFaucet API
SQL, dashboards, or third-party RPCData providers
## Official Aptos Labs endpoints [](#official-aptos-labs-endpoints) [Aptos Labs](https://aptoslabs.com) operates these deployments for each [Aptos network](/network/nodes/networks) on behalf of the [Aptos Foundation](https://aptosnetwork.com/foundation). `fullnode.{network}.aptoslabs.com` is an alias of `api.{network}.aptoslabs.com`; prefer the `api.` hostnames.
NetworkREST API (/v1)Indexer GraphQLTransaction Stream gRPCFaucet
Mainnethttps://api.mainnet.aptoslabs.com/v1https://api.mainnet.aptoslabs.com/v1/graphqlgrpc.mainnet.aptoslabs.com:443—
Testnethttps://api.testnet.aptoslabs.com/v1https://api.testnet.aptoslabs.com/v1/graphqlgrpc.testnet.aptoslabs.com:443Mint page and https://faucet-e2.testnet.aptoslabs.com (Google sign-in)
Devnethttps://api.devnet.aptoslabs.com/v1https://api.devnet.aptoslabs.com/v1/graphqlgrpc.devnet.aptoslabs.com:443https://faucet.devnet.aptoslabs.com (programmatic)
The Node API spec is published on this site as [OpenAPI JSON](/aptos-spec.json) and a browsable [REST API reference](/rest-api). Live Swagger UIs also run on each fullnode at `/v1/spec`. ## Fullnode REST API [](#fullnode-rest-api) This API ships with every fullnode. It is the low-latency path for reading state, submitting transactions, and simulating transactions. [REST API reference](/rest-api) Browsable docs generated from the Aptos Node API OpenAPI spec [REST API guide](/build/apis/fullnode-rest-api) Rate limits, pruning, view functions, and how to query state [Mainnet explorer](https://api.mainnet.aptoslabs.com/v1/spec#/) Live Swagger UI against api.mainnet.aptoslabs.com [Testnet explorer](https://api.testnet.aptoslabs.com/v1/spec#/) Live Swagger UI against api.testnet.aptoslabs.com [Devnet explorer](https://api.devnet.aptoslabs.com/v1/spec#/) Live Swagger UI against api.devnet.aptoslabs.com ## Indexer [](#indexer) [Indexer GraphQL API](/build/indexer) High-level GraphQL for NFTs, Aptos Objects, fungible assets, and custom contract data [Transaction Stream API](/build/indexer/txn-stream) gRPC stream of historical and real-time transactions for Aptos Core Indexing and app-specific processors ## Faucet (Devnet and Testnet) [](#faucet-devnet-and-testnet) [Faucet API](/build/apis/faucet-api) Mint test APT on Devnet programmatically, or on Testnet through Google sign-in / the mint page ## Geomi and data providers [](#geomi-and-data-providers) [Geomi](/build/apis/aptos-labs-developer-portal) API keys, higher rate limits, gas station, and no-code indexing for Aptos Labs hosted APIs [Data providers](/build/apis/data-providers) SQL datasets, analytics dashboards, and third-party RPC endpoints The Node API, Indexer, Transaction Stream, and faucet implementations are open source in [aptos-core](https://github.com/aptos-labs/aptos-core). Anyone can run them; independent operators and builders do so worldwide. Additional RPC vendors are listed in the [Aptos ecosystem directory](https://aptosnetwork.com/ecosystem/directory/category/rpc). ## Authentication and rate limits [](#authentication-and-rate-limits) Labs-hosted Node, Indexer, and Transaction Stream APIs allow **anonymous** access with a low per-IP rate limit. For higher limits and usage metrics, create a [Geomi](https://geomi.dev/) API key and send it as a bearer token. ``` curl "https://api.mainnet.aptoslabs.com/v1" \ -H "Authorization: Bearer YOUR_API_KEY" ``` ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const aptos = new Aptos( new AptosConfig({ network: Network.MAINNET, clientConfig: { API_KEY: process.env.APTOS_API_KEY }, }),); ``` # Fullnode REST API > Low-level REST API for reading state, submitting transactions, and simulating operations on the Aptos blockchain This API ships with every fullnode. It is a simple, low-latency, low-level way to read state, submit transactions, and simulate transactions on Aptos. For NFTs, objects, historical activity, and aggregated tables, use the [Indexer GraphQL API](/build/indexer) instead. Base URL (Aptos Labs): `https://api.{network}.aptoslabs.com/v1` — for example `https://api.mainnet.aptoslabs.com/v1`. `fullnode.{network}.aptoslabs.com` is an alias of the same service. ## Spec and explorers [](#spec-and-explorers) The Node API is OpenAPI 3.0 (`Aptos Node API` 1.2.0). This site publishes the spec and a generated reference; each network also hosts a live Swagger UI. [REST API reference](/rest-api) Browsable docs generated from aptos-spec.json [OpenAPI spec (JSON)](/aptos-spec.json) Machine-readable Aptos Node API specification [Mainnet explorer](https://api.mainnet.aptoslabs.com/v1/spec#/) Live Swagger UI for Mainnet [Testnet explorer](https://api.testnet.aptoslabs.com/v1/spec#/) Live Swagger UI for Testnet [Devnet explorer](https://api.devnet.aptoslabs.com/v1/spec#/) Live Swagger UI for Devnet The spec YAML on a node is `GET /v1/spec.yaml`. Health is `GET /v1/-/healthy`. Ledger info (chain ID, version, epoch, role) is `GET /v1`. Node identity is `GET /v1/info`. ``` curl "https://api.mainnet.aptoslabs.com/v1" ``` ## Authentication and rate limits [](#authentication-and-rate-limits) Anonymous access is limited per IP. Attach a [Geomi](https://geomi.dev/) API key for higher limits: ``` curl "https://api.mainnet.aptoslabs.com/v1/accounts/0x1" \ -H "Authorization: Bearer YOUR_API_KEY" ``` Labs-hosted Node and Indexer APIs bill in compute units and also enforce HTTP rate limits. See the [Geomi billing docs](https://geomi.dev/docs/admin/billing). ## Common operations [](#common-operations)
OperationMethod and pathReference
Ledger infoGET /v1get_ledger_info
HealthGET /v1/-/healthyhealthy
AccountGET /v1/accounts/{address}get_account
Coin or FA balanceGET /v1/accounts/{address}/balance/{asset_type}get_account_balance
View functionPOST /v1/viewview
Submit transactionPOST /v1/transactionssubmit_transaction
Simulate transactionPOST /v1/transactions/simulatesimulate_transaction
Transaction by versionGET /v1/transactions/by_version/{txn_version}get_transaction_by_version
Account transactionsGET /v1/accounts/{address}/transactionsget_account_transactions
Events by handleGET /v1/accounts/{address}/events/{event_handle}/{field_name}get_events_by_event_handle
`asset_type` for [get\_account\_balance](/rest-api/operations/get_account_balance) can be a coin type such as `0x1::aptos_coin::AptosCoin` or a fungible asset metadata address such as `0xa` (APT). After the [Fungible Asset migration](/build/smart-contracts/fungible-asset), prefer this endpoint (or SDK helpers such as `getAccountAPTAmount`) over reading a `CoinStore` resource. ## Viewing current and historical state [](#viewing-current-and-historical-state) Most integrations need both current and historical state. Aptos provides historical transactions, state, and events as the result of transaction execution. * Historical transactions include execution status, output, and related events. Each transaction has a unique **version** that is its global sequential position in the ledger. * State at a version is the accumulation of all transaction outputs up to and including that version. * Executing transactions may emit [events](/network/blockchain/events), which hint at on-chain data changes. Nodes prune old ledger history (and can prune state) to bound disk use. The default window keeps the most recent 150 million transactions; almost all Mainnet and Testnet nodes use that default. Disable or resize pruning only if you run your own node — see [Data Pruning](/network/nodes/configure/data-pruning). For historical data beyond a pruned window, use the [Indexer](/build/indexer). Account transaction queries return sequence-number transactions from that account. They do not return [orderless](/build/guides/orderless-transactions) transactions sent from the account. ## Reading state with the View function [](#reading-state-with-the-view-function) View functions do not modify blockchain state when you call them through the API. A view function and its arguments can compute complex on-chain state in Move — for example, the highest bid in an auction. The REST operation is [POST /view](/rest-api/operations/view). The call looks like simulation, but it has no side effects and returns the function output. You pass the module, function name, type arguments, and values. A function does not have to be immutable to use `#[view]`; if it is mutable, the API still will not commit state. Prefer making such functions private so they cannot be called as entry functions at runtime. Framework modules already expose view functions, so you do not need to publish a module to try the endpoint: ``` curl -X POST "https://api.mainnet.aptoslabs.com/v1/view" \ -H "Content-Type: application/json" \ -d '{"function":"0x1::chain_id::get","type_arguments":[],"arguments":[]}' ``` ``` aptos move view --function-id 0x1::chain_id::get ``` ``` import { Aptos, AptosConfig, Network, type InputViewFunctionData } from "@aptos-labs/ts-sdk"; const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET }));const payload: InputViewFunctionData = { function: "0x1::chain_id::get",};const [chainId] = await aptos.view<[number]>({ payload }); ``` For your own module, [publish it](/build/cli/working-with-move-contracts) with the [Aptos CLI](/build/cli), then call `aptos move view --function-id
::::`. The response is a JSON array of return values. You can also request Binary Canonical Serialization (BCS) by setting the appropriate `Accept` / content type on the REST call. # Faucet API > Mint test APT on Devnet and Testnet using the faucet API, SDKs, CLI, or the Testnet mint page The faucet mints test `APT` so you can develop before Mainnet. **Devnet** is programmable with no Google login. **Testnet** requires Google sign-in (the [mint page](/network/faucet) or `POST /fund` with a Firebase ID token). There is no Mainnet faucet. Amounts are in [Octas](/network/glossary#octa) (`1 APT = 100,000,000` Octas).
NetworkEndpointHow to mint
Devnethttps://faucet.devnet.aptoslabs.comSDKs, CLI, or POST /fund with no auth
Testnethttps://faucet-e2.testnet.aptoslabs.comMint page, or POST /fund with a Google ID token
Mainnet—Not available
OpenAPI (live): [Devnet spec](https://faucet.devnet.aptoslabs.com/spec.yaml) and [Testnet spec](https://faucet-e2.testnet.aptoslabs.com/spec.yaml). Explorer: [Devnet `/spec`](https://faucet.devnet.aptoslabs.com/spec). Source: [crates/aptos-faucet/doc/spec.yaml](https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-faucet/doc/spec.yaml). The current operation is **`POST /fund`** with a JSON `FundRequest` body (`address`, `auth_key`, or `pub_key`, and optional `amount`). Devnet still accepts a legacy **`POST /mint?amount=&address=`** query; new integrations should use `/fund`. ## Using the faucet in a wallet [](#using-the-faucet-in-a-wallet) Most wallets, such as [Petra](https://aptosnetwork.com/ecosystem/directory/petra), have a Devnet faucet button. See the [Aptos wallets directory](https://aptosnetwork.com/ecosystem/projects/wallets). ## Using the faucet in the Aptos CLI [](#using-the-faucet-in-the-aptos-cli) After [CLI setup](/build/cli/setup-cli), fund an account on **Devnet**: ``` aptos account fund-with-faucet --account 0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6 --amount 100000000 ``` On Testnet, use the [mint page](/network/faucet) instead of this command. ## Using the faucet in the TypeScript SDK [](#using-the-faucet-in-the-typescript-sdk) This example funds `0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6` with 1 APT on Devnet. ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const aptos = new Aptos(new AptosConfig({ network: Network.DEVNET }));await aptos.fundAccount({ accountAddress: "0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6", amount: 100_000_000,}); ``` See each [SDK](/build/sdks) for more client examples. ## Using the faucet in the Python SDK [](#using-the-faucet-in-the-python-sdk) ``` from aptos_sdk.v2 import Aptos, AptosConfig, Network async with Aptos(AptosConfig(network=Network.DEVNET)) as aptos: await aptos.faucet.fund_account( "0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6", 100_000_000, ) ``` ## Using the faucet in the Go SDK [](#using-the-faucet-in-the-go-sdk) ``` package main import ( "github.com/aptos-labs/aptos-go-sdk") func main() { client, err := aptos.NewClient(aptos.DevnetConfig) if err != nil { panic("Failed to create client: " + err.Error()) } address := aptos.AccountAddress{} err = address.ParseStringRelaxed("0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6") if err != nil { panic("Failed to parse address: " + err.Error()) } err = client.Fund(address, 100_000_000) if err != nil { panic("Failed to fund account: " + err.Error()) }} ``` ## Calling the faucet without an SDK [](#calling-the-faucet-without-an-sdk) `POST /fund` on Devnet: ``` curl -X POST "https://faucet.devnet.aptoslabs.com/fund" \ -H "Content-Type: application/json" \ -d '{"address":"0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6","amount":100000000}' ``` A successful response looks like `{"txn_hashes":["..."]}`. If `amount` is omitted, the faucet uses its configured default (capped at the maximum mint). ### Testnet: Google sign-in [](#testnet-google-sign-in) Testnet `POST /fund` requires a human Google login. The [mint page](/network/faucet) does this for you. To call the API directly, send a Firebase ID token for project `aptos-api-gateway-prod` (scopes `openid`, `email`, `profile`): ``` curl -X POST "https://faucet-e2.testnet.aptoslabs.com/fund" \ -H "Authorization: Bearer FIREBASE_ID_TOKEN" \ -H "x-is-jwt: true" \ -H "Content-Type: application/json" \ -d '{"address":"0xd0f523c9e73e6f3d68c16ae883a9febc616e484c4998a72d8899a1009e5a89d6"}' ``` There is no agent-registration shortcut. See [`/auth.md`](/auth.md) for the OAuth discovery documents. # Exchange Integration Guide > Comprehensive guide for integrating Aptos and its assets into cryptocurrency exchanges with balance tracking and testing. This describes how to integrate Aptos and Aptos assets into an exchange. It provides generic information for tracking balances, transferring assets, and testing the integration. ## Overview [](#overview) This document will guide you through the following tasks to integrate with Aptos: * Infrastructure * Address standards * Asset standards * Retrieving balances * Tracking balance changes * Transferring assets * Testing the integration ## Infrastructure [](#infrastructure) It’s suggested that you run your own [full node](/network/nodes/full-node) to interact with the Aptos blockchain. This will allow you to query the blockchain for the latest state and submit transactions. You can also use the [Indexer](/build/indexer) to query for on-chain data efficiently. ## Address Standards [](#address-standards) ### Addresses [](#addresses) A single address can be represented in three ways. We recommend you show all leading zeros, and the `0x`. Here is an example of all three representations for the framework address `0x1`: * `0x00000000000000000000000000000001` - A full representation of 32-bytes in hex with a leading `0x`. This is preferred. * `0x1` - The short representation of the address with a leading `0x`. This is kept around for compatibility, but preferred with all leading 0s. * `00000000000000000000000000000001` - A full representation of 32-bytes in hex without a leading `0x`. This is kept around for compatibility, but preferred with leading 0x. For example SDKs will handle this parsing automatically, and we suggest you use the SDKs directly to handle it for you. ``` import { AccountAddress } from "@aptos-labs/ts-sdk";const address = AccountAddress.from("0x1");address.toStringLong(); // 0x00000000000000000000000000000001 ``` There is additionally, Aptos Name Service (ANS) for friendly .apt names. For more information about addresses and Aptos Names, see our page on [Accounts](/network/blockchain/accounts). ## Account Standards [](#account-standards) [AIP-115](/build/aips/aip-115) treats every 32-byte address as a valid account. You do **not** need to create an `0x1::account::Account` resource before sending funds or submitting a transaction. The resource is created on demand when a sequence-number transaction (or another feature that needs it) first requires it. `0x1::aptos_account::transfer` still funds the recipient and will create the resource if needed. `0x1::aptos_account::create_account` remains available if you want to create the resource explicitly. Do not treat a missing `0x1::account::Account` resource as “this address does not exist.” Check balances and on-chain activity instead. See [Application Integration](/build/guides/application-integration) for the same guidance. For hot wallets that submit from many machines without coordinating sequence numbers, use [orderless transactions](/build/guides/orderless-transactions). ``` import { Aptos, Ed25519Account, Ed25519PrivateKey } from "@aptos-labs/ts-sdk"; const aptos = new Aptos();const account = new Ed25519Account({privateKey: new Ed25519PrivateKey("private key")})const transaction = await aptos.transferCoinTransaction({sender: account.accountAddress, recipient: "receiver address", amount: 100000000})const pendingTransaction = await aptos.transaction.signAndSubmitTransaction({signer: account, transaction})const committedTransaction = await aptos.waitForTransaction({transactionHash: pendingTransaction.hash}); ``` ## Asset Standards [](#asset-standards) Aptos provides two standards for fungible tokens, similar to ERC-20 tokens on Ethereum: * An earlier [Coin standard](/build/smart-contracts/aptos-coin) used by assets on Aptos. * A newer [Fungible Asset Standard](/build/smart-contracts/fungible-asset) which is more featured. Additionally, there is a migratory period for assets from Coin to Fungible Asset standards. We will call this from now on **migrated coins**. Migrated coins may have two forms, but either can be used interchangeably with Coin standards. This is important to note when querying balances, to use coin functions and not fungible asset functions. The FA standard can only deal with the FA form. ### Coin Standard (tl;dr) [](#coin-standard-tldr) A **coin** has an associated contract that holds the on-chain struct that represents the coin. The coin is represented as a struct name e.g. `0x1::aptos_coin::AptosCoin` for `APT`. All coins are stored in an account resource called `0x1::coin::CoinStore`. Coins must be registered prior to using the `CoinStore`, but if using the proper functions e.g. `0x1::aptos_account::transfer` or `0x1::aptos_account::transfer_coins`, this will be done automatically. Coins can be _migrated_ to a fungible asset. In order to support a migrated asset, continue calling the coin functions as will be mentioned later. More info can be found at: [Coin Standard](/build/smart-contracts/aptos-coin) ### Fungible Asset Standard (tl;dr) [](#fungible-asset-standard-tldr) A **fungible asset** has an associated metadata address that holds the metadata for the fungible asset. This is commonly called the fa metadata address. The asset is represented as an address e.g. `0xA` for `APT`. All fungible assets are stored in an `object`, which is called a `fungible asset store`. For exchanges, the most important store is `primary_fungible_store`, which is the default store for fungible assets. This is directly connected to an owner. From this point on in this guide, we will only talk about supporting `primary_fungible_store` for fungible assets. More info can be found at: [Fungible Asset Standard](/build/smart-contracts/fungible-asset) ## Retrieving Balances [](#retrieving-balances) Retrieving current balances for assets are different for each standard. Integration is considered complete when it can handle both. Balances are always returned in their subunits. For example, `APT` is returned in `octas` (1e-8 APT). So, when an API returns a balance of `100000000`, this is `1 APT`. If it returns `100`, this is `0.000001 APT`. ### Coin (and migrated coins) Balances [](#coin-and-migrated-coins-balances) To retrieve the balance of a coin, or a coin that was migrated to a fungible asset, you can use the `0x1::coin::balance(account address)` view function. This will combine the coin and coin migrated to fungible asset balances. ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const config = new AptosConfig({ network: Network.DEVNET });const aptos = new Aptos(config); const coinType = "0x1::aptos_coin::AptosCoin";const account = "0x00000000000000000000000000000001";const [balanceStr] = await aptos.view<[string]>({ payload: { function: "0x1::coin::balance", typeArguments: [coinType], functionArguments: [account] }});const balance = parseInt(balanceStr, 10); ``` A specific ledger version (transaction height) can be provided to get the balance at that point in time. The below example shows for ledger version `1,000,000`. ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const config = new AptosConfig({ network: Network.DEVNET });const aptos = new Aptos(config); const coinType = "0x1::aptos_coin::AptosCoin";const account = "0x00000000000000000000000000000001";const [balanceStr] = await aptos.view<[string]>({ payload: { function: "0x1::coin::balance", typeArguments: [coinType], functionArguments: [account], options: { ledgerVersion: 1_000_000 } }});const balance = parseInt(balanceStr, 10); ``` ### Fungible Asset Balances [](#fungible-asset-balances) To retrieve the balance of a fungible asset, you can use the `0x1::primary_fungible_store::balance<0x1::object::ObjectCore>(account address, fungible asset metadata address)` view function. Note, that this will not include the balance of coins if it’s a migrated coin. ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const config = new AptosConfig({ network: Network.DEVNET });const aptos = new Aptos(config); const faMetadataAddress = "0xA";const account = "0x00000000000000000000000000000001";const [balanceStr] = await aptos.view<[string]>({ payload: { function: "0x1::primary_fungible_store::balance", typeArguments: ["0x1::object::ObjectCore"], functionArguments: [account, faMetadataAddress] }});const balance = parseInt(balanceStr, 10); ``` A specific ledger version (transaction height) can be provided to get the balance at that point in time. The below example shows for ledger version `1,000,000`. ``` import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const config = new AptosConfig({ network: Network.DEVNET });const aptos = new Aptos(config); const faMetadataAddress = "0xA";const account = "0x00000000000000000000000000000001";const [balanceStr] = await aptos.view<[string]>({ payload: { function: "0x1::primary_fungible_store::balance", typeArguments: ["0x1::object::ObjectCore"], functionArguments: [account, faMetadataAddress] }, options: { ledgerVersion: 1_000_000 }});const balance = parseInt(balanceStr, 10); ``` Besides SDK, you can also directly use aptos node’s [balance API endpoint](/build/apis/fullnode-rest-api#tag/accounts/GET/accounts/%7Baddress%7D/balance/%7Basset_type%7D) to get the balance of a migrated coin or fungible asset. ## Tracking Balance Changes [](#tracking-balance-changes) Balance changes can be queried in one of two ways: 1. By watching for events that change the balance for each transaction. 2. By querying the indexer for indexed balance change events. In the past, it was able to use the `events` endpoint for an account to get the transactions that changed the balance. This is still possible, but will be deprecated in the future, and is not recommended for new integrations. ### Coin Balance Changes [](#coin-balance-changes) Coin balances are tracked as two items, write set changes, and events. Write set changes are end state of the coin balance, and events are the events that are emitted when a coin is withdrawn or deposited. Here is an [example of a coin transfer](https://explorer.aptoslabs.com/txn/1747361321?network=mainnet). The coin transfer can be tracked as an individual transaction [here](https://fullnode.mainnet.aptoslabs.com/v1/transactions/by_version/1747361321) from the REST API. We’ll break it down into a few parts: 1. The general transaction details tell information about the transaction. The most important thing here is the transaction version is `1747361321`. This gives us total order of all transactions on the blockchain. Think of it like block height, but for transactions. 2. The Write set `changes` are the end state of the transaction. It shows all resources that were modified by the transaction, and what it’s final state was. In this case, we only care about coin store changes. 3. Events are the events that were emitted by the transaction. In this case, we only care about the `0x1::coin::Withdraw` and `0x1::coin::Deposit` events. The Coin withdraw event is emitted when coins are withdrawn from an account. The account’s balance will decrease by that amount in the field `data.amount`. To determine the matching asset, you must match the `guid` in the `withdraw_events` to the `guid` in the `changes` section for a `CoinStore`. But if the `CoinStore` is not found in the `changes`, it means it got deleted, and a `CoinStoreDeleteEvent` must be present instead. Then you can match the `guid` with `deleted_withdraw_event_handle_creation_number` and `event_handle_creation_address`. The Coin deposit event is emitted when coins are deposited into an account. The account’s balance will increase by that amount in the field `data.amoount`. To determine the matching asset, you must match the `guid` in the `deposit_events` to the `guid` in the `changes` section for a `CoinStore`. Similarly, if the `CoinStore` is not found in the `changes`, it means it got deleted, and a `CoinStoreDeleteEvent` must be present instead. Then you can match the `guid` with `deleted_deposit_event_handle_creation_number` and `event_handle_creation_address`. 4. Gas usage only is tracked for APT. There is no direct event for tracking gas, but it can be calculated from the transaction. Using the `gas_used` field, and the `gas_unit_price` field, you can calculate the total gas used. In this case, the `gas_used` is `999` and the `gas_unit_price` is `100`, so the total gas deducted from the sender(`0x559d4f690c683fca7c539237aa8dc4c6ec09886b7016bf66f2cdeffef55468f0`) is `999 * 100 = 99900 subunits` Remember that the subunits are used here. The value in the gas token `APT` is `0.00099900 APT`. 5. Overall, you need both the events and the changes to determine the amount transferred of the account. The final balances will show in the changes alone. If you watch all of these events, you will be able to handle all possible transactions. Below is the full example of the transaction response. ### Fungible Asset Balance Changes [](#fungible-asset-balance-changes) For fungible assets, the balance changes are tracked in the `primary_fungible_store`. The primary fungible store address is deterministic, and will always be tracked by the owner of the store. An example: [https://api.mainnet.aptoslabs.com/v1/transactions/by\\\_version/1750174030](https://api.mainnet.aptoslabs.com/v1/transactions/by%5C_version/1750174030) There are a few steps when tracking fungible assets: 1. There will be two types of events for fungible assets. `0x1::fungible_asset::Deposit` and `0x1::fungible_asset::Withdraw`. `Withdraw` events are similar to the coin events, where the balance will decrease by the amount in the `data.amount` field. And similarly `Deposit` events will increase the balance by the amount in the `data.amount` field. Note that, I’ve omitted the sequence number, and GUID fields, as they do not apply to module events. Each event has a `store` field, which in this case is `0x8a9d57692a9d4deb1680eaf107b83c152436e10f7bb521143fa403fa95ef76a`. This is the address of the `FungibleStore` for the asset, where the balance is stored. Note this, for the next step. 2. Next, we take a look at the `0x1::fungible_asset::FungibleStore` changes. This will show the end state of the balance for the fungible asset. The balance is in the `data.balance` field. The `address` field will match the `store` field from the events. The identifier of the fungible asset, is the `metadata` field. It is the address of the `metadata` for the fungible asset. Additionally, to figure out the actual owner of the assets, you will need to look at the owner of the store. In this case, you will need the `0x1::object::ObjectCore`, where the `address` field matches the `store` field from the events. The `owner` field will show the asset owner’s address. similar to the coin events, if the `ObjectCore` is not found in the `changes`, it means it got deleted, and a `FungibleStoreDeletion` event must be present instead. Then you can match the `store` fields between the `Withdraw`/`Deposit` events and the `FungibleStoreDeletion` event. ### Coins migrated to Fungible Asset Balance Changes [](#coins-migrated-to-fungible-asset-balance-changes) For coins migrated to fungible assets, it is just simply tracking of the two above. A coin migrated to a fungible asset will have both the coin store changes and the primary fungible asset store changes. The amounts would need to be aggregated together, and otherwise, handled as a coin. The Fungible asset metadata address is the hash of the coin type and 0xA ``` address = sha3_256(0xA | coin_type | 0xFE) ``` Here is an example of a migrated coin with APT: [https://api.mainnet.aptoslabs.com/v1/transactions/by\\\_version/1642580695](https://api.mainnet.aptoslabs.com/v1/transactions/by%5C_version/1642580695) ## Transferring Assets [](#transferring-assets) ### Coin (or migrated coin) Transfers [](#coin-or-migrated-coin-transfers) We suggest you use `0x1::aptos_account::transfer_coins(receiver address, amount)` for transferring coins. It will register the coin if it hasn’t been registered yet, and create the associated account if it hasn’t been created yet. This will continue to work with any coins that were migrated to a fungible asset, including APT. Coins can be transferred in the following ways: * [`0x1::aptos_account::transfer_coins(receiver address, amount)`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/aptos_account.move#L108-L112) - Transfer a coin to another account. * [`0x1::aptos_account::batch_transfer_coins(receiver addresses, amounts)`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/aptos_account.move#L93-L106) - Transfer a coin to multiple accounts. * [`0x1::aptos_account::transfer(receiver address, amount)`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/aptos_account.move#L74-L91) - Transfer specifically APT to another account. ### Fungible Asset Transfers [](#fungible-asset-transfers) We suggest you use `0x1::primary_fungible_store::transfer<0x1::object::ObjectCore>(receiver address, amount)` for transferring fungible assets. It will send the associated fungible asset, and create a primary store for the asset if it hasn’t been created yet. Caution Note: This will not create an account for the user if it hasn’t been created yet. You will need to call `0x1::aptos_account::create_account(account address)` to create the account before the user can submit transactions. ## Testing [](#testing) In order to check that everything is working correctly, we’ve provided these checks. ### Balance Checks [](#balance-checks) To test balance checks, you can check the balance for the account `0x5` for the asset `0x1::aptos_coin::AptosCoin`. The balance should show `0.002 APT`, where 0.001 APT is a coin, and 0.001 APT is a migrated coin (fungible asset). If your balance is not correct, see [Coin and Migrated Coin Balances](#coin-and-migrated-coins-balances) for more information. ### Balance Change / Transfer Checks [](#balance-change--transfer-checks) #### Check Coin Transfer [](#check-coin-transfer) To test a transfer, create a transaction to transfer 0.001 APT to another account. The transaction should be successful, and the balance should be updated, where the balance is 0.001 APT smaller and minus the gas cost associated. #### Check Fungible Asset Transfer [](#check-fungible-asset-transfer) To test a transfer, you can fund an account with the fungible asset here [https://test-token-faucet.vercel.app/](https://test-token-faucet.vercel.app/) and then transfer the fungible asset to another account. The balance should be updated according to the change, and you should be able to track the mint on the website. ## Stablecoin Addresses [](#stablecoin-addresses)
Token NameToken SymbolToken AddressSource of Address
Tether USDUSDt0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2bAptos Foundation
USDCUSDC0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3bCircle
Ondo US Dollar YieldUSDY0xcfea864b32833f157f042618bd845145256b1bf4c0da34a7013b76e42daa53cc::usdy::USDYOndo Finance
## FAQ [](#faq) ### What is the finality of a transaction? [](#what-is-the-finality-of-a-transaction) Aptos uses a BFT consensus algorithm, so transactions are finalized immediately after committing to the blockchain. See [Payments](/build/guides/payments) for how that relates to block time and end-to-end latency. ### What is the transaction fee on a transaction? [](#what-is-the-transaction-fee-on-a-transaction) Transaction fees are variable, but for most cases here are fixed. Check out [simulating transactions](/network/blockchain/gas-txn-fee#estimating-gas-consumption-via-simulation) to get an idea of the fee. # Indexer API Access > Access Aptos Indexer GraphQL API for historical data, transactions, fungible assets, and tokens with SDK integration and direct endpoints Aptos Labs hosts a public version of the Indexer GraphQL API that anyone can use to get basic historical and aggregate data about transactions, fungible assets, and tokens from on-chain. You can explore it by hand by viewing the Hasura Explorer below for the network you are interested in. You can also access the API via the GraphQL endpoints below. For more information on the format of data in each field / table, please see the [table reference page](/build/indexer/indexer-api/indexer-reference). ## SDK Access (Primary Method) [](#sdk-access-primary-method) The primary way to use the Indexer is to access it through the [TypeScript SDK](/build/sdks/ts-sdk/fetch-data-via-sdk). The TypeScript SDK will automatically handle rate limits, and can seamlessly allow for both [Fullnode REST API](/build/apis/fullnode-rest-api) access and Indexer access depending on what data is needed. ## Hasura Explorer (Manual Queries) [](#hasura-explorer-manual-queries) Choose a network to explore the free Aptos-Hosted Indexer API using the Hasura Explorer: [Mainnet](https://cloud.hasura.io/public/graphiql?endpoint=https://api.mainnet.aptoslabs.com/v1/graphql) Hasura GraphQL Explorer for Aptos Mainnet [Testnet](https://cloud.hasura.io/public/graphiql?endpoint=https://api.testnet.aptoslabs.com/v1/graphql) Hasura GraphQL Explorer for Aptos Testnet [Devnet](https://cloud.hasura.io/public/graphiql?endpoint=https://api.devnet.aptoslabs.com/v1/graphql) Hasura GraphQL Explorer for Aptos Devnet ## GraphQL API Endpoints (Direct Access) [](#graphql-api-endpoints-direct-access) If you need to directly make GraphQL queries to the Aptos-Labs hosted Indexer API, then use the following endpoints: * **Mainnet:** `https://api.mainnet.aptoslabs.com/v1/graphql` * **Testnet:** `https://api.testnet.aptoslabs.com/v1/graphql` * **Devnet:** `https://api.devnet.aptoslabs.com/v1/graphql` ### Rate limits [](#rate-limits) Learn more about the rate limits that apply to the Aptos Labs hosted indexer API by reading the [Geomi docs](https://geomi.dev/docs/admin/billing). If you need a higher rate limit, consider the following solutions: 1. Get an API Key from [Geomi](https://geomi.dev/). Learn more about API keys at the [Geomi docs site](https://geomi.dev/docs/api-keys). 2. Run the Aptos Indexer API yourself. See the guide to self-hosting [here](/build/indexer/txn-stream/self-hosted). # Indexer API Reference > Complete GraphQL API reference for Aptos Indexer with table schemas, query examples, and field documentation for tokens and accounts The Indexer API allows you to access rich data about tokens, fungible assets, and accounts on-chain using GraphQL queries. **You can access it [here](/build/indexer/indexer-api).** For common queries, check out the sidebar for examples to work from. When building your own, this reference guide should help you determine which tables are most relevant, and how to format your queries. Caution Before relying on a table for production services, check the bottom of this page to see if that table is deprecated. If so, use the note section for guidance on what to do to migrate to a non-deprecated table. # Indexer Table Reference [](#indexer-table-reference) This page was checked against the mainnet GraphQL schema at `https://api.mainnet.aptoslabs.com/v1/graphql`. New tables such as `public_key_auth_keys`, `current_objects`, and `confidential_asset_activities` are included below. ## Filtering (with `where` clauses) [](#filtering-with-where-clauses) To ensure your queries filter data efficiently, check out the available indexes for each table. Some indexes are composite B-tree indexes, meaning they consist of multiple columns. B-tree indexes are ordered and perform optimally when queries utilize a left-most prefix of the indexed columns. ## General [](#general) ### `user_transactions` [](#user_transactions) Transactions filtered to user\_transactions (not system).
Index NameIndexed Columns
user_transactions_pkeyversion
user_transactions_sender_sequence_number_keysender, sequence_number
ut_epoch_indexepoch
ut_insat_indexinserted_at
ut_sender_seq_indexsender, sequence_number
user_transactions_contract_info_indexentry_function_contract_address, entry_function_module_name, entry_function_function_name
### `block_metadata_transactions` [](#block_metadata_transactions) A type of system transaction emitted once per block, useful for mapping to timestamp or epoch.
Index NameIndexed Columns
block_metadata_transactions_block_height_keyblock_height
block_metadata_transactions_pkeyversion
bmt_insat_indexinserted_at
### `account_transactions` [](#account_transactions) _Has an aggregate view for summary data called `account_transactions_aggregate`_
Index NameIndexed Columns
account_transactions_pkeyaccount_address, transaction_version
at_insat_indexinserted_at
at_version_indextransaction_version DESC
This table maps accounts and transactions that interact with that account.
FieldTypePrimary KeyDescription
delegated_staking_activitiesJoinUse the Hasura explorer to see these sub-fields.
fungible_asset_activitiesJoinReferences fungible_asset_activities.
token_activitiesJoinUse the Hasura explorer to see these sub-fields.
token_activities_aggregateJoinUse the Hasura explorer to see these sub-fields.
token_activities_v2JoinReferences token_activities_v2.
token_activities_v2_aggregateJoinReferences token_activities_v2.
account_addressString!YesThis is an Aptos account address. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
transaction_versionbigint!YesBlockchain version of the transaction. Ex. 10000000
### `ledger_infos` [](#ledger_infos) This table shares what chain is currently being queried.
FieldTypePrimary KeyDescription
chain_idintYesThe unique identifier for the chain you are accessing. Ex. 1 (for Mainnet), 2 (for Testnet), etc.
### `processor_status` [](#processor_status) This table shares how current this processor’s data is. This table shares how current this processor’s data is. It reports the latest version processed per processor.
FieldTypePrimary KeyDescription
last_success_versionbigintYesThe version number of the last successful processor run. Ex. 5000000
last_transaction_timestampStringTimestamp of the last processed transaction. Ex. “2024-04-17T02:14:25.68771”
last_updatedStringTimestamp of the last update to this processor’s status. Ex. “2024-04-17T02:14:25.68771”
processorStringYesName of the processor. Ex. “transaction_processor”
## NFT [](#nft) ### `token_activities_v2` [](#token_activities_v2) _Has an aggregate view for summary data called `token_activities_v2_aggregate`_
Index NameIndexed Columns
ta2_from_type_indexfrom_address, type
ta2_insat_indexinserted_at
ta2_owner_type_indexevent_account_address, type
ta2_tid_indextoken_data_id
ta2_to_type_indexto_address, type
token_activities_v2_pkeytransaction_version, event_index
This table tracks token activities and is especially useful for tracking NFT activity. This includes both v1 and v2 data.
FieldTypePrimary KeyDescription
aptos_names_fromJoinUse the Hasura explorer to see these sub-fields.
aptos_names_from_aggregateJoinUse the Hasura explorer to see these sub-fields.
aptos_names_toJoinUse the Hasura explorer to see these sub-fields.
aptos_names_to_aggregateJoinUse the Hasura explorer to see these sub-fields.
current_token_dataJoinUse the Hasura explorer to see these sub-fields.
after_valueStringThe value of a token property after the transaction. Ex. “100”
before_valueStringThe value of a token property before the transaction. Ex. “50”
entry_function_id_strStringThe identifier of the function called in this transaction. Ex. “0x1::aptos_account::transfer”
event_account_addressStringThis is an Aptos account address related to the event. This address must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
event_indexbigintYesIndex of the event within the transaction. Ex. 1
from_addressStringThis is an Aptos account address from which the token was sent. This address must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
is_fungible_v2BooleanIndicates whether the token is fungible. Soon to be deprecated. Ex. False for NFTs.
property_version_v1bigintThe version of the token’s properties under schema version 1. This field is only for token standard v1. It is always 0 for v2. Ex. 0
to_addressStringThis is an Aptos account address to which the token was sent. This address must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
token_amountbigintThe amount of the token transferred in this activity. Ex. 3
token_data_idStringUnique identifier for this particular token’s data. For token standard v1, this is derived from a combination of creator_address, collection_name, and token_name. This ID must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
transaction_timestampStringTimestamp when the transaction occurred. Ex. “2024-04-17T02:14:25.68771”
transaction_versionbigintYesBlockchain version of the transaction. Ex. 10000000
typeStringType of transfer - like “deposit” or “withdrawal”. Ex. “0x3::token::DepositEvent”
### `nft_metadata_crawler_parsed_asset_uris` [](#nft_metadata_crawler_parsed_asset_uris) This table allows you to look up the cdn and uris for NFT images / content.
FieldTypePrimary KeyDescription
animation_optimizer_retry_countIntNumber of retries to optimize animation. Ex. 3
asset_uriStringYesURI of the asset. Ex. “https://example.com/nft/123”
cdn_animation_uriStringContent Delivery Network URI for animation. Ex. “https://cdn.example.com/animations/123”
cdn_image_uriStringContent Delivery Network URI for image. Ex. “https://cdn.example.com/images/123”
cdn_json_uriStringContent Delivery Network URI for JSON metadata. Ex. “https://cdn.example.com/metadata/123.json”
raw_animation_uriStringOriginal URI for animation before CDN optimization. Ex. “https://example.com/raw/animations/123”
raw_image_uriStringOriginal URI for image before CDN optimization. Ex. “https://example.com/raw/images/123”
Index NameIndexed Columns
nft_inserted_atinserted_at
nft_raw_animation_uriraw_animation_uri
nft_raw_image_uriraw_image_uri
parsed_asset_uris_pkeyasset_uri
### `current_token_ownerships_v2` [](#current_token_ownerships_v2) _Has an aggregate view for summary data called `current_token_ownerships_v2_aggregate`_ This table tracks who owns which NFTs. This includes both v1 and v2 tokens. Fungible tokens are not tracked as consistently.
FieldTypePrimary KeyDescription
composed_nfts_aggregateJoinAggregate information about the composed NFTs, such as count or other statistics.
current_token_dataJoinDetailed information about the token’s current data; structure is defined in a related table.
amountbigintThe amount of the token owned. Example: 1 for an NFT.
composed_nftsArrayAn array containing the IDs of NFTs that compose this token, if applicable.
is_fungible_v2BooleanIndicates whether the token is fungible. Example: true or null
is_soulbound_v2BooleanIndicates whether the token is soulbound (non-transferable once owned). Example: true or null
last_transaction_timestampStringTimestamp of the last transaction involving the token. Example: “2024-04-17T02:14:25.68771”
last_transaction_versionbigintThe version number of the last transaction involving the token. Example: 20747031
non_transferrable_by_ownerBooleanIndicates whether the token is non-transferrable by the owner. Example: true or null
owner_addressStringYesThe Aptos account address that currently owns the token. Addresses must be 66 characters so may be 0 padded. Example: “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
property_version_v1bigintYesThe version number of the token’s properties as of the last update. This field is only for token standard v1. It is always 0 for v2. Example: 0
storage_idStringYesA unique identifier used for storage purposes. IDs must be 66 characters long, so may be 0 padded. Ex. “0xd8d41ff9f67d17d7dee061b5b683b92013b420cb6a30c21fc7c287454792d7a8”
table_type_v1StringThe Move function type. Example: “0x3::token::TokenStore”
token_data_idStringYesA unique identifier for the token data, typically a hash or a numeric ID. Ex. “0x3d911af2dc3e47848fbba17b8694cf526942be183b84f8393a6c048232fb976d”
token_properties_mutated_v1ObjectProperties of the token that have been mutated from the original. Often in JSON or similar format. Example:
token_standardStringThe standard used to generate this token. Ex. “v1” or “v2”
Index NameIndexed Columns
curr_to2_insat_indexinserted_at
curr_to2_owner_indexowner_address
curr_to2_wa_indexstorage_id
current_token_ownerships_v2_pkeytoken_data_id, property_version_v1, owner_address, storage_id
### `current_token_datas_v2` [](#current_token_datas_v2) This table tracks the metadata associated with each NFT (Ex. URI, supply, etc.). This tracks both v1 and v2 tokens.
FieldTypePrimary KeyDescription
cdn_asset_urisJoinUse the Hasura explorer to see these sub-fields.
current_collectionJoinUse the Hasura explorer to see these sub-fields.
current_token_ownershipsJoinUse the Hasura explorer to see these sub-fields.
current_token_ownerships_aggregateJoinUse the Hasura explorer to see these sub-fields.
aptos_nameStringThis is a name tied to this token using the Aptos Name Service (ANS). Ex. “EpicDragon”
collection_idStringYesIdentifier for the collection that includes this token. Ex. “0x360f6eeabb4d7a9d2fab1f35b01e02831e3b5c4b73c7fd6c98dcc1c301c817c8”
decimalsbigintNumber of decimal places for token value, typically for fungible tokens. Ex. 18
descriptionStringDescription of the token. Ex. “A legendary dragon from the mystical lands.”
is_fungible_v2BooleanWhether the token is fungible. Ex. False for NFTs
largest_property_version_v1bigintThe largest version number of the token’s properties under the first schema. Ex. 1
last_transaction_timestampbigintUnix timestamp of the last transaction involving this token. Ex. 2024-03-27T07:41:58.800893
last_transaction_versionbigintBlockchain version of the last transaction involving this token. Ex. 30000000
maximumbigintMaximum possible quantity of this token, relevant for fungibles. Ex. 1000000
supplybigintCurrent supply of the token in circulation. Ex. 500000
token_data_idStringUnique identifier for the token’s data. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
token_nameStringThe formal name of the token. Ex. “Mystic Dragon”
token_propertiesObjectUse the Hasura explorer to see these sub-fields.
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
token_uriStringURI linking to further information about the token. Ex. “https://example.com/tokens/987654321”
Index NameIndexed Columns
cur_td2_cid_name_indexcollection_id, token_name
cur_td2_insat_indexinserted_at
current_token_datas_v2_pkeytoken_data_id
### `current_collections_v2` [](#current_collections_v2) This table tracks the metadata associated with each NFT collection (Ex. collection\_id, creator\_address, etc.). This tracks both v1 and v2 tokens.
FieldTypePrimary KeyDescription
cdn_asset_urisJoinUse the Hasura explorer to see these sub-fields.
collection_idStringYesUnique identifier for the collection. IDs must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b88”
collection_nameStringThe formal name of the collection. Ex. “Mythic Dragons”
creator_addressStringThis is an Aptos account address that created the collection. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
current_supplybigintCurrent supply of tokens in this collection. Ex. 500
descriptionStringDescription of the collection. Ex. “A collection of rare digital dragons.”
last_transaction_timestampStringTimestamp of the last transaction involving this collection. Ex. “2024-04-17T02:14:25.68771”
last_transaction_versionbigintBlockchain version of the last transaction involving this collection. Ex. 3000000002
max_supplybigintMaximum possible quantity of tokens in this collection. If the max supply is 0, there is no limit on the supply. Ex. 1000
mutable_descriptionStringChangeable description of the collection. Ex. “Updated collection description.”
mutable_uriBooleanTrue if the uri is changeable by the creator. Ex. True
table_handle_v1StringLegacy identifier handle for the collection in earlier schema versions. Ex. “handle_12345”
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
total_minted_v2bigintTotal number of tokens minted in this collection under schema version 2. Ex. 800
uriStringThis is a URI to where the image live. This can also be JSON data. Ex. “https://example.com/collections/9876543210”
Index NameIndexed Columns
cur_col2_crea_cn_indexcreator_address, collection_name
cur_col2_insat_indexinserted_at
current_collections_v2_pkeycollection_id
### `current_collection_ownership_v2_view` [](#current_collection_ownership_v2_view) _Has an aggregate view for summary data called `current_collection_ownership_v2_view_aggregate`_ This table maps collections to who owns them and helps count how much of a collection is owned by other accounts.
FieldTypePrimary KeyDescription
current_collectionJoinUse the Hasura explorer to see these sub-fields.
collection_idStringYesUnique identifier for the collection. IDs must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
collection_nameStringThe formal name of the collection. Ex. “Mythic Dragons”
collection_uriStringURI linking to further information about the collection. Ex. “https://example.com/collections/9876543210”
creator_addressStringThis is an Aptos account address that created the collection. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
distinct_tokensbigintThe count of distinct tokens owned within this collection. Ex. 150
last_transaction_versionbigintThe version number of the last transaction involving this collection. Ex. 3000000002
owner_addressStringYesThis is an Aptos account address that currently owns the token. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
single_token_uriStringURI linking to information about a specific token within the collection. Ex. “https://example.com/tokens/9876543210”
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
## Fungible Assets [](#fungible-assets) ### `fungible_asset_metadata` [](#fungible_asset_metadata) This tracks the metadata tied to each fungible asset (ex. decimals of precision). It includes v1 token data. This is a current\_ table.
FieldTypePrimary KeyDescription
asset_typeStringYesThe type of the asset, described by a Move resource. Ex. “0x1::aptos_coin::AptosCoin”
creator_addressStringThis is an Aptos account address that created the asset. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
decimalsbigintNumber of decimal places for token value, typically for fungible tokens. Ex. 18
icon_uriStringURI for the icon of the asset. Ex. “https://cdn.example.com/icons/123”
last_transaction_timestampStringTimestamp of the last transaction involving this asset. Ex. “2024-04-17T02:14:25.68771”
last_transaction_versionbigintBlockchain version of the last transaction involving this asset. Ex. 10000000
nameStringThe formal name of the asset. Ex. “Digital Gold”
project_uriStringURI linking to the project information associated with this asset. Ex. “https://www.example.com/project\_name/”
supply_aggregator_table_handle_v1StringLegacy handle for the supply aggregator table from an earlier schema version. Ex. “handle_67890”
supply_aggregator_table_key_v1StringLegacy key for accessing the supply aggregator table in earlier schema versions. Ex. “key_12345”
symbolStringThe trading symbol of the asset. Ex. “DGOLD”
token_standardStringStandard that the asset adheres to. Ex. “v1”
Index NameIndexed Columns
fam_creator_indexcreator_address
fam_insat_indexinserted_at
fungible_asset_metadata_pkeyasset_type
### `fungible_asset_activities` [](#fungible_asset_activities) This tracks the activity of fungible assets. It includes v1 token data.
FieldTypePrimary KeyDescription
owner_aptos_namesJoinReferences owner_aptos_names.
owner_aptos_names_aggregateJoinReferences owner_aptos_names.
amountbigintThe amount of the asset involved in the activity. Ex. 1000
asset_typeStringYesThe type of the asset, described by a Move resource. For fungible assets, this will be the address of the metadata object. Ex. “0x1::aptos_coin::AptosCoin”
block_heightbigintThe blockchain id at which this activity occurred. Ex. 1500000
entry_function_id_strStringThe identifier of the function called in this transaction. Ex. “0x1::aptos_account::transfer”
event_indexbigintIndex of the event within the transaction. Ex. 1
gas_fee_payer_addressStringThis is an Aptos account address that paid the gas fee for the transaction. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
is_frozenBooleanTrue if this activity is a freeze asset activity. Ex. null
is_gas_feeBooleanIndicates whether this activity involved a gas fee. Ex. True
is_transaction_successBooleanIndicates whether the transaction was successful. Ex. True
metadataObjectUse the Hasura explorer to see fields for metadata in this table.
owner_addressStringThis is an Aptos account address that owns the asset. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
storage_idStringIdentifier for the storage used in the transaction. IDs must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
storage_refund_amountbigintAmount refunded for storage after the transaction. This is always in APT octas. Ex. 50
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
transaction_timestampStringTimestamp when the transaction occurred. Ex. “2024-04-17T02:14:25.68771”
transaction_versionbigintBlockchain version of the transaction. Ex. 2
typeStringType of the transaction, described by a Move entry function. Ex. “0x1::coin::WithdrawEvent”
Index NameIndexed Columns
faa_at_indexasset_type
faa_gfpa_indexgas_fee_payer_address
faa_insat_idxinserted_at
faa_owner_type_indexowner_address, type
faa_si_indexstorage_id
fungible_asset_activities_pkeytransaction_version, event_index
### `current_fungible_asset_balances` [](#current_fungible_asset_balances) _Has an aggregate view for summary data called `current_fungible_asset_balances_aggregate`_ This tracks the asset balances of each account on-chain. It includes v1 token data.
FieldTypePrimary KeyDescription
amountbigintThe amount of the asset owned. Ex. 2000
asset_typeStringThe type of the asset, described by a Move resource. For v2 tokens this is the address of the fungible asset metadata object. For v1 it’s the fully qualified path of the move resource. Ex. “0x1::aptos_coin::AptosCoin”
is_frozenBooleanIndicates whether the account is frozen. Ex. False
is_primaryBooleanIndicates whether this is the primary balance of the owner. Ex. True
last_transaction_timestampStringTimestamp of the last transaction involving this balance. Ex. “2024-04-17T02:14:25.68771”
last_transaction_versionbigintBlockchain version of the last transaction involving this balance. Ex. 30000000
metadataObjectUse the Hasura explorer to see fields for metadata in current_fungible_asset_balances.
owner_addressStringThis is an Aptos account address that owns the asset. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
storage_idStringYesIdentifier for the storage associated with this balance. IDs must be 66 characters long, and so may be 0 padded. Ex. “0xa815a9a09105973084bfc31530e7c8f002846787c2f0521e1e34dc144ad83b89”
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
Index NameIndexed Columns
cufab_insat_indexinserted_at
cufab_owner_at_indexowner_address, asset_type
current_unified_fungible_asset_balances_pkeystorage_id
## Delegated Staking [](#delegated-staking) With [AIP-6](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-006-delegation-pool-for-node-operators.md) we added the ability for staking pools to be formed with delegated funds (delegation pools). Once these pools hold over 1M APT, they can become a staking pool (validator node). ### `current_delegated_staking_pool_balances` [](#current_delegated_staking_pool_balances) This table tracks the current balances of each account in a delegated staking pool.
FieldTypePrimary KeyDescription
staking_pool_addressStringYesThe address of the delegation pool.
total_coinsbigintAmount of APT in the staking pool.
total_sharesbigintThe total number of shares in the delegation pool.
operator_commission_percentagebigintThe commission percentage taken by the staking pool operator.
inactive_table_handleStringThe table handle for the inactive table.
active_table_handleStringThe table handle for the active table.
last_transaction_versionint8Transaction version (identifier) for the last transaction involving this staking pool.
inserted_atStringThe timestamp when the record was inserted.
Index NameIndexed Columns
current_delegated_staking_pool_balances_pkeystaking_pool_address
### `current_delegated_voter` [](#current_delegated_voter) This table tracks the current delegated voters of a delegation pool.
FieldTypePrimary KeyDescription
delegation_pool_addressStringYesThe address of the delegation pool.
delegator_addressStringYesThe address of the delegator.
table_handleStringThe table handle tracking this position.
voterStringThe address of the current voter in the delegation pool.
pending_voterStringThe address of the pending voter awaiting confirmation.
last_transaction_versionbigintThe transaction version (identifier) of the last transaction involving this delegation.
last_transaction_timestampTimestampThe block timestamp of the last transaction involving this delegation.
inserted_atTimestampThe timestamp when the record was inserted into the database.
Index NameIndexed Columns
current_delegated_voter_pkeydelegation_pool_address, delegator_address
cdv_da_indexdelegator_address
### `current_delegator_balances` [](#current_delegator_balances) This table tracks the current balances of each account in a delegated staking pool.
FieldTypePrimary KeyDescription
delegator_addressStringYesThe address of the delegator.
pool_addressStringThe address of the delegator pool.
pool_typeStringIf the shares are active or inactive
table_handleStringThe table handle for the pool.
sharesbigintThe number of shares in the pool.
parent_table_handleStringThe table handle for the parent table.
last_transaction_versionbigintTransaction version (identifier) for the last transaction involving this staking pool.
inserted_atTimestampThe timestamp when the record was inserted.
Index NameIndexed Columns
current_delegator_balances_pkeydelegator_address, pool_address, pool_type, table_handle
### `current_staking_pool_voter` [](#current_staking_pool_voter) This table tracks the current voters of a staking pool.
FieldTypePrimary KeyDescription
staking_pool_addressStringYesThe address of the staking pool.
voter_addressStringThe address of the voter.
operator_addressStringThe address of the operator.
last_transaction_versionbigintTransaction version (identifier) for the last transaction involving this staking pool.
inserted_atTimestampThe timestamp when the record was inserted.
Index NameIndexed Columns
current_staking_pool_voter_pkeystaking_pool_address
ctpv_va_indexvoter_address
ctpv_insat_indexinserted_at
### `delegated_staking_activities` [](#delegated_staking_activities) This table tracks delegated staking events.
FieldTypePrimary KeyDescription
transaction_versionbigintTransaction version (identifier) for activity
event_indexbigintThe index of the event. Ex. 1
delegator_addressStringThe address of the delegator.
pool_addressStringThe address of the pool.
event_typeStringDistributeRewards, AddStake, UnlockStake, ReactivateStake, WithdrawStake
amountbigintThe amount being staked. Ex. 1000
inserted_atTimestampThe timestamp when the record was inserted.
Index NameIndexed Columns
delegated_staking_activities_pkeytransaction_version, event_index
dsa_pa_da_indexpool_address, delegator_address, transaction_version, event_index
dsa_insat_indexinserted_at
### `delegated_staking_pool_balances` [](#delegated_staking_pool_balances) This table tracks the historical balances of each account in a delegated staking pool.
FieldTypePrimary KeyDescription
transaction_versionbigintTransaction version (identifier) for activity
staking_pool_addressStringThe address of the delegation pool.
total_coinsbigintAmount of APT in the staking pool.
total_sharesbigintThe total number of shares in the delegation pool.
operator_commission_percentagebigintThe commission percentage taken by the staking pool operator.
inactive_table_handleStringThe table handle for the inactive table.
active_table_handleStringThe table handle for the active table.
inserted_atStringThe timestamp when the record was inserted.
Index NameIndexed Columns
delegated_staking_pool_balances_pkeytransaction_version, staking_pool_address
### `delegated_staking_pools` [](#delegated_staking_pools) This table tracks when a delegated pool was created.
FieldTypePrimary KeyDescription
staking_pool_addressStringThe address of the staking pool.
first_transaction_versionbigintThe version number of the first transaction involving this pool. Ex. 5000000
inserted_atTimestampThe timestamp when the record was inserted.
Index NameIndexed Columns
delegated_staking_pools_pkeystaking_pool_address
### `delegator_balances` [](#delegator_balances) This table tracks the historical balances of each account in a delegation pool.
FieldTypePrimary KeyDescription
transaction_versionbigintThe version number of the transaction. Ex. 5000000
write_set_change_indexbigintThe index of the write set change. Ex. 1
delegator_addressStringThe address of the delegator.
pool_addressStringThe address of the delegator pool.
pool_typeStringThe type of the pool. Ex. “delegated”
table_handleStringThe table handle for the pool.
sharesbigintThe number of shares in the pool.
parent_table_handleStringThe table handle for the parent table.
inserted_atTimestampThe timestamp when the record was inserted.
Index NameIndexed Columns
delegator_balances_pkeytransaction_version, write_set_change_index
## Aptos Naming Service (ANS) [](#aptos-naming-service-ans) ### `current_aptos_names` [](#current_aptos_names) _Has an aggregate view for summary data called `current_aptos_names_aggregate`_ This view of [`current_ans_lookup_v2`](#current_ans_lookup_v2) helps query by name instead of account.
FieldTypePrimary KeyDescription
domainStringThe domain associated with this Aptos name. Ex. “example.crypto”
domain_with_suffixStringThe full domain name including any suffix. Ex. “example.crypto.aptos”
expiration_timestampStringTimestamp when the domain registration expires. Ex. “2024-04-17T02:14:25.68771”
is_activeBooleanIndicates whether the domain is currently active. Ex. True
is_domain_ownerBooleanIndicates whether the registered address is the owner of the domain. Ex. False
is_primaryBooleanIndicates whether this is the primary domain for the registered address. Ex. True
last_transaction_versionbigintThe version number of the last transaction involving this domain. Ex. 5000000
owner_addressStringThis is an Aptos account address that owns the domain. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x123abc456def7890abcdef1234567890abcdef1234”
registered_addressStringThis is an Aptos account address registered to the domain. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
subdomainStringAny subdomain part of the domain name. Ex. “sub.example”
token_nameStringThe name of the token associated with this domain. Ex. “ExampleToken”
token_standardStringAptos standard that the collection adheres to. Ex. “v1”
### `current_ans_lookup_v2` [](#current_ans_lookup_v2) This table maps tokens, standards, and addresses to human readable names.
FieldTypePrimary KeyDescription
domainStringYesThe domain associated with this Aptos name. Ex. “example.crypto”
expiration_timestampStringTimestamp when the domain registration expires. Ex. “2024-04-17T02:14:25.68771”
is_deletedBooleanIndicates whether the domain registration has been deleted. Ex. False
last_transaction_versionbigintThe version number of the last transaction involving this domain. Ex. 5000000
registered_addressStringThis is an Aptos account address registered to the domain. Addresses must be 66 characters long, and so may be 0 padded. Ex. “0x50bc83f01d48ab3b9c00048542332201ab9cbbea61bda5f48bf81dc506caa78a”
subdomainStringYesAny subdomain part of the domain name. Ex. “sub.example”
token_nameStringThe name of the token associated with this domain. Ex. “ExampleToken”
token_standardStringYesAptos standard that the collection adheres to. Ex. “v1”
Index NameIndexed Columns
ans_v2_et_indexexpiration_timestamp
ans_v2_insat_indexinserted_at
ans_v2_ra_indexregistered_address
ans_v2_tn_indextoken_name, token_standard
current_ans_lookup_v2_pkeydomain, subdomain, token_standard
## Accounts, objects, and signatures [](#accounts-objects-and-signatures) These tables map authentication keys, objects, and transaction signatures. They are useful with [stateless accounts](/build/aips/aip-115) and key rotation. ### `public_key_auth_keys` [](#public_key_auth_keys) Maps public keys to authentication keys and whether the public key has been used on chain.
FieldTypePrimary KeyDescription
auth_keyString!YesDerived authentication key.
public_keyString!YesPublic key bytes as a hex string.
public_key_typeString!YesKey type, for example Ed25519.
account_public_keyStringAccount public key when the scheme uses one.
signature_typeString!Signature scheme used with this key.
is_public_key_usedBoolean!True if this public key has signed a committed transaction.
last_transaction_versionbigint!Last transaction version that updated this row.
### `auth_key_account_addresses` [](#auth_key_account_addresses) Maps an authentication key to the account addresses that currently use it.
FieldTypePrimary KeyDescription
account_addressString!YesAccount address using this authentication key.
auth_keyString!Authentication key.
is_auth_key_usedBoolean!True if this key has been used on chain.
last_transaction_versionbigint!Last transaction version that updated this row.
### `current_objects` [](#current_objects) Current Object model owners and transfer settings (`0x1::object`).
FieldTypePrimary KeyDescription
object_addressString!YesAddress of the object.
owner_addressString!Current owner of the object.
state_key_hashString!State key hash for the object.
allow_ungated_transferBoolean!Whether ungated transfer is allowed.
is_deletedBoolean!True if the object has been deleted.
last_guid_creation_numnumeric!Last GUID creation number for the object.
last_transaction_versionbigint!Last transaction version that updated this row.
### `signatures` [](#signatures) Per-signer cryptographic material for committed transactions. Use this to inspect multi-agent, fee-payer, and multi-sig signatures.
FieldTypePrimary KeyDescription
transaction_versionbigint!YesTransaction version.
is_sender_primaryBoolean!YesTrue if this is the primary sender signature.
multi_agent_indexbigint!YesIndex among secondary signers.
multi_sig_indexbigint!YesIndex within a multi-sig authenticator.
transaction_block_heightbigint!Block height of the transaction.
signerString!Signer address.
typeString!Signature type string.
public_keyString!Public key for this signature.
public_key_typeStringPublic key type when present.
signatureString!Signature bytes as hex.
thresholdbigint!Multi-sig threshold when applicable.
public_key_indicesjsonb!Indices of keys that signed, for multi-sig.
any_signature_typeStringConcrete signature variant when present.
function_infoStringAbstraction authenticator function info.
## Confidential assets [](#confidential-assets) ### `confidential_asset_activities` [](#confidential_asset_activities) Activity for [confidential assets](/build/smart-contracts/confidential-asset). Amounts may be encrypted; `event_data` holds the raw event payload. Observed `event_type` values on mainnet include `Registered`, `Deposited`, `Withdrawn`, `Transferred`, `RolledOver`, `Normalized`, `KeyRotated`, `IncomingTransfersPauseChanged`, and `ConfidentialityForAssetTypeChanged`.
FieldTypePrimary KeyDescription
transaction_versionbigint!YesTransaction version.
event_indexbigint!YesEvent index within the transaction.
owner_addressString!Account that owns the confidential store.
counterparty_addressStringCounterparty when the event is a transfer.
asset_typeStringFungible asset metadata address.
amountnumericAmount when the event exposes one; otherwise null.
event_typeString!Confidential asset event type.
event_datajsonb!Raw event data, including ciphertexts.
event_data_versionString!Event data schema version.
entry_function_id_strStringEntry function that emitted the activity, when present.
is_transaction_successBoolean!Whether the transaction succeeded.
block_heightbigint!Block height.
transaction_timestamptimestamp!Transaction timestamp.
metadataJoinReferences fungible_asset_metadata.
## Governance [](#governance) ### `proposal_votes` [](#proposal_votes) On-chain governance votes from staking pools.
FieldTypePrimary KeyDescription
transaction_versionbigint!YesTransaction version of the vote.
proposal_idbigint!YesGovernance proposal id.
voter_addressString!YesVoter address.
staking_pool_addressString!Staking pool that voted.
num_votesnumeric!Voting power applied.
should_passBoolean!True if the vote is in favor.
transaction_timestamptimestamp!Timestamp of the vote transaction.
## Table items [](#table-items) These tables expose raw Move table contents. Prefer product tables (tokens, fungible assets) when they cover your use case. ### `table_items` [](#table_items) Historical writes to table items.
FieldTypePrimary KeyDescription
transaction_versionbigint!YesTransaction version.
write_set_change_indexbigint!YesWrite-set change index.
table_handleString!Table handle.
keyString!Raw table key.
decoded_keyjsonb!Decoded key.
decoded_valuejsonbDecoded value, if present.
### `current_table_items` [](#current_table_items) Latest value for each table item.
FieldTypePrimary KeyDescription
table_handleString!YesTable handle.
key_hashString!YesHash of the table key.
keyString!Raw table key.
decoded_keyjsonb!Decoded key.
decoded_valuejsonbDecoded value, if present.
is_deletedBoolean!True if the item was deleted.
last_transaction_versionbigint!Last updating transaction version.
### `table_metadatas` [](#table_metadatas) Key and value types for a table handle.
FieldTypePrimary KeyDescription
handleString!YesTable handle.
key_typeString!Move type of keys.
value_typeString!Move type of values.
## Token extras [](#token-extras) ### `current_token_pending_claims` [](#current_token_pending_claims) Outstanding token v1 pending claims (direct-transfer offers).
FieldTypePrimary KeyDescription
token_data_id_hashString!YesHash of the token data id.
from_addressString!YesAddress offering the token.
to_addressString!YesAddress that can claim the token.
property_versionnumeric!YesToken v1 property version.
token_data_idString!Token data id.
amountnumeric!Amount offered.
table_handleString!Pending-claims table handle.
collection_idString!Collection id.
collection_data_id_hashString!Hash of the collection data id.
collection_nameString!Collection name.
creator_addressString!Collection creator.
nameString!Token name.
last_transaction_timestamptimestamp!Last updating timestamp.
last_transaction_versionbigint!Last updating transaction version.
### `current_token_royalty_v1` [](#current_token_royalty_v1) Token v1 royalty configuration.
FieldTypePrimary KeyDescription
token_data_idString!YesToken data id.
payee_addressString!Royalty recipient.
royalty_points_numeratornumeric!Royalty numerator.
royalty_points_denominatornumeric!Royalty denominator.
last_transaction_timestamptimestamp!Last updating timestamp.
last_transaction_versionbigint!Last updating version.
## Delegated staking extras [](#delegated-staking-extras) ### `delegator_distinct_pool` [](#delegator_distinct_pool) Distinct pools a delegator participates in, with current pool metadata. This is a GraphQL view (no `_by_pk` query).
FieldTypeDescription
delegator_addressStringDelegator address.
pool_addressStringDelegation pool address.
current_pool_balanceJoinReferences current_delegated_staking_pool_balances.
staking_pool_metadataJoinReferences current_staking_pool_voter.
### `num_active_delegator_per_pool` [](#num_active_delegator_per_pool) Count of active delegators in each pool. This is a GraphQL view (no `_by_pk` query).
FieldTypeDescription
pool_addressStringDelegation pool address.
num_active_delegatorbigintNumber of active delegators.
## Deprecated Tables [](#deprecated-tables) The following tables are planned for deprecation, or are already deprecated. See the notes section for any direct replacements or notes on how to migrate if you currently depend on one of these tables. Please do not use any of the below tables for production services.
TableNotes
address_version_from_move_resourcesReplace with account_transactions
address_events_summaryTo query custom events, you should create a No-Code Indexer
address_version_from_eventsTo query custom events, you should create a No-Code Indexer
coin_activitiesReplace with fungible_asset_activities
coin_balancesReplace with current_fungible_asset_balances
coin_infosReplace with fungible_asset_metadata
coin_supplyNo replacement; non-realtime APT coin supply is available with this query
collection_datasReplace with current_collections_v2
current_ans_lookupReplace with current_ans_lookup_v2
current_coin_balancesReplace with current_fungible_asset_balances
current_collection_datasReplace with current_collections_v2
current_token_datasReplace with current_token_datas_v2
current_token_ownershipsReplace with current_token_ownerships_v2
events_viewTo query custom events, you should create a No-Code Indexer
move_resourcesReplace with account_transactions
move_resources_viewReplace with account_transactions
nft_marketplace_v2_*No direct replacement; query marketplace activity via the Indexer API
token_activitiesReplace with token_activities_v2
token_datasReplace with current_token_datas_v2
token_ownershipsReplace with current_token_ownerships_v2
tokensReplace with current_token_datas_v2
transactionsNo replacement; non-realtime data is available in BigQuery
transactions_viewNo replacement; non-realtime data is available in BigQuery
# Transaction Stream Service > Real-time transaction streaming service for Aptos blockchain data, supporting both Aptos-hosted and self-hosted deployment options The Transaction Stream Service is a service that listens to the Aptos blockchain and emits transactions as they are processed. These docs explain how this system works, how to use the Labs-Hosted instance of the service, and how to deploy it yourself. You can get API access to a transaction stream hosted by Aptos Labs [here](/build/indexer/txn-stream/aptos-hosted-txn-stream). # TypeScript SDK > Official TypeScript SDK for building applications on Aptos - the most comprehensive and up-to-date SDK [ ![Github Repo Stars](https://img.shields.io/github/stars/aptos-labs/aptos-ts-sdk) ](https://github.com/aptos-labs/aptos-ts-sdk)[ ![NPM Version](https://img.shields.io/npm/v/%40aptos-labs%2Fts-sdk) ](https://www.npmjs.com/package/@aptos-labs/ts-sdk)[ ![Node Version](https://img.shields.io/node/v/%40aptos-labs%2Fts-sdk) ](https://www.npmjs.com/package/@aptos-labs/ts-sdk)[ ![NPM bundle size](https://img.shields.io/bundlephobia/min/%40aptos-labs/ts-sdk) ](https://www.npmjs.com/package/@aptos-labs/ts-sdk)[ ![Static Badge](https://img.shields.io/badge/SDK_Reference-Docs) ](https://aptos-labs.github.io/aptos-ts-sdk/@aptos-labs/ts-sdk-latest) The TypeScript SDK allows you to connect, explore, and interact on the Aptos blockchain. You can use it to request data, send transactions, set up test environments, and more! ``` npm i @aptos-labs/ts-sdk ``` ## Examples [](#examples) [Quickstart](/build/sdks/ts-sdk/quickstart) See the quickstart to get a working demo in < 5 minutes [Accounts](/build/sdks/ts-sdk/account) Generate, restore, and fund accounts [Fetching Data](/build/sdks/ts-sdk/fetch-data-via-sdk) Read ledger, account, and view-function data [Submitting Transactions](/build/sdks/ts-sdk/building-transactions) Build, simulate, sign, and submit transactions [Examples](/build/sdks/ts-sdk/ts-examples) Catalog of runnable examples in the SDK repository [Tests](https://github.com/aptos-labs/aptos-ts-sdk/tree/main/tests/e2e) End-to-end tests that demonstrate each SDK feature ### Transfer APT from the tested example suite [](#transfer-apt-from-the-tested-example-suite) The snippet below is pulled from [`simple_transfer.ts`](https://github.com/aptos-labs/aptos-ts-sdk/blob/main/examples/typescript/simple_transfer.ts) in the SDK repository. simple\_transfer.ts ``` /* eslint-disable no-console */ /** * This example shows how to use the Aptos client to create accounts, fund them, and transfer between them. */ import { Account, AccountAddress, Aptos, AptosConfig, Network, NetworkToNetworkName } from "@aptos-labs/ts-sdk"; const ALICE_INITIAL_BALANCE = 1_000_000_000;const BOB_INITIAL_BALANCE = 100;const TRANSFER_AMOUNT = 100; // Default to devnet, but allow for overridingconst APTOS_NETWORK: Network = NetworkToNetworkName[process.env.APTOS_NETWORK ?? Network.DEVNET]; const balance = async ( aptos: Aptos, name: string, address: AccountAddress, versionToWaitFor?: bigint,): Promise => { const amount = await aptos.getAccountAPTAmount({ accountAddress: address, minimumLedgerVersion: versionToWaitFor, }); console.log(`${name}'s balance is: ${amount}`); return amount;}; const example = async () => { console.log("This example will create two accounts (Alice and Bob), fund them, and transfer between them."); // Set up the client const config = new AptosConfig({ network: APTOS_NETWORK }); const aptos = new Aptos(config); // Create two accounts const alice = Account.generate(); const bob = Account.generate(); console.log("=== Addresses ===\n"); console.log(`Alice's address is: ${alice.accountAddress}`); console.log(`Bob's address is: ${bob.accountAddress}`); // Fund the accounts console.log("\n=== Funding accounts ===\n"); const aliceFundTxn = await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: ALICE_INITIAL_BALANCE, }); console.log("Alice's fund transaction: ", aliceFundTxn); const bobFundTxn = await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: BOB_INITIAL_BALANCE, }); console.log("Bob's fund transaction: ", bobFundTxn); // Show the balances console.log("\n=== Balances ===\n"); const aliceBalance = await balance(aptos, "Alice", alice.accountAddress); const bobBalance = await balance(aptos, "Bob", bob.accountAddress); if (aliceBalance !== ALICE_INITIAL_BALANCE) throw new Error("Alice's balance is incorrect"); if (bobBalance !== BOB_INITIAL_BALANCE) throw new Error("Bob's balance is incorrect"); // Transfer between users const txn = await aptos.transaction.build.simple({ sender: alice.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [bob.accountAddress, TRANSFER_AMOUNT], }, }); console.log("\n=== Transfer transaction ===\n"); const committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn }); await aptos.waitForTransaction({ transactionHash: committedTxn.hash }); console.log(`Committed transaction: ${committedTxn.hash}`); console.log("\n=== Balances after transfer ===\n"); const newAliceBalance = await balance(aptos, "Alice", alice.accountAddress); const newBobBalance = await balance(aptos, "Bob", bob.accountAddress); // Bob should have the transfer amount if (newBobBalance !== TRANSFER_AMOUNT + BOB_INITIAL_BALANCE) throw new Error("Bob's balance after transfer is incorrect"); // Alice should have the remainder minus gas if (newAliceBalance >= ALICE_INITIAL_BALANCE - TRANSFER_AMOUNT) throw new Error("Alice's balance after transfer is incorrect");}; example(); ``` # TypeScript SDK Quickstart > Get started with the Aptos TypeScript SDK by creating accounts, funding them, and transferring APT tokens between accounts 1. Initialize A Project This will initialize a typescript package with `quickstart.ts` * [npm](#tab-panel-11-0) * [pnpm](#tab-panel-11-1) * [yarn](#tab-panel-11-2) ``` npm init && npm add -D typescript @types/node ts-node && npx tsc --init && mkdir src && echo 'async function example() { console.log("Running example!")}; example()' > src/quickstart.ts ``` ``` pnpm init && pnpm add -D typescript @types/node ts-node && pnpx tsc --init && mkdir src && echo 'async function example() { console.log("Running example!")}; example()' > src/quickstart.ts ``` ``` yarn init -y && yarn add -D typescript @types/node ts-node && npx tsc --init && mkdir src && echo 'async function example() { console.log("Running example!")}; example()' > src/quickstart.ts ``` 2. Test Initialization To test if you have initialized the package correctly run: * [npm](#tab-panel-12-0) * [pnpm](#tab-panel-12-1) * [yarn](#tab-panel-12-2) ``` npx ts-node src/quickstart.ts ``` ``` pnpx ts-node src/quickstart.ts ``` ``` yarn ts-node src/quickstart.ts ``` 3. Install the TypeScript SDK using the package manager of your choice: ``` npm i @aptos-labs/ts-sdk ``` 4. Set up the Aptos client You can use the `Aptos` object to handle everything that requires a connection to the Aptos network. A connection is established as soon as you create the object. ``` import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; // Specify which network to connect to via AptosConfigasync function example() { console.log( "This example will create two accounts (Alice and Bob), fund them, and transfer between them.", ); // Setup the client const config = new AptosConfig({ network: Network.DEVNET }); const aptos = new Aptos(config);} example() ``` 5. Fetch data from on-chain You can use the `Aptos` client to fetch all sorts of data from on-chain such as information about the network itself or account-specific information. ``` ...const ledgerInfo = await aptos.getLedgerInfo();const modules = await aptos.getAccountModules({ accountAddress: "0x123" });const tokens = await aptos.getAccountOwnedTokens({ accountAddress: "0x123" });... ``` 6. Send Transactions You can send transactions to change the state of the ledger. Transactions let you send tokens like APT, trigger Move modules, trade NFTs, and more. You can find an in-depth tutorial on transactions [here](/build/sdks/ts-sdk/building-transactions). To begin with though, here’s how you can send a basic transaction to transfer APT. #### 1\. Create an Account [](#1-create-an-account) To create a new account, you first generate new credentials then fund the account. On localnet / devnet you can fund an account programmatically by asking a “faucet” which has a lot of test APT to send some to your new account. ``` ...// Generate a new account key pairconst alice: Account = Account.generate(); // Fund the account on chain. Funding an account creates it on-chain.await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100000000,}); // Also create a second account to transfer tokens toconst bob: Account = Account.generate(); // Fund the account on chainawait aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 100000000,});... ``` #### 2\. Build the Transaction [](#2-build-the-transaction) You can build transactions with `aptos.transaction.build.simple({...})` by specifying: 1. `sender` - The account that’s sending the transaction. This account will pay the gas fees. 2. `data` - The information needed for Aptos to identify what transaction to execute. 1. `function` - Which smart contract on chain to call. This has the format `::::`. 2. `functionArguments` - These are specific to the function being called. You can look up what parameters a function needs by searching for the account and module on chain with an explorer [like this](https://explorer.aptoslabs.com/account/0x0000000000000000000000000000000000000000000000000000000000000001/modules/code/aptos_account?network=mainnet). For example: ``` ...const transaction = await aptos.transaction.build.simple({ sender: alice.accountAddress, data: { // The Move entry-function function: "0x1::aptos_account::transfer", functionArguments: [bob.accountAddress, 100], }, // Lower default gas fits typical devnet faucet funding (1 APT) options: { maxGasAmount: 100_000 },});... ``` #### 3\. Sign and Submit [](#3-sign-and-submit) Signing proves that you own or manage the account that is executing the transaction. This is important since the sender must pay gas fees for the work the network does to execute the transaction. Once signed, you can submit to the network for on chain verification and execution. You can use `aptos.signAndSubmitTransaction` which combines those two steps into one: ``` ...// Both signs and submits (although these can be done separately too)const pendingTransaction = await aptos.signAndSubmitTransaction({ signer: alice, transaction,});... ``` #### 4\. Wait for completion [](#4-wait-for-completion) You can run `aptos.waitForTransaction` to guarantee your code executes after the transaction has been processed and applied. This also helps you get any errors that may occur after submitting, such as the transaction being rejected. ``` ...const executedTransaction = await aptos.waitForTransaction({ transactionHash: pendingTransaction.hash });... ``` ## Full Quickstart Code [](#full-quickstart-code) ### Run Quickstart [](#run-quickstart) * [npm](#tab-panel-13-0) * [pnpm](#tab-panel-13-1) * [yarn](#tab-panel-13-2) ``` npx ts-node src/quickstart.ts ``` ``` pnpx ts-node src/quickstart.ts ``` ``` yarn ts-node src/quickstart.ts ``` ``` /** * This example shows how to use the Aptos client to create accounts, fund them, and transfer between them. */ import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; const ALICE_INITIAL_BALANCE = 100_000_000;const BOB_INITIAL_BALANCE = 100;const TRANSFER_AMOUNT = 100; async function example() { console.log( "This example will create two accounts (Alice and Bob), fund them, and transfer between them.", ); // Setup the client const config = new AptosConfig({ network: Network.DEVNET }); const aptos = new Aptos(config); // Generate two account credentials // Each account has a private key, a public key, and an address const alice = Account.generate(); const bob = Account.generate(); console.log("=== Addresses ===\n"); console.log(`Alice's address is: ${alice.accountAddress}`); console.log(`Bob's address is: ${bob.accountAddress}`); // Fund the accounts using a faucet console.log("\n=== Funding accounts ===\n"); await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: ALICE_INITIAL_BALANCE, }); await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: BOB_INITIAL_BALANCE, }); console.log("Alice and Bob's accounts have been funded!"); // Look up the newly funded account's balances (uses Fungible Asset balance APIs; // legacy CoinStore resources may be absent on new accounts) console.log("\n=== Balances ===\n"); const aliceBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress, }); console.log(`Alice's balance is: ${aliceBalance}`); const bobBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress, }); console.log(`Bob's balance is: ${bobBalance}`); // Send a transaction from Alice's account to Bob's account const txn = await aptos.transaction.build.simple({ sender: alice.accountAddress, data: { // All transactions on Aptos are implemented via smart contracts. function: "0x1::aptos_account::transfer", functionArguments: [bob.accountAddress, TRANSFER_AMOUNT], }, options: { maxGasAmount: 100_000 }, }); console.log("\n=== Transfer transaction ===\n"); // Both signs and submits const committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: txn, }); // Waits for Aptos to verify and execute the transaction const executedTransaction = await aptos.waitForTransaction({ transactionHash: committedTxn.hash, }); console.log("Transaction hash:", executedTransaction.hash); console.log("\n=== Balances after transfer ===\n"); const newAliceBalance = await aptos.getAccountAPTAmount({ accountAddress: alice.accountAddress, }); console.log(`Alice's balance is: ${newAliceBalance}`); const newBobBalance = await aptos.getAccountAPTAmount({ accountAddress: bob.accountAddress, }); console.log(`Bob's balance is: ${newBobBalance}`); // Bob should have the transfer amount if (newBobBalance !== TRANSFER_AMOUNT + BOB_INITIAL_BALANCE) throw new Error("Bob's balance after transfer is incorrect"); // Alice should have the remainder minus gas if (newAliceBalance >= ALICE_INITIAL_BALANCE - TRANSFER_AMOUNT) throw new Error("Alice's balance after transfer is incorrect");} example(); ``` ## Summary [](#summary) All told, you just learned how to transfer APT via a transaction by: 1. Connecting to the network using the `Aptos` client. 2. Creating an account. 3. Looking up data from on-chain using client helper functions like [`aptos.getAccountModules`](https://aptos-labs.github.io/aptos-ts-sdk/@aptos-labs/ts-sdk-7.2.0/classes/Aptos.html#getaccountmodules). 4. Signing and submitting a transaction to the network. 5. Waiting for Aptos to execute the transaction. To see all this in action, you can copy and run the full working code snippet for this quickstart above. # Python SDK > Official Python SDK for Aptos blockchain development with accounts, data fetching, and transaction building [ ![Github Repo Stars](https://img.shields.io/github/stars/aptos-labs/aptos-python-sdk) ](https://github.com/aptos-labs/aptos-python-sdk)[ ![PyPI Version](https://img.shields.io/pypi/v/aptos-sdk) ](https://pypi.org/project/aptos-sdk/)[ ![Python Version](https://img.shields.io/pypi/pyversions/aptos-sdk) ](https://pypi.org/project/aptos-sdk/) The Python SDK lets you connect, explore, and interact with the Aptos blockchain. You can use it to request data, send transactions, set up test environments, and more. ## Installing the Python SDK [](#installing-the-python-sdk) Aptos publishes the official Python SDK on [PyPI](https://pypi.org/project/aptos-sdk/) with source code in the [aptos-python-sdk GitHub repository](https://github.com/aptos-labs/aptos-python-sdk). The SDK requires **Python 3.12+**. Install with `pip`: ``` pip install aptos-sdk ``` Or from source: ``` git clone https://github.com/aptos-labs/aptos-python-sdkcd aptos-python-sdkpip install . ``` ## Examples [](#examples) [Quickstart](/build/sdks/python-sdk/quickstart) Get a working transfer on devnet in a few minutes [Accounts](/build/sdks/python-sdk/account) Generate, restore, and fund accounts [Fetching Data](/build/sdks/python-sdk/fetch-data-via-sdk) Read ledger, account, and view-function data [Submitting Transactions](/build/sdks/python-sdk/building-transactions) Build, simulate, sign, and submit transactions [Examples](/build/sdks/python-sdk/python-examples) Catalog of runnable examples in the SDK repository [Tests](https://github.com/aptos-labs/aptos-python-sdk/tree/main/v2/tests) Unit and integration tests that exercise the v2 API ### Transfer APT from the tested example suite [](#transfer-apt-from-the-tested-example-suite) The snippet below is pulled from [`v2/examples/transfer_apt.py`](https://github.com/aptos-labs/aptos-python-sdk/blob/main/v2/examples/transfer_apt.py) in the SDK repository. When you install from PyPI, import the same APIs from `aptos_sdk.v2` instead of `aptos_sdk_v2`. transfer\_apt.py ``` """Example: Transfer APT between accounts on devnet.""" import asyncio from aptos_sdk_v2 import Account, Aptos, AptosConfig, Network async def main(): config = AptosConfig(network=Network.DEVNET) async with Aptos(config) as aptos: # Create two accounts alice = Account.generate() bob = Account.generate() print(f"Alice: {alice.address}") print(f"Bob: {bob.address}") # Fund Alice print("\nFunding Alice...") await aptos.faucet.fund_account(alice.address, 100_000_000) # Fund Bob so account exists on-chain print("Funding Bob...") await aptos.faucet.fund_account(bob.address, 10_000_000) # Check balances alice_balance = await aptos.coin.balance(alice.address) bob_balance = await aptos.coin.balance(bob.address) print(f"\nAlice balance: {alice_balance}") print(f"Bob balance: {bob_balance}") # Transfer 1000 octas from Alice to Bob print("\nTransferring 1000 octas from Alice to Bob...") txn_hash = await aptos.coin.transfer(alice, bob.address, 1_000) result = await aptos.transaction.wait_for_transaction(txn_hash) print(f"Transaction: {txn_hash}") print(f"Success: {result['success']}") # Check final balances alice_balance = await aptos.coin.balance(alice.address) bob_balance = await aptos.coin.balance(bob.address) print(f"\nAlice balance: {alice_balance}") print(f"Bob balance: {bob_balance}") if __name__ == "__main__": asyncio.run(main()) ``` # Python SDK Quickstart > Get started with the Aptos Python SDK by creating accounts, funding them, and transferring APT 1. Install the Python SDK The SDK requires **Python 3.12+**. ``` pip install aptos-sdk ``` 2. Create a project file ``` mkdir aptos-python-quickstartcd aptos-python-quickstarttouch quickstart.py ``` 3. Set up the Aptos client Use the v2 API (`aptos_sdk.v2`). A connection is established as soon as you create the client. ``` import asyncio from aptos_sdk.v2 import Account, Aptos, AptosConfig, Network async def main(): async with Aptos(AptosConfig(network=Network.DEVNET)) as aptos: print("Connected to Aptos devnet") asyncio.run(main()) ``` 4. Create and fund accounts Generate credentials, then fund the accounts so the network knows they exist. On localnet and devnet you can fund from a faucet. ``` alice = Account.generate()bob = Account.generate() await aptos.faucet.fund_account(alice.address, 100_000_000)await aptos.faucet.fund_account(bob.address, 10_000_000) ``` On testnet, mint from the [faucet page](/network/faucet). 5. Transfer APT `aptos.coin.transfer` builds, signs, and submits an APT transfer. Then wait for the transaction to land. ``` txn_hash = await aptos.coin.transfer(alice, bob.address, 1_000)result = await aptos.transaction.wait_for_transaction(txn_hash)print(f"Success: {result['success']}") ``` For the lower-level build → simulate → sign → submit → wait flow, see [Building Transactions](/build/sdks/python-sdk/building-transactions). ## Full Quickstart Code [](#full-quickstart-code) ``` """Create two accounts, fund them, and transfer APT on devnet.""" import asyncio from aptos_sdk.v2 import Account, Aptos, AptosConfig, Network ALICE_INITIAL_BALANCE = 100_000_000BOB_INITIAL_BALANCE = 10_000_000TRANSFER_AMOUNT = 1_000 async def main(): async with Aptos(AptosConfig(network=Network.DEVNET)) as aptos: alice = Account.generate() bob = Account.generate() print("=== Addresses ===") print(f"Alice: {alice.address}") print(f"Bob: {bob.address}") await asyncio.gather( aptos.faucet.fund_account(alice.address, ALICE_INITIAL_BALANCE), aptos.faucet.fund_account(bob.address, BOB_INITIAL_BALANCE), ) print("=== Initial Balances ===") print(f"Alice: {await aptos.coin.balance(alice.address)}") print(f"Bob: {await aptos.coin.balance(bob.address)}") txn_hash = await aptos.coin.transfer(alice, bob.address, TRANSFER_AMOUNT) result = await aptos.transaction.wait_for_transaction(txn_hash) print(f"Transaction: {txn_hash}") print(f"Success: {result['success']}") print("=== Final Balances ===") print(f"Alice: {await aptos.coin.balance(alice.address)}") print(f"Bob: {await aptos.coin.balance(bob.address)}") asyncio.run(main()) ``` Run it with: ``` python quickstart.py ``` ## Summary [](#summary) You just learned how to transfer APT by: 1. Connecting to the network with the `Aptos` client. 2. Creating and funding accounts. 3. Submitting a transfer and waiting for execution. # Go SDK > Official Go SDK for Aptos blockchain development with comprehensive examples and transaction building capabilities [ ![Github Repo Stars](https://img.shields.io/github/stars/aptos-labs/aptos-go-sdk) ](https://github.com/aptos-labs/aptos-go-sdk)[ ![Go Reference](https://pkg.go.dev/badge/github.com/aptos-labs/aptos-go-sdk.svg) ](https://pkg.go.dev/github.com/aptos-labs/aptos-go-sdk) The Go SDK lets you connect, explore, and interact with the Aptos blockchain. You can use it to request data, send transactions, set up test environments, and more. ## Installing the Go SDK [](#installing-the-go-sdk) Aptos publishes the official Go SDK in the [aptos-go-sdk GitHub](https://github.com/aptos-labs/aptos-go-sdk) repository. The SDK requires **Go 1.25+**. ``` go get github.com/aptos-labs/aptos-go-sdk ``` ## Examples [](#examples) [Quickstart](/build/sdks/go-sdk/quickstart) Get a working transfer on devnet in a few minutes [Accounts](/build/sdks/go-sdk/account) Generate, restore, and fund accounts [Fetching Data](/build/sdks/go-sdk/fetch-data-via-sdk) Read ledger, account, and view-function data [Submitting Transactions](/build/sdks/go-sdk/building-transactions) Build, simulate, sign, and submit transactions [Examples](/build/sdks/go-sdk/go-examples) Catalog of runnable examples in the SDK repository [Tests](https://github.com/aptos-labs/aptos-go-sdk/tree/main/integration_test) Integration tests and package tests that exercise the SDK ### Transfer APT from the tested example suite [](#transfer-apt-from-the-tested-example-suite) The snippet below is pulled from [`examples/transfer_coin`](https://github.com/aptos-labs/aptos-go-sdk/tree/main/examples/transfer_coin) in the SDK repository. main.go ``` // transfer_coin is an example of how to make a coin transfer transaction in the simplest possible waypackage main import ( "fmt" "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/bcs") const ( FundAmount = 1_000_000_000 TransferAmount = 1_000) // example This example shows you how to make an APT transfer transaction in the simplest possible wayfunc example(networkConfig aptos.NetworkConfig) { // Create a client for Aptos client, err := aptos.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } // Create accounts locally for alice and bob alice, err := aptos.NewEd25519Account() if err != nil { panic("Failed to create alice:" + err.Error()) } bob, err := aptos.NewEd25519Account() if err != nil { panic("Failed to create bob:" + err.Error()) } fmt.Printf("\n=== Addresses ===\n") fmt.Printf("Alice: %s\n", alice.Address.String()) fmt.Printf("Bob:%s\n", bob.Address.String()) // Fund the sender with the faucet to create it on-chain err = client.Fund(alice.Address, FundAmount) if err != nil { panic("Failed to fund alice:" + err.Error()) } aliceBalance, err := client.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } bobBalance, err := client.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } fmt.Printf("\n=== Initial Balances ===\n") fmt.Printf("Alice: %d\n", aliceBalance) fmt.Printf("Bob:%d\n", bobBalance) // 1. Build transaction accountBytes, err := bcs.Serialize(&bob.Address) if err != nil { panic("Failed to serialize bob's address:" + err.Error()) } amountBytes, err := bcs.SerializeU64(TransferAmount) if err != nil { panic("Failed to serialize transfer amount:" + err.Error()) } rawTxn, err := client.BuildTransaction( alice.AccountAddress(), aptos.TransactionPayload{ Payload: &aptos.EntryFunction{ Module: aptos.ModuleId{ Address: aptos.AccountOne, Name: "aptos_account", }, Function: "transfer", ArgTypes: []aptos.TypeTag{}, Args: [][]byte{ accountBytes, amountBytes, }, }, }, ) if err != nil { panic("Failed to build transaction:" + err.Error()) } // 2. Simulate transaction (optional) // This is useful for understanding how much the transaction will cost // and to ensure that the transaction is valid before sending it to the network // This is optional, but recommended simulationResult, err := client.SimulateTransaction(rawTxn, alice) if err != nil { panic("Failed to simulate transaction:" + err.Error()) } fmt.Printf("\n=== Simulation ===\n") fmt.Printf("Gas unit price: %d\n", simulationResult[0].GasUnitPrice) fmt.Printf("Gas used: %d\n", simulationResult[0].GasUsed) fmt.Printf("Total gas fee: %d\n", simulationResult[0].GasUsed*simulationResult[0].GasUnitPrice) fmt.Printf("Status: %s\n", simulationResult[0].VmStatus) // 3. Sign transaction signedTxn, err := rawTxn.SignedTransaction(alice) if err != nil { panic("Failed to sign transaction:" + err.Error()) } // 4. Submit transaction submitResult, err := client.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } txnHash := submitResult.Hash // 5. Wait for the transaction to complete _, err = client.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } // Check balances aliceBalance, err = client.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } bobBalance, err = client.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } fmt.Printf("\n=== Intermediate Balances ===\n") fmt.Printf("Alice: %d\n", aliceBalance) fmt.Printf("Bob:%d\n", bobBalance) // Now do it again, but with a different method resp, err := client.BuildSignAndSubmitTransaction( alice, aptos.TransactionPayload{ Payload: &aptos.EntryFunction{ Module: aptos.ModuleId{ Address: aptos.AccountOne, Name: "aptos_account", }, Function: "transfer", ArgTypes: []aptos.TypeTag{}, Args: [][]byte{ accountBytes, amountBytes, }, }, }, ) if err != nil { panic("Failed to sign transaction:" + err.Error()) } _, err = client.WaitForTransaction(resp.Hash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } aliceBalance, err = client.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } bobBalance, err = client.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } fmt.Printf("\n=== Final Balances ===\n") fmt.Printf("Alice: %d\n", aliceBalance) fmt.Printf("Bob:%d\n", bobBalance)} func main() { example(aptos.DevnetConfig)} ``` # Go SDK Quickstart > Get started with the Aptos Go SDK by creating accounts, funding them, and transferring APT 1. Install the Go SDK The SDK requires **Go 1.25+**. ``` mkdir aptos-go-quickstartcd aptos-go-quickstartgo mod init example/aptos-go-quickstartgo get github.com/aptos-labs/aptos-go-sdk ``` 2. Set up the Aptos client ``` client, err := aptos.NewClient(aptos.DevnetConfig)if err != nil { panic("Failed to create client:" + err.Error())} ``` 3. Create and fund accounts `NewEd25519Account` returns both the account and an error. ``` alice, err := aptos.NewEd25519Account()if err != nil { panic("Failed to create alice:" + err.Error())}bob, err := aptos.NewEd25519Account()if err != nil { panic("Failed to create bob:" + err.Error())} err = client.Fund(alice.Address, 1_000_000_000)if err != nil { panic("Failed to fund alice:" + err.Error())} ``` On testnet, mint from the [faucet page](/network/faucet). 4. Transfer APT Build an `aptos_account::transfer` payload, then sign, submit, and wait. `BuildSignAndSubmitTransaction` combines those steps. ``` accountBytes, err := bcs.Serialize(&bob.Address)amountBytes, err := bcs.SerializeU64(1_000)resp, err := client.BuildSignAndSubmitTransaction(alice, aptos.TransactionPayload{ Payload: &aptos.EntryFunction{ Module: aptos.ModuleId{ Address: aptos.AccountOne, Name: "aptos_account", }, Function: "transfer", ArgTypes: []aptos.TypeTag{}, Args: [][]byte{accountBytes, amountBytes}, },})_, err = client.WaitForTransaction(resp.Hash) ``` For the lower-level build → simulate → sign → submit → wait flow, see [Building Transactions](/build/sdks/go-sdk/building-transactions). ## Full Quickstart Code [](#full-quickstart-code) ``` package main import ( "fmt" "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/bcs") const ( FundAmount = 1_000_000_000 TransferAmount = 1_000) func main() { client, err := aptos.NewClient(aptos.DevnetConfig) if err != nil { panic("Failed to create client:" + err.Error()) } alice, err := aptos.NewEd25519Account() if err != nil { panic("Failed to create alice:" + err.Error()) } bob, err := aptos.NewEd25519Account() if err != nil { panic("Failed to create bob:" + err.Error()) } fmt.Printf("=== Addresses ===\n") fmt.Printf("Alice: %s\n", alice.Address.String()) fmt.Printf("Bob: %s\n", bob.Address.String()) err = client.Fund(alice.Address, FundAmount) if err != nil { panic("Failed to fund alice:" + err.Error()) } aliceBalance, err := client.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } bobBalance, err := client.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } fmt.Printf("=== Initial Balances ===\n") fmt.Printf("Alice: %d\n", aliceBalance) fmt.Printf("Bob: %d\n", bobBalance) accountBytes, err := bcs.Serialize(&bob.Address) if err != nil { panic("Failed to serialize bob's address:" + err.Error()) } amountBytes, err := bcs.SerializeU64(TransferAmount) if err != nil { panic("Failed to serialize transfer amount:" + err.Error()) } resp, err := client.BuildSignAndSubmitTransaction(alice, aptos.TransactionPayload{ Payload: &aptos.EntryFunction{ Module: aptos.ModuleId{ Address: aptos.AccountOne, Name: "aptos_account", }, Function: "transfer", ArgTypes: []aptos.TypeTag{}, Args: [][]byte{ accountBytes, amountBytes, }, }, }) if err != nil { panic("Failed to submit transaction:" + err.Error()) } _, err = client.WaitForTransaction(resp.Hash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } aliceBalance, err = client.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } bobBalance, err = client.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } fmt.Printf("=== Final Balances ===\n") fmt.Printf("Alice: %d\n", aliceBalance) fmt.Printf("Bob: %d\n", bobBalance) fmt.Printf("See txn: https://explorer.aptoslabs.com/txn/%s?network=devnet\n", resp.Hash)} ``` Run it with: ``` go run quickstart.go ``` ## Summary [](#summary) You just learned how to transfer APT by: 1. Connecting to the network with `aptos.NewClient`. 2. Creating and funding accounts. 3. Submitting a transfer and waiting for execution. # Rust SDK > Official Rust SDK for Aptos blockchain development with accounts, data fetching, and transaction building [ ![Github Repo Stars](https://img.shields.io/github/stars/aptos-labs/aptos-rust-sdk) ](https://github.com/aptos-labs/aptos-rust-sdk)[ ![Crates.io Version](https://img.shields.io/crates/v/aptos-sdk) ](https://crates.io/crates/aptos-sdk)[ ![docs.rs](https://img.shields.io/docsrs/aptos-sdk) ](https://docs.rs/aptos-sdk) The Rust SDK lets you connect, explore, and interact with the Aptos blockchain. You can use it to request data, send transactions, set up test environments, and more. ## Installing the Rust SDK [](#installing-the-rust-sdk) Aptos publishes the official Rust SDK in the [aptos-rust-sdk GitHub](https://github.com/aptos-labs/aptos-rust-sdk) repository and on [crates.io](https://crates.io/crates/aptos-sdk). Add it to your `Cargo.toml`: ``` [dependencies]aptos-sdk = "0.7"tokio = { version = "1", features = ["full"] }anyhow = "1" ``` To use the latest unreleased changes: ``` [dependencies]aptos-sdk = { git = "https://github.com/aptos-labs/aptos-rust-sdk", package = "aptos-sdk" } ``` The SDK requires **Rust 1.95+**. Unlike the legacy crate in `aptos-core`, this SDK does not need git patches or a `.cargo/config.toml` `tokio_unstable` flag. ### Feature flags [](#feature-flags)
FeatureDefaultDescription
ed25519YesEd25519 signature scheme
secp256k1YesSecp256k1 ECDSA signatures
secp256r1YesSecp256r1 (P-256) ECDSA signatures
mnemonicYesBIP-39 mnemonic phrase support
indexerYesGraphQL indexer client
faucetYesFaucet integration for testnets
blsNoBLS12-381 signatures
macrosNoProc macros for type-safe contract bindings
Minimal build: ``` [dependencies]aptos-sdk = { version = "0.7", default-features = false, features = ["ed25519"] } ``` ## Examples [](#examples) [Quickstart](/build/sdks/rust-sdk/quickstart) Get a working transfer on devnet in a few minutes [Accounts](/build/sdks/rust-sdk/account) Generate, restore, and fund accounts [Fetching Data](/build/sdks/rust-sdk/fetch-data-via-sdk) Read ledger, account, and view-function data [Submitting Transactions](/build/sdks/rust-sdk/building-transactions) Build, simulate, sign, and submit transactions [Examples](/build/sdks/rust-sdk/rust-examples) Catalog of runnable examples in the SDK repository [Tests](https://github.com/aptos-labs/aptos-rust-sdk/tree/main/crates/aptos-sdk/tests) Crate tests that exercise the SDK APIs ### Transfer APT from the tested example suite [](#transfer-apt-from-the-tested-example-suite) The snippet below is pulled from [`transfer.rs`](https://github.com/aptos-labs/aptos-rust-sdk/blob/main/crates/aptos-sdk/examples/transfer.rs) in the SDK repository. Fund well above the transfer amount: the default `max_gas_amount` is `2_000_000`. transfer.rs ``` //! Example: Basic APT transfer//!//! This example demonstrates how to://! 1. Create an Aptos client//! 2. Generate or load an account//! 3. Fund the account using the faucet//! 4. Transfer APT to another account//!//! Run with: `cargo run --example transfer --features "ed25519,faucet"` use aptos_sdk::{Aptos, AptosConfig, account::Ed25519Account}; #[tokio::main]async fn main() -> anyhow::Result<()> { // Create client for devnet let aptos = Aptos::new(AptosConfig::devnet())?; println!("Connected to devnet"); // Generate sender account let sender = Ed25519Account::generate(); println!("Sender address: {}", sender.address()); // Fund sender using faucet println!("Funding sender account..."); aptos.fund_account(sender.address(), 100_000_000).await?; // Wait for funding to complete tokio::time::sleep(std::time::Duration::from_secs(2)).await; // Check sender balance let balance = aptos.get_balance(sender.address()).await?; println!("Sender balance: {} APT", balance as f64 / 100_000_000.0); // Generate recipient account let recipient = Ed25519Account::generate(); println!("Recipient address: {}", recipient.address()); // Transfer 0.1 APT (10_000_000 octas) println!("Transferring 0.1 APT..."); let result = aptos .transfer_apt(&sender, recipient.address(), 10_000_000) .await?; let success = result .data .get("success") .and_then(serde_json::value::Value::as_bool); if success == Some(true) { println!("Transfer successful!"); // Check balances let sender_balance = aptos.get_balance(sender.address()).await?; let recipient_balance = aptos.get_balance(recipient.address()).await?; println!( "Sender balance: {} APT", sender_balance as f64 / 100_000_000.0 ); println!( "Recipient balance: {} APT", recipient_balance as f64 / 100_000_000.0 ); } else { let vm_status = result .data .get("vm_status") .and_then(|v| v.as_str()) .unwrap_or("unknown"); println!("Transfer failed: {vm_status}"); } Ok(())} ``` # Rust SDK Quickstart > Get started with the Aptos Rust SDK by creating accounts, funding them, and transferring APT 1. Create a Cargo project and add the SDK The SDK requires **Rust 1.95+**. ``` cargo new aptos-rust-quickstartcd aptos-rust-quickstart ``` Add dependencies to `Cargo.toml`: ``` [dependencies]aptos-sdk = "0.7"tokio = { version = "1", features = ["full"] }anyhow = "1"serde_json = "1" ``` 2. Set up the Aptos client ``` use aptos_sdk::{Aptos, AptosConfig}; let aptos = Aptos::new(AptosConfig::devnet())?;println!("Connected to Aptos devnet"); ``` 3. Create and fund accounts ``` use aptos_sdk::account::Ed25519Account; let alice = Ed25519Account::generate();let bob = Ed25519Account::generate(); // Default max_gas_amount is 2_000_000. Fund well above the transfer amount.aptos.fund_account(alice.address(), 1_000_000_000).await?; ``` You can also generate and fund in one step with `aptos.create_funded_account(amount)`. On testnet, mint from the [faucet page](/network/faucet). 4. Transfer APT `aptos.transfer_apt` builds, signs, submits, and waits. ``` let result = aptos.transfer_apt(&alice, bob.address(), 1_000).await?;println!("Submitted: {:?}", result.data.get("hash")); ``` For the lower-level build → simulate → sign → submit → wait flow, see [Building Transactions](/build/sdks/rust-sdk/building-transactions). ## Full Quickstart Code [](#full-quickstart-code) ``` use aptos_sdk::{Aptos, AptosConfig, account::Ed25519Account}; const FUND_AMOUNT: u64 = 1_000_000_000;const TRANSFER_AMOUNT: u64 = 1_000; #[tokio::main]async fn main() -> anyhow::Result<()> { let aptos = Aptos::new(AptosConfig::devnet())?; let alice = Ed25519Account::generate(); let bob = Ed25519Account::generate(); println!("=== Addresses ==="); println!("Alice: {}", alice.address()); println!("Bob: {}", bob.address()); aptos.fund_account(alice.address(), FUND_AMOUNT).await?; println!("=== Initial Balances ==="); println!("Alice: {}", aptos.get_balance(alice.address()).await?); println!("Bob: {}", aptos.get_balance(bob.address()).await?); let result = aptos .transfer_apt(&alice, bob.address(), TRANSFER_AMOUNT) .await?; println!("Submitted: {:?}", result.data.get("hash")); println!("=== Final Balances ==="); println!("Alice: {}", aptos.get_balance(alice.address()).await?); println!("Bob: {}", aptos.get_balance(bob.address()).await?); Ok(())} ``` Run it with: ``` cargo run ``` ## Summary [](#summary) You just learned how to transfer APT by: 1. Connecting to the network with `Aptos::new`. 2. Creating and funding accounts. 3. Submitting a transfer and waiting for execution. # Sponsored Transactions > Allow applications to pay transaction fees for users, simplifying onboarding by removing the need for gas tokens. As outlined in [AIP-39](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-039-sponsored-transactions.md), sponsored transactions allow one account to pay the fees associated with executing a transaction for another account, essentially setting up a fee payer. Sponsored transactions simplify the process for onboarding users into applications by allowing the application to cover all associated fees for interacting with the Aptos blockchain. Here are two examples: * [MerkleTrade](https://merkle.trade/) offers low cost trading to those with Ethereum wallets by creating an Aptos wallet for users and covering all transaction fees so that the user does not need to acquire utility tokens for Aptos. * Community engagement applications like [Graffio](https://medium.com/aptoslabs/graffio-web3s-overnight-sensation-81a6cf18b626) offered to cover transaction fees for custodial accounts to support the collaborative drawing application for those without wallets. ## Process Overview [](#process-overview) The process for sending a sponsored transaction follows: * The sender of the transaction determines upon an operation, as defined by a `RawTransaction`. * The sender generates a `RawTransactionWithData::MultiAgentWithFeePayer` structure * Prior to the framework 1.8 release, this must contain the fee payer’s address. * After framework release 1.8, this can optionally be set to `0x0`. * (Optionally) the sender aggregates signatures from other signers. * The sender can forward the signed transaction to the fee payer to sign and forward it to the blockchain. * Upon execution of the transaction, gas fees are deducted from the fee payer and refunds return to the fee payer. Sequence-number transactions also increment the sender’s sequence number; [orderless](/build/guides/orderless-transactions) sponsored transactions use a nonce instead. Alternatively, if the fee payer knows the operation and all signers involved, the fee payer could generate and sign the transaction and send it back to the other signers to sign. ## Technical Details [](#technical-details) In Aptos, a sponsored transaction reuses the same SignedTransaction as any other user transaction: ``` pub struct SignedTransaction { /// The raw transaction raw_txn: RawTransaction, /// Public key and signature to authenticate authenticator: TransactionAuthenticator,} ``` The difference is in the `TransactionAuthenticator`, which stores the authorization from the fee payer of the transaction to extract utility fees from their account: ``` pub enum TransactionAuthenticator {... /// Optional Multi-agent transaction with a fee payer. FeePayer { sender: AccountAuthenticator, secondary_signer_addresses: Vec, secondary_signers: Vec, fee_payer_address: AccountAddress, fee_payer_signer: AccountAuthenticator, },...} ``` As of framework 1.8 and [AIP-115](/build/aips/aip-115) stateless accounts, the sender does not need a pre-created `0x1::account::Account` resource. The first transaction that creates that resource still needs enough gas to cover creation in addition to execution. During signing of the transaction, all parties sign the following: ``` pub enum RawTransactionWithData {... MultiAgentWithFeePayer { raw_txn: RawTransaction, secondary_signer_addresses: Vec, fee_payer_address: AccountAddress, },} ``` Prior to framework release 1.8, all signers were required to know the actual fee payer address prior to signing. As of framework release 1.8, signers can optionally set the address to `0x0` and only the fee payer must sign with their address set. ## SDK Support [](#sdk-support) Build sponsored transactions with `withFeePayer: true`, then have the sender `.sign` and the sponsor `.signAsFeePayer`. See the [TypeScript SDK sponsoring guide](/build/sdks/ts-sdk/building-transactions/sponsoring-transactions) for a full walkthrough. Each official SDK documents sponsored transactions and ships a tested example: * [TypeScript SDK](/build/sdks/ts-sdk/building-transactions/sponsoring-transactions) — [`simple_sponsored_transaction.ts`](https://github.com/aptos-labs/aptos-ts-sdk/blob/main/examples/typescript/simple_sponsored_transaction.ts) * [Python SDK](/build/sdks/python-sdk/building-transactions/sponsoring-transactions) — [`sponsored_transaction.py`](https://github.com/aptos-labs/aptos-python-sdk/blob/main/v2/examples/sponsored_transaction.py) * [Go SDK](/build/sdks/go-sdk/building-transactions/sponsoring-transactions) — [`examples/sponsored_transaction`](https://github.com/aptos-labs/aptos-go-sdk/tree/main/examples/sponsored_transaction) * [Rust SDK](/build/sdks/rust-sdk/building-transactions/sponsoring-transactions) — [`sponsored_transaction.rs`](https://github.com/aptos-labs/aptos-rust-sdk/blob/main/crates/aptos-sdk/examples/sponsored_transaction.rs) For how sponsored transactions compose with APT, stablecoin, confidential, and two-party payments, see [Payments](/build/guides/payments#compose-every-payment). # Orderless Transactions > Execute transactions out of order for multi-machine signing scenarios while maintaining replay protection and security. As outlined in [AIP-123](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-123-orderless-transactions.md) ([FAQ](/build/aips/aip-123)), orderless transactions execute without a sequence number. This is useful when multiple machines submit from a single sending account and the order of submission does not matter. Replay is protected by a nonce. The blockchain stores `(sender, nonce)` pairs for committed orderless transactions from the last 60 seconds. A transaction executes only if that pair is unused, and orderless transactions expire after at most 60 seconds — shorter than sequence-number transactions. Both accounts with an on-chain `0x1::account::Account` resource and [stateless accounts](/build/aips/aip-115) can send orderless transactions. ## Process Overview [](#process-overview) Orderless transactions use the extra payload fields specified in [AIP-129](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-129-add-extra-information-in-transaction-payload.md). 1. Build a transaction with a unique `replayProtectionNonce` (a random `u64`) and the Move entry function you want to call. 2. Sign and submit the transaction as usual. The nonce replaces the sequence number for replay protection. The nonce does **not** order transactions. It only ensures a transaction cannot execute twice with the same nonce before it expires. ## TypeScript example [](#typescript-example) Pass `replayProtectionNonce` in the transaction `options`: ``` const transaction = await aptos.transaction.build.simple({ sender: sender.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [destination.accountAddress, 100], }, options: { replayProtectionNonce: 12345n, },}); ``` You can combine orderless replay protection with [sponsored transactions](/build/guides/sponsored-transactions) and [encrypted pending transactions](/build/guides/encrypted-pending-transactions). For how orderless transactions compose with each payment type, see [Payments](/build/guides/payments#compose-every-payment). ## SDK support [](#sdk-support) Each official SDK documents orderless transactions and ships a tested example: * [TypeScript SDK](/build/sdks/ts-sdk/building-transactions/orderless-transactions) — [`simple_orderless_transfer.ts`](https://github.com/aptos-labs/aptos-ts-sdk/blob/main/examples/typescript/simple_orderless_transfer.ts) * [Python SDK](/build/sdks/python-sdk/building-transactions/orderless-transactions) — [`orderless_transfer.py`](https://github.com/aptos-labs/aptos-python-sdk/blob/main/v2/examples/orderless_transfer.py) * [Go SDK](/build/sdks/go-sdk/building-transactions/orderless-transactions) — [`examples/orderless_transaction`](https://github.com/aptos-labs/aptos-go-sdk/tree/main/examples/orderless_transaction) * [Rust SDK](/build/sdks/rust-sdk/building-transactions/orderless-transactions) — [`orderless_transaction.rs`](https://github.com/aptos-labs/aptos-rust-sdk/blob/main/crates/aptos-sdk/examples/orderless_transaction.rs) # Encrypted Pending Transactions > Encrypt transaction payloads before they reach consensus so pending execution details stay confidential on supported networks. Encrypted pending transactions let you submit a transaction whose **Move payload** (entry function, arguments, and related executable data) is **encrypted while the transaction is pending**—for example while it is held in mempool and propagated between nodes. Validators decrypt the payload only when preparing execution after the block is confirmed. This reduces what observers can learn from the public pending transaction stream compared to a fully plaintext payload. This feature is live on **devnet**, **testnet**, and **mainnet**. The fullnode you use must expose a ledger **`encryption_key`** when encrypted submission is enabled. On networks or nodes where the key is absent, the client cannot build encrypted transactions. ## What clients can still observe [](#what-clients-can-still-observe) Encryption protects the **payload bytes** in transit and at rest in the pending phase, but a transaction is still a signed request to the chain. Depending on configuration and payload type, clients may still see metadata such as sender, gas parameters, expiration, signatures, and—where the protocol requires it—**metadata derived from the payload** (for example a **claimed entry function** for certain multisig or sponsored flows). Treat “encrypted pending” as **payload privacy**, not anonymity of the whole transaction. For the precise security model, see **[AIP-144: Encrypted Mempool](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-144-encrypted-mempool.md)** and the underlying cryptography in [eprint 2025/2032](https://eprint.iacr.org/2025/2032). At the protocol level this feature is called **encrypted mempool** (AIP-144); the names are interchangeable. ## Cost [](#cost) Encrypted transactions cost more than plaintext transactions. The extra cost covers validator decryption work and has two parts: * **Higher minimum gas-unit price.** Encrypted transactions pay a **minimum gas-unit price of 200 Octas/gas-unit**, twice the network base minimum. SDKs enforce this floor at build time; servers reject encrypted submissions priced below it. * **Flat decryption charge.** Each encrypted transaction is charged an extra **375 gas units** on top of the gas its payload uses. If you set `maxGasAmount` yourself, leave room for this charge. Otherwise, the transaction is rejected during validation or runs out of gas. As a rough guide, for a transaction without storage fees: if its plaintext version uses `G` gas units, the encrypted version costs about `(G + 375) × max(gas_unit_price, 200)` Octas. For example, a transfer that uses 150 gas units costs 15,000 Octas as plaintext at 100 Octas/gas-unit. Encrypted, it costs about (150 + 375) × 200 = 105,000 Octas (0.00105 APT). The flat charge matters most for small transactions. Both values are governance-controlled parameters in the on-chain gas schedule (`0x1::gas_schedule::GasScheduleV2`): `txn.encrypted_txn_min_price_per_gas_unit` and `txn.encrypted_txn_decryption.base`. The second value is in internal gas units. Divide it by `txn.gas_unit_scaling_factor` to get gas units. ## Signer restrictions [](#signer-restrictions) **Keyless**, **federated keyless**, and **account abstraction** accounts cannot sign encrypted transactions. The rule is enforced both client-side (where supported) and server-side. ## Relationship to orderless transactions [](#relationship-to-orderless-transactions) You can combine encrypted payloads with **[orderless transactions](/build/guides/orderless-transactions)** so parallel submitters use replay-protection nonces while still encrypting the executable. See the TypeScript SDK page below for build options. ## Not the same as confidential assets [](#not-the-same-as-confidential-assets) **Encrypted pending transactions** protect the transaction payload for _pending transactions_ on the way to execution. They are unrelated to **[confidential assets](/build/sdks/ts-sdk/confidential-asset)** transactions, which allow for privacy of balances and amounts _even after transactions are confirmed._ ## SDK support [](#sdk-support) **[TypeScript SDK](/build/sdks/ts-sdk/building-transactions/encrypted-pending-transactions)** — build with `options.encrypted` (`senderAuthenticationKey` is optional; SDK auto-fetches), submit encrypted builds. ## Further reading [](#further-reading) * [AIP-144: Encrypted Mempool](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-144-encrypted-mempool.md) — protocol-level specification and rationale. * [Aptos Encrypted Mempool (eprint 2025/2032)](https://eprint.iacr.org/2025/2032) — formal cryptographic treatment. # Aptos Keyless > Integrate Keyless accounts for seamless user onboarding using social logins instead of traditional private key management. ## Integrate with Aptos Keyless accounts [](#integrate-with-aptos-keyless-accounts) * [Introduction](/build/guides/aptos-keyless/introduction) * [OIDC Support and Configuration](/build/guides/aptos-keyless/oidc-support) * [Integration Guide](/build/guides/aptos-keyless/integration-guide) * [Simple Example](/build/guides/aptos-keyless/simple-example) * [How Aptos Keyless works](/build/guides/aptos-keyless/how-keyless-works) * [Terminology and FAQ](/build/guides/aptos-keyless/other) ## Using an IAM Provider? Integrate with Aptos Federated Keyless [](#using-an-iam-provider-integrate-with-aptos-federated-keyless) * [Federated Keyless](/build/guides/aptos-keyless/federated-keyless) # Transaction Management > Build scalable transaction management systems on Aptos with proper account handling and sequence number management. This guide explains how to build a transaction management harness that can scale on the Aptos blockchain. ## Background [](#background) In Aptos, transactions are mapped back to an account in terms of the entity that signs or authorizes that transaction and provides an account-based sequence number. When the Aptos network receives a new transaction, several rules are followed with respect to this: * The transaction sent from an account must be authorized correctly by that account. * The current time as defined by the most recent ledger update must be before the expiration timestamp of the transaction. * The transaction’s sequence number must be equal to or greater than the sequence number on-chain for that account. Once the initial node has accepted a transaction, the transaction makes its way through the system by an additional rule. If a transaction’s sequence number is higher than the current on-chain sequence number, it can only progress toward consensus if every node in the path has seen a transaction with the sequence number between the on-chain state and the current sequence number. Example: Alice owns an account whose current on-chain sequence number is 5. Alice submits a transaction to node Bob with sequence number 6. Bob the node accepts the transaction but does not forward it, because Bob has not seen 5. In order to make progress, Alice must either send Bob transaction number 5 or Bob must be notified from consensus that 5 was committed. In the latter, Alice submitted the transaction through another node. Beyond this there are two remaining principles: * A single account can have at most 100 uncommitted transactions submitted to the blockchain. Any more than that and the transactions will be rejected. This can happen silently if Alice submits the first 100 to Bob the node and the next 100 to Carol the node. If both those nodes share a common upstream, then that upstream will accept Alice’s 100 sent via Bob but silently reject Alice’s 100 sent via Carol. * Submitting to distinct transactions to multiple nodes will result in slow resolution as transactions will not make progress from the submitted node until the submitted knows that all preceding transactions have been committed. For example, if Alice sends the first 50 via Bob and the next 50 via Carol. ## Building a Transaction Manager [](#building-a-transaction-manager) Now that we understand the nuances of transactions, let’s dig into building a robust transaction manager. This consists of the following core components: * A sequence number generator that allocates and manages available sequence numbers for a single account. * A transaction manager that receives payloads from an application or a user, sequence numbers from the sequence number generator, and has access to the account key to combine the three pieces together into a viable signed transaction. It then also takes the responsibility for pushing the transaction to the blockchain. * An on-chain worker, leader harness that lets multiple accounts share the signer of a single shared account. Currently, this framework assumes that the network builds no substantial queue, that is a transaction that is submitted executes and commits with little to no delay. In order to address high demand, this work needs to be extended with the following components: * Optimizing `base_gas_unit` price to ensure priority transactions can be committed to the blockchain. * Further handling of transaction processing rates to ensure that the expiration timer is properly set. * Handling of transaction failures to either be ignored or resubmitted based upon desired outcome. Note, an account should be managed by a single instance of the transaction manager. Otherwise, each instance of the transaction manager will likely have stale in-memory state resulting in overlapping sequence numbers. ### Implementations [](#implementations) * Python * [Sequence number manager](https://github.com/aptos-labs/aptos-core/pull/7987) * [Transaction manager](https://github.com/aptos-labs/aptos-core/pull/7987) * [Worker-leader smart contract](https://github.com/aptos-labs/aptos-core/pull/7986) Those pull requests show a historical sequence-number manager. For current SDK builders, see [Building Transactions](/build/sdks/ts-sdk/building-transactions) and [Orderless Transactions](/build/sdks/ts-sdk/building-transactions/orderless-transactions). ## When to use orderless transactions instead [](#when-to-use-orderless-transactions-instead) Sequence numbers serialize all submissions from one account. If several machines must submit from the same sender without coordinating a sequence-number allocator — for example an exchange hot wallet — use [orderless transactions](/build/guides/orderless-transactions) (AIP-123). Each transaction carries a unique `replayProtectionNonce` and expires in at most 60 seconds. You can still use the sequence-number model above when you need strict ordering or longer expiration. ### Managing Sequence Numbers [](#managing-sequence-numbers) Each transaction requires a distinct sequence number that is sequential to previously submitted transactions. This can be provided by the following process: 1. At startup, query the blockchain for the account’s current sequence number. 2. Support up to 100 transactions in flight at the same time, that is 100 sequence numbers can be allocated without confirming that any have been committed. 3. If there are 100 transactions in flight, determine the actual committed state by querying the network. This will update the current sequence number. 4. If there are less than 100 transactions in flight, return to step 2. 5. Otherwise, sleep for .1 seconds and continue to re-evaluate the current on-chain sequence number. 6. All transactions should have an expiration time. If the expiration time has passed, assume that there has been a failure and reset the sequence number. The trivial case is to only monitor for failures when the maximum number of transactions are in flight and to let other services manages this otherwise. In parallel, monitor new transactions submitted. Once the earliest transaction expiration time has expired synchronize up to that transaction. Then repeat the process for the next transaction. If there is any failure, wait until all outstanding transactions have timed out and leave it to the application to decide how to proceed, e.g., replay failed transactions. The best method to waiting for outstanding transactions is to query the ledger timestamp and ensure it is at least elapsed the maximum timeout from the last transactions submit time. From there, validate with mempool that all transactions since the last known committed transaction are either committed or no longer exist within the mempool. This can be done by querying the REST API for transactions of a specific account, specifying the currently being evaluated sequence number and setting a limit to 1. Once these checks are complete, the local transaction number can be resynchronized. These failure handling steps are critical for the following reasons: * Mempool does not immediate evict expired transactions. * A new transaction cannot overwrite an existing transaction, even if it is expired. * Consensus, i.e., the ledger timestamp, dictates expirations, the local node will only expire after it sees a committed timestamp after the transactions expiration time and a garbage collection has happened. ### Managing Transactions [](#managing-transactions) Once a transaction has been submitted it goes through a variety of steps: 1. Submission to a REST endpoint. 2. Pre-execution validation in the Mempool during submission. 3. Transmission from Mempool to Mempool with pre-execution validation happening on each upstream node. 4. Inclusion in a consensus proposal. 5. One more pre-execution validation. 6. Execution and committing to storage. There are many potential failure cases that must be considered: * Failure during transaction submission (1 and 2): * Visibility: The application will receive an error either that the network is unavailable or that the transaction failed pre-execution validation. * If the error is related to availability or duplicate sequence numbers, wait until access is available and the sequence number has re-synchronized. * Pre-execution validation failures are currently out of scope, outside of those related to duplicate sequence numbers, account issues are likely related to an invalid key for the account or the account lacks sufficient funds for gas. * Failure between submission and execution (3, 4, and 5): * Visibility: Only known by waiting until the transaction has expired. * These are the same as other pre-execution validation errors due to changes to the account as earlier transactions execute. It is likely either duplicate sequence numbers or the account lacks sufficient funds for gas. * Failure during execution (6): * Visibility: These are committed to the blockchain. * These errors occur as a result of on-chain state issues, these tend to be application specific, such as an auction where a new bid might not actually be higher than the current bid. ### Workers and Identity [](#workers-and-identity) Using the above framework, a single account can push upwards of 100 transactions from the start of a block to the end of a block. Assuming that all 100 transactions are consumed within 1 block, it will take a bit of time for the next 100 slots to be available. This is due to the network delays as well as the multi-staged validator pipeline. To fully leverage the blockchain for massive throughput, using a single user account is not enough. Instead, Aptos supports the concept of worker accounts that can share the responsibility of pushing work through a shared account, also known as a resource account. In this model, each worker has access to the `SignerCap` of the shared account, which enables them to impersonate the shared account or generate the `signer` for the shared account. Upon gaining the `signer`, the transaction can execute the logic that is gated by the signer of the shared account. Another model, if viable, is to decouple the `signer` altogether away from permissions and to make an application specific capability. Then this capability can be given to each worker that lets them operate on the shared infrastructure. Note that parallelization on the shared infrastructure can be limited if any transaction would have any read or write conflicts. This won’t prevent multiple transactions from executing within a block, but can impact maximum blockchain performance. # AI Tools for Aptos Development > Use AI tools like Claude, Cursor, Codex, and GitHub Copilot to build on Aptos faster. Access the Aptos MCP server and LLMs.txt documentation feeds. Aptos provides first-class support for AI-powered development workflows. Whether you’re using an AI coding assistant or an AI chat tool, you can give it deep knowledge of the Aptos blockchain, Move language, SDKs, and APIs. ## Aptos MCP Server [](#aptos-mcp-server) The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) lets AI coding tools directly call Aptos APIs, query on-chain data, and generate correct Aptos code — without needing to copy-paste documentation. [Claude Code](/build/ai/aptos-mcp/claude) Set up the Aptos MCP server for Claude Code [Cursor](/build/ai/aptos-mcp/cursor) Set up the Aptos MCP server for Cursor [OpenAI Codex](/build/ai/aptos-mcp/codex) Set up the Aptos MCP server for Codex Any MCP client that can launch a local stdio server — including GitHub Copilot — can use the same `npx -y @aptos-labs/aptos-mcp` command. See the [Aptos MCP overview](/build/ai/aptos-mcp) for prerequisites and the Geomi Bot Key. ## Aptos Agent Skills [](#aptos-agent-skills) [Aptos Agent Skills](https://github.com/aptos-labs/aptos-agent-skills) provides pre-built AI skills that give coding assistants deep Aptos expertise — covering Move smart contracts, the TypeScript SDK, and full-stack dApp scaffolding. ``` npx skills add aptos-labs/aptos-agent-skills ``` This command uses the [Skills CLI](https://www.npmjs.com/package/skills), which is invoked via `npx`. If `npx skills` is not available in your environment, ensure you have Node.js and npm installed and refer to the Skills CLI documentation for installation and troubleshooting details. [Aptos Agent Skills](/build/ai/aptos-agent-skills) Browse available skills for Move development, TypeScript SDK, and project scaffolding ## LLMs.txt Documentation Feeds [](#llmstxt-documentation-feeds) The [LLMs.txt standard](https://llmstxt.org/) provides machine-readable documentation feeds that AI tools can ingest to understand the full Aptos documentation. We publish three feeds to suit different context window sizes:
FeedURLBest for
llms.txt/llms.txtStructured index with page titles, descriptions, and per-page .md links
llms-small.txt/llms-small.txtCondensed docs for smaller context windows
llms-full.txt/llms-full.txtFull documentation — all pages concatenated
Some clients resolve `/.well-known/llms.txt`; production serves the same index via a redirect to [`/llms.txt`](/llms.txt) ([`https://aptos.dev/.well-known/llms.txt`](https://aptos.dev/.well-known/llms.txt)). The [`llms.txt`](/llms.txt) router also surfaces machine-readable **API** links—[`/aptos-spec.json`](/aptos-spec.json) (OpenAPI 3 JSON for the node REST API) and [`/rest-api`](/rest-api) (HTML reference)—plus **MCP**, Agent Skills, Explorer, GitHub, standards, and Indexer GraphQL `.md` links in one place. [How to use LLMs.txt with AI tools](/llms-txt) Instructions for Cursor, Claude Code, GitHub Copilot, ChatGPT, Codex, Devin Desktop, and more ## Agent discovery endpoints [](#agent-discovery-endpoints) The docs site publishes a handful of standardized discovery documents so coding agents can bootstrap from a single root. Every page also returns a [`Link`](https://www.rfc-editor.org/rfc/rfc8288) response header and matching `` tags that advertise the same URLs.
EndpointPurpose
/.well-known/api-catalogRFC 9727 linkset pointing at the REST API spec, documentation, Indexer GraphQL, and the LLMs.txt feeds.
/.well-known/mcp/server-card.jsonMCP Server Card (SEP-2127) describing the @aptos-labs/aptos-mcp server.
/.well-known/agent-skills/index.jsonAgent Skills Discovery index for aptos-agent-skills with per-skill SHA-256 digests.
/.well-known/oauth-protected-resourceOAuth 2.0 Protected Resource Metadata (RFC 9728) for https://aptos.dev. Lists the resource identifier, the Firebase + Google authorization servers used by the Aptos Testnet Faucet, and supported scopes.
/.well-known/openid-configurationOpenID Connect Discovery 1.0 document advertising the issuer, authorization/token endpoints, JWKS URI, and supported grant types used by the Aptos Testnet Faucet sign-in flow.
/.well-known/oauth-authorization-serverOAuth 2.0 Authorization Server Metadata (RFC 8414) mirror of the OIDC discovery document for clients that prefer the pure OAuth 2.0 endpoint name.
/.well-known/ai-catalog.jsonARD / AI Catalog capability manifest listing the MCP Server Card, Agent Skills index, REST OpenAPI spec, and RFC 9727 API catalog.
/auth.mdauth.md agent authentication instructions. Documents that aptos.dev is public (no agent registration) and that the Testnet Faucet uses human Google OIDC.
/robots.txtIncludes Content Signals (ai-train=yes, search=yes, ai-input=yes), an Agentmap: pointer to the AI Catalog, and Sitemap: https://aptos.dev/sitemap.xml.
The origin-level RFC 9728 document identifies `https://aptos.dev` so clients that require the `resource` identifier to match this host will accept it. Documentation on this host is unauthenticated. The listed authorization servers (Firebase + Google) mint the bearer tokens that the [Aptos Testnet Faucet](/network/faucet) accepts on `Authorization: Bearer …`; the faucet API itself lives at `https://faucet-e2.testnet.aptoslabs.com`. [`/auth.md`](/auth.md) is the prose companion: there is no agent-registration endpoint. ### DNS for AI Discovery (DNS-AID) [](#dns-for-ai-discovery-dns-aid) [DNS-AID](https://datatracker.ietf.org/doc/draft-mozleywilliams-dnsop-dnsaid/) records cannot be published from this repository. The `aptos.dev` zone is hosted on Google Cloud DNS (`ns-cloud-c1.googledomains.com` through `ns-cloud-c4.googledomains.com`). The organization index already exists: ``` _index._agents.aptos.dev. 3600 IN HTTPS 1 aptos.dev. alpn="h2,h3" port=443 ``` That record points agents at `https://aptos.dev`, where the MCP Server Card, API catalog, AI Catalog, and other well-known documents live. Do not publish `_a2a._agents` or `_mcp._agents` until Aptos hosts those protocols on HTTPS — the MCP server is stdio (`npx @aptos-labs/aptos-mcp`), not a remote MCP endpoint. The zone has `DNSKEY` and `RRSIG` records, but validating resolvers still return `AD=0` because there is no `DS` record at the `.dev` parent. Agent scanners that require DNSSEC therefore fail even though the HTTPS record is present. Operators should publish the KSK `DS` at the registrar (or enable DNSSEC in Google Cloud DNS so it submits the `DS` automatically), then confirm: ``` dig +short HTTPS _index._agents.aptos.devdig +dnssec HTTPS _index._agents.aptos.devdig DS aptos.dev ``` To advertise the AI Catalog over DNS as well, add: ``` _catalog._agents.aptos.dev. 3600 IN TXT "url=https://aptos.dev/.well-known/ai-catalog.json" ``` ### Markdown content negotiation [](#markdown-content-negotiation) Any docs URL that has a `.md` mirror (for example [`/build/sdks`](/build/sdks) → [`/build/sdks.md`](/build/sdks.md)) will also respond to `Accept: text/markdown` with `Content-Type: text/markdown`: ``` curl -H "Accept: text/markdown" https://aptos.dev/build/sdks ``` HTML stays the default for browsers that send the usual `Accept: text/html`. ### WebMCP [](#webmcp) Chrome and other browsers that implement the [WebMCP proposal](https://webmachinelearning.github.io/webmcp/) can discover the following tools on every docs page via `navigator.modelContext`: `aptos-docs.search`, `aptos-docs.open-doc`, `aptos-docs.fetch-doc-markdown`, and `aptos-docs.list-llms-feeds`. # Aptos Model Context Protocol (MCP) > Learn how to use the Aptos MCP server to build applications with AI tools like Cursor, Claude Code, and Codex The [Aptos MCP server](https://github.com/aptos-labs/aptos-npm-mcp) (`npx @aptos-labs/aptos-mcp`) provides tools, prompts, and resources to help developers build applications on the Aptos blockchain through [Geomi](https://geomi.dev). It is designed to be used with AI tools like Cursor, Claude Code, Codex, and others that support the [Model Context Protocol](https://modelcontextprotocol.io/). The published npm package is pinned on the [MCP Server Card](/.well-known/mcp/server-card.json). Do not use the `latest` tag in production configs; run `npx -y @aptos-labs/aptos-mcp` so npm resolves the current release, or pin the version from that card. ## Getting Started [](#getting-started) ### Prerequisites [](#prerequisites) * [Node.js and npm](https://nodejs.org/en) (Node.js 22.12 or later; npm 10 ships with Node.js 22) * A Geomi Bot Key ### Generate a Geomi Bot Key [](#generate-a-geomi-bot-key) To make Geomi actions such as managing API keys, follow these steps to create a Bot Key for the MCP server. * Go to [https://geomi.dev/](https://geomi.dev/) * Click on your name in the bottom left corner * Click on **Bot Keys** * Click on the **Create Bot Key** button * Copy the Bot Key and paste it into the MCP configuration as `APTOS_BOT_KEY=` Never commit the Bot Key to git. Prefer interpolating an environment variable (for example Cursor’s `${env:APTOS_BOT_KEY}`) over hard-coding the secret in a shared config file. ### Supported Interfaces [](#supported-interfaces) We’ve provided guides for Claude Code, Cursor, and OpenAI Codex. Other MCP clients — including GitHub Copilot — can reuse the same stdio command and `APTOS_BOT_KEY` environment variable. [Claude Code](/build/ai/aptos-mcp/claude) Set up for Claude Code [Cursor](/build/ai/aptos-mcp/cursor) Set up for Cursor [OpenAI Codex](/build/ai/aptos-mcp/codex) Set up for Codex # Aptos Agent Skills > Pre-built AI skills for Claude Code, Cursor, and GitHub Copilot to write Move smart contracts, use the Aptos TypeScript SDK, and build full Aptos dApps. [Aptos Agent Skills](https://github.com/aptos-labs/aptos-agent-skills) is a collection of pre-built AI skills that give coding assistants like Claude Code, Cursor, and GitHub Copilot deep expertise in Aptos development. The skills cover Move smart contracts, the TypeScript SDK, and full-stack dApp scaffolding. [Aptos Agent Skills on GitHub](https://github.com/aptos-labs/aptos-agent-skills) Browse the source code, skill definitions, and contribution guidelines ## Installation [](#installation) ### Using the Skills CLI (recommended) [](#using-the-skills-cli-recommended) ``` npx skills add aptos-labs/aptos-agent-skills ``` This installs the skills so your AI coding assistant can use them automatically. Target a specific agent with `-a`: ``` npx skills add aptos-labs/aptos-agent-skills -a claude-codenpx skills add aptos-labs/aptos-agent-skills -a cursornpx skills add aptos-labs/aptos-agent-skills -a copilot ``` See the upstream [INSTALL.md](https://github.com/aptos-labs/aptos-agent-skills/blob/main/INSTALL.md) for selective skill installs. ### Claude Code plugin [](#claude-code-plugin) Inside a Claude Code session, add the repository as a plugin marketplace: ``` /plugin marketplace add aptos-labs/aptos-agent-skills ``` ### Manual installation [](#manual-installation) Clone the repository and copy the skills into your agent’s skills directory: ``` git clone https://github.com/aptos-labs/aptos-agent-skills.gitcp -r aptos-agent-skills/skills/* ~/.claude/skills/cp -r aptos-agent-skills/patterns/* ~/.claude/patterns/ ``` Include `CLAUDE.md` from the cloned repository in your workspace context so the assistant can route to the right skill. ## Available Skills [](#available-skills) ### Move Skills [](#move-skills) These skills help AI assistants write, test, audit, and deploy Move smart contracts:
SkillDescription
write-contractsGenerate secure Aptos Move V2 smart contracts
generate-testsGenerate Move unit tests targeting 100% code coverage
security-auditSecurity audit for Move smart contracts before deployment
deploy-contractsDeploy Move modules to Aptos devnet, testnet, or mainnet
search-aptos-examplesSearch aptos-core for reference implementations and patterns
analyze-gas-optimizationAnalyze and reduce gas costs in Move smart contracts
modernize-moveMigrate Move V1 resource accounts to the V2 object model
### TypeScript SDK Skills [](#typescript-sdk-skills) These skills help AI assistants use the Aptos TypeScript SDK correctly:
SkillDescription
use-ts-sdkAptos TypeScript SDK orchestrator for frontend integration
ts-sdk-clientSet up the Aptos client with AptosConfig and network selection
ts-sdk-accountCreate Aptos accounts and signers from private keys or derivation paths
ts-sdk-addressParse and derive Aptos account addresses (AIP-40)
ts-sdk-transactionsBuild, sign, and submit transactions, including sponsored and multi-agent
ts-sdk-view-and-queryCall Move view functions and query on-chain Aptos data
ts-sdk-typesMap Move types to TypeScript (u64, u128, address, vector)
ts-sdk-wallet-adapterIntegrate Aptos wallets into React apps with useWallet
### Project Skills [](#project-skills)
SkillDescription
create-aptos-projectScaffold a new Aptos dApp with create-aptos-dapp
## Recommended Workflow [](#recommended-workflow) For a typical Aptos dApp, use the skills in this order: 1. **Scaffold** — Use `create-aptos-project` to set up the project structure 2. **Write** — Use `write-contracts` to create your Move smart contracts 3. **Test** — Use `generate-tests` to create comprehensive test coverage 4. **Audit** — Use `security-audit` to check for vulnerabilities 5. **Deploy** — Use `deploy-contracts` to publish to devnet or testnet 6. **Frontend** — Use `use-ts-sdk` and the other TypeScript SDK skills to build the UI ## Community Skills [](#community-skills) The repository includes a `community-skills/` directory. Community skills are independently maintained and have not been reviewed by Aptos Labs.
SkillAuthorDescription
smoothsend-gaslessivedmohanSponsor gas fees for Aptos transactions with SmoothSend
To add your own: 1. Create a new skill following the existing format under `community-skills/` 2. Submit a pull request to the [aptos-agent-skills repository](https://github.com/aptos-labs/aptos-agent-skills) See [CONTRIBUTING.md](https://github.com/aptos-labs/aptos-agent-skills/blob/main/CONTRIBUTING.md) for details. # LLMs.txt > How to get tools like Cursor, GitHub Copilot, ChatGPT, Claude, Codex, and Devin to understand Aptos documentation. ## What is LLMs.txt? [](#what-is-llmstxt) We support [LLMs.txt](https://llmstxt.org/) files for making the Aptos documentation available to large language models (LLMs). This feature helps AI tools better understand the Aptos blockchain, its Move language, SDKs, and development patterns. ## Available Routes [](#available-routes) We provide the following LLMs.txt routes to help AI tools access our documentation: * [llms.txt](/llms.txt) - A compact routing file that points AI tools to the most useful Aptos docs and machine-readable exports * [llms-small.txt](/llms-small.txt) - A curated low-token subset of the most useful Aptos documentation for IDE assistants and smaller context windows * [llms-full.txt](/llms-full.txt) - The full rendered Aptos documentation corpus for large-context ingestion **Well-known URL:** Some tools look for [`https://aptos.dev/.well-known/llms.txt`](https://aptos.dev/.well-known/llms.txt). That URL permanently redirects to [`/llms.txt`](/llms.txt) (same content). The [`llms.txt`](/llms.txt) index also lists **structured API assets** that are not prose docs—for example the [Aptos Fullnode OpenAPI spec](/aptos-spec.json) (JSON) and the [REST API reference](/rest-api) (HTML) generated from that spec. It also surfaces **agent tooling** (Aptos MCP, Agent Skills, Explorer, GitHub org) and key **Markdown** deep links (AI hub, standards, Indexer GraphQL reference) so models can fetch the right surface without guessing URLs. Discovery endpoints, the MCP Server Card, and WebMCP tools are documented on the [AI tools overview](/build/ai). ## Per-Page Markdown Access [](#per-page-markdown-access) Every documentation page is also available as rendered Markdown by appending `.md` to the URL:
Page URLMarkdown URL
https://aptos.dev/build/guides/first-transactionhttps://aptos.dev/build/guides/first-transaction.md
https://aptos.dev/build/sdks/ts-sdkhttps://aptos.dev/build/sdks/ts-sdk.md
https://aptos.dev/zh/build/guides/first-transactionhttps://aptos.dev/zh/build/guides/first-transaction.md
You can also send `Accept: text/markdown` to the HTML URL. This is useful for AI tools that need to fetch individual pages with minimal tokens, rather than ingesting the full documentation. The [llms.txt](/llms.txt) file acts as a compact router, while [llms-small.txt](/llms-small.txt) and [llms-full.txt](/llms-full.txt) provide curated and comprehensive corpus exports. ## Usage with AI Tools [](#usage-with-ai-tools) ### Claude Code [](#claude-code) Add Aptos documentation context to [Claude Code](https://code.claude.com/docs/en/overview) projects: 1. Add `https://aptos.dev/llms.txt` to your project’s `CLAUDE.md` or `AGENTS.md` file as a reference 2. Claude Code will read the index and fetch relevant pages via `.md` URLs as needed 3. For on-chain tools, see [Aptos MCP for Claude Code](/build/ai/aptos-mcp/claude) ### Cursor [](#cursor) Cursor’s `@Docs` index was removed. Point Agent at the feeds instead: 1. Add `https://aptos.dev/llms.txt` to the project `AGENTS.md` (or a [project rule](https://cursor.com/docs/rules)) 2. Paste a feed URL in chat when you need a one-off fetch — Agent can retrieve it directly 3. For on-chain tools, see [Aptos MCP for Cursor](/build/ai/aptos-mcp/cursor) ### GitHub Copilot [](#github-copilot) In [Copilot Chat](https://code.visualstudio.com/docs/chat/copilot-chat-context), fetch a feed for the current session: ``` #fetch https://aptos.dev/llms.txt ``` For standing project context, add the URLs to [`.github/copilot-instructions.md`](https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions): ``` https://aptos.dev/llms.txthttps://aptos.dev/llms-small.txthttps://aptos.dev/llms-full.txt ``` ### OpenAI Codex [](#openai-codex) Add `https://aptos.dev/llms.txt` to `AGENTS.md`, then start Codex. For on-chain tools, see [Aptos MCP for Codex](/build/ai/aptos-mcp/codex). ### Devin Desktop (formerly Windsurf) [](#devin-desktop-formerly-windsurf) Devin Desktop reads `AGENTS.md` and `.devin/rules/` (legacy `.windsurfrules` still works). Put `https://aptos.dev/llms.txt` in the project `AGENTS.md`. [Read more about AGENTS.md in Devin Desktop](https://docs.devin.ai/desktop/cascade/agents-md) ### Claude.ai [](#claudeai) Add Aptos documentation as project knowledge in [Claude Projects](https://claude.ai): 1. Open [Claude.ai](https://claude.ai) and create or open a Project 2. Add project knowledge / content 3. Paste `https://aptos.dev/llms-full.txt` as a URL source 4. Claude will now have Aptos documentation context in conversations within that Project ### ChatGPT [](#chatgpt) Reference the Aptos docs directly in ChatGPT conversations: * Paste `https://aptos.dev/llms-full.txt` into your message and ask ChatGPT to read it before answering Aptos questions * For custom GPTs: add `https://aptos.dev/llms.txt` as a knowledge source ### Other AI Tools [](#other-ai-tools) Any AI tool that supports LLMs.txt can use these routes to better understand Aptos. Simply point your tool to any of the routes above. # Aptos Network Nodes > Learn about validator nodes, validator fullnodes, and public fullnodes that power the Aptos network The Aptos network consists of three node types: validator nodes, validator fullnodes (VFNs), and public fullnodes (PFNs). To participate in consensus, you are required to run a validator node and stake the minimum amount of utility coins. VFNs and PFNs are not required to participate in consensus, but they are necessary to distribute blockchain data and enable ecosystem services, e.g., indexing, querying, and RESTful API services (see [Aptos APIs](/build/apis)). VFNs can only be run by validator operators, while PFNs can be run by anyone. You can learn more about the different types of nodes in the [Blockchain Deep Dive](/network/blockchain) section. This section provides detailed, step-by-step instructions on how to deploy and operate Aptos nodes in different environments. It also describes everything you need to stake and participate in consensus and governance. ## Quick Links [](#quick-links) ### Validation on Aptos [](#validation-on-aptos) Everything you need to know about how validation, staking and governance works on Aptos. [How validation works](/network/blockchain/staking#validation-on-the-aptos-blockchain) Validator-leader proposes and earns rewards on success. [Validator states](/network/blockchain/staking#validator-state-and-stake-state) Learn how a validator gets into a validator set. ### Staking [](#staking) [Staking on Aptos](/network/blockchain/staking) A comprehensive guide to how staking works on Aptos. [Governance](/network/blockchain/governance) Who can propose, who can vote, and how an AIP is resolved. [Owner](/network/nodes/validator-node/connect-nodes/staking-pool-operations) Describes the owner operations performed for staking. [Voter](/network/nodes/validator-node/connect-nodes/staking-pool-voter) Describes the voter operations performed for staking. ### Validators and VFNs [](#validators-and-vfns) A comprehensive guide to deploying nodes, staking operations and participate in consensus. [Node requirements](/network/nodes/validator-node/node-requirements) Details the compute and storage resources you need. Read this first before anything. [Running validator node](/network/nodes/validator-node/deploy-nodes) In the cloud or on-premises, Docker or source, you will read step-by-step instructions here. [Node health](/network/nodes/validator-node/verify-nodes/node-liveness-criteria) You can verify your node health using several options. [Connecting to Aptos network](/network/nodes/validator-node/connect-nodes/connect-to-aptos-network) Steps to connect your nodes to an Aptos network. [Staking pool operations](/network/nodes/validator-node/connect-nodes/staking-pool-operations) Step-by-step guide for how to perform staking pool operations. [Shutting down nodes](/network/nodes/validator-node/modify-nodes/shutting-down-nodes) Leave the validator set first, and then shut down your node. ### Public Fullnodes (PFNs) [](#public-fullnodes-pfns) A section with detailed, step-by-step instructions on everything related to Aptos PFNs. [Deploy a PFN](/network/nodes/full-node/deployments) Follow this section to deploy a PFN. [Indexer PFN](/build/indexer/legacy/indexer-fullnode) Describes how to run an indexer PFN on the Aptos network. ### Common Operations [](#common-operations) [Develop with localnet](/network/nodes/localnet/local-development-network) Run a localnet for development (including validator nodes). [Upgrade your PFN](/network/nodes/full-node/modify/update-fullnode-with-new-releases) Upgrade your node with new releases. [Bootstrap from a snapshot](/network/nodes/bootstrap-fullnode/bootstrap-fullnode) Use a snapshot to bootstrap a new node. [Bootstrap from a backup](/network/nodes/bootstrap-fullnode/aptos-db-restore) Use data restore to bootstrap a new node. # Run a Public Fullnode > Deploy and operate your own public fullnode (PFN) to synchronize with the Aptos blockchain and stay up-to-date with the latest state. You can run your own public fullnode (PFN) to synchronize the state of the Aptos blockchain and stay up-to-date. PFNs replicate the entire state of the blockchain by syncing from other Aptos VFNs and PFNs. PFNs can be run by anyone. This section explains how to deploy a PFN and connect to an Aptos network. You can learn more about the different types of nodes in the [Blockchain Deep Dive](/network/blockchain) section. # Run a Validator and VFN > Learn how to participate in the Aptos consensus protocol by deploying and running a validator node and validator fullnode (VFN) with step-by-step guidance. To participate in the Aptos consensus protocol, you must deploy and run a validator node and (optionally) a validator fullnode (VFN). This document provides a high-level overview of the important steps required for deploying both node types. Before initializing a staking pool or delegation pool, read about [Staking](/network/blockchain/staking) and [Delegated Staking](/network/blockchain/delegated-staking) to learn the differences between the stake pool types. Note that once a stake pool has been created, it cannot be changed to a delegation pool or vice versa. Use the documents within this section to run an Aptos validator and a VFN. At a high-level, the process is as follows: 1. Understand the requirements and deployment types. Read the node requirements and select a deployment method (e.g., on-premises or cloud services). Start by reading the node requirements to get to know the compute, memory, networking and storage resources you need. Also, select a method to deploy your nodes, i.e., use cloud managed Kubernetes, Docker, or source code. 2. Generate identities for your nodes. Create your public/private keypairs and account addresses for the validator and VFN. Remember to keep your private keys confidential! 3. Configure your validator and VFN. Configure your nodes to use the generated keys and identities. Using YAML files, configure your nodes with the keys and identities generated in the previous step. This is required to allow your nodes to connect to other nodes (i.e., peers) securely. 4. Download genesis and a waypoint for your nodes. Bootstrap the nodes with a genesis and waypoint, and prepare them for startup. With the nodes configured correctly, install the binaries and download the genesis blob and waypoint files. These will give your nodes the information they need to start syncing with other peers. 5. Join the validator set and start participating. Initialize the staking pool, join the validator set and start validating to earn rewards. Before other peers will accept connections from your nodes, you will need to join the validator set. To do this, you must initialize a staking pool and delegate to operators and voters. Once your staking pool has been set up, you can join the validator set. At this point your nodes will begin to sync with the network and your validator will be able to start participating in consensus. This is when you can start earning rewards. # Latest Aptos Releases > Find the latest Aptos releases for mainnet, testnet, and devnet with their corresponding GitHub branches Each Aptos release can be found on the GitHub site for [Aptos-core releases](https://github.com/aptos-labs/aptos-core/releases). Each release is mirrored by the following git branches: * [Latest Mainnet Release](https://github.com/aptos-labs/aptos-core/tree/mainnet) * [Latest Testnet Release](https://github.com/aptos-labs/aptos-core/tree/testnet) * [Latest Devnet Release](https://github.com/aptos-labs/aptos-core/tree/devnet) Aptos typically conducts multiple devnet releases for each testnet and mainnet release. Hence, devnet releases use commit hashes for tracking rather than version numbers. Testnet and mainnet releases usually have a one-to-one correlation, meaning each testnet release rolls into mainnet. Hot fixes are exceptions that may occur in mainnet to address urgent issues in production. See the [Aptos Release Process](https://github.com/aptos-labs/aptos-core/blob/main/RELEASE.md) for more details. ## Update nodes [](#update-nodes) If you are a node operator, [update your nodes with the new release](/network/nodes/full-node/modify/update-fullnode-with-new-releases). ## Subscribe to Release Announcements [](#subscribe-to-release-announcements) ### Subscribe via GitHub [](#subscribe-via-github) 1. Go to the [aptos-labs/aptos-core](https://github.com/aptos-labs/aptos-core) repository. 2. Open the **Watch** menu and select **Custom**. 3. Select the **Releases** checkbox and click **Apply**. ### Subscribe via [Aptos Discord](https://discord.gg/aptosnetwork) [](#subscribe-via-aptos-discord) Join the Aptos Discord server to interact with us and our community. We also post upcoming releases in these channels. * [#mainnet-release](https://discord.com/channels/945856774056083548/1042502400507916349) * [#testnet-release](https://discord.com/channels/945856774056083548/1025614160555413545) * [#devnet-release](https://discord.com/channels/945856774056083548/956692649430093904) ### Subscribe via [Aptos Twitter](https://x.com/AptosRelease) [](#subscribe-via-aptos-twitter) Follow [@AptosRelease](https://x.com/AptosRelease) on Twitter to get the latest updates about our upcoming mainnet releases and be notified when it is time to update your node. Every couple of days, [@AptosRelease](https://x.com/AptosRelease) will tweet a countdown to remind you to update to the latest version. _Note: We do not post about hotfixes here!_ ## Aptos Release Process [](#aptos-release-process) To understand how we conduct releases, review the [Aptos Release Process](https://github.com/aptos-labs/aptos-core/blob/main/RELEASE.md). # Aptos Glossary > Comprehensive glossary of terms and concepts used throughout the Aptos ecosystem and documentation ## A [](#a) ### Accumulator Root Hash [](#accumulator-root-hash) * An **accumulator root hash** is the root hash of a [Merkle accumulator](https://eprint.iacr.org/2009/625.pdf). ### Account [](#account) * An **account** in the Aptos blockchain is a container for an arbitrary number of [Move modules](#move-module) and [Move resources](#move-resources). * The state of each account is composed of both code and data. * The account is identified by [account address](#account-address). * After [AIP-115](/build/aips/aip-115), an address does not need an on-chain `0x1::account::Account` resource to be a valid account. REST `GET /accounts/{address}` returns default values instead of 404 when that resource is missing. See [Accounts](/network/blockchain/accounts) for more information. ### Account Address [](#account-address) * An **account address** is the address of an Aptos account. * Account address refers to a specific destination on the Aptos network. The address dictates the destination and source of a specific amount of assets exchanged by two parties on the blockchain. * Aptos addresses are 64-character hex string (32 bytes). Often times these strings are prefixed with `0x` and for first 16 addresses, the leading 0s are excluded (ex. `0x1`) See [Accounts](/network/blockchain/accounts) for more information. ### Agent Skills [](#agent-skills) * **Agent Skills** are installable instruction packs that give coding assistants Aptos-specific knowledge for Move contracts, the TypeScript SDK, and dApp scaffolding. * Install them with `npx skills add aptos-labs/aptos-agent-skills`. See [Aptos Agent Skills](/build/ai/aptos-agent-skills) for more information. ### API [](#api) * An **Application Programming Interface (API)** is a set of protocols and tools that allow users to interact with Aptos blockchain nodes and client networks via external applications. Aptos nodes expose a REST API; Aptos Labs also hosts an Indexer GraphQL API and a Transaction Stream gRPC API. * See [Aptos APIs](/build/apis) for more details. ### APT [](#apt) **Aptos token (APT)** is the Aptos blockchain native token used for paying network and transaction fees. ### Aptos [](#aptos) **Aptos** is a Layer 1 blockchain for everyone. It uses the Move programming language and launched its mainnet on 2022-10-17 to redefine the web3 user experience. The Aptos blockchain is dedicated to creating better user experiences through increased speed, security, scalability, reliability and usability with low transaction costs. The word “Aptos” means “The People” in the Ohlone language. Learn more about the Aptos blockchain on the [official Aptos website](https://aptosnetwork.com). ### AptosBFT [](#aptosbft) * **AptosBFT** is the Aptos protocol’s BFT consensus algorithm. * AptosBFT is based on Jolteon. ### Aptos Blockchain [](#aptos-blockchain) * The **Aptos blockchain** is a ledger of immutable transactions agreed upon by the validators on the Aptos network (the network of validators). ### Aptos Name Service (ANS) [](#aptos-name-service-ans) * The **Aptos Name Service (ANS)** is a decentralized naming address service for the Aptos blockchain. An Aptos name is a human-readable _.apt_ domain name that is used in place of a public key, for example _love.apt_. * This service also allows users to register subdomain names in addition to the registered domain. Find out more at: [Aptosnames.com](https://www.aptosnames.com/) ### Aptos Core [](#aptos-core) **Aptos-core** is the [open-source repository](https://github.com/aptos-labs/aptos-core/) containing the code for Aptos Network software. Aptos-core contains software for * the Aptos blockchain itself, which generates and stores the immutable ledger of confirmed transactions and * the validation process, which implements the consensus algorithm to validate transactions and add them to the Aptos blockchain immutable ledger. ### Aptos Ecosystem [](#aptos-ecosystem) * **Aptos ecosystem** refers to various components of the Aptos blockchain network and their interactions. The Aptos ecosystem includes the community, [community-driven projects](https://aptosnetwork.com/ecosystem/directory), and [events](https://aptosnetwork.com/events). ### Aptos Explorer [](#aptos-explorer) * The **[Aptos Explorer](https://explorer.aptoslabs.com/)** is an interface that helps users examine details of the Aptos blockchain, including account information, validators, and transactions. * The Aptos Explorer help users validate their work in Aptos wallets and other tools in the blockchain. ### Aptos Framework [](#aptos-framework) The **Aptos Framework** defines the public API for blockchain updates and the structure of on-chain data. It defines the business logic and access control for the three key pillars of Aptos functionality: payments, treasury, and on-chain governance. It is implemented as a set of modules written in the Move programming language and stored on-chain as Move bytecode. ### Aptos Node [](#aptos-node) An **Aptos node** is a peer entity of the Aptos network that tracks the state of the Aptos blockchain. There are two types of Aptos nodes, [validators](#validator) and [fullnodes](#fullnodes). ### Aptos Protocol [](#aptos-protocol) * **Aptos protocol** is the specification of how transactions are submitted, ordered, executed, and recorded within the Aptos network. ### AptosAccount [](#aptosaccount) * **`AptosAccount`** is a historical name from early Aptos/Diem Move APIs for account administrative state (sequence number and authentication key). * The on-chain resource is `0x1::account::Account`. After [AIP-115](/build/aips/aip-115), that resource is created only when needed; it is not present on every account. * Account balances live in CoinStore or Fungible Store resources, not in `Account`. ### AptosAccount module [](#aptosaccount-module) * **The AptosAccount module** is a historical name for the Move module that manages `0x1::account::Account`. Use `0x1::account` in current code and docs. ### Aptos Devnet [](#aptos-devnet) * See [devnet](#devnet). ## B [](#b) ### Blocks [](#blocks) * On Aptos, blocks are a batch of [transactions](#transaction) committed at the same time. Each block starts with a `BlockMetadata` transaction and, except for the last block of an [epoch](#epoch), ends with a [block epilogue](#block-epilogue). * Block number is analogous to “block height” in blockchain literature. * Transactions are referenced by ledger version rather than by block. Ledger state is versioned per transaction, not per block. See [Blocks](/network/blockchain/blocks) for more information. ### Block Epilogue [](#block-epilogue) * A **block epilogue** is a system transaction (`block_epilogue_transaction`) that ends a block and carries `BlockEndInfo` (gas and output limits for that block). It replaced the earlier `StateCheckpoint` transaction type. * The last block of an epoch has no block epilogue. See [AIP-88](/build/aips/aip-88) for more information. ### BlockSTM [](#blockstm) * **BlockSTM** is the state-of-the-art dynamic parallelism execution engine developed by the Aptos Labs team. * Dynamic parallelism allows developers to flexibly write applications without facing design constraints of statically declaring write sets of transactions. * It has been adopted across the industry by multiple blockchains. * More details can be found in [the blog post](https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba) and [presentation at a16z crypto](https://www.youtube.com/watch?v=2SE5tqPzhyw) ### Byzantine (Validator) [](#byzantine-validator) * A **validator** that does not follow the specification of the consensus protocol, and wishes to compromise the correct execution of the protocol. * BFT algorithms traditionally support up to one-third of the algorithm’s voting power being held by Byzantine validators. ### Byzantine Fault Tolerance (BFT) [](#byzantine-fault-tolerance-bft) * **Byzantine Fault Tolerance** (BFT) is the ability of a distributed system to provide safety and liveness guarantees in the presence of faulty, or “[Byzantine](https://en.wikipedia.org/wiki/Byzantine_fault),” validators below a certain threshold. * The Aptos blockchain uses AptosBFT, a consensus protocol based on [Jolteon](#jolteon). * BFT algorithms typically operate with a number of entities, collectively holding NNN votes (which are called “validators” in the Aptos network’s application of the system). * NNN is chosen to withstand some number of validators holding fff votes, which might be malicious. * In this configuration, NNN is typically set to 3f+13f + 13f+1. Validators holding up to fff votes will be allowed to be faulty — offline, malicious, slow, etc. As long as 2f+12f + 12f+1 votes are held by [honest](#honest-validator) validators, they will be able to reach consensus on consistent decisions. * This implies that BFT consensus protocols can function correctly, even if up to one-third of the voting power is held by validators that are compromised or fail. ## C [](#c) ### CLI [](#cli) * **Command line interface** refers to the Aptos CLI used for developing on the Aptos blockchain, operating nodes, and debugging issues. Find out more at [the Aptos CLI page](/build/cli). ### Client [](#client) * **Client** is software that receives information from the blockchain and manages transactions. Clients interact with the blockchain through the Aptos nodes. ### Code Labs [](#code-labs) * **Code labs and tutorials** depict various workflows - such as the use of the Aptos CLI in minting non-fungible tokens (NFTs) - in order for users to understand how the process works and employ related functions in their code. If users have the necessary funds in their accounts, they can follow the same code lab and tutorial steps used in devnet, testnet and mainnet networks. ### Confidential Asset [](#confidential-asset) * A **confidential asset (CA)** wraps a [fungible asset](#fungible-asset) so transfer amounts and confidential balances stay hidden, including from validators, using zero-knowledge proofs. Sender and recipient addresses remain visible. * Incoming funds accumulate in a pending confidential balance and must be rolled over before they are spendable. See [Confidential Asset](/build/smart-contracts/confidential-asset) and the [TypeScript SDK client](/build/sdks/ts-sdk/confidential-asset). For how CA fits among payment flows, see [Payments](/build/guides/payments#confidential-transfers). ### Consensus [](#consensus) * **Consensus** is a component of a validator. * The consensus component is responsible for coordination and agreement amongst all validators on the block of transactions to be executed, their order, and the execution results. * The Aptos blockchain is formed with these agreed-upon transactions and their corresponding execution results. * The consensus component is accountable for achieving security, trust, and agreement among all validators on the Aptos blockchain. ### Consensus Protocol [](#consensus-protocol) * A **consensus protocol** is collectively executed by n validators to accept or reject a transaction and to agree on the ordering of transactions and execution results. * See [BFT](#byzantine-fault-tolerance-bft). ## D [](#d) ### Dapps [](#dapps) * **Decentralized applications (dapps)** are programs or digital applications that run on the Aptos blockchain autonomously. Smart contracts are commonly used to achieve this function. ### Devnet [](#devnet) * The **Aptos devnet** is a publicly deployed instance of the Aptos network that runs using a set of validator test nodes. * The devnet is a demonstration of the Aptos network that is built for experimenting with new ideas * The devnet simulates a digital payment system and the coins on the devnet have _no real world value_. * The devnet is the network by which developers are given the opportunity to test given protocols. It is similar to testnet as it operates independently of the mainnet yet is reset weekly. ## E [](#e) ### Ed25519 [](#ed25519) * **Ed25519** is our supported digital signature scheme. * More specifically, the Aptos network uses the PureEdDSA scheme over the Ed25519 curve, as defined in RFC 8032. ### Encrypted Mempool [](#encrypted-mempool) * **Encrypted mempool** is the protocol feature (AIP-144) in which a transaction’s **Move executable payload** is encrypted while the transaction is **pending** (for example in mempool and during dissemination), then decrypted by validators for execution right after the block is confirmed. * Also known as **encrypted pending transactions** in consumer-facing material. * The submitting client uses the fullnode’s current **ledger `encryption_key`** (per-epoch batch threshold encryption on BLS12-381). Gas limits, signatures, sender metadata, and sometimes a **claimed entry function** may still be visible depending on payload type—this is **payload confidentiality**, not full transaction anonymity. * Encrypted submissions pay a minimum gas-unit price of **200 Octas/gas-unit** (twice the base minimum) and a flat **375 gas-unit** decryption charge per transaction to cover validator decryption cost. **Keyless**, **federated keyless**, and **account abstraction** signers are not supported. * Example: an app builds `aptos.transaction.build.simple` with `options.encrypted` and `options.senderAuthenticationKey` on the TypeScript SDK so a transfer’s arguments are not sent as plaintext before commit. See [Encrypted Pending Transactions](/build/guides/encrypted-pending-transactions) for more information. ### Encrypted Pending Transactions [](#encrypted-pending-transactions) * **Encrypted pending transactions** is the consumer-facing name for the protocol feature defined in AIP-144. See [Encrypted Mempool](#encrypted-mempool) for the full definition, and the [Encrypted Pending Transactions](/build/guides/encrypted-pending-transactions) guide for the product-level overview. ### Epoch [](#epoch) * An **epoch** is the period of time between reconfigurations of the validator set and other administrative actions by the blockchain. On Aptos mainnet currently, it is every 2 hours. ### Event [](#event) * An **event** is the user-facing representation of the effects of executing a transaction. * Modules emit **module events** (type-keyed streams marked `#[event]`). Older **EventHandle** streams still exist on some resources but are deprecated. * For example, a coin transfer can emit withdraw and deposit events so the recipient can confirm that a payment arrived. * Events are persisted on the blockchain and are queried by [clients](#client) through the REST API or the [Indexer](/build/indexer/indexer-api). See [Events](/network/blockchain/events) for more information. ### Execution [](#execution) * **Execution** in the Aptos blockchain is an Aptos node component that manages the block of transactions. The execution component stores successful transactions. ### Expiration Time [](#expiration-time) A transaction ceases to be valid after its **expiration time**. If it is assumed that: * TimeCTime\_CTimeC​ is the current time that is agreed upon between validators (TimeCTime\_CTimeC​ is not the local time of the client); * TimeETime\_ETimeE​ is the expiration time of a transaction TNT\_NTN​; and * TimeC\>TimeETime\_C > Time\_ETimeC​\>TimeE​ and transaction TNT\_NTN​ has not been included in the blockchain, then there is a guarantee that TNT\_NTN​ will never be included in the blockchain. ## F [](#f) ### Faucet [](#faucet) * The **faucet** is a service that mints APT on Devnet (programmatically) and Testnet (Google sign-in / the [mint page](/network/faucet)). * APT on devnet and testnet has no real world value, it is only for development purposes. * To use a faucet, see [Faucet API](/build/apis/faucet-api). ### Finality [](#finality) * **Finality** is the point after which a committed transaction cannot be reversed. Aptos uses [BFT](#byzantine-fault-tolerance-bft) consensus, so a transaction is final as soon as it commits. Clients do not wait for extra block confirmations. See [Payments](/build/guides/payments) for how finality relates to block time and end-to-end latency, and the [exchange FAQ](/build/guides/exchanges#what-is-the-finality-of-a-transaction). ### Fullnodes [](#fullnodes) * **Fullnodes** are clients that ensure data are stored up-to-date on the network. They replicate blockchain state and transactions from other fullnodes and validator nodes. ### Fungible Asset [](#fungible-asset) * A **fungible asset** is an asset, such as a currency, share, in-game resource, etc., that is interchangeable with another identical asset without any loss in its value. For example, APT is a fungible asset because you can exchange one APT for another. * Follow the [Asset Standards](/build/smart-contracts/aptos-standards#asset-standards) to create fungible assets on the Aptos blockchain. * Next generation of the Coin standard that addresses shortcomings of `aptos_framework::coin` such as lack of guaranteed enforcement of freeze and burn and advanced functionalities such as programmable transfers, e.g., approve in ERC-20. ### Fungible Token [](#fungible-token) * For the legacy Aptos Token Standard (aptos\_token::token), a **fungible token** is a token that is interchangeable with other identical tokens (i.e., tokens that share the same `TokenId`). This means the tokens have the same `creator address`, `collection name`, `token name`, and `property version`. * For the Aptos Digital Asset Standard (aptos\_token\_objects::token), a \* _fungible token_\* is a fungible asset with metadata object that includes a Digital Asset resource. ### Fungible Unit [](#fungible-unit) * A **fungible unit** is an individual unit of a fungible asset. These units are identical and interchangeable without any loss in value. For example, each [Octa](#octa) (the smallest unit of APT) is a fungible unit. ## G [](#g) ### Gas [](#gas) * **Gas** is a way to pay for computation and storage on a blockchain network. All transactions on the Aptos network cost a certain amount of gas. * The gas required for a transaction depends on the size of the transaction, the computational cost of executing the transaction, and the amount of additional global state created by the transaction (e.g., if new accounts are created). * The purpose of gas is regulating demand for the limited computational and storage resources of the validators, including preventing denial of service ( DoS) attacks. See [Gas and Storage Fees](/network/blockchain/gas-txn-fee) for more information. ### Gas Unit Price [](#gas-unit-price) * Each transaction specifies the **gas unit price** the sender is willing to pay per unit of gas. * The price of gas required for a transaction depends on the current demand for usage of the network. * Gas price is expressed in [Octas](#octa). See [Gas and Storage Fees](/network/blockchain/gas-txn-fee) for more information. ### Geomi [](#geomi) * **[Geomi](https://geomi.dev/)** (formerly Aptos Build) is the Aptos Labs developer portal for API keys, hosted indexer access, Gas Station, and no-code indexing. See [Data Providers](/build/apis/data-providers) for more information. ## H [](#h) ### Honest (Validator) [](#honest-validator) * **Honesty** means a validator that faithfully executes the consensus protocol and is not Byzantine. ## I [](#i) ### Indexer [](#indexer) * **[Indexer](/build/indexer)** is the component of Aptos that retrieves, processes, and efficiently stores raw data in the database to provide speedy access to the Aptos blockchain state. * At a high level, indexer gets data from a gRPC stream and runs processors to transform raw blockchain data and serve transformed data via GraphQL endpoint. ## J [](#j) ### Jolteon [](#jolteon) * **Jolteon** is a recent proposal for a [BFT](#byzantine-fault-tolerance-bft) consensus protocol. * AptosBFT, the Aptos network’s consensus algorithm, is based on Jolteon. * It simplifies the reasoning about safety, and it addresses some performance limitations of previous consensus protocols. In particular, it reduces latency by 33% compared to HotStuff. ## L [](#l) ### Leader [](#leader) * A **leader** is a validator that proposes a block of transactions for the consensus protocol. * In leader-based protocols, nodes must agree on a leader to make progress. * Leaders are selected by a function that takes the current [round number](#round-number) as input. ### LLMs.txt [](#llmstxt) * **LLMs.txt** is a machine-readable documentation index that points AI tools at Aptos docs, per-page Markdown exports, and related API assets. * Aptos publishes `/llms.txt` (index), `/llms-small.txt` (condensed corpus), and `/llms-full.txt` (full corpus). See [LLMs.txt](/llms-txt) for more information. ## M [](#m) ### Mainnet [](#mainnet) * **Mainnet** refers to a working, fully-operational blockchain. A mainnet network has been fully deployed and performs the functionality of transferring digital currency from a sender to a recipient. ### Maximum Gas Amount [](#maximum-gas-amount) * The **Maximum Gas Amount** of a transaction is the maximum gas amount in gas units that the sender is ready to pay for the transaction. * The transaction can be successfully executed only if the gas used does not exceed the maximum gas amount. * The gas charged is equal to the gas price multiplied by units of gas required to process this transaction. * If the transaction runs out of gas while it is being executed or the account runs out of balance during execution, then the sender will be charged for gas used and the transaction will fail. See [Gas and Storage Fees](/network/blockchain/gas-txn-fee) for more information. ### Multi-Agent Transaction [](#multi-agent-transaction) * A **multi-agent transaction** is a single transaction that several accounts sign. Use it when **both parties must agree** before funds or resources move, rather than a one-sided send from payer to recipient. * The usual payment shape is a **peer-to-peer swap**: both accounts sign one entry function that moves each party’s asset, so both legs commit or neither does. * Distinct from **multisig**, which is N-of-M control of one account. See [Multi-Agent Transactions](/build/sdks/ts-sdk/building-transactions/multi-agent-transactions) and [Payments](/build/guides/payments#peer-to-peer-swap). ### Mempool [](#mempool) * **Mempool** is one of the components of the validator. It holds an in-memory buffer of transactions that have been submitted but not yet agreed upon and executed. Mempool receives transactions from other [full nodes](#fullnodes). * Transactions in the mempool of a validator are added from the [REST API Service](#rest-api-service) of fullnodes and from other Aptos nodes. * [Quorum Store](#quorum-store) then disseminates those transactions in batches within the validator set. When the current validator is the leader, consensus proposes a block that orders certified batches. The validator quorum votes on the proposal. ### Merkle Trees [](#merkle-trees) * **Merkle tree** is a type of authenticated data structure that allows for efficient verification of data integrity and updates. * The Aptos network treats the entire blockchain as a single data structure that records the history of transactions and states over time. * The [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree) implementation simplifies the work of apps accessing the blockchain. It allows apps to: * Read any data from any point in time. * Verify the integrity of the data using a unified framework. ### Merkle Accumulator [](#merkle-accumulator) * The **[Merkle Accumulator](https://www.usenix.org/legacy/event/sec09/tech/full_papers/crosby.pdf)** is an _append-only_ Merkle tree that the Aptos blockchain uses to store the ledger. * A Merkle accumulator can provide proofs that a transaction was included in the chain (“proof of inclusion”). * They are also called “history trees” in literature. ### Model Context Protocol (MCP) [](#model-context-protocol-mcp) * The **Model Context Protocol (MCP)** is an open protocol that lets AI coding tools call external tools and data sources. * Aptos publishes an MCP server (`@aptos-labs/aptos-mcp`) so assistants can query on-chain data, call Aptos APIs, and follow current Move workflows. See [Aptos MCP](/build/ai/aptos-mcp) for more information. ### Module [](#module) * A **module** in the Move programming language may either be a program or library that can create, transfer, or store assets. ### Move [](#move) * **Move** is a new programming language that implements all the transactions on the Aptos blockchain. * It has two different kinds of code — [Move scripts](#move-script) and [Move modules](#move-module). * Move is a safe and secure programming language for web3 that emphasizes access control and scarcity. It is the programming language used to build the Aptos blockchain. You can read more about it in [Move on Aptos](/network/blockchain/move). ### Move Bytecode [](#move-bytecode) * Move programs are compiled into **Move bytecode**. * Move bytecode is used to express Move scripts and Move modules. ### Move Module [](#move-module) * A **Move module** defines the rules for updating the global state of the Aptos blockchain. * In the Aptos protocol, a Move module is a **smart contract**. * Each user-submitted transaction includes a Move script. The Move script invokes procedures of one or more Move modules to update the global state of the blockchain according to the rules. ### Move Resources [](#move-resources) * **Move resources** contain data that can be accessed according to the \* _procedures_\* declared in a Move **module.** * Move resources can never be copied, reused, or lost. This protects Move programmers from accidentally or intentionally losing track of a resource. ### Move Script [](#move-script) * Each transaction submitted by a user includes a **Move script**. * These transactions, also known as Move scripts, represent the operations a client submits to a validator. * The operation could be a request to move coins from user A to user B, or it could involve interactions with published [Move modules](#move-module) (smart contracts). * The Move script is an arbitrary program that interacts with resources published in the global storage of the Aptos blockchain by calling the procedures of a module. It encodes the logic for a transaction. * A single Move script can send funds to multiple recipients and invoke procedures from several different modules. * A Move script **is not** stored in the global state and cannot be invoked by other Move scripts. It is a single-use program. To see example uses of Move scripts, follow [Move scripts](/build/smart-contracts/scripts/script-tutorial). ### Move Virtual Machine (MVM) [](#move-virtual-machine-mvm) * The **Move virtual machine** executes Move scripts written in [Move bytecode](#move-bytecode) to produce an execution result. This result is used to update the blockchain **state**. * The virtual machine is part of a [validator](#validator). * The Move virtual machine (MoveVM) processes each validator node that translates transactions along with the current blockchain ledger state to produce a changeset as input or storage delta as output. ## N [](#n) ### Node [](#node) * A **node** is a peer entity of the Aptos network that tracks the state of the Aptos blockchain. * An Aptos node consists of logical components. [Mempool](#mempool), [consensus](#consensus), and the [Move virtual machine](#move-virtual-machine-mvm) are examples of node components. ### Nonce [](#nonce) * **Nonce** is a number only used once, a random or semi-random number that is generated for a specific use for authentication protocols and cryptographic hash functions. * On Aptos, [orderless transactions](#orderless-transactions) use a `u64` nonce as the replay protector instead of a [sequence number](#sequence-number). ## O [](#o) ### Octa [](#octa) * An **Octa** is the smallest unit of [APT](#apt). 1 APT = 108 Octas. ### Open-Source Community [](#open-source-community) * **Open-source community** is a term used for a group of developers who work on open-source software. If you’re reading this glossary, then you are part of the Aptos project’s developer community. ### Orderless Transactions [](#orderless-transactions) * **Orderless transactions** (AIP-123) use a [nonce](#nonce) for replay protection instead of a [sequence number](#sequence-number). They can execute in any order, expire after at most 60 seconds, and do not require an on-chain `Account` resource. * Use sequence-number transactions when the application needs ordered execution from one sender. See [AIP-123](/build/aips/aip-123) for more information. ## P [](#p) ### Payments [](#payments) * **Payments** on Aptos are on-chain transfers of APT, stablecoins, and other [fungible assets](#fungible-asset), including [confidential](#confidential-asset) variants. Typical mainnet block times are tens of milliseconds; committed transactions are [final](#finality) immediately; user-visible end-to-end latency is typically sub-second. * Each payment type can be [sponsored](/build/guides/sponsored-transactions) (another account pays gas), [orderless](#orderless-transactions) (parallel submit with a nonce), or [multi-agent](#multi-agent-transaction) (both parties sign one transaction). See [Payments](/build/guides/payments) for latency, fees, and the APIs for each payment type. ### Proof [](#proof) * A **proof** is a way to verify the accuracy of data in the blockchain. * Every operation in the Aptos blockchain can be verified cryptographically that it is indeed correct and that data has not been omitted. * For example, if a user queries the information within a particular executed transaction, they will be provided with a cryptographic proof that the data returned to them is correct. ### Proof-of-Stake (PoS) [](#proof-of-stake-pos) **Proof-of-Stake (PoS)** is a security mechanism that serves in confirming the uniqueness and legitimacy of blockchain transactions. The PoS consensus mechanism is leveraged by the Aptos blockchain powered by a network of validators, which in turn update the system and process transactions. ## Q [](#q) ### Quorum Store [](#quorum-store) * **Quorum Store** is the component that disseminates transactions (in batches) within the validator set. * It significantly improves consensus throughput by removing the leader bottleneck. * It decouples data dissemination from metadata ordering, allowing validators to disseminate data asynchronously in parallel. * More details can be found in the [blog post](https://medium.com/aptoslabs/quorum-store-how-consensus-horizontally-scales-on-the-aptos-blockchain-988866f6d5b0) ## R [](#r) ### Randapp [](#randapp) * A [dapp](#dapps) that uses randomness for its functionality. ### Resource Account [](#resource-account) * A **resource account** is used to manage resources independent of an account managed by a user. For example, a developer may use a resource account to manage an account for module publishing, say managing a contract. * The contract itself does not require a signer post initialization. A resource account gives you the means for the module to provide a signer to other modules and sign transactions on behalf of the module. See [Resource accounts](/build/smart-contracts/resource-accounts) for instructions on use. ### REST API Service [](#rest-api-service) * The **REST API Service** component is the external interface of an Aptos node. Any incoming client request, such as submitted transactions or queries, must first go through the REST Service. A client needs to go through the REST Service component to access storage or any other component in the system. This filters requests and protects the system. * Whenever a client submits a new transaction, the REST Service passes it to [mempool](#mempool). ### Round [](#round) * A **round** consists of achieving consensus on a block of transactions and their execution results. ### Round Number [](#round-number) * A **round number** is a shared counter used to select leaders during an [epoch](#epoch) of the consensus protocol. ## S [](#s) ### SDKs [](#sdks) * Aptos **software development kits (SDKs)** are sets of tools that enable a developer to quickly create a custom app on the Aptos platform. Find out more at [Use the Aptos SDKs](/build/sdks). ### Sequence Number [](#sequence-number) * The **sequence number** for an account indicates the number of transactions that have been submitted and committed on chain from that account. It is incremented every time a transaction sent from that account is executed or aborted and stored in the blockchain. * A transaction is executed only if it matches the current sequence number for the sender account. This helps sequence multiple transactions from the same sender and prevents replay attacks. * If the current sequence number of an account A is X, then a transaction T on account A will only be executed if T’s sequence number is X. * These transactions will be held in mempool until they are the next sequence number for that account (or until they expire). * When the transaction is applied, the sequence number of the account will become X+1. The account has a strictly increasing sequence number. * [Orderless transactions](#orderless-transactions) do not use a sequence number. They use a nonce and can commit in any order. ### Sender [](#sender) * _Alternate name_: Sender address. * **Sender** is the address that originates the transaction. A transaction must be signed by the sender but can have more than one signer. ### Shoal [](#shoal) * Method for decreasing latency for BFT protocols. See the [Shoal paper](https://arxiv.org/pdf/2306.03058.pdf) ### Smart Contract [](#smart-contract) * **Smart contract** refers to a computer program that automatically and directly carries out the contract’s terms. * See [Move Module](#move-module) for related details. ### State [](#state) * A **state** in the Aptos protocol is a snapshot of the distributed database. * A transaction modifies the database and produces a new and updated state. ### State Root Hash [](#state-root-hash) * **State root hash** is a [Merkle hash](https://en.wikipedia.org/wiki/Merkle_tree) over all keys and values the state of the Aptos blockchain at a given version. ### Stateless Account [](#stateless-account) * A **stateless account** is an address that has not yet created an on-chain `0x1::account::Account` resource. It is still a valid account: the default authentication key is the address itself and the default sequence number is `0`. * The resource is created when a sequence-number transaction or a feature such as key rotation needs it. [Orderless transactions](#orderless-transactions) can be sent without creating the resource. See [AIP-115](/build/aips/aip-115) for more information. ## T [](#t) ### Table [](#table) * A [**table**](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-stdlib/doc/table.md) implements the Table type and in Aptos is used to store information as key-value data within an account at large scale. See [`table.move`](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-stdlib/sources/table.move) for the associated Aptos source file. ### Testnet [](#testnet) * **Testnet** describes the Aptos network that is not fully functional yet more stable than devnet; it is an alternative network to mainnet to be used for testing. ### Tokens [](#tokens) * **Tokens** are digital units of value issued on a blockchain. They can be redeemed for assets or value held. Tokens can be of the types: Fungible Token (FT), Non-Fungible Token (NFT), and Semi-Fungible Token (SFT). ### Transaction [](#transaction) * A raw **transaction** contains the following fields: * [Sender (account address)](#account-address) * [Move script](#move-script) * [Gas price](#gas-unit-price) * [Maximum gas amount](#maximum-gas-amount) * [Sequence number](#sequence-number) * [Expiration time](#expiration-time) * A signed transaction is a raw transaction with the digital signature. * An executed transaction changes the state of the Aptos blockchain. ### Transaction Script [](#transaction-script) * See [Move script](#move-script) ### Trusted Setup [](#trusted-setup) * The **trusted setup** is the pair of binary blobs (`digest_key.bin` and `pp.bin`) consumed by Aptos validator consensus before participating in distributed key generation (DKG). * Aptos Labs publishes the blobs in the [`aptos-labs/aptos-networks`](https://github.com/aptos-labs/aptos-networks) repository and rotates them periodically. All validators in a network must load the same bytes. * VFNs and PFNs do not need these files. See [Update Trusted Setup](/network/nodes/validator-node/modify-nodes/update-trusted-setup) for the operator runbook covering download, CLI verification, and rotation. ## V [](#v) ### Validator [](#validator) * _Alternate name_: Validators. * A **validator** is an entity of the Aptos ecosystem that validates on the Aptos blockchain. It receives requests from clients and runs consensus, execution, and storage. * A validator maintains the history of all the transactions on the blockchain. * Internally, a validator needs to keep the current state, to execute transactions, and to calculate the next state. * Aptos validators are in charge of verifying transactions. ### Validator Nodes [](#validator-nodes) * **Validator nodes** are a unique class of fullnodes that take part in consensus, specifically a Byzantine Fault Tolerance (BFT) consensus protocol in Aptos. Validators agree upon transactions to be added to the Aptos blockchain as well as the order in which they are added. ### Version [](#version) * A **version** is a sequentially increasing number that increments for every [transaction](#transaction). * On aptos, transactions are globally ordered and every transaction has a version (often called “height” in blockchain literature.) * Transaction version 0 is the first transaction (genesis transaction), and a transaction version 100 is the 101st transaction in the blockchain. ## W [](#w) ### WebMCP [](#webmcp) * **WebMCP** is a browser proposal that lets pages register tools on `navigator.modelContext`. * Every Aptos docs page registers search, navigation, Markdown fetch, and LLMs.txt discovery tools for browsers that implement the proposal. See [AI Tools Overview](/build/ai) for more information. ### Well-Formed Transaction [](#well-formed-transaction) An Aptos transaction is **well-formed** if each of the following conditions are true for the transaction: * The transaction has a valid signature. * An account exists at the sender address. * It includes a public key, and the hash of the public key matches the sender account’s authentication key. * The sequence number of the transaction matches the sender account’s sequence number. * The sender account’s balance is greater than the [maximum gas amount](#maximum-gas-amount). * The expiration time of the transaction has not passed. # Aptos Error Codes > Learn about error codes for Move smart contract development on Aptos blockchain. This page catalogs common errors encountered in the Aptos blockchain and explains how to resolve them wherever possible. As with all software, the code itself is the source of truth for error handling and will always contain entries not found here. Instead, this matrix aims to help you address those errors most typically found, misunderstood, or both. For the sources of these errors, see: * [vm\_status.rs](https://github.com/aptos-labs/aptos-core/blob/main/third_party/move/move-core/types/src/vm_status.rs) * [error.move](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/move-stdlib/sources/error.move) * [account.move](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/account/account.move) * [coin.move](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-framework/sources/coin.move) * [token.move](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-token/sources/token.move) * [token\_transfers.move](https://github.com/aptos-labs/aptos-core/blob/main/aptos-move/framework/aptos-token/sources/token_transfers.move) Help us update this list by sending pull requests containing the errors you encounter. If you don’t know how to resolve the error, as described in the _Action_ column, simply leave it blank. ## Frequent Errors [](#frequent-errors) ### INSUFFICIENT\_BALANCE\_FOR\_TRANSACTION\_FEE [](#insufficient_balance_for_transaction_fee) This means that the highest possible gas used for the transaction is greater than the balance of APT in the transaction sender’s (or fee payer’s) account. To resolve, please submit with a lower max gas amount, and try again. For example, if the max gas amount is 1000 gas units, and the gas unit price is `100` octas, the total APT required in the account would be `0.00100000` APT (`1000 * 100 / 100000000`). The default is often `200000` gas units which would end up requiring `0.20000000` APT. If you are having issues with this, please reach out to your wallet provider. ### OUT\_OF\_GAS [](#out_of_gas) This means that the transaction used more gas than the sender specified as the max gas amount for the transaction, and aborted as a result. To resolve, please try to increase the max gas amount, and submit the transaction again. ### SEQUENCE\_NUMBER\_TOO\_OLD [](#sequence_number_too_old) This means that the transaction’s sequence number in the sender’s account has already been used and committed to the blockchain. In order to submit a new transaction to the blockchain, please try and submit it again with a new sequence number. If the application does not need ordered execution from one sender, consider [orderless transactions](/build/aips/aip-123), which use a nonce instead of a sequence number. ### SEQUENCE\_NUMBER\_TOO\_NEW [](#sequence_number_too_new) This only occurs in simulation, but means that the sequence number being submitted is greater than the next sequence number for the account. Please reduce the sequence number and try again. ### NONCE\_ALREADY\_USED [](#nonce_already_used) This means an [orderless transaction](/build/aips/aip-123) reused a `(sender, nonce)` pair that is still stored in the on-chain nonce history. Pick a new random `u64` nonce, or wait until the previous nonce is garbage-collected (more than 100 seconds after the previous transaction’s expiration). ## Move Virtual Machine (VM) [](#move-virtual-machine-vm)
ErrorMeaningPossible Resolution
LOOKUP_FAILEDA function that is being called isn’t present on the network being usedCheck that your dependencies on-chain have the same version
UNKNOWN_VALIDATION_STATUSWe don’t want the default value to be valid.N/A
INVALID_SIGNATUREThe transaction has a bad signature.Submit a new transaction with a new signature
INVALID_AUTH_KEYBad account authentication key.Submit a new transaction with a new signature, check that the account matches the authentication key and hasn’t been rotated
SEQUENCE_NUMBER_TOO_OLDSequence number is too old.Submit a new transaction with a newer sequence number from the account
SEQUENCE_NUMBER_TOO_NEWSequence number is too new.Decrease the sequence number to the account’s next sequence number
INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEEInsufficient balance to pay for max_gas specified in the transaction. Balance needs to be above max_gas_amount * gas_unit_price to proceed.Fund the account with more APT to pay for the gas fee
TRANSACTION_EXPIREDThe transaction has expired.Submit a new transaction with an expiration time further in the future
SENDING_ACCOUNT_DOES_NOT_EXISTThe sending account does not exist.With AIP-115, missing Account resources no longer fail this way; GET /accounts/{address} returns defaults instead of 404. This status is retained for compatibility.
REJECTED_WRITE_SETThis write set transaction was rejected because it did not meet the requirements for one.N/A
INVALID_WRITE_SETThis write set transaction cannot be applied to the current state.N/A
EXCEEDED_MAX_TRANSACTION_SIZELength of program field in raw transaction exceeded max length.The transaction is too large for a single transaction; if this is a package publish, try to break it into multiple packages
UNKNOWN_SCRIPTThis script is not in our allowlist of scripts.N/A
UNKNOWN_MODULETransaction is trying to publish a new module.N/A
MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUNDMax gas units submitted with transaction exceeds max gas units bound in VM.Decrease the max gas amount in the transaction below the maximum value in the gas schedule
MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITSMax gas units submitted with transaction not enough to cover the intrinsic cost of the transaction.Increase the max gas amount above the minimum value in the gas schedule
GAS_UNIT_PRICE_BELOW_MIN_BOUNDGas unit price submitted with transaction is below minimum gas price set in the VM.Increase the gas unit price to at least the minimum gas unit price in the gas schedule
GAS_UNIT_PRICE_ABOVE_MAX_BOUNDGas unit price submitted with the transaction is above the maximum gas price set in the VM.Decrease the gas unit price below the maximum gas unit price in the gas schedule
INVALID_GAS_SPECIFIERGas specifier submitted is either malformed (not a valid identifier), or does not refer to an accepted gas specifier.N/A
SENDING_ACCOUNT_FROZENThe sending account is frozen.N/A
UNABLE_TO_DESERIALIZE_ACCOUNTUnable to deserialize the account blob.N/A
CURRENCY_INFO_DOES_NOT_EXISTThe currency info was unable to be found.N/A
INVALID_MODULE_PUBLISHERThe account sender doesn’t have permissions to publish modules.N/A
NO_ACCOUNT_ROLEThe sending account has no role.N/A
BAD_CHAIN_IDThe transaction’s chain_id does not match the one published on-chain.Verify that your chain ID matches the chain ID for your network
SEQUENCE_NUMBER_TOO_BIGThe sequence number is too large and would overflow if the transaction were executed.N/A
BAD_TRANSACTION_FEE_CURRENCYThe gas currency is not registered as a TransactionFee currency.N/A
FEATURE_UNDER_GATINGThe feature requested is intended for a future Aptos version instead of the current one.N/A
SECONDARY_KEYS_ADDRESSES_COUNT_MISMATCHThe number of secondary signer addresses is different from the number of secondary public keys provided.Verify the multi-agent or multi-ed25519 secondary signer addresses match the secondary public keys
SIGNERS_CONTAIN_DUPLICATESThere are duplicates among signers, including the sender and all the secondary signers.Remove any duplicate signers
SEQUENCE_NONCE_INVALIDThe sequence nonce in the transaction is invalid (too new, too old, or already used).N/A
CHAIN_ACCOUNT_INFO_DOES_NOT_EXISTThere was an error when accessing chain-specific account information.N/A
MODULE_ADDRESS_DOES_NOT_MATCH_SENDERthe module publisher is not the account that will eventually hold the module.Confirm the module address in the move contract matches the sender of the transaction
ZERO_SIZED_STRUCTReported when a struct has zero fields.N/A
DUPLICATE_MODULE_NAMEThe sender is trying to publish two modules with the same name in one transaction.Confirm every module has a unique name
BACKWARD_INCOMPATIBLE_MODULE_UPDATEThe sender is trying to publish a module that breaks the compatibility checks.Confirm your new modules being published don’t break backwards compatibility
CYCLIC_MODULE_DEPENDENCYThe updated module introduces a cyclic dependency (i.e., A uses B and B also uses A).Check for loops in your module dependencies in the modules being published
INVALID_FRIEND_DECL_WITH_SELFCannot mark the module itself as a friend.Confirm no module has itself marked as a friend in the modules being published
INVALID_FRIEND_DECL_WITH_MODULES_OUTSIDE_ACCOUNT_ADDRESSCannot declare modules outside of account address as friends.Confirm all friends are in the same account address in the modules being published
INVALID_FRIEND_DECL_WITH_MODULES_IN_DEPENDENCIESCannot declare modules that this module depends on as friends.Check friend declarations of the modules being published
CYCLIC_MODULE_FRIENDSHIPThe updated module introduces a cyclic friendship (i.e., A friends B and B also friends A).Check friend declarations of the modules being published
INVALID_PHANTOM_TYPE_PARAM_POSITIONA phantom type parameter was used in a non-phantom position.Confirm phantom types are used only with generics
LOOP_MAX_DEPTH_REACHEDLoops are too deeply nested.Check for many nested loops
TYPE_RESOLUTION_FAILUREFailed to resolve type due to linking being broken after verification.N/A
RESOURCE_DOES_NOT_EXISTWe tried to access a resource that does not exist under the account.Check the contract and possibly change it to handle resources that don’t exist
RESOURCE_ALREADY_EXISTSWe tried to create a resource under an account where that resource already exists.Check the contract and possibly change it to handle resources that already exist
UNKNOWN_STATUSA reserved status to represent an unknown vm status. This is std::u64::MAX, but we can’t pattern match on that, so put the hardcoded value in.N/A
LINKER_ERRORThis may be due to the function has not been published on chain or by trying to call an invalid function as the result of either an incorrect account address, module name, or function name. This might not happen locally if the sources are available locally but have yet to be published on-chain.There are many reasons, but you should check your account addresses, module names, and function names to determine that they’re correct and published
FAILED_TO_DESERIALIZE_ARGUMENTThis error in deserializing argument is triggered by one of the following validation checks. 1) It exceeds the limit on the number of nested or unpacked structs (including in a vector). The maximum overall args equals to depth * number of args. The max depth is currently 10. 2) The nested struct exceeds the aforementioned max depth. 3) The serialized arguments to constructor contained extra data. 4) It was derializing utf8 but struct_constructors are disabled. 5) The string argument is too long. 6) BCS deserialization fails for utf8.N/A
GAS_PAYER_ACCOUNT_MISSINGThe fee-payer account is missing for a sponsored transaction.Confirm the fee payer exists and is included as a signer
NONCE_ALREADY_USEDThe orderless transaction reused a (sender, nonce) pair that is still in the on-chain nonce history.Submit with a new random u64 nonce. See AIP-123.
EMPTY_PAYLOAD_PROVIDEDThe transaction executable was empty on a non-multisig transaction.Include a valid entry function or script. An empty executable is only valid for some multisig flows.
TRANSACTION_EXPIRATION_TOO_FAR_IN_FUTUREThe expiration time is too far in the future. Orderless transactions may expire at most 60 seconds from now.Lower the expiration time; for orderless transactions keep it within 60 seconds
## Move Standard Library (stdlib) [](#move-standard-library-stdlib)
ErrorMeaning
INVALID_ARGUMENTCaller specified an invalid argument (HTTP: 400).
OUT_OF_RANGEAn input or result of a computation is out of range (HTTP: 400).
INVALID_STATEThe system is not in a state where the operation can be performed (HTTP: 400).
UNAUTHENTICATEDRequest not authenticated due to missing, invalid, or expired authentication token (HTTP: 401).
PERMISSION_DENIEDThe client does not have sufficient permission (HTTP: 403).
NOT_FOUNDA specified resource is not found (HTTP: 404).
ABORTEDConcurrency conflict, such as read-modify-write conflict (HTTP: 409).
ALREADY_EXISTSThe resource that a client tried to create already exists (HTTP: 409).
RESOURCE_EXHAUSTEDOut of gas or other forms of quota (HTTP: 429).
CANCELLEDRequest cancelled by the client (HTTP: 499).
INTERNALInternal error (HTTP: 500).
NOT_IMPLEMENTEDFeature not implemented (HTTP: 501).
UNAVAILABLEThe service is currently unavailable. Indicates that a retry could solve the issue (HTTP: 503).
## Aptos accounts [](#aptos-accounts)
ErrorMeaningPossible Resolution
EACCOUNT_ALREADY_EXISTSAccount already exists.N/A
EACCOUNT_DOES_NOT_EXISTAccount does not exist.Create the account first
ESEQUENCE_NUMBER_TOO_BIGSequence number exceeds the maximum value for a u64.Provide a smaller sequence number
EMALFORMED_AUTHENTICATION_KEYThe provided authentication key has an invalid length.Check your authentication key; it should be a 32-byte vector
ECANNOT_RESERVED_ADDRESSCannot create account because address is reserved.N/A
EOUT_OF_GASTransaction exceeded its allocated max gas.Increase the max gas amount
EWRONG_CURRENT_PUBLIC_KEYSpecified current public key is not correct.Confirm the public key matches the account
EINVALID_PROOF_OF_KNOWLEDGESpecified proof of knowledge required to prove ownership of a public key is invalid.Check your proof of knowledge in key rotation to ensure it has proper signatures
ENO_CAPABILITYThe caller does not have a digital-signature-based capability to call this function.Confirm you have the capability for the called functions
EINVALID_ACCEPT_ROTATION_CAPABILITYThe caller does not have a valid rotation capability offer from the other account.Confirm the account being rotated is correct
ENO_VALID_FRAMEWORK_RESERVED_ADDRESSAddress to create is not a valid reserved address for Aptos framework.N/A
EINVALID_SCHEMESpecified scheme required to proceed with the smart contract operation - can only be ED25519_SCHEME(0) OR MULTI_ED25519_SCHEME(1).Confirm the transaction was signed correctly when creating the account
EINVALID_ORIGINATING_ADDRESSAbort the transaction if the expected originating address is different from the originating address on-chain.Confirm you are rotating the correct account’s key
ENO_SUCH_SIGNER_CAPABILITYThe signer capability doesn’t exist at the given address.Confirm the address is correct
## Aptos coins [](#aptos-coins)
ErrorMeaningPossible Resolution
ECOIN_INFO_ADDRESS_MISMATCHAddress of account which is used to initialize a coin CoinType doesn’t match the deployer of module.Create the coin using a CoinType in the same account creating the coin.
ECOIN_INFO_ALREADY_PUBLISHEDCoinType is already initialized as a coin.N/A
ECOIN_INFO_NOT_PUBLISHEDCoinType hasn’t been initialized as a coin.Create the coin with CoinType first before using it
ECOIN_STORE_ALREADY_PUBLISHEDAccount already has CoinStore registered for CoinType.N/A
ECOIN_STORE_NOT_PUBLISHEDAccount hasn’t registered CoinStore for CoinType.Register the account for the CoinType
EINSUFFICIENT_BALANCENot enough coins to complete transaction.Transfer less coins, or acquire more coins prior to the transfer
EDESTRUCTION_OF_NONZERO_TOKENCannot destroy non-zero coins.N/A
EZERO_COIN_AMOUNTCoin amount cannot be zero.Don’t burn coins or conduct other actions with zero coins
EFROZENCoinStore is frozen. Coins cannot be deposited or withdrawn.Account is frozen for this token; talk to the coin owner
ECOIN_SUPPLY_UPGRADE_NOT_SUPPORTEDCannot upgrade the total supply of coins to different implementation.N/A
ECOIN_NAME_TOO_LONGName of the coin is too long.Coin name must be less than or equal to 32 characters
ECOIN_SYMBOL_TOO_LONGSymbol of the coin is too long.Coin symbol must be less than or equal to 10 characters
## Aptos tokens [](#aptos-tokens)
ErrorMeaning
EALREADY_HAS_BALANCEThe token has balance and cannot be initialized.
ECOLLECTIONS_NOT_PUBLISHEDThere isn’t any collection under this account.
ECOLLECTION_NOT_PUBLISHEDCannot find collection in creator’s account.
ECOLLECTION_ALREADY_EXISTSThe collection already exists.
ECREATE_WOULD_EXCEED_COLLECTION_MAXIMUMExceeds the collection’s maximal number of token_data.
EINSUFFICIENT_BALANCEInsufficient token balance.
EINVALID_TOKEN_MERGECannot merge the two tokens with different token IDs.
EMINT_WOULD_EXCEED_TOKEN_MAXIMUMExceed the token data maximal allowed.
ENO_BURN_CAPABILITYNo burn capability.
ETOKEN_DATA_ALREADY_EXISTSTokenData already exists.
ETOKEN_DATA_NOT_PUBLISHEDTokenData not published.
ETOKEN_STORE_NOT_PUBLISHEDTokenStore doesn’t exist.
ETOKEN_SPLIT_AMOUNT_LARGER_THAN_TOKEN_AMOUNTCannot split token to an amount larger than its amount.
EFIELD_NOT_MUTABLEThe field is not mutable.
ENO_MUTATE_CAPABILITYNot authorized to mutate.
ENO_TOKEN_IN_TOKEN_STOREToken not in the token store.
EUSER_NOT_OPT_IN_DIRECT_TRANSFERUser didn’t opt-in direct transfer.
EWITHDRAW_ZEROCannot withdraw 0 token.
ENFT_NOT_SPLITABLECannot split a token that only has 1 amount.
ENO_MINT_CAPABILITYNo mint capability
ECOLLECTION_NAME_TOO_LONGThe collection name is too long.
ENFT_NAME_TOO_LONGThe NFT name is too long.
EURI_TOO_LONGThe URI is too long.
ENO_DEPOSIT_TOKEN_WITH_ZERO_AMOUNTCannot deposit a token with 0 amount.
ENO_BURN_TOKEN_WITH_ZERO_AMOUNTCannot burn 0 token.
EWITHDRAW_PROOF_EXPIRESWithdraw proof expires.
EOWNER_CANNOT_BURN_TOKENToken is not burnable by owner.
ECREATOR_CANNOT_BURN_TOKENToken is not burnable by creator.
ECANNOT_UPDATE_RESERVED_PROPERTYReserved fields for token contract. Cannot be updated by user.
EURI_TOO_SHORTURI too short.
ETOKEN_OFFER_NOT_EXISTToken offer doesn’t exist.
# Transaction Payloads and BCS > Learn the Aptos transaction payload types, how REST JSON maps to BCS, and how to build and decode payloads with TypeScript. A transaction payload defines the operation that a transaction executes. The sender, sequence number, gas settings, expiration time, and signature are not part of the payload. The Aptos REST API represents payloads as JSON. Transaction signing and network transport use [BCS](https://github.com/aptos-labs/bcs) (Binary Canonical Serialization) to represent payloads and transactions. ## Payload types [](#payload-types) `TransactionPayload` is a BCS enum. Each variant begins with a ULEB128-encoded enum index.
BCS indexPayloadREST JSON typeDescription
0Script payloadscript_payloadExecutes a Move script included in the transaction.
1Module bundle payloadmodule_bundle_payloadDeprecated.
2Entry function payloadentry_function_payloadCalls an entry function in a published module.
3Multisig payloadmultisig_payloadExecutes an operation as an on-chain multisig account.
4Versioned payloadNot exposed directlyVersioned payload used by orderless transactions.
5Encrypted payloadencrypted_transaction_payloadContains an encrypted transaction payload.
`write_set_payload` is used only by genesis and system transactions. It is not a `TransactionPayload` that a regular user transaction can submit. ## BCS encoding rules [](#bcs-encoding-rules) The following rules apply to the BCS layouts in this document:
TypeEncoding
EnumULEB128 enum index followed by the fields of the selected variant.
vector<T>ULEB128 element count followed by each element.
vector<u8>ULEB128 byte length followed by the bytes.
Option<T>0x00 for None; 0x01 followed by T for Some(T).
u64, u128, u256Fixed-width, little-endian.
Address32 bytes.
## Script payload [](#script-payload) `Script` contains Move script bytecode, type arguments, and script arguments. REST JSON: ``` { "type": "script_payload", "code": { "bytecode": "0xa11ceb0b..." }, "type_arguments": [], "arguments": ["0x123", "100000000"]} ``` BCS layout: ``` uleb128(0) // TransactionPayload::Scriptvector // Move script bytecodevector // Type argumentsvector // Script arguments ``` `TransactionArgument` is an enum that includes a type index. New applications generally use entry function payloads. Script payloads are intended for operations that must include Move bytecode in the transaction. ## Module bundle payload [](#module-bundle-payload) `ModuleBundle` is deprecated. Nodes retain its enum position for BCS compatibility but reject new transactions that use it. Use the SDK package publishing API to publish a Move package. REST JSON: ``` { "type": "module_bundle_payload"} ``` Retained BCS layout: ``` uleb128(1) // TransactionPayload::ModuleBundleu64 // Compatibility field with no current behavior ``` ## Entry function payload [](#entry-function-payload) `EntryFunction` calls a `public entry fun` in a published module. REST JSON: ``` { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": [], "arguments": ["0x123", "100000000"]} ``` BCS layout: ``` uleb128(2) // TransactionPayload::EntryFunctionModuleId // Module address and nameIdentifier // Function namevector // Type argumentsvector> // Function arguments ``` Each function argument is BCS-encoded according to its Move type in the ABI and stored in a separate `vector`. The argument bytes do not include type information, so decoding requires the function ABI. Build an entry function payload with the TypeScript SDK: ``` import { AccountAddress, Aptos, AptosConfig, Network, U64 } from "@aptos-labs/ts-sdk"; const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET })); const transaction = await aptos.transaction.build.simple({ sender: AccountAddress.fromString("0xabc"), data: { function: "0x1::aptos_account::transfer", functionArguments: [AccountAddress.fromString("0x123"), new U64(100_000_000)], },}); const payloadHex = transaction.rawTransaction.payload.bcsToHex().toString(); ``` ## Multisig payload [](#multisig-payload) `Multisig` specifies an on-chain multisig account and can include an entry function or script payload. REST JSON: ``` { "type": "multisig_payload", "multisig_address": "0x123", "transaction_payload": { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": [], "arguments": ["0x456", "100000000"] }} ``` BCS layout: ``` uleb128(3) // TransactionPayload::MultisigAccountAddress // Multisig account addressOption // Payload to execute ``` `MultisigTransactionPayload` is a nested enum: index `0` is an entry function and index `1` is a script. `None` uses a payload already stored in the on-chain multisig account. An on-chain multisig account is different from a multi-agent transaction. A multi-agent transaction has multiple signers but uses a regular transaction payload. ## Versioned payload [](#versioned-payload) `Payload` is an extensible, versioned structure. Its current inner version is `TransactionPayloadInner::V1`. BCS layout: ``` uleb128(4) // TransactionPayload::Payloaduleb128(0) // TransactionPayloadInner::V1TransactionExecutable // Entry function, script, empty, or encrypted operationTransactionExtraConfig // Multisig address, replay-protection nonce, and other settings ``` The REST API converts this structure into entry function, script, or multisig JSON based on `TransactionExecutable` and `TransactionExtraConfig`. It does not return `Payload::V1` as a separate REST payload type. ### Orderless transactions [](#orderless-transactions) An orderless transaction is not a separate payload variant. It uses `TransactionPayload::Payload` and sets `replay_protection_nonce: Some(u64)` in `TransactionExtraConfig`. Its `RawTransaction.sequence_number` is set to `u64::MAX`. ``` const transaction = await aptos.transaction.build.simple({ sender: sender.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [recipient.accountAddress, 100], }, options: { replayProtectionNonce: 12345n, },}); ``` `replayProtectionNonce` must be unique during the transaction’s validity period. An orderless transaction has a maximum expiration period of 60 seconds. ## Encrypted payload [](#encrypted-payload) `EncryptedPayload` is available on networks that support AIP-144. On submission, it contains the ciphertext, payload hash, encryption epoch, extra configuration, and an optional claimed entry function. REST JSON: ``` { "type": "encrypted_transaction_payload", "encrypted_state": "encrypted", "payload_hash": "0x...", "ciphertext": "0x...", "encryption_epoch": "123", "claimed_entry_fun": null} ``` BCS layout: ``` uleb128(5) // TransactionPayload::EncryptedPayloaduleb128(0) // EncryptedPayload::EncryptedCiphertext // CiphertextTransactionExtraConfig // Extra configuration[u8; 32] // Payload hashu64 // Encryption epochOption // Optional claimed entry function ``` The REST API uses `encrypted_state` to distinguish `encrypted`, `decrypted`, and `failed_decryption`. Only the `encrypted` state can be submitted. See [Encrypted Pending Transactions](/build/guides/encrypted-pending-transactions). ## Decode a BCS payload [](#decode-a-bcs-payload) `TransactionPayload.deserialize()` decodes the payload enum and its fields. Entry function arguments remain raw bytes and must be decoded separately using the ABI. ``` import { Deserializer, TransactionPayload, TransactionPayloadEntryFunction, U64,} from "@aptos-labs/ts-sdk"; function decodeEntryFunctionPayload(payloadHex: string) { const decoded = TransactionPayload.deserialize(Deserializer.fromHex(payloadHex)); if (!(decoded instanceof TransactionPayloadEntryFunction)) { throw new Error("Expected an entry function payload"); } // The second argument is u64 according to the function ABI. const amountBytes = decoded.entryFunction.args[1].bcsToBytes(); return U64.deserialize(new Deserializer(amountBytes)).value;} ``` `TransactionPayload`, `RawTransaction`, and `SignedTransaction` are different BCS objects. A transaction signature covers the complete raw transaction, not only its payload. # Aptos Improvement Proposals (AIPs) > Learn about Aptos Improvement Proposals - how the community proposes changes and improvements to the Aptos protocol Aptos Improvement Proposals (AIPs) are a way for the Aptos community to propose changes, improvements, and new features to the Aptos protocol. AIPs are designed to be a collaborative process that allows anyone in the community to contribute ideas and feedback. AIPs are documented in the [AIPs repository](https://github.com/aptos-foundation/AIPs) and are administered by the Aptos Foundation. Each AIP is assigned a unique number and goes through a rigorous review process before it is accepted or rejected. Proposal files in that repository use the name `aip-NNN-short-title.md` (for example, `aip-115-stateless-account-update.md`). Older short paths such as `aips/aip-115.md` no longer resolve. ## What do AIPs cover? [](#what-do-aips-cover) AIPs can cover a wide range of topics, including: * Node protocol changes - Mempool changes, consensus changes, etc. * Framework (smart contract) changes - New modules, new functions, etc. * Governance changes - Changes to the way the Aptos Foundation operates, changes to the way AIPs are processed, etc. ## What is this section of the docs mostly about? [](#what-is-this-section-of-the-docs-mostly-about) This section of the docs is mostly about AIPs that are relevant to developers and providing FAQs and quick information about them. ## Developer-facing AIPs [](#developer-facing-aips) These proposals most often affect application, indexer, and wallet integrations. The FAQ pages in this section go deeper on the ones that change day-to-day API and account behavior.
AIPTopicIn these docs
AIP-21Fungible assetsFungible Asset standard
AIP-39Sponsored transactionsSponsored transactions
AIP-62Wallet standardWallet adapter
AIP-88Block epilogue transactionsAIP-88 FAQ
AIP-113Derivable account abstractionDerivable account abstraction
AIP-115Stateless accountsAIP-115 FAQ
AIP-123Orderless transactionsAIP-123 FAQ
AIP-129Transaction payload variantsTransaction payloads and BCS
AIP-144Encrypted mempoolEncrypted pending transactions
Browse the full list in the [AIPs repository](https://github.com/aptos-foundation/AIPs/tree/main/aips). # External Resources > Official and community references, learning material, and tools for building on Aptos ## Official references [](#official-references) Lookup pages that belong in the Reference section of these docs: * [Glossary](/network/glossary) — terms used across Aptos docs. * [Error codes](/build/smart-contracts/error-codes) — common VM and Move abort codes. * [Transaction payloads and BCS](/network/blockchain/transaction-payloads) — payload variants and encoding. * [Indexer GraphQL reference](/build/indexer/indexer-api/indexer-reference) — hosted indexer tables and fields. * [REST API reference](/rest-api) — fullnode OpenAPI reference generated from [`/aptos-spec.json`](/aptos-spec.json). * [AIPs](/build/aips) — developer-facing Aptos Improvement Proposal FAQs. Move language and framework books (mdBook, hosted outside this site): * [Move Book](https://aptos-labs.github.io/move-book/) — Move language reference. * [Aptos Framework Book](https://aptos-labs.github.io/framework-book/) — `aptos-framework`, `aptos-stdlib`, `move-stdlib`, and token-object packages. Network explorers and hosted developer services: * [Aptos Explorer](https://explorer.aptoslabs.com/) — accounts, transactions, and validators. * [Geomi](https://geomi.dev/) (formerly Aptos Build) — API keys, Gas Station, and no-code indexing. * [AI tools](/build/ai) — Aptos MCP, Agent Skills, and LLMs.txt. ## Move learning resources [](#move-learning-resources) ### Tutorials [](#tutorials) * [Aptos Learn](https://learn.aptoslabs.com) — Learn how to build on the Aptos Blockchain with various tutorials. ### Videos [](#videos) * [Aptos Dev YouTube Channel](https://www.youtube.com/@aptosdev) — Learn about how to build on the Aptos Blockchain with various videos. ### Examples [](#examples) * [Move By Examples](https://github.com/aptos-labs/move-by-examples) — A collection of Move examples. * [Daily Move](https://github.com/aptos-labs/daily-move) — A collection of short Move examples illustrating Aptos features. * [Aptos-Core Move Examples](https://github.com/aptos-labs/aptos-core/tree/main/aptos-move/move-examples) — A collection of Move examples actively tested in CI in the Aptos Core repository. ## Community developer tools [](#community-developer-tools) * [Surf](https://github.com/ThalaLabs/surf) — Generated TypeScript interfaces and React hooks for Aptos smart contracts. * [Revela](https://revela.verichains.io/) — Move bytecode decompiler. The Aptos CLI can also decompile with `aptos move decompile --package-dir /bytecode_modules`. ## Data and analytics [](#data-and-analytics) SQL datasets, dashboards, and RPC vendors are listed on [Data Providers](/build/apis/data-providers).