### Run Aptos SDK Quickstart Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx Execute the TypeScript quickstart script using npm, pnpm, or yarn. ```bash npx ts-node src/quickstart.ts ``` ```bash pnpx ts-node src/quickstart.ts ``` ```bash yarn ts-node src/quickstart.ts ``` -------------------------------- ### Install Dependencies for Aptos TS SDK Examples Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/first-coin.mdx Navigate to the TypeScript examples directory and install the necessary Node.js dependencies using pnpm. ```bash cd examples/typescript/ pnpm install ``` -------------------------------- ### Run Python Key Rotation Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/key-rotation.mdx Navigate to the Python SDK directory, install dependencies, and run the key rotation example script. ```bash cd aptos-core/ecosystem/python/sdk poetry install && poetry run python -m examples.rotate-key ``` -------------------------------- ### Aptos SDK TypeScript Quickstart Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx This script demonstrates creating accounts, funding them, checking balances, and transferring APT using the Aptos TypeScript SDK. ```typescript /** * 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 APTOS_COIN = "0x1::aptos_coin::AptosCoin"; const COIN_STORE = `0x1::coin::CoinStore<${APTOS_COIN}>`; 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 console.log("\n=== Balances ===\n"); const aliceAccountBalance = await aptos.getAccountResource({ accountAddress: alice.accountAddress, resourceType: COIN_STORE, }); const aliceBalance = Number(aliceAccountBalance.coin.value); console.log(`Alice's balance is: ${aliceBalance}`); const bobAccountBalance = await aptos.getAccountResource({ accountAddress: bob.accountAddress, resourceType: COIN_STORE, }); const bobBalance = Number(bobAccountBalance.coin.value); 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, 100], }, }); 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 newAliceAccountBalance = await aptos.getAccountResource({ accountAddress: alice.accountAddress, resourceType: COIN_STORE, }); const newAliceBalance = Number(newAliceAccountBalance.coin.value); console.log(`Alice's balance is: ${newAliceBalance}`); const newBobAccountBalance = await aptos.getAccountResource({ accountAddress: bob.accountAddress, resourceType: COIN_STORE, }); const newBobBalance = Number(newBobAccountBalance.coin.value); 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(); ``` -------------------------------- ### Local Testnet Startup Output Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/cli/running-a-local-network.mdx This is an example of the expected output when starting a local Aptos testnet. It shows the readiness endpoints for various services like the Node API, Indexer API, and Faucet. ```bash Readiness endpoint: http://0.0.0.0:8070/ Indexer API is starting, please wait... Node API is starting, please wait... Transaction stream is starting, please wait... Postgres is starting, please wait... Faucet is starting, please wait... Completed generating configuration: Log file: "/Users/dport/.aptos/testnet/validator.log" Test dir: "/Users/dport/.aptos/testnet" Aptos root key path: "/Users/dport/.aptos/testnet/mint.key" Waypoint: 0:397412c0f96b10fa3daa24bfda962671c3c3ae484e2d67ed60534750e2311f3d ChainId: 4 REST API endpoint: http://0.0.0.0:8080 Metrics endpoint: http://0.0.0.0:9101/metrics Aptosnet fullnode network endpoint: /ip4/0.0.0.0/tcp/6181 Indexer gRPC node stream endpoint: 0.0.0.0:50051 Aptos is running, press ctrl-c to exit Node API is ready. Endpoint: http://0.0.0.0:8080/ Postgres is ready. Endpoint: postgres://postgres@127.0.0.1:5433/local_testnet Transaction stream is ready. Endpoint: http://0.0.0.0:50051/ Indexer API is ready. Endpoint: http://127.0.0.1:8090/ Faucet is ready. Endpoint: http://127.0.0.1:8081/ Applying post startup steps... Setup is complete, you can now use the local testnet! ``` -------------------------------- ### Simulate APT Transfer Transaction in Go Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/go-sdk/building-transactions/simulating-transactions.mdx This example demonstrates how to build and simulate a simple APT transfer transaction using the Aptos Go SDK. It covers client creation, account setup, funding, building the transaction payload for a transfer, and simulating the transaction to view gas estimates and VM status. Use this to test transaction logic and cost before on-chain submission. ```go package main import ( "fmt" "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/bcs" ) const FundAmount = 100_000_000 const TransferAmount = 1_000 // example This example shows you how to make an APT transfer transaction in the simplest possible way func 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 // 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) } func main() { example(aptos.DevnetConfig) } ``` -------------------------------- ### Run Aptos Python SDK Your Coin Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/first-coin.mdx Execute the 'your_coin' example script using Poetry and Python. This requires the path to the MoonCoin Move example directory. ```bash poetry run python -m examples.your_coin ~/aptos-core/aptos-move/move-examples/moon_coin ``` -------------------------------- ### Run TypeScript key rotation example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/key-rotation.mdx Commands to navigate to the TypeScript SDK directory, install dependencies, and run the key rotation example script. ```bash cd ~/aptos-core/ecosystem/typescript/sdk/examples/typescript-esm pnpm install && pnpm rotate_key ``` -------------------------------- ### Install Aptos Go SDK Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/go-sdk.mdx Use this command to get the main package for the Aptos Go SDK. ```bash go get github.com/aptos-labs/aptos-go-sdk ``` -------------------------------- ### Full TypeScript Example for Building Transactions Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/building-transactions.mdx This example demonstrates the complete process of building, signing, and submitting a simple APT transfer transaction using the Aptos TypeScript SDK. Ensure you have installed the SDK before running. ```typescript /** * This example shows how to use the Aptos SDK to send a transaction. * Don't forget to install @aptos-labs/ts-sdk before running this example! */ import { Account, Aptos, AptosConfig, Network, } from "@aptos-labs/ts-sdk"; async function example() { console.log("This example will create two accounts (Alice and Bob) and send a transaction transfering APT to Bob's account."); // 0. Setup the client and test accounts const config = new AptosConfig({ network: Network.DEVNET }); const aptos = new Aptos(config); let alice = Account.generate(); let bob = Account.generate(); console.log("=== Addresses ===\n"); console.log(`Alice's address is: ${alice.accountAddress}`); console.log(`Bob's address is: ${bob.accountAddress}`); console.log("\n=== Funding accounts ===\n"); await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: 100_000_000, }); await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: 100, }); console.log("Funded Alice and Bob's accounts!") // 1. Build console.log("\n=== 1. Building the transaction ===\n"); const transaction = 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, 100], }, }); console.log("Built the transaction!") // 2. Simulate (Optional) console.log("\n === 2. Simulating Response (Optional) === \n") const [userTransactionResponse] = await aptos.transaction.simulate.simple({ signerPublicKey: alice.publicKey, transaction, }); console.log(userTransactionResponse) // 3. Sign console.log("\n=== 3. Signing transaction ===\n"); const senderAuthenticator = aptos.transaction.sign({ signer: alice, transaction, }); console.log("Signed the transaction!") // 4. Submit console.log("\n=== 4. Submitting transaction ===\n"); const submittedTransaction = await aptos.transaction.submit.simple({ transaction, senderAuthenticator, }); console.log(`Submitted transaction hash: ${submittedTransaction.hash}`); // 5. Wait for results console.log("\n=== 5. Waiting for result of transaction ===\n"); const executedTransaction = await aptos.waitForTransaction({ transactionHash: submittedTransaction.hash }); console.log(executedTransaction) }; example(); ``` -------------------------------- ### Start Production Server Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/README.md After building for production, run this command from the nextra directory to start the production server. ```bash pnpm start ``` -------------------------------- ### Install Aptos CLI with Homebrew Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/cli/install-cli/install-cli-mac.mdx Use Homebrew to install the Aptos CLI. Ensure Homebrew is installed first, then update and install the CLI. Verify the installation by running `aptos help`. ```bash brew update brew install aptos ``` ```bash aptos help ``` -------------------------------- ### Install Aptos Python SDK from Source Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/python-sdk.mdx Clone the aptos-python-sdk repository and install it locally using pip. ```bash git clone https://github.com/aptos-labs/aptos-python-sdk pip3 install . --user ``` -------------------------------- ### Run Simple Transfer Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/ts-examples.mdx Execute the 'simple_transfer' example script using pnpm. ```bash pnpm run simple_transfer ``` -------------------------------- ### Install create-aptos-dapp using yarn Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/create-aptos-dapp.mdx Install `create-aptos-dapp` using yarn. This command initiates the project scaffolding process. ```bash yarn create aptos-dapp ``` -------------------------------- ### Initialize TransactionStreamStep with Starting Version Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/indexer/indexer-sdk/documentation/version-tracking.mdx Example of initializing a TransactionStreamStep with a starting version retrieved from a checkpoint. If no checkpoint exists, the processor starts from the beginning of the chain. ```rust let transaction_stream = TransactionStreamStep::new(TransactionStreamConfig { starting_version: Some(starting_version), ..self.config.transaction_stream_config.clone() }) .await?; ``` -------------------------------- ### Install Legacy Wallet Plugin Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/wallet-adapter/dapp.mdx For older wallets not supporting AIP-62, install their specific adapter plugin. This example shows installing the OKX Wallet plugin. ```bash npm i @okwallet/aptos-wallet-adapter ``` -------------------------------- ### Full Go Example: Building and Submitting APT Transfer Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/go-sdk/building-transactions.mdx This comprehensive example illustrates the complete lifecycle of an APT transfer transaction using the Aptos Go SDK. It covers client initialization, account creation, funding, balance checks, transaction building, simulation, signing, submission, and waiting for confirmation. It also shows an alternative method for building, signing, and submitting in a single call. ```go // transfer_coin is an example of how to make a coin transfer transaction in the simplest possible way package main import ( "fmt" "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/bcs" ) const FundAmount = 100_000_000 const TransferAmount = 1_000 // example This example shows you how to make an APT transfer transaction in the simplest possible way func 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) } ``` -------------------------------- ### View Dev Setup Script Help Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/network/nodes/building-from-source.mdx Display the available options and usage instructions for the dev setup script by running it with the --help flag. ```bash ./scripts/dev_setup.sh --help ``` -------------------------------- ### Test Project Initialization with npm Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx Executes the quickstart.ts file using ts-node with npm to verify the project setup. ```bash npx ts-node src/quickstart.ts ``` -------------------------------- ### Event GUID Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/system-integrators-guide.mdx This JSON snippet shows the GUID structure for an event, which is used to correlate events with resource changes. The 'key' field is being deprecated in favor of 'guid'. ```json {"addr": "0x5098df8e7969b58ab3bd2d440c6203f64c60a1fd5c08b9d4abe6ae4216246c3e", "creation_num": "2"} ``` -------------------------------- ### Run Aptos .NET SDK Examples Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/dotnet-sdk/dotnet-examples.mdx Navigate to the Aptos.Examples directory and execute the .NET application using the specified framework. This command will launch the example runner. ```bash cd Aptos.Examples dotnet run --framework net8.0 ``` -------------------------------- ### Get GUID Next Creation Number Source: https://github.com/aptos-labs/developer-docs/blob/main/packages/aptos-nextra-components/src/utils/mdast/examples/account.error.md Retrieves the next GUID creation number for an account. Requires the account to exist. ```move #[view] public fun get_guid_next_creation_num(addr: address): u64 aborts_if !exists(addr); ensures result == global(addr).guid_creation_num; ``` -------------------------------- ### Set up AptosClient Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/dotnet-sdk/getting-started.mdx Instantiate an AptosClient with a predefined network configuration or your own custom settings. ```csharp using Aptos; class Program { static void Main(string[] args) { var config = new AptosConfig(Aptos.Networks.Mainnet); var client = new AptosClient(config); } } ``` -------------------------------- ### Get Account GUID Next Creation Number Source: https://github.com/aptos-labs/developer-docs/blob/main/packages/aptos-nextra-components/src/utils/mdast/examples/account.error.md Retrieves the next available GUID creation number for an account. This is a view function. ```move #[view] public fun get_guid_next_creation_num(addr: address): u64 ``` ```move public fun get_guid_next_creation_num(addr: address): u64 acquires Account { borrow_global(addr).guid_creation_num } ``` -------------------------------- ### Run Aptos TS SDK Your Coin Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/first-coin.mdx Execute the 'your_coin' example script using pnpm. This demonstrates minting and transferring a custom coin. ```bash pnpm run your_coin ``` -------------------------------- ### Example of Withdrawing Confidential Assets Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/smart-contracts/confidential-asset.mdx Demonstrates how to withdraw confidential assets to another user. This example includes setup, deposit, and withdrawal steps, verifying balances before and after. ```move #[test_only] module confidential_asset_example::withdraw_example { /// ... fun withdraw(bob: &signer, alice: &signer, token: Object) { let bob_addr = signer::address_of(bob); let alice_addr = signer::address_of(alice); // It's a test-only function, so we don't need to worry about the security of the keypair. let (bob_dk, bob_ek) = twisted_elgamal::generate_twisted_elgamal_keypair(); let (_alice_dk, alice_ek) = twisted_elgamal::generate_twisted_elgamal_keypair(); let bob_ek_bytes = twisted_elgamal::pubkey_to_bytes(&bob_ek); let alice_ek_bytes = twisted_elgamal::pubkey_to_bytes(&alice_ek); confidential_asset::register(bob, token, bob_ek_bytes); confidential_asset::register(alice, token, alice_ek_bytes); let bob_current_amount = 500; let bob_new_amount = 450; let transfer_amount = 50; // Bob withdraws all available tokens confidential_asset::deposit(bob, token, (bob_current_amount as u64)); confidential_asset::rollover_pending_balance(bob, token); print(&utf8(b"Alice's FA balance before the withdrawal is zero:")); print(&primary_fungible_store::balance(alice_addr, token)); assert!(primary_fungible_store::balance(alice_addr, token) == 0); print(&utf8(b"Bob's actual balance before the withdrawal is 500")); assert!(confidential_asset::verify_actual_balance(bob_addr, token, &bob_dk, bob_current_amount)); let current_balance = confidential_balance::decompress_balance( &confidential_asset::actual_balance(bob_addr, token) ); let (proof, new_balance) = confidential_proof::prove_withdrawal( &bob_dk, &bob_ek, transfer_amount, bob_new_amount, ¤t_balance ); let new_balance = confidential_balance::balance_to_bytes(&new_balance); let (sigma_proof, zkrp_new_balance) = confidential_proof::serialize_withdrawal_proof(&proof); confidential_asset::withdraw_to( bob, token, alice_addr, transfer_amount, new_balance, zkrp_new_balance, sigma_proof ); print(&utf8(b"Alice's FA balance after the withdrawal is 50:")); print(&primary_fungible_store::balance(alice_addr, token)); assert!(primary_fungible_store::balance(alice_addr, token) == 50); print(&utf8(b"Bob's actual balance after the withdrawal is 450")); assert!(confidential_asset::verify_actual_balance(bob_addr, token, &bob_dk, bob_new_amount)); } } ``` -------------------------------- ### Test Project Initialization with pnpm Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx Executes the quickstart.ts file using ts-node with pnpm to verify the project setup. ```bash pnpx ts-node src/quickstart.ts ``` -------------------------------- ### Example Move Prover Error Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/cli/setup-cli/install-move-prover.mdx This is an example of an error that may occur if the Aptos CLI version is incorrect or multiple versions are installed, leading to syntax issues in Move code. ```bash error: unexpected token ┌─ ~/.move/https___github_com_aptos-labs_aptos-core_git_main/aptos-move/framework/aptos-framework/sources/randomness.move:515:16 │ 515 │ for (i in 0..n) { │ - ^ Expected ')' │ │ │ To match this '(' { "Error": "Move Prover failed: exiting with model building errors" } ``` -------------------------------- ### Example: Registering and Checking Balances Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/smart-contracts/confidential-asset.mdx This test-only example demonstrates how to register a `ConfidentialAssetStore` for a user, generate an encryption key, and then check the initial zero balances and the set encryption key. It also prints messages to indicate the status. ```move #[test_only] module confidential_asset_example::register_example { /// ... fun register(bob: &signer, token: Object) { let bob_addr = signer::address_of(bob); // It's a test-only function, so we don't need to worry about the security of the keypair. let (_bob_dk, bob_ek) = twisted_elgamal::generate_twisted_elgamal_keypair(); let bob_ek = twisted_elgamal::pubkey_to_bytes(&bob_ek); confidential_asset::register(bob, token, bob_ek); print(&utf8(b"Bob's pending balance is zero:")); print(&confidential_asset::pending_balance(bob_addr, token)); print(&utf8(b"Bob's actual balance is zero:")); print(&confidential_asset::actual_balance(bob_addr, token)); print(&utf8(b"Bob's encryption key is set:")); print(&confidential_asset::encryption_key(bob_addr, token)); } } ``` -------------------------------- ### Get GUID Next Creation Number in Move Source: https://github.com/aptos-labs/developer-docs/blob/main/packages/aptos-nextra-components/src/utils/mdast/examples/account.md Retrieves the next GUID creation number for a given account address. This is a view function and requires acquiring the Account resource. ```move #[view] public fun get_guid_next_creation_num(addr: address): u64 acquires Account { borrow_global<Account>(addr).guid_creation_num } ``` -------------------------------- ### Get Account GUID Next Creation Number Source: https://github.com/aptos-labs/developer-docs/blob/main/packages/aptos-nextra-components/src/utils/mdast/examples/account.md Retrieves the next available GUID creation number for an account. Aborts if the account does not exist. Ensures the result matches the account's guid_creation_num. ```move #[view] public fun get_guid_next_creation_num(addr: address): u64 aborts_if !exists<Account>(addr); ensures result == global<Account>(addr).guid_creation_num; ``` -------------------------------- ### Get Address from Signer Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/smart-contracts/book/signer.mdx Example of using the `signer::address_of` function to retrieve the address associated with a signer. ```move signer::address_of(&s) ``` -------------------------------- ### Test Project Initialization with yarn Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx Executes the quickstart.ts file using ts-node with yarn to verify the project setup. ```bash yarn ts-node src/quickstart.ts ``` -------------------------------- ### Navigate to Workspace Directory Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/create-aptos-dapp.mdx Before installing, navigate to the directory where you want to create your project. ```bash cd your/workspace ``` -------------------------------- ### Build and Send APT Transfer Transaction (Kotlin) Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/community-sdks/kotlin-sdk/building-transactions.mdx This example demonstrates the complete process of generating accounts, funding them, building a transaction to transfer APT, signing, submitting, and waiting for its execution. It prints account balances before and after the transaction. Use this for end-to-end transaction testing and demonstration. ```kotlin const val FUNDING_AMOUNT = 100_000_000L const val SEND_AMOUNT_APT = 0.5f const val UNIT_CONVERSION = 100_000_000 const val SEND_AMOUNT_UNITS = (SEND_AMOUNT_APT * UNIT_CONVERSION) const val SEND_AMOUNT = 1_000_000UL /** * This example demonstrates how to transfer APT from one account to another. * * Each run generates and creates new accounts on-chain using faucet funding. After funding, the APT * balance of each account is printed; if funding fails, an error is thrown. * * Next, a transaction is constructed to send 0.5 APT from Alice to Bob. The transaction is then * signed and submitted using the one-step `signAndSubmitTransaction` method. We wait for the * transaction to complete and print the updated balances of Alice and Bob. If the transaction * fails, an error is thrown. */ fun main() = runBlocking { val aptos = Aptos(AptosConfig(AptosSettings(network = Network.DEVNET))) println("Generating Alice and Bob's accounts") val alice = Account.generate() val bob = Account.generate() aptos.fundAccount(alice.accountAddress, FUNDING_AMOUNT).expect("Failed to fund Alice's account") aptos.fundAccount(bob.accountAddress, FUNDING_AMOUNT).expect("Failed to fund Bob's account") println("Created accounts on chain") println("Alice's balance: ${aptos.getAccountAPTAmount(alice.accountAddress)}") println("Bob's balance: ${aptos.getAccountAPTAmount(bob.accountAddress)}") println("=============================================") println( "Building transaction to send ${SEND_AMOUNT / 100_000_000u} APT to Bob: ${bob.accountAddress}" ) val txn = aptos.buildTransaction.simple( sender = alice.accountAddress, data = entryFunctionData { function = "0x1::coin::transfer" typeArguments = typeArguments { +TypeTagStruct("0x1::aptos_coin::AptosCoin") } functionArguments = functionArguments { +bob.accountAddress +U64(SEND_AMOUNT_UNITS.toULong()) } }, ) // Sign and submit the transaction val commitedTransaction = aptos.signAndSubmitTransaction(alice, txn) val executedTransaction = aptos.waitForTransaction( HexInput.fromString(commitedTransaction.expect("Transaction failed").hash) ) println( "Transaction wait response: $executedTransaction\n=============================================" ) val aliceNewBalance = aptos.getAccountAPTAmount(alice.accountAddress).expect("Alice's account does not exist") val bobNewBalance = aptos.getAccountAPTAmount(bob.accountAddress).expect("Bob's account does not exist") println("Alice's new balance: $aliceNewBalance") println("Bob's new balance: $bobNewBalance") } ``` -------------------------------- ### Borrow Address from Signer Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/smart-contracts/book/signer.mdx Example of using the `signer::borrow_address` function to get a reference to the address associated with a signer. ```move signer::borrow_address(&s) ``` -------------------------------- ### Example .csproj with Aptos Package Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/dotnet-sdk/godot-integration.mdx An example of how your .csproj file should look after adding the Aptos NuGet package. Ensure the `` is within an ``. ```xml net6.0 net7.0 net8.0 true AptosSDKExample ``` -------------------------------- ### Aptos CLI Initialization Success Output Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/first-move-module.mdx This is an example of the success output after initializing your Aptos CLI. It confirms the account address and profile setup. ```json { "Result": "Success" } ``` -------------------------------- ### Move Entry Function Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/smart-contracts/move-security-guidelines.mdx The entry modifier indicates entry points for transactions, serving as the starting point of execution when a transaction is submitted to the blockchain. ```move module 0x42::example { entry fun f(){} } ``` -------------------------------- ### Run Go SDK Coin Transfer Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/go-sdk/go-examples.mdx Execute a sample script from the examples directory to demonstrate coin transfer functionality using the Go SDK. ```bash go run examples/transfer_coin/main.go ``` -------------------------------- ### Example Wallet Registration in registry.ts Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/wallet-adapter/browser-extension-wallets.mdx An example demonstrating how to populate the `AptosStandardSupportedWallet` interface with specific wallet details, including name, URL, and icon. ```typescript { name: "Petra" as WalletName<"Petra">, url: "https://chromewebstore.google.com/detail/petra-aptos-wallet/ejjladinnckdgjemekebdpeokbikhfci?hl=en", icon: "data:image/png;base64,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", readyState: WalletReadyState.NotDetected, isAIP62Standard: true, } ``` -------------------------------- ### Run Aptos Dev Setup Script Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/network/nodes/building-from-source.mdx Execute the automated script to prepare your development environment for building Aptos Core. This script handles the installation of necessary dependencies. ```bash ./scripts/dev_setup.sh ``` -------------------------------- ### Set Up Working Directory and Username Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/network/nodes/validator-node/deploy-nodes/using-source-code.mdx Define environment variables for your workspace and username, then create the working directory for your Aptos nodes. ```bash export WORKSPACE=mainnet export USERNAME=alice mkdir ~/$WORKSPACE ``` -------------------------------- ### Python: Initialize Aptos SDK Clients and Accounts Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/guides/first-transaction.mdx Sets up the RestClient and FaucetClient, and generates Alice and Bob accounts for the transaction. ```python import asyncio from aptos_sdk.account import Account from aptos_sdk.async_client import FaucetClient, RestClient from aptos_sdk.transactions import EntryFunction, TransactionPayload, TransactionArgument, RawTransaction from aptos_sdk.bcs import Serializer import time # Network configuration NODE_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()}") ``` -------------------------------- ### npm2yarn Component Example Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/developer-platforms/contribute.mdx Shows how to use the npm2yarn component to easily manage package installations across different package managers like npm, yarn, pnpm, and bun. ```bash npm i -D @aptos-labs/ts-sdk ``` -------------------------------- ### Initialize TypeScript Project with npm Source: https://github.com/aptos-labs/developer-docs/blob/main/apps/nextra/pages/en/build/sdks/ts-sdk/quickstart.mdx Initializes a new npm project, installs TypeScript and related types, initializes TypeScript configuration, creates a source directory, and sets up a basic quickstart.ts file. ```bash 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 ```