### Quick Start: Aptos Go SDK Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md A basic example demonstrating how to initialize an Aptos client, create a new Ed25519 account, fund it, and check its APT balance on the Aptos testnet. ```go package main import ( "fmt" "log" "github.com/aptos-labs/aptos-go-sdk" ) func main() { client, err := aptos.NewClient(aptos.TestnetConfig) if err != nil { log.Fatal(err) } account, err := aptos.NewEd25519Account() if err != nil { log.Fatal(err) } err = client.Fund(account.AccountAddress(), 100_000_000) if err != nil { log.Fatal(err) } balance, err := client.AccountAPTBalance(account.AccountAddress()) if err != nil { log.Fatal(err) } fmt.Printf("Balance: %d octas\n", balance) } ``` -------------------------------- ### Install Aptos Go SDK Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Installs the Aptos Go SDK using the go get command. This is the primary step to include the SDK in your Go project. ```bash go get github.com/aptos-labs/aptos-go-sdk ``` -------------------------------- ### Test Utilities Setup (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Shows the usage of the `testutil` package in v2 for creating fake clients and setting up mock account states. This is useful for unit testing interactions with the Aptos network. ```go import "github.com/aptos-labs/aptos-go-sdk/v2/testutil" // Create fake client for testing fake := testutil.NewFakeClient() fake.SetAccount(addr, &aptos.AccountInfo{...}) // Use in tests result, err := myFunction(fake) ``` -------------------------------- ### Install and Run aptosfix Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/cmd/aptosfix/README.md Commands to install the migration tool via Go and execute it against project files to perform automated code updates. ```bash go install github.com/aptos-labs/aptos-go-sdk/v2/cmd/aptosfix@latest aptosfix -w ./... ``` -------------------------------- ### Keyless Authentication Setup (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Introduces the new keyless authentication feature in v2, utilizing ZK-based and social login methods. This snippet shows the basic setup for creating a keyless account. ```go import "github.com/aptos-labs/aptos-go-sdk/v2/keyless" // Create keyless account (ZK-based, social login) config := keyless.Config{ // Configuration } account, err := keyless.NewAccount(config) ``` -------------------------------- ### Structured Logging Configuration (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Illustrates how to configure structured logging with the `slog` package in Go v2. The example shows creating a JSON logger and passing it to the Aptos client configuration. ```go import "log/slog" logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) client, _ := aptos.NewClient(aptos.Testnet, aptos.WithLogger(logger)) ``` -------------------------------- ### Write New Integration Test (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/INTEGRATION_TESTS.md Example of a new integration test in Go for the Aptos SDK. It demonstrates best practices like skipping short tests, running in parallel, obtaining a test client and context, and asserting results. ```go func TestIntegration_NewFeature(t *testing.T) { skipIfShort(t) t.Parallel() client := createTestClient(t) ctx := testContext(t) result, err := client.NewFeature(ctx, ...) require.NoError(t, err) assert.NotNil(t, result) t.Logf("NewFeature result: %+v", result) } ``` -------------------------------- ### Migration Example: v1 to v2 Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/cmd/aptosfix/README.md A comparison showing the necessary code changes when migrating from v1 to v2, specifically the addition of context.Context to client method calls. ```go // Before (v1) import "github.com/aptos-labs/aptos-go-sdk" client, _ := aptos.NewClient(aptos.Testnet) info, _ := client.Info() // After (v2) import ( "context" "github.com/aptos-labs/aptos-go-sdk/v2" ) ctx := context.Background() client, _ := aptos.NewClient(aptos.Testnet) info, _ := client.Info(ctx) ``` -------------------------------- ### Aptos Names Service (ANS) Client Operations in Go Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to use the ANS client from the aptos-go-sdk to resolve names to addresses, retrieve primary names, check name availability, and get detailed name information. It also includes examples for generating payloads for registering, setting primary names, setting target addresses, and renewing names. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" "github.com/aptos-labs/aptos-go-sdk/v2/account" "github.com/aptos-labs/aptos-go-sdk/v2/ans" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Mainnet) // Create ANS client ansClient := ans.NewClient(client) // For testnet, use: // ansClient := ans.NewTestnetClient(client) // Resolve a name to an address address, err := ansClient.Resolve(ctx, "alice.apt") if err != nil { if err == ans.ErrNameNotFound { fmt.Println("Name not registered") } else if err == ans.ErrNameExpired { fmt.Println("Name registration has expired") } else { log.Fatal(err) } } else { fmt.Printf("alice.apt resolves to: %s\n", address) } // Get primary name for an address primaryName, err := ansClient.GetPrimaryName(ctx, address) if err != nil { fmt.Printf("No primary name for address: %v\n", err) } else { fmt.Printf("Primary name: %s\n", primaryName) } // Check if a name is available available, err := ansClient.IsAvailable(ctx, "myname.apt") if err != nil { log.Fatal(err) } fmt.Printf("myname.apt available: %v\n", available) // Get detailed name information name, _ := ans.ParseName("alice.apt") nameInfo, err := ansClient.GetNameInfo(ctx, *name) if err == nil { fmt.Printf("Name: %s\n", nameInfo.Name.String()) fmt.Printf("Target: %s\n", nameInfo.Target) fmt.Printf("Expires: %s\n", nameInfo.ExpiresAt) fmt.Printf("Is Expired: %v\n", nameInfo.IsExpired()) } // Register a name (requires funded account) sender, _ := account.NewEd25519() registerPayload, err := ansClient.RegisterPayload("mynewname.apt", ans.RegisterOptions{ Years: 1, }) if err != nil { log.Fatal(err) } // Submit registration transaction _, err = client.SignAndSubmitTransaction(ctx, sender, registerPayload) if err != nil { fmt.Printf("Registration error (expected without funds): %v\n", err) } // Set primary name setPrimaryPayload, _ := ansClient.SetPrimaryNamePayload("mynewname.apt") _ = setPrimaryPayload // Use with SignAndSubmitTransaction // Set target address setTargetPayload, _ := ansClient.SetTargetAddressPayload("mynewname.apt", address) _ = setTargetPayload // Use with SignAndSubmitTransaction // Renew a name renewPayload, _ := ansClient.RenewPayload("mynewname.apt", 1) _ = renewPayload // Use with SignAndSubmitTransaction } ``` -------------------------------- ### BCS Serialization with Aptos Go SDK v2 Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Provides an example of using the reflection-based BCS (Binary Canonical Serialization) marshaling in Aptos Go SDK v2. It shows how to define a struct with `bcs` tags and then serialize an instance of that struct into byte data. ```go // v2 - reflection-based serialization type MyStruct struct { Value uint64 `bcs:"value"` Name string `bcs:"name"` } data, err := bcs.Marshal(&MyStruct{Value: 42, Name: "test"}) ``` -------------------------------- ### Querying Blocks and Transactions in Go Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Provides examples for querying blockchain state, including block details by height or version, and transaction details by hash, version, or account address. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Testnet) info, _ := client.Info(ctx) fmt.Printf("Current block height: %d\n", info.BlockHeight) fmt.Printf("Current ledger version: %d\n", info.LedgerVersion) block, err := client.BlockByHeight(ctx, info.BlockHeight-10, false) if err != nil { log.Fatal(err) } fmt.Printf("Block %d:\n", block.BlockHeight) fmt.Printf(" Hash: %s\n", block.BlockHash) blockWithTxns, err := client.BlockByHeight(ctx, info.BlockHeight-10, true) if err != nil { log.Fatal(err) } fmt.Printf("Block has %d transactions\n", len(blockWithTxns.Transactions)) limit := uint64(5) transactions, err := client.Transactions(ctx, nil, &limit) if err != nil { log.Fatal(err) } for _, txn := range transactions { fmt.Printf(" %s - Version: %d, Success: %v\n", txn.Hash, txn.Version, txn.Success) } txnByVersion, err := client.TransactionByVersion(ctx, info.LedgerVersion-50) if err != nil { log.Fatal(err) } fmt.Printf("\nTransaction at version %d: %s\n", info.LedgerVersion-50, txnByVersion.Hash) } ``` -------------------------------- ### Generate Type-Safe Go Code from Move ABIs Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Provides command-line instructions to install the aptosgen tool and generate Go code from on-chain Move modules or local ABI JSON files. ```bash # Install the generator go install github.com/aptos-labs/aptos-go-sdk/cmd/aptosgen@latest # Generate from on-chain module aptosgen -address 0x1 -module coin -package coin -output coin/ # Generate from local ABI file aptosgen -abi coin.json -package coin -output coin/ ``` -------------------------------- ### Iterating Over Transactions (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Demonstrates the new iterator pattern introduced in v2 for efficiently handling large result sets, such as streaming transactions without loading them all into memory. Includes examples using `Take`, `Filter`, and `Collect` from the `iter` package. ```go // Iterate over transactions without loading all into memory for txn, err := range client.TransactionsIter(ctx, nil) { if err != nil { log.Fatal(err) } fmt.Println(txn.Hash) } ``` ```go import "github.com/aptos-labs/aptos-go-sdk/v2/iter" // Take first 10 first10 := iter.Take(client.TransactionsIter(ctx, nil), 10) // Filter userTxns := iter.Filter(client.TransactionsIter(ctx, nil), func(t *Transaction, _ error) bool { return t.Type == "user_transaction" }) // Collect to slice txns, err := iter.Collect(iter.Take(client.TransactionsIter(ctx, nil), 100)) ``` -------------------------------- ### Migrating Aptos Go SDK Import Paths from v1 to v2 Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Illustrates the change in import paths when migrating from version 1 to version 2 of the Aptos Go SDK. The v2 SDK uses a versioned import path to allow for parallel installation with v1. ```go // v1 import "github.com/aptos-labs/aptos-go-sdk" // v2 import aptos "github.com/aptos-labs/aptos-go-sdk/v2" ``` -------------------------------- ### GET /v1/info Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Retrieves general information about the Aptos blockchain node, including the current chain ID, block height, and ledger version. ```APIDOC ## GET /v1/info ### Description Retrieves the current ledger information from the connected Aptos node. ### Method GET ### Endpoint /v1/info ### Parameters None ### Request Example client.Info(ctx) ### Response #### Success Response (200) - **ChainID** (uint8) - The ID of the blockchain network. - **BlockHeight** (uint64) - The current block height. - **LedgerVersion** (uint64) - The current ledger version. #### Response Example { "chain_id": 2, "block_height": 12345678, "ledger_version": 12345678 } ``` -------------------------------- ### GET /transactions (Iterator) Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Retrieves an iterator for streaming transactions from the Aptos blockchain, allowing for memory-efficient processing of large transaction histories. ```APIDOC ## GET /transactions (Iterator) ### Description Provides a streaming interface to fetch transactions from the Aptos network. This method returns an iterator that can be consumed to process transactions one by one or in batches. ### Method GET ### Endpoint client.TransactionsIter(ctx, options) ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - The context for the request lifecycle. #### Query Parameters - **options** (interface{}) - Optional - Configuration options for transaction retrieval (e.g., limit, start version). ### Request Example ```go iter := client.TransactionsIter(ctx, nil) ``` ### Response #### Success Response (200) - **txn** (*aptos.Transaction) - The transaction object containing hash, success status, and gas metrics. #### Response Example ```json { "Hash": "0x123...", "Success": true, "GasUsed": 100 } ``` ``` -------------------------------- ### Configure Client with Options Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Shows how to initialize a client with custom timeouts, retry logic, and API key authentication. ```go client, err := aptos.NewClient(aptos.Mainnet, aptos.WithTimeout(30 * time.Second), aptos.WithRetry(3, 100*time.Millisecond), aptos.WithAPIKey("your-api-key"), ) ``` -------------------------------- ### Initialize Client and Fetch Account Info Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Demonstrates how to create an Aptos client for Devnet and retrieve account sequence information. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() client, err := aptos.NewClient(aptos.Devnet) if err != nil { log.Fatal(err) } address := aptos.MustParseAddress("0x1") info, err := client.Account(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Sequence number: %d\n", info.SequenceNumber) } ``` -------------------------------- ### Initialize and Configure Aptos Client Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to instantiate an Aptos client for various networks and apply custom configurations such as timeouts, retries, and API keys. It also shows how to retrieve basic chain information. ```go package main import ( "context" "fmt" "log" "time" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() // Create a client for testnet with default options client, err := aptos.NewClient(aptos.Testnet) if err != nil { log.Fatal(err) } // Create a client with custom options clientWithOptions, err := aptos.NewClient(aptos.Mainnet, aptos.WithTimeout(60*time.Second), aptos.WithRetry(5, 200*time.Millisecond), aptos.WithAPIKey("your-api-key"), aptos.WithHeader("X-Custom-Header", "value"), ) if err != nil { log.Fatal(err) } // Get node information info, err := client.Info(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", info.ChainID) fmt.Printf("Block Height: %d\n", info.BlockHeight) fmt.Printf("Ledger Version: %d\n", info.LedgerVersion) _ = clientWithOptions } ``` -------------------------------- ### ANS Client Initialization and Usage (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Demonstrates the integration of the Aptos Names Service (ANS) in v2. It shows how to create an `ans.Client` and use it for resolving addresses from names and performing reverse lookups. ```go import "github.com/aptos-labs/aptos-go-sdk/v2/ans" ansClient := ans.NewClient(client) address, err := ansClient.Resolve(ctx, "myname.apt") name, err := ansClient.ReverseLookup(ctx, address) ``` -------------------------------- ### Query Account Information and Resources with Aptos Go SDK Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to parse addresses, retrieve account metadata, check APT balances, and fetch account-specific resources or modules using the Aptos Client. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Testnet) address := aptos.MustParseAddress("0x1") accountInfo, err := client.Account(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Sequence Number: %d\n", accountInfo.SequenceNumber) fmt.Printf("Auth Key: %s\n", accountInfo.AuthenticationKey) balance, err := client.AccountBalance(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Balance: %d octas (%.4f APT)\n", balance, float64(balance)/1e8) resources, err := client.AccountResources(ctx, address) if err != nil { log.Fatal(err) } for _, resource := range resources { fmt.Printf("Resource: %s\n", resource.Type) } coinResource, err := client.AccountResource(ctx, address, "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>") if err != nil { log.Fatal(err) } fmt.Printf("Coin data: %v\n", coinResource.Data) module, err := client.AccountModule(ctx, aptos.AccountOne, "coin") if err != nil { log.Fatal(err) } fmt.Printf("Module has %d exposed functions\n", len(module.ABI.ExposedFunctions)) } ``` -------------------------------- ### Testing with Aptos Go SDK Test Utilities Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Demonstrates how to use the `testutil` package to create a fake Aptos client for testing. It shows how to mock accounts, balances, and record client interactions for verification. This is useful for unit testing your Aptos-related Go code without needing a live network connection. ```go import "github.com/aptos-labs/aptos-go-sdk/v2/testutil" func TestMyFunction(t *testing.T) { // Create a fake client client := testutil.NewFakeClient(). WithAccount(addr, &aptos.AccountInfo{SequenceNumber: 5}). WithBalance(addr, 100_000_000). WithRecording() // Test your code result, err := myFunction(client, addr) require.NoError(t, err) // Verify interactions calls := client.RecordedCalls() assert.Len(t, calls, 2) } ``` -------------------------------- ### Aptos Network Configuration Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Demonstrates how to initialize an Aptos client for different networks: Testnet, Devnet, Mainnet, and a local node. ```go // Testnet (recommended for development) client, _ := aptos.NewClient(aptos.TestnetConfig) // Devnet (resets weekly) client, _ := aptos.NewClient(aptos.DevnetConfig) // Mainnet client, _ := aptos.NewClient(aptos.MainnetConfig) // Local node client, _ := aptos.NewClient(aptos.LocalnetConfig) ``` -------------------------------- ### Estimate Gas Prices using Aptos Go SDK Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt This snippet demonstrates how to initialize an Aptos client and fetch gas price estimates. It also shows how to calculate the total transaction cost based on the estimated gas price and a specified gas limit. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Testnet) // Get gas price estimates gasEstimate, err := client.EstimateGasPrice(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Gas Price Estimates:\n") fmt.Printf(" Standard: %d octas per gas unit\n", gasEstimate.GasEstimate) fmt.Printf(" Deprioritized: %d octas per gas unit\n", gasEstimate.DeprioritizedGasEstimate) fmt.Printf(" Prioritized: %d octas per gas unit\n", gasEstimate.PrioritizedGasEstimate) // Calculate estimated transaction cost maxGas := uint64(2000) estimatedCost := maxGas * gasEstimate.GasEstimate fmt.Printf("\nEstimated max cost for 2000 gas units: %d octas (%.6f APT)\n", estimatedCost, float64(estimatedCost)/1e8) prioritizedCost := maxGas * gasEstimate.PrioritizedGasEstimate fmt.Printf("Prioritized max cost for 2000 gas units: %d octas (%.6f APT)\n", prioritizedCost, float64(prioritizedCost)/1e8) } ``` -------------------------------- ### Creating Aptos Go SDK Clients: v1 vs v2 Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Shows the difference in client creation between Aptos Go SDK v1 and v2. Version 2 introduces functional options for configuring the client, such as setting timeouts, which were not available in v1. ```go // v1 client, err := aptos.NewClient(aptos.DevnetConfig) // v2 client, err := aptos.NewClient(aptos.Devnet, aptos.WithTimeout(30*time.Second), ) ``` -------------------------------- ### Simulate Transactions with Aptos Go SDK Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Shows how to simulate a transaction to estimate gas costs and verify success before on-chain execution. This pattern helps prevent failed transactions by checking the VM status and gas usage beforehand. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" "github.com/aptos-labs/aptos-go-sdk/v2/account" "github.com/aptos-labs/aptos-go-sdk/v2/transaction" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Devnet) sender, _ := account.NewEd25519() recipient := aptos.MustParseAddress("0x456") client.Fund(ctx, sender.Address(), 100_000_000) rawTxn, err := transaction.TransferAPT(sender.Address(), recipient, 1_000_000). Build(ctx, client) if err != nil { log.Fatal(err) } simResult, err := client.SimulateTransaction(ctx, rawTxn, sender.Signer()) if err != nil { log.Fatal(err) } fmt.Printf("Simulation success: %v\n", simResult.Success) if !simResult.Success { log.Fatalf("Simulation failed: %s", simResult.VMStatus) } signedTxn, _ := aptos.SignTransaction(sender.Signer(), rawTxn) submitResult, err := client.SubmitTransaction(ctx, signedTxn) if err != nil { log.Fatal(err) } fmt.Printf("Transaction submitted: %s\n", submitResult.Hash) } ``` -------------------------------- ### Sign and Submit Transactions with Aptos Go SDK Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates two methods for handling transactions: manually building, signing, and submitting, or using the convenience SignAndSubmitTransaction method. These methods require an initialized client and a valid account signer. ```go package main import ( "context" "fmt" "log" "time" aptos "github.com/aptos-labs/aptos-go-sdk/v2" "github.com/aptos-labs/aptos-go-sdk/v2/account" "github.com/aptos-labs/aptos-go-sdk/v2/transaction" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Devnet) sender, _ := account.NewEd25519() recipient := aptos.MustParseAddress("0x456") client.Fund(ctx, sender.Address(), 100_000_000) rawTxn, err := transaction.TransferAPT(sender.Address(), recipient, 1_000_000). Build(ctx, client) if err != nil { log.Fatal(err) } signedTxn, err := aptos.SignTransaction(sender.Signer(), rawTxn) if err != nil { log.Fatal(err) } submitResult, err := client.SubmitTransaction(ctx, signedTxn) if err != nil { log.Fatal(err) } fmt.Printf("Submitted transaction: %s\n", submitResult.Hash) confirmedTxn, err := client.WaitForTransaction(ctx, submitResult.Hash, aptos.WithPollInterval(500*time.Millisecond), aptos.WithPollTimeout(30*time.Second), ) if err != nil { log.Fatal(err) } fmt.Printf("Transaction confirmed! Success: %v\n", confirmedTxn.Success) payload := &aptos.EntryFunctionPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "aptos_account"}, Function: "transfer", TypeArgs: nil, Args: []any{recipient.Bytes(), uint64(500_000)}, } result, err := client.SignAndSubmitTransaction(ctx, sender, payload, aptos.WithMaxGas(2000), aptos.WithGasPrice(100), ) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", result.Hash) } ``` -------------------------------- ### Configure Client with Functional Options Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md v2 replaces struct-based configuration with functional options, allowing for cleaner and more flexible client initialization. ```go client, err := aptos.NewClient( aptos.Testnet, aptos.WithTimeout(10*time.Second), aptos.WithHeader("Authorization", "Bearer token"), aptos.WithRetry(3, time.Second), ) ``` -------------------------------- ### Run All Integration Tests (Bash) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/INTEGRATION_TESTS.md Executes all integration tests for the v2 SDK using the go test command. It includes verbose output, a specific test pattern, and a timeout. This command is suitable for a comprehensive test run. ```bash go test -v -run "TestIntegration_" -timeout 120s ./v2/... ``` -------------------------------- ### Instrument HTTP Client with OpenTelemetry Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Shows how to configure an instrumented HTTP client using the Aptos telemetry package to enable observability in your application. ```go import "github.com/aptos-labs/aptos-go-sdk/telemetry" httpClient, _ := telemetry.NewInstrumentedHTTPClient( telemetry.WithServiceName("my-app"), ) client, _ := aptos.NewNodeClientWithHttpClient( aptos.MainnetConfig.NodeUrl, aptos.MainnetConfig.ChainId, httpClient, ) ``` -------------------------------- ### Implement Sponsored (Fee Payer) Transactions in Go Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to use a third-party sponsor to cover gas fees for a transaction. The snippet provides both a high-level convenience method and a manual flow for granular control over signing messages. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" "github.com/aptos-labs/aptos-go-sdk/v2/account" "github.com/aptos-labs/aptos-go-sdk/v2/sponsored" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Devnet) sender, _ := account.NewEd25519() sponsor, _ := account.NewEd25519() recipient := aptos.MustParseAddress("0x456") client.Fund(ctx, sponsor.Address(), 100_000_000) payload := &aptos.EntryFunctionPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "aptos_account"}, Function: "transfer", TypeArgs: nil, Args: []any{recipient.Bytes(), uint64(1_000_000)}, } result, err := sponsored.SignAndSubmitSponsoredTransaction( ctx, client, sender, sponsor, payload, aptos.WithMaxGas(2000), ) if err != nil { log.Fatal(err) } fmt.Printf("Sponsored transaction submitted: %s\n", result.Hash) fpTxn, err := sponsored.BuildFeePayerTransaction( ctx, client, sender.Address(), sponsor.Address(), payload, ) if err != nil { log.Fatal(err) } signingMsg, _ := fpTxn.SigningMessage() senderAuth, _ := sender.Sign(signingMsg) sponsorAuth, _ := sponsor.Sign(signingMsg) signedTxn, err := fpTxn.Sign(senderAuth, nil, sponsorAuth) if err != nil { log.Fatal(err) } submitResult, err := client.SubmitTransaction(ctx, signedTxn) if err != nil { log.Fatal(err) } fmt.Printf("Manual sponsored transaction: %s\n", submitResult.Hash) } ``` -------------------------------- ### Build and Send Transactions Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Demonstrates building custom transactions via the fluent builder and using convenience methods for token transfers. ```go txn, err := transaction.New(). Sender(senderAddress). EntryFunction("0x1::aptos_account::transfer", nil, recipientAddress.Bytes(), uint64(1_000_000), ). MaxGas(2000). GasPrice(100). Build(ctx, client) txn, err = transaction.TransferAPT(sender, recipient, 1_000_000).Build(ctx, client) ``` -------------------------------- ### Implement Keyless Authentication Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/README.md Shows the workflow for generating ephemeral keys and deriving addresses from OIDC claims. ```go ephemeralKeyPair, err := keyless.GenerateEphemeralKeyPair(time.Hour) nonce := ephemeralKeyPair.Nonce() claims, err := keyless.ParseJWT(jwtToken) address, err := keyless.DeriveAddress(claims, "sub", pepper) ``` -------------------------------- ### Account Creation (Go) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Shows account creation methods. While the API appears similar between v1 and v2 for `NewEd25519Account`, the import path for `NewEd25519SingleSenderAccount` has changed to `NewEd25519SingleSignerAccount` in v2. ```go account, err := aptos.NewEd25519Account() singleSigner, err := aptos.NewEd25519SingleSenderAccount() ``` ```go // Same API, just different import account, err := aptos.NewEd25519Account() singleSigner, err := aptos.NewEd25519SingleSignerAccount() ``` -------------------------------- ### Querying Blockchain State with View Functions Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to use the client.View method to read on-chain data such as account balances and existence checks. It also shows how to perform historical queries by specifying a ledger version. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Testnet) address := aptos.MustParseAddress("0x1") // Call a view function to get coin balance result, err := client.View(ctx, &aptos.ViewPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "coin"}, Function: "balance", TypeArgs: []aptos.TypeTag{aptos.AptosCoinTypeTag}, Args: []any{address.String()}, }) if err != nil { log.Fatal(err) } fmt.Printf("Balance result: %v\n", result) // Check if an account exists existsResult, err := client.View(ctx, &aptos.ViewPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "account"}, Function: "exists_at", TypeArgs: nil, Args: []any{address.String()}, }) if err != nil { log.Fatal(err) } fmt.Printf("Account exists: %v\n", existsResult[0]) // Query at a specific ledger version (historical query) historicalResult, err := client.View(ctx, &aptos.ViewPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "coin"}, Function: "balance", TypeArgs: []aptos.TypeTag{aptos.AptosCoinTypeTag}, Args: []any{address.String()}, }, aptos.AtLedgerVersion(1000000)) // Query at ledger version 1M if err != nil { fmt.Printf("Historical query error: %v\n", err) } else { fmt.Printf("Historical balance: %v\n", historicalResult) } } ``` -------------------------------- ### Resolve and Manage Aptos Names Service (ANS) Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Demonstrates how to initialize an ANS client to resolve domain names to addresses, retrieve primary names for specific addresses, and check the availability of new names. ```go ansClient := aptos.NewANSClient(client) // Resolve name to address address, err := ansClient.Resolve("alice.apt") // Get primary name for address name, err := ansClient.GetPrimaryName(address) // Check availability available, err := ansClient.IsAvailable("myname") ``` -------------------------------- ### Manage Aptos Accounts and Keys Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Covers account generation using different cryptographic schemes (Ed25519, Secp256k1) and importing accounts from private keys or AIP-80 strings. It also demonstrates how to derive authentication and public keys. ```go package main import ( "fmt" "log" "github.com/aptos-labs/aptos-go-sdk/v2/account" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { // Generate a new Ed25519 account ed25519Account, err := account.NewEd25519() if err != nil { log.Fatal(err) } fmt.Printf("Ed25519 Address: %s\n", ed25519Account.Address()) // Generate a Secp256k1 account secp256k1Account, err := account.NewSecp256k1() if err != nil { log.Fatal(err) } fmt.Printf("Secp256k1 Address: %s\n", secp256k1Account.Address()) // Generate Ed25519 with SingleKeyScheme singleKeyAccount, err := account.NewEd25519SingleKey() if err != nil { log.Fatal(err) } fmt.Printf("SingleKey Address: %s\n", singleKeyAccount.Address()) // Import from hex-encoded private key importedAccount, err := account.FromPrivateKeyHex("0x1234567890abcdef...") if err != nil { log.Fatal(err) } fmt.Printf("Imported Address: %s\n", importedAccount.Address()) // Import from AIP-80 formatted string aip80Account, err := account.FromAIP80("ed25519-priv-0x...") if err != nil { log.Fatal(err) } fmt.Printf("AIP-80 Address: %s\n", aip80Account.Address()) // Direct key generation using crypto package privKey, err := aptos.GenerateEd25519PrivateKey() if err != nil { log.Fatal(err) } // Get authentication key and derive address authKey := privKey.AuthKey() fmt.Printf("Auth Key: %x\n", authKey[:]) // Public key for verification pubKey := privKey.PubKey() fmt.Printf("Public Key: %x\n", pubKey.Bytes()) } ``` -------------------------------- ### Batch Transaction Submission in Go Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Demonstrates how to build and submit multiple transactions in a single request to improve throughput. It involves creating signed transactions with sequential sequence numbers and handling potential submission failures. ```go package main import ( "context" "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" "github.com/aptos-labs/aptos-go-sdk/v2/account" ) func main() { ctx := context.Background() client, _ := aptos.NewClient(aptos.Devnet) sender, _ := account.NewEd25519() client.Fund(ctx, sender.Address(), 100_000_000) recipient := aptos.MustParseAddress("0x456") var signedTxns []*aptos.SignedTransaction accountInfo, _ := client.Account(ctx, sender.Address()) seqNum := accountInfo.SequenceNumber for i := 0; i < 5; i++ { payload := &aptos.EntryFunctionPayload{ Module: aptos.ModuleID{Address: aptos.AccountOne, Name: "aptos_account"}, Function: "transfer", TypeArgs: nil, Args: []any{recipient.Bytes(), uint64(100_000)}, } rawTxn, err := client.BuildTransaction(ctx, sender.Address(), payload, aptos.WithSequenceNumber(seqNum+uint64(i)), aptos.WithMaxGas(2000), ) if err != nil { log.Fatal(err) } signedTxn, err := aptos.SignTransaction(sender.Signer(), rawTxn) if err != nil { log.Fatal(err) } signedTxns = append(signedTxns, signedTxn) } batchResult, err := client.BatchSubmitTransaction(ctx, signedTxns) if err != nil { log.Fatal(err) } if len(batchResult.TransactionFailures) > 0 { for _, failure := range batchResult.TransactionFailures { fmt.Printf("Transaction %d failed: %s\n", failure.TransactionIndex, failure.Error.Message) } } else { fmt.Printf("Successfully submitted %d transactions\n", len(signedTxns)) } } ``` -------------------------------- ### Working with Type Tags Source: https://context7.com/aptos-labs/aptos-go-sdk/llms.txt Explains how to use and manipulate Move type tags within the Aptos Go SDK, covering parsing, predefined tags, manual creation, and various type constructors. ```APIDOC ## Working with Type Tags Type tags represent Move types and are used for generic type arguments in entry functions and view calls. The SDK provides utilities for parsing and creating type tags. ### Parsing Type Tags ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { // Parse type tag from string coinType, err := aptos.ParseTypeTag("0x1::aptos_coin::AptosCoin") if err != nil { log.Fatal(err) } fmt.Printf("Coin type: %s\n", coinType.String()) } ``` ### Predefined Type Tags ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { // Use predefined APT coin type tag aptCoin := aptos.AptosCoinTypeTag fmt.Printf("APT coin: %s\n", aptCoin.String()) } ``` ### Creating Custom Type Tags #### Struct Type Tag ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { structTag := &aptos.StructTag{ Address: aptos.AccountOne, Module: "coin", Name: "CoinStore", TypeParams: []aptos.TypeTag{ aptos.AptosCoinTypeTag, }, } fmt.Printf("CoinStore type: %s\n", structTag.String()) } ``` #### Vector Type ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { vectorTag := aptos.NewVectorTag(aptos.NewTypeTag(&aptos.U8Tag{})) fmt.Printf("Vector: %s\n", vectorTag.String()) } ``` #### String Type ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { stringTag := aptos.NewStringTag() fmt.Printf("String type: %s\n", stringTag.String()) } ``` #### Option Type ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { optionTag := aptos.NewOptionTag(aptos.AptosCoinTypeTag) fmt.Printf("Option type: %s\n", optionTag.String()) } ``` #### Object Type ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { objectTag := aptos.NewObjectTag(aptos.AptosCoinTypeTag) fmt.Printf("Object type: %s\n", objectTag.String()) } ``` ### Primitive Type Tags ```go package main import ( "fmt" "log" aptos "github.com/aptos-labs/aptos-go-sdk/v2" ) func main() { boolTag := aptos.NewTypeTag(&aptos.BoolTag{}) u8Tag := aptos.NewTypeTag(&aptos.U8Tag{}) u64Tag := aptos.NewTypeTag(&aptos.U64Tag{}) u128Tag := aptos.NewTypeTag(&aptos.U128Tag{}) u256Tag := aptos.NewTypeTag(&aptos.U256Tag{}) addressTag := aptos.NewTypeTag(&aptos.AddressTag{}) fmt.Printf("bool: %s, u8: %s, u64: %s, u128: %s, u256: %s, address: %s\n", boolTag.String(), u8Tag.String(), u64Tag.String(), u128Tag.String(), u256Tag.String(), addressTag.String()) } ``` ``` -------------------------------- ### Build Simple APT Transfer Transaction Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Constructs, signs, and submits a simple APT transfer transaction using the Aptos Go SDK. ```go txn, err := aptos.APTTransferTransaction(client, sender, receiver, amount) signedTxn, err := txn.SignedTransaction(sender) resp, err := client.SubmitTransaction(signedTxn) ``` -------------------------------- ### Build Transaction with Options Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/README.md Builds a raw Aptos transaction with custom options such as maximum gas amount, gas unit price, and expiration time. ```go rawTxn, err := client.BuildTransaction( sender.AccountAddress(), payload, aptos.MaxGasAmount(10_000), aptos.GasUnitPrice(100), aptos.ExpirationSeconds(300), ) ``` -------------------------------- ### Implement HTTPDoer Interface in Go Source: https://github.com/aptos-labs/aptos-go-sdk/blob/main/v2/MIGRATION.md Shows how to ensure a custom HTTP client implements the 'HTTPDoer' interface, which is required for certain Aptos SDK operations in Go. ```go type HTTPDoer interface { Do(ctx context.Context, req *http.Request) (*http.Response, error) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.