### PostgreSQL Installation and Setup (macOS) Source: https://aptos.dev/llms-full.txt Commands to install PostgreSQL C API library, PostgreSQL itself, start the service, create a user, and install the Diesel CLI for PostgreSQL. ```bash export PATH="/opt/homebrew/opt/libpq/bin:$PATH" export LDFLAGS="-L/opt/homebrew/opt/libpq/lib" export CPPFLAGS="-I/opt/homebrew/opt/libpq/include" brew install libpq brew install postgres pg_ctl -D /opt/homebrew/var/postgres start brew services start postgresql /opt/homebrew/bin/createuser -s postgres psql postgres cargo install diesel_cli --no-default-features --features postgres ``` -------------------------------- ### TypeScript: Build and Run Your Coin Example Source: https://aptos.dev/llms-full.txt Clones the aptos-ts-sdk repository, builds the SDK, navigates to the examples directory, installs dependencies, and runs the 'your_coin' example. ```bash git clone https://github.com/aptos-labs/aptos-ts-sdk.git cd aptos-ts-sdk pnpm install pnpm build cd examples/typescript/ pnpm install pnpm run your_coin ``` -------------------------------- ### Complete AptosKit iOS Example Source: https://aptos.dev/build/sdks/community-sdks/kotlin-sdk/for-ios-devs/getting-started A full SwiftUI example demonstrating AptosKit setup and fetching the chain ID on an iOS device. ```swift import SwiftUI import AptosKit struct ContentView: View { @State private var chainId: String? = nil var body: some View { VStack { if let chainId = chainId { Text("Chain ID: \(chainId)") } else { Text("Fetching Chain ID...") } }.padding() .onAppear { fetchChainId() } } private func fetchChainId() { DispatchQueue.main.async { Task { do { let clientConfig = ClientConfig( followRedirects: true, agent: "AptosClient", likeAgent: nil, requestTimeout: 5000, retryOnServerErrors: 3, maxRetries: 5, cache: false, proxy: nil ) let aptosSettings = AptosSettings( network: .devnet, fullNode: nil, faucet: nil, indexer: nil, client: nil, clientConfig: clientConfig, fullNodeConfig: nil, indexerConfig: nil, faucetConfig: nil ) let aptosConfig = AptosConfig(settings: aptosSettings) let aptos = Aptos(config: aptosConfig, graceFull: false) let chainId = try await aptos.getChainId() self.chainId = chainId.expect(message: "Failed...")?.stringValue ?? "null" } catch { print("Failed to get chain ID: \(error)") self.chainId = "Error" } } } } } ``` -------------------------------- ### Clone Example Repository Source: https://aptos.dev/build/indexer/indexer-sdk/advanced-tutorials/migration-guide Clone the example repository to use as a starting point for migration. ```bash git clone https://github.com/aptos-labs/aptos-indexer-processor-example.git ``` -------------------------------- ### Run Aptos .NET Examples Source: https://aptos.dev/build/sdks/dotnet-sdk/dotnet-examples Navigate to the Aptos.Examples directory and execute the .NET run command to start the example applications. Ensure you specify the correct framework version. ```bash cd Aptos.Examples dotnet run --framework net8.0 ``` -------------------------------- ### Local Testnet Startup Output Example Source: https://aptos.dev/network/nodes/localnet/local-development-network This is an example of the expected output when the local Aptos network successfully starts. It provides endpoints for various services. ```text 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! ``` -------------------------------- ### Python: Clone and Install Dependencies for Your Coin Example Source: https://aptos.dev/llms-full.txt Clones the aptos-core repository, navigates to the Python SDK directory, and installs project dependencies using Poetry. ```bash git clone https://github.com/aptos-labs/aptos-core cd aptos-core/ecosystem/python/sdk curl -sSL https://install.python-poetry.org | python3 poetry install ``` -------------------------------- ### Install Aptos Go SDK Source: https://aptos.dev/build/sdks/go-sdk Use this command to get the main Aptos Go SDK package. Ensure you have Go installed and configured. ```go go get github.com/aptos-labs/aptos-go-sdk ``` -------------------------------- ### Run Python Key Rotation Example Source: https://aptos.dev/build/guides/key-rotation Commands to navigate to the Python SDK directory, install dependencies, and run the key rotation example script using Poetry. ```bash cd aptos-core/ecosystem/python/sdkpoetry install && poetry run python -m examples.rotate-key ``` -------------------------------- ### Start Local Aptos Network Source: https://aptos.dev/build/cli/trying-things-on-chain/ledger Starts a local Aptos network. The network is ready when it prints 'Setup is complete, you can now use the localnet!'. ```bash aptos node run-localnet ``` -------------------------------- ### Run TypeScript Key Rotation Example Source: https://aptos.dev/build/guides/key-rotation 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-esmpnpm install && pnpm rotate_key ``` -------------------------------- ### Run Dev Setup Script (macOS/Linux) Source: https://aptos.dev/network/nodes/building-from-source Execute the automated dev setup script to prepare your macOS or Linux environment for building Aptos. Ensure 'brew' is installed on macOS. ```bash ./scripts/dev_setup.sh ``` -------------------------------- ### Aptos SDK Quickstart Example Source: https://aptos.dev/build/sdks/ts-sdk/quickstart This example demonstrates creating accounts, funding them, and transferring APT between them using the Aptos TypeScript SDK. It covers account generation, faucet funding, balance checks, and transaction submission. ```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 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(); ``` -------------------------------- ### Get Account Modules using http package (Dart) Source: https://aptos.dev/rest-api/operations/get_account_modules Fetch account modules in Dart using the http package. This example includes basic setup for an asynchronous GET request. ```dart import 'package:http/http.dart' as http; void main() async { final response = await http.get(Uri.parse('https://api.mainnet.aptoslabs.com/v1/accounts/{address}/modules')); print(response.body); } ``` -------------------------------- ### Aptos Digital Asset Tutorial Setup Source: https://aptos.dev/llms-full.txt Initializes the Aptos client, logs environment variables, and sets up accounts for Alice and Bob. This code demonstrates the initial setup and account funding for the tutorial. ```typescript // Update the TODOs below to customize this digital asset to your needs. // You will want to customize the Collection values and individual Digital Asset values. // This example demonstrates creating a collection, populating it with digital assets, and transferring them. import "dotenv/config"; import { Account, Aptos, AptosConfig, Network, NetworkToNetworkName, } from "@aptos-labs/ts-sdk"; // Verify environment variables are loaded console.log("Environment variables loaded:", { APTOS_NETWORK: process.env.APTOS_NETWORK || "not set" }); const INITIAL_BALANCE = 100_000_000; console.log("Step 1: Setting up a client to connect to Aptos"); const APTOS_NETWORK = NetworkToNetworkName[process.env.APTOS_NETWORK!] || Network.DEVNET; const config = new AptosConfig({ network: APTOS_NETWORK }); const aptos = new Aptos(config); async function example() { console.log("\n=== Step 2: Creating and funding accounts ===\n"); const alice = Account.generate(); const bob = Account.generate(); console.log(`Alice's address: ${alice.accountAddress}`); console.log(`Bob's address: ${bob.accountAddress}`); console.log("Funding Alice's account..."); await aptos.fundAccount({ accountAddress: alice.accountAddress, amount: INITIAL_BALANCE }); console.log("Alice's account funded!"); console.log("Funding Bob's account..."); await aptos.fundAccount({ accountAddress: bob.accountAddress, amount: INITIAL_BALANCE }); console.log("Bob's account funded!"); console.log("\n=== Step 3: Creating a collection ===\n"); // TODO: Update these values to customize your Digital Asset! const collectionName = "Example Collection"; const collectionDescription = "This is an example collection."; const collectionURI = "aptos.dev"; console.log("Building the collection creation transaction..."); const createCollectionTransaction = await aptos.createCollectionTransaction({ creator: alice, description: collectionDescription, name: collectionName, uri: collectionURI, }); console.log("Submitting the collection creation transaction..."); const committedTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: createCollectionTransaction, }); console.log("Waiting for the collection creation transaction to complete..."); await aptos.waitForTransaction({ transactionHash: committedTxn.hash }); console.log("Collection created successfully!"); console.log("\n=== Step 4: Minting a digital asset ===\n"); // TODO: Update the values of the Digital Assets you are minting! const tokenName = "Example Asset"; const tokenDescription = "This is an example digital asset."; const tokenURI = "aptos.dev/asset"; console.log("Building the mint transaction..."); const mintTokenTransaction = await aptos.mintDigitalAssetTransaction({ creator: alice, collection: collectionName, description: tokenDescription, name: tokenName, uri: tokenURI, }); console.log(mintTokenTransaction) console.log("Submitting the mint transaction..."); const mintTxn = await aptos.signAndSubmitTransaction({ signer: alice, transaction: mintTokenTransaction, }); console.log(mintTxn) console.log("Waiting for the mint transaction to complete..."); await aptos.waitForTransaction({ transactionHash: mintTxn.hash }); console.log("Digital asset minted successfully!"); console.log("\n=== Step 5: Transferring the digital asset ===\n"); } example(); ``` -------------------------------- ### Get Transactions using NSURLSession (Objective-C) Source: https://aptos.dev/rest-api/operations/get_transactions This Objective-C example demonstrates how to make a GET request using NSURLSession, the standard networking framework in iOS and macOS. It shows request creation and session setup. ```objectivec #import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.mainnet.aptoslabs.com/v1/transactions"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"GET"]; NSURLSession *session = [NSURLSession sharedSession]; ``` -------------------------------- ### Full Go Example for Aptos Source: https://aptos.dev/llms-full.txt This snippet shows a complete Go program that initializes an Aptos client configuration for the devnet and calls an example function. Ensure you have the Aptos SDK imported. ```go package main import ( "fmt" "aptos" ) func main() { example(aptos.DevnetConfig) } func example(config aptos.Config) { fmt.Printf("Using Aptos config: %+v\n", config) } ``` -------------------------------- ### Get Account Modules using Node.js Axios Source: https://aptos.dev/rest-api/operations/get_account_modules Retrieve account modules using Axios in Node.js. This example includes setup and error handling for the request. ```javascript const axios = require('axios').default; const options = { method: 'GET', url: 'https://api.mainnet.aptoslabs.com/v1/accounts/{address}/modules' }; try { const { data } = await axios.request(options); console.log(data); } catch (error) { console.error(error); } ``` -------------------------------- ### Aptos TypeScript SDK Full Quickstart Example Source: https://aptos.dev/llms-full.txt This example demonstrates creating accounts, funding them, and transferring APT between them using the Aptos TypeScript SDK. It covers account generation, faucet funding, balance checks, transaction building, signing, submission, and verification. ```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 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(); ``` -------------------------------- ### Get Account Modules using Objective-C Foundation Source: https://aptos.dev/rest-api/operations/get_account_modules Basic Objective-C setup for making an HTTP request using Foundation. This is a starting point for iOS/macOS development. ```objectivec #import ``` -------------------------------- ### Get Block by Version using Objective-C Foundation Source: https://aptos.dev/rest-api/operations/get_block_by_version Basic setup for making an HTTP request in Objective-C using Foundation framework. This snippet is a starting point for network operations. ```objectivec #import // ... other imports // Example placeholder for network request setup ``` -------------------------------- ### Full Go Coin Transfer Example Source: https://aptos.dev/llms-full.txt This example shows how to make an APT transfer transaction in the simplest possible way. It includes steps for building, simulating, signing, submitting, and waiting for the transaction, as well as an alternative method for a combined build-sign-submit operation. ```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 = 100_000_000 const 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)} ``` -------------------------------- ### Get Transactions using .NET HttpClient Source: https://aptos.dev/rest-api/operations/get_transactions This example demonstrates how to make a GET request using .NET's HttpClient, similar to the C# example but using a different syntax. ```csharp let httpRequestMessage = new HttpRequestMessage( HttpMethod("get"), new Uri("https://api.mainnet.aptoslabs.com/v1/transactions") ) let client = new HttpClient() let! result = client.SendAsync(httpRequestMessage) ``` -------------------------------- ### Set up AptosClient Source: https://aptos.dev/build/sdks/dotnet-sdk/getting-started Instantiate an AptosClient using a predefined network configuration or a custom one. Ensure the Aptos namespace is included. ```csharp using Aptos; class Program{ static void Main(string[] args) { var config = new AptosConfig(Aptos.Networks.Mainnet); var client = new AptosClient(config); } } ``` -------------------------------- ### Get Creation Number from GUID Source: https://aptos.dev/move-reference/mainnet/aptos-framework/guid Retrieves the creation number associated with a given GUID. This function is part of the GUID module. ```move public fun creation_num(guid: &guid::GUID): u64 ``` ```move // This enforces high-level requirement 2: aborts_if false; ``` -------------------------------- ### Navigate to Move Examples Directory Source: https://aptos.dev/build/cli/working-with-move-contracts/arguments-in-json-tutorial Change your working directory to the cli_args example package within the aptos-core repository. This is a prerequisite for following the deployment steps. ```bash cd /aptos-core/aptos-move/move-examples/cli_args ``` -------------------------------- ### Get Creator Address from GUID Source: https://aptos.dev/move-reference/mainnet/aptos-framework/guid Retrieves the creator address associated with a given GUID. This function is part of the GUID module. ```move public fun creator_address(guid: &guid::GUID): address ``` ```move // This enforces high-level requirement 2: aborts_if false; ``` -------------------------------- ### Get Account Balance with requests (Python) Source: https://aptos.dev/rest-api/operations/get_account_balance A concise way to get account balance using the popular 'requests' library in Python. Ensure 'requests' is installed (`pip install requests`). ```python requests.get( "https://api.mainnet.aptoslabs.com/v1/accounts/{address}/balance/{asset_type}" ) ``` -------------------------------- ### Get Creation Number from GUID Function Source: https://aptos.dev/move-reference/mainnet/aptos-framework/guid Returns the creation number associated with the GUID. ```move public fun creation_num(guid: &GUID): u64 { guid.id.creation_num } ``` -------------------------------- ### Download Trusted Setup Blobs Source: https://aptos.dev/network/nodes/validator-node/modify-nodes/update-trusted-setup Use `wget` to download the `digest_key.bin` and `pp.bin` files. Replace `` with `testnet` or `mainnet`. Ensure you use the correct download URL format to avoid fetching LFS pointers. ```bash wget -O /opt/aptos/genesis/digest_key.bin \ https://github.com/aptos-labs/aptos-networks/raw/main//digest_key.binwget -O /opt/aptos/genesis/pp.bin \ https://github.com/aptos-labs/aptos-networks/raw/main//pp.bin ``` -------------------------------- ### Install Extension from Source Source: https://aptos.dev/build/smart-contracts/move-vscode-extension Builds the extension and installs it locally. Also installs the language server. ```bash cargo run -p xtask -- install --server --client ``` -------------------------------- ### Get ID from GUID Function Source: https://aptos.dev/move-reference/mainnet/aptos-framework/guid Retrieves the non-privileged ID associated with a given GUID. ```move public fun id(guid: &GUID): ID { guid.id } ``` -------------------------------- ### Get Event Handle GUID Source: https://aptos.dev/move-reference/mainnet/aptos-framework/event Returns the GUID associated with an EventHandle. This function is deprecated. ```move public fun guid(handle_ref: &EventHandle): &GUID { &handle_ref.guid } ``` -------------------------------- ### View Dev Setup Script Help (macOS/Linux) Source: https://aptos.dev/network/nodes/building-from-source Display the available options and usage instructions for the dev setup script by running it with the --help flag. This helps in customizing the setup. ```bash ./scripts/dev_setup.sh --help ``` -------------------------------- ### Aptos CLI Initialization Prompts and Output Source: https://aptos.dev/llms-full.txt This example shows the interactive prompts during Aptos CLI initialization with a Ledger device and the expected success output. It includes selecting a network and choosing a Ledger account index. ```bash Configuring for profile Choose network from [devnet, testnet, mainnet, local, custom | defaults to devnet] No network given, using devnet...Please choose an index from the following 5 ledger accounts, or choose an arbitrary index that you want to use:[0] Derivation path: m/44'/637'/0'/0'/0' (Address: 59836ba1dd0c845713bdab34346688d6f1dba290dbf677929f2fc20593ba0cfb)[1] Derivation path: m/44'/637'/1'/0'/0' (Address: 21563230cf6d69ee72a51d21920430d844ee48235e708edbafbc69708075a86e)[2] Derivation path: m/44'/637'/2'/0'/0' (Address: 667446181b3b980ef29f5145a7a2cc34d433fc3ee8c97fc044fd978435f2cb8d)[3] Derivation path: m/44'/637'/3'/0'/0' (Address: 2dcf037a9f31d93e202c074229a1b69ea8ee4d2f2d63323476001c65b0ec4f31)[4] Derivation path: m/44'/637'/4'/0'/0' (Address: 23c579a9bdde1a59f1c9d36d8d379aeefe7a5997b5b58bd5a5b0c12a4f170431) 0Account 59836ba1dd0c845713bdab34346688d6f1dba290dbf677929f2fc20593ba0cfb has been already found on-chain ---Aptos CLI is now set up for account 59836ba1dd0c845713bdab34346688d6f1dba290dbf677929f2fc20593ba0cfb as profile ! Run `aptos --help` for more information about commands{ "Result": "Success" } ``` -------------------------------- ### HTTP Request Example Source: https://aptos.dev/rest-api/operations/get_block_by_height A raw HTTP GET request example for fetching block data. ```http GET /v1/blocks/by_height/{block_height} HTTP/1.1 Host: api.mainnet.aptoslabs.com ``` -------------------------------- ### Initialize AptosClient Source: https://aptos.dev/build/sdks/dotnet-sdk/transactions/basic-transactions Set up your Aptos client by adding the Aptos namespace and instantiating an AptosClient. You can use a predefined configuration from Networks or configure your own. ```csharp using Aptos; class Program{ static void Main(string[] args) { var config = new AptosConfig(Aptos.Networks.Mainnet); var client = new AptosClient(config); } } ``` -------------------------------- ### Set Up Test Environment and Configurations Source: https://aptos.dev/build/indexer/indexer-sdk/advanced-tutorials/processor-test Fetches test configurations, sets up the database, initializes the test context with transactions, and starts a mock gRPC service. Ensure to replace placeholder transaction variables. ```rust let (generate_file_flag, custom_output_path) = get_test_config();let output_path = custom_output_path.unwrap_or_else(|| format!("{}/imported_mainnet_txns", DEFAULT_OUTPUT_FOLDER)); // Setup DB and replace as neededlet mut db = PostgresTestDatabase::new();db.setup().await.unwrap(); let mut test_context = SdkTestContext::new(&[CONST_VARIABLE_OF_YOUR_TEST_TRANSACTION]); // Replace with your test transactionif test_context.init_mock_grpc().await.is_err() { panic!("Failed to initialize mock grpc"); }; ``` -------------------------------- ### Get Creator Address from GUID Function Source: https://aptos.dev/move-reference/mainnet/aptos-framework/guid Returns the account address that originally created the GUID. ```move public fun creator_address(guid: &GUID): address { guid.id.addr } ``` -------------------------------- ### View All Aptos Templates Source: https://aptos.dev/build/cli/start-from-template Run this command to see all available templates and access general help for initializing a package. ```bash aptos move init --help ``` -------------------------------- ### Install TypeScript SDK Dependencies Source: https://aptos.dev/build/guides/first-coin Install the necessary dependencies for the TypeScript examples within the aptos-ts-sdk repository. ```bash cd examples/typescript/ pnpm install ``` -------------------------------- ### Start Aptos Full Node Source: https://aptos.dev/network/nodes/full-node/deployments/using-source-code Run the Aptos node binary with the specified configuration file to start a PFN. Use --release for optimized performance. ```bash cargo run -p aptos-node --release -- -f ./fullnode.yaml ``` -------------------------------- ### Run Multisig Managed Coin Example (Localnet) Source: https://aptos.dev/llms-full.txt Execute the multisig_managed_coin example using a local Aptos instance with a faucet. Set Aptos node and faucet URLs. ```bash export APTOS_NODE_URL=http://0.0.0.0:8080export APTOS_FAUCET_URL=http://0.0.0.0:8081export MODULE_ADDR=${DEFAULT_ACCOUNT_ADDRESS}pnpm run multisig_managed_coin ``` -------------------------------- ### Get Reconfiguration Start Time Source: https://aptos.dev/move-reference/mainnet/aptos-framework/reconfiguration_state Retrieves the Unix timestamp when the current reconfiguration started. Aborts if no reconfiguration is in progress. ```move public(friend) fun start_time_secs(): u64 acquires State { let state = borrow_global(@aptos_framework); let variant_type_name = *state.variant.type_name().bytes(); if (variant_type_name == b"0x1::reconfiguration_state::StateActive") { let active = state.variant.unpack(); active.start_time_secs } else { abort(error::invalid_state(ERECONFIG_NOT_IN_PROGRESS)) } } ``` -------------------------------- ### Rust: Get Transaction by Hash using reqwest Source: https://aptos.dev/rest-api/operations/get_transaction_by_hash Example of making an asynchronous GET request using the reqwest crate. ```rust let client = reqwest::Client::new(); let request = client.get("https://api.mainnet.aptoslabs.com/v1/transactions/by_hash/{txn_hash}"); let response = request.send().await?; ``` -------------------------------- ### Run Aptos Go SDK Coin Transfer Example Source: https://aptos.dev/build/sdks/go-sdk/go-examples Execute a sample script demonstrating coin transfer functionality using the Aptos Go SDK. ```bash go run examples/transfer_coin/main.go ``` -------------------------------- ### Get Transaction by Hash using Unirest Source: https://aptos.dev/rest-api/operations/get_transaction_by_hash Fetch transaction data using the Unirest library. This example shows a concise way to make a GET request and get the response as a string. ```java HttpResponse response = Unirest.get("https://api.mainnet.aptoslabs.com/v1/transactions/by_hash/{txn_hash}") .asString(); ``` -------------------------------- ### Get Events using Unirest (Java) Source: https://aptos.dev/rest-api/operations/get_events_by_creation_number Retrieve events using the Unirest library in Java. This example shows a concise way to make a GET request and get the response as a string. ```java HttpResponse response = Unirest.get("https://api.mainnet.aptoslabs.com/v1/accounts/{address}/events/{creation_number}") .asString(); ``` -------------------------------- ### Download Example Baseline Configurations Source: https://aptos.dev/network/nodes/measure/node-health-checker Download example baseline configuration YAML files for different network environments. These files require modification before use. ```bash mkdir /tmp/nhccd /tmp/nhcconfigs=(devnet_fullnode testnet_fullnode mainnet_fullnode); for c in ${configs[@]}; do wget https://raw.githubusercontent.com/aptos-labs/aptos-core/main/ecosystem/node-checker/configuration_examples/$c.yaml; done ``` -------------------------------- ### Install Python SDK Dependencies with Poetry Source: https://aptos.dev/build/guides/first-coin Install Python dependencies using Poetry. This is required for running the Python SDK examples. ```bash cd aptos-core/ecosystem/python/sdk curl -sSL https://install.python-poetry.org | python3 poetry install ``` -------------------------------- ### Navigate to Example Contract Directory Source: https://aptos.dev/build/cli/working-with-move-contracts/local-simulation-benchmarking-and-gas-profiling Change into the directory of the hello_blockchain example contract. This is a prerequisite for publishing the contract. ```bash cd aptos-move/move-examples/hello_blockchain ``` -------------------------------- ### Raw HTTP GET Request Source: https://aptos.dev/rest-api/operations/get_events_by_creation_number A raw HTTP GET request example showing the necessary headers and path for fetching events. ```http GET /v1/accounts/{address}/events/{creation_number} HTTP/1.1 Host: api.mainnet.aptoslabs.com ``` -------------------------------- ### Initialize Aptos Project with Template Source: https://aptos.dev/build/cli/start-from-template Run this command to initialize a new package using the 'hello-blockchain' template. ```bash aptos move init --name hello_blockchain --template hello-blockchain ``` -------------------------------- ### Get Event Handle GUID (Deprecated) Source: https://aptos.dev/move-reference/mainnet/aptos-framework/event Deprecated function to retrieve the GUID associated with an event handle. Always returns successfully. ```move #[deprecated] public fun guid(handle_ref: &event::EventHandle): &guid::GUID ``` ```move // This enforces high-level requirement 5: aborts_if false; ``` -------------------------------- ### Aptos Staking Contract Example Source: https://aptos.dev/llms-full.txt This example demonstrates the setup of a staking contract within the Aptos framework, enabling staking functionalities. ```move module aptos_examples::staking_example { use aptos_framework::staking_contract; struct MY_STAKING_CONTRACT has drop, store {} #[test] fun main() { staking_contract::initialize(); } } ``` -------------------------------- ### Full Go Example for Aptos Transaction Source: https://aptos.dev/build/sdks/go-sdk/building-transactions This example demonstrates the complete lifecycle of an Aptos transaction using the Go SDK. It covers account creation, funding, building, simulating, signing, submitting, and waiting for transaction completion. It also shows two methods for building and submitting transactions: a step-by-step approach and a combined 'BuildSignAndSubmitTransaction' approach. ```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 (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) } ``` -------------------------------- ### Run Multisig Managed Coin Example (Devnet) Source: https://aptos.dev/llms-full.txt Execute the multisig_managed_coin example using Aptos devnet. Ensure devnet is live. ```bash MODULE_ADDR=${DEFAULT_ACCOUNT_ADDRESS} pnpm run multisig_managed_coin ``` -------------------------------- ### Get Reconfig Start Time Function Signature Source: https://aptos.dev/move-reference/mainnet/aptos-framework/stake Declares the `get_reconfig_start_time_secs` function, which returns the current reconfiguration start time in seconds. ```move fun get_reconfig_start_time_secs(): u64 ```