### TON DNS Client Setup and Domain Resolution Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-dns.md Demonstrates the setup and usage of the TON DNS client, including obtaining the DNS root contract address, creating a client instance, and resolving a domain. This example also shows how to retrieve and update wallet records. ```go import ( "github.com/xssnick/tonutils-go/ton/dns" "github.com/xssnick/tonutils-go/ton/wallet" "github.com/xssnick/tonutils-go/tlb" ) // Get DNS root root, err := dns.GetRootContractAddr(ctx, api) if err != nil { log.Fatal(err) } // Create DNS client dnsClient := dns.NewDNSClient(api, root) // Resolve domain domainInfo, err := dnsClient.Resolve(ctx, "mysite.ton") if err != nil { log.Fatal(err) } // Get current wallet record currentWallet := domainInfo.GetWalletRecord() fmt.Printf("Current wallet: %s\n", currentWallet.String()) // Update wallet record using owner wallet newWallet := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") body := domainInfo.BuildSetWalletRecordPayload(newWallet) // ownerWallet is the wallet that owns the domain (from seed) err = ownerWallet.Send(ctx, &wallet.Message{ Mode: 1, // pay fees separately InternalMessage: &tlb.InternalMessage{ Bounce: true, DstAddr: domainInfo.GetNFTAddress(), Amount: tlb.MustFromTON("0.03"), Body: body, }, }, true) if err != nil { log.Fatal(err) } fmt.Println("Domain record updated successfully") ``` -------------------------------- ### Get Jetton Balance and Transfer Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Demonstrates how to get a jetton balance and initiate a transfer. This involves fetching jetton master data, obtaining the owner's jetton wallet, checking the balance, and then performing a transfer if sufficient balance exists. ```go jettonMasterAddr := address.MustParseAddr("EQAbMQzuuGiCne0R7QEj9nrXsjM7gNjeVmrlBZouyC-SCLlO") ownerAddr := address.MustParseAddr("EQC9bWZd29foipyPOGWlVNVCQzpGAjvi1rGWF7EbNcSVClpA") // Get master info master := jetton.NewJettonMasterClient(api, jettonMasterAddr) jettonData, err := master.GetJettonData(ctx) if err != nil { log.Fatal(err) } // Get wallet for owner jettonWallet, err := master.GetJettonWallet(ctx, ownerAddr) if err != nil { log.Fatal(err) } // Check balance balance, err := jettonWallet.GetBalance(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Balance: %s\n", balance.String()) // Transfer if balance.Cmp(big.NewInt(1000000000)) > 0 { recipient := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") err = jettonWallet.Transfer(ctx, myWallet, recipient, big.NewInt(1000000000)) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Development Setup with Testnet Configuration Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Configure the connection pool to use testnet servers with lenient proof validation. This setup is suitable for development and testing. ```go // Testnet with lenient configuration pool := liteclient.NewConnectionPool() pool.AddConnectionsFromConfigUrl(context.Background(), "https://ton-blockchain.github.io/testnet-global.config.json") api := ton.NewAPIClient(pool, ton.ProofCheckPolicyFast). WithRetryTimeout(3, 5*time.Second) ``` -------------------------------- ### Run Contract GET Method Source: https://github.com/xssnick/tonutils-go/blob/master/README.md Shows how to execute a contract's GET method (e.g., 'mult') with integer arguments and parse the returned cell result. Ensure you have fresh block information before running GET methods. ```Go // api = initialized ton.APIClient, see Connection in readme // we need fresh block info to run get methods block, err := api.CurrentMasterchainInfo(context.Background()) if err != nil { panic(err) } // contract address addr := address.MustParseAddr("kQB3P0cDOtkFDdxB77YX-F2DGkrIszmZkmyauMnsP1gg0inM") // run get method `mult` of contract with int arguments 7 and 8 res, err := api.RunGetMethod(context.Background(), block, addr, "mult", 7, 8) if err != nil { // if contract exit code != 0 it will be treated as an error too panic(err) } // we are sure that return value is 1 cell, we can directly cast it and parse slice, err := res.MustCell(0).BeginParse() if err != nil { panic(err) } val, err := slice.LoadUInt(64) if err != nil { panic(err) } // prints 56 println(val) ``` -------------------------------- ### StoreAddr Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a TON address. ```go func (b *Builder) StoreAddr(addr *address.Address) (*Builder, error) ``` -------------------------------- ### Custom Unmarshaler Implementation Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-tlb.md Example of implementing the Unmarshaler interface for custom parsing logic within LoadFromCell. ```go type CustomType struct { // Fields } func (c *CustomType) LoadFromCell(s *cell.Slice) error { // Custom parsing logic val, err := s.LoadUInt(32) if err != nil { return err } // ... more parsing return nil } ``` -------------------------------- ### Parse Account State Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-tlb.md Demonstrates fetching account information and printing its balance, status, code hash, and data. ```go block, _ := api.CurrentMasterchainInfo(ctx) account, _ := api.GetAccount(ctx, block, addr) fmt.Printf("Balance: %s TON\n", account.State.Balance.String()) fmt.Printf("Status: %s\n", account.State.Status) if account.State.Status == tlb.AccountStatusActive { fmt.Printf("Code hash: %x\n", account.Code.Hash()) fmt.Printf("Data: %s\n", account.Data.Dump()) } ``` -------------------------------- ### StoreBoolBit Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a single bit, representing true as 1 and false as 0. ```go func (b *Builder) StoreBoolBit(value bool) (*Builder, error) ``` -------------------------------- ### BeginParse Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Creates a reader slice from a cell for parsing its data. Handles potential errors during slice creation. ```go slice, err := cell.BeginParse() if err != nil { log.Fatal(err) } value, err := slice.LoadUInt(32) fmt.Println("Value:", value) ``` ```go func (c *Cell) BeginParse() (*Slice, error) ``` -------------------------------- ### Build Merkle Proof Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Demonstrates how to use MerkleProofBuilder to load a value from a dictionary and create a Merkle proof. Ensure the root cell is correctly provided during initialization. ```go proofBuilder := cell.NewMerkleProofBuilder(dictRoot) dict := proofBuilder.Root().AsDict(256) value, err := dict.LoadValue(myKey) if err != nil { log.Fatal(err) } proof, err := proofBuilder.CreateProof() if err != nil { log.Fatal(err) } ``` -------------------------------- ### StoreDict Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a dictionary reference. A nil dictionary will be stored as empty. ```go func (b *Builder) StoreDict(dict *Dictionary) (*Builder, error) ``` -------------------------------- ### Production Setup with Mainnet Configuration Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Configure the connection pool for mainnet with secure proof validation. Includes setting a trusted block for validation and enabling error details. ```go // Mainnet with strict validation pool := liteclient.NewConnectionPool() pool.AddConnectionsFromConfigUrl(context.Background(), "https://ton-blockchain.github.io/global.config.json") api := ton.NewAPIClient(pool, ton.ProofCheckPolicySecure). WithRetryTimeout(5, 15*time.Second). WithLSInfoInErrors() // Set trusted block for proof validation api.SetTrustedBlockFromConfig(cfg) ``` -------------------------------- ### Call Smart Contract GET Method Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/integration-guide.md Executes a 'GET' method on a smart contract and logs the results. This is useful for querying contract state without sending a transaction. ```go package main import ( "context" "log" "time" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/liteclient" "github.com/xssnick/tonutils-go/ton" ) func main() { client := liteclient.NewConnectionPool() defer client.Stop() ctx := context.Background() client.AddConnectionsFromConfigUrl(ctx, "https://ton-blockchain.github.io/testnet-global.config.json") api := ton.NewAPIClient(client).WithRetryTimeout(3, 5*time.Second) block, _ := api.CurrentMasterchainInfo(ctx) // Contract address contractAddr := address.MustParseAddr("EQArzJx8_WHsF2KTZeS7VBGHeurT0DtjfDOPA2BtMscSwXMe") // Call get method with parameters result, err := api.RunGetMethod(ctx, block, contractAddr, "get_contract_state") if err != nil { log.Fatal(err) } // Parse result cells if result.ExitCode == 0 { for i := 0; i < result.CellsCount(); i++ { cell := result.MustCell(i) log.Printf("Result cell %d: %s\n", i, cell.Dump()) } } } ``` -------------------------------- ### DumpBits Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Returns a binary representation of the cell, showing individual bits. ```go func (c *Cell) DumpBits() string ``` -------------------------------- ### StoreCoins Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a coin amount in the compact format used by TON. The amount is specified in nanotons. ```go func (b *Builder) StoreCoins(amount *big.Int) (*Builder, error) ``` -------------------------------- ### Roundtrip Serialization Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-tlb.md Demonstrates serializing a struct to a cell and then deserializing it back to verify the roundtrip process. ```go // Struct -> Cell payloadCell, err := tlb.ToCell(myPayload) // Cell -> Struct (verify roundtrip) var decoded MyPayloadType err = tlb.Parse(&decoded, payloadCell) ``` -------------------------------- ### Build Custom Cells Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-tlb.md Shows how to construct a custom cell by storing various data types like unsigned integers, addresses, and coins, then serializing it to BOC. ```go cell := cell.BeginCell(). MustStoreUInt(0x12345678, 32). MustStoreUInt(42, 256). MustStoreAddr(myAddr). MustStoreCoins(tlb.MustFromTON("1.0")), EndCell() // Serialize to BoC boc := cell.ToBOC() ``` -------------------------------- ### Execute GET Method on a Smart Contract Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Use RunGetMethod to execute a GET method of a smart contract. Parameters can be integers, cells, or slices. Ensure you have the correct block information, contract address, and method name. ```go func (c *APIClient) RunGetMethod(ctx context.Context, blockInfo *BlockIDExt, addr *address.Address, method string, params ...interface{}) (*ExecutionResult, error) ``` ```go block, err := api.CurrentMasterchainInfo(ctx) if err != nil { log.Fatal(err) } addr := address.MustParseAddr("kQB3P0cDOtkFDdxB77YX-F2DGkrIszmZkmyauMnsP1gg0inM") result, err := api.RunGetMethod(ctx, block, addr, "mult", 7, 8) if err != nil { log.Fatal(err) } // Extract result (assuming single cell return) cell := result.MustCell(0) slice, err := cell.BeginParse() if err != nil { log.Fatal(err) } value, err := slice.LoadUInt(64) if err != nil { log.Fatal(err) } fmt.Println("Result:", value) // 56 ``` -------------------------------- ### Create Wallet from Private Key with Options Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md Creates a wallet from a private key, allowing for custom configuration options. This is useful for advanced setups requiring specific wallet behaviors. ```go func FromPrivateKeyWithOptions(ctx context.Context, api *ton.APIClient, key ed25519.PrivateKey, version Version, options ...wallet.Option) (Wallet, error) ``` -------------------------------- ### BitsSize Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Returns the total number of bits stored in the cell. The size is capped at 1024 bits. ```go func (c *Cell) BitsSize() int ``` -------------------------------- ### Hash Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Returns the SHA-256 hash of the cell's representation. The output is a 32-byte slice. ```go func (c *Cell) Hash() []byte ``` -------------------------------- ### Setup TON Lite Client Connection Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/README.md Initializes a connection pool for TON lite servers and adds connections from a configuration URL. It's recommended to defer stopping the client pool. ```go client := liteclient.NewConnectionPool() defer client.Stop() client.AddConnectionsFromConfigUrl(ctx, "https://ton-blockchain.github.io/testnet-global.config.json") api := ton.NewAPIClient(client).WithRetryTimeout(3, 5*time.Second) ``` -------------------------------- ### Iterate and Print Dictionary Items Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Example of iterating through all items loaded from a dictionary using LoadAll(). It demonstrates how to extract and print key and value data after loading. ```go items, err := dict.LoadAll() if err != nil { log.Fatal(err) } for _, item := range items { keyData, _ := item.Key.LoadUInt(256) valData, _ := item.Value.LoadUInt(32) fmt.Printf("Key: %d, Value: %d\n", keyData, valData) } ``` -------------------------------- ### StoreInt Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a signed integer in two's complement form. The bit length must be between 1 and 64. ```go func (b *Builder) StoreInt(value int64, bits int) (*Builder, error) ``` -------------------------------- ### Dump Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Returns a human-readable string representation of the cell structure, including bit counts and hexadecimal data. It also shows nested cell references. ```go cell := cell.BeginCell(). MustStoreUInt(0xABCD, 16). MustStoreRef( cell.BeginCell().MustStoreUInt(42, 32).EndCell(), ). EndCell() fmt.Println(cell.Dump()) ``` ```go func (c *Cell) Dump() string ``` -------------------------------- ### Get Wallet State Initialization Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md Retrieves the StateInit (code and data) for a wallet, which is necessary for wallet deployment. Requires the public key, wallet version configuration, and subwallet ID. ```go func GetStateInit(pubKey ed25519.PublicKey, version VersionConfig, subWallet uint32) (*tlb.StateInit, error) ``` -------------------------------- ### Handle Request Timeout Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/errors-reference.md Handle request timeouts by setting a context deadline. This example demonstrates how to use context.WithTimeout and check for context.DeadlineExceeded to implement retries with a longer deadline. ```Go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) def cancel() err := client.QueryLiteserver(ctx, request, result) if err == context.DeadlineExceeded { log.Println("Request timed out, retrying with longer deadline") } ``` -------------------------------- ### Initialize and Use Wallet Source: https://github.com/xssnick/tonutils-go/blob/master/README.md Demonstrates how to initialize a wallet from a seed phrase, check its balance, and send a transfer if the balance is sufficient. The library handles wallet deployment if it's not already initialized. ```Go words := strings.Split("birth pattern ...", " ") w, err := wallet.FromSeedWithOptions(api, words, wallet.V3) if err != nil { panic(err) } block, err := api.CurrentMasterchainInfo(context.Background()) if err != nil { panic(err) } balance, err := w.GetBalance(context.Background(), block) if err != nil { panic(err) } if balance.Nano().Uint64() >= 3000000 { addr := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") err = w.Transfer(context.Background(), addr, tlb.MustFromTON("0.003"), "Hey bro, happy birthday!") if err != nil { panic(err) } } ``` -------------------------------- ### StoreSlice Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores raw bits from a byte slice. The specified bit length determines how many bits are stored from the data. ```go func (b *Builder) StoreSlice(data []byte, bits int) (*Builder, error) ``` -------------------------------- ### Safe Mode API Client Setup Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Configure the TON API client for maximum safety using ProofCheckPolicySecure and set retry timeouts. This is recommended for critical operations. ```go // Maximum safety for important operations api := ton.NewAPIClient(pool, ton.ProofCheckPolicySecure). WithRetryTimeout(10, 30*time.Second) // Use sticky context for related operations ctx := pool.StickyContext(context.Background()) // Always verify wallet state before sending account, _ := api.GetAccount(ctx, block, w.GetAddress()) balance, _ := w.GetBalance(ctx, block) if account.State.Status != tlb.AccountStatusActive { log.Println("Wallet not active") return } ``` -------------------------------- ### Create and Dump Low-Level Proof Skeleton Source: https://github.com/xssnick/tonutils-go/blob/master/README.md Demonstrates creating a proof skeleton by specifying exact references to keep and then generating and dumping the merkle proof. Use this when you know the exact refs you want to keep. ```golang sk := cell.CreateProofSkeleton() sk.ProofRef(0).ProofRef(1) // Tips: // you could also do SetRecursive() on needed ref to add all its child cells to proof // you can merge 2 proof skeletons using Merge merkleProof, err := someCell.CreateProof(sk) if err != nil { t.Fatal(err) } fmt.Println(merkleProof.Dump()) ``` -------------------------------- ### High-Throughput Setup with Multiple Pools Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Distribute requests across multiple independent connection pools to achieve high throughput. Requests are distributed using a modulo operation on the request ID. ```go // Multiple independent pools for parallel requests pools := []*liteclient.ConnectionPool{} for i := 0; i < 4; i++ { p := liteclient.NewConnectionPool() p.AddConnectionsFromConfigUrl(ctx, configURL) pools = append(pools, p) } // Distribute requests across pools api := ton.NewAPIClient(pools[requestID % 4]). WithRetryTimeout(2, 3*time.Second) ``` -------------------------------- ### Execute GET Method by ID on a Smart Contract Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Use RunGetMethodByID to execute a GET method of a smart contract using its numeric ID. This is an alternative to using the method name string. ```go func (c *APIClient) RunGetMethodByID(ctx context.Context, blockInfo *BlockIDExt, addr *address.Address, methodID uint64, params ...interface{}) (*ExecutionResult, error) ``` -------------------------------- ### Build and Verify Proof with MerkleProofBuilder Source: https://github.com/xssnick/tonutils-go/blob/master/README.md Illustrates building a proof for data loaded from a dictionary using MerkleProofBuilder, then unwrapping and verifying the proof to load the data again. This is the recommended approach for proof generation. ```golang dict := cell.NewDict(32) key := cell.BeginCell().MustStoreUInt(7, 32).EndCell() value := cell.BeginCell(). MustStoreUInt(0xAB, 8). MustStoreRef( cell.BeginCell(). MustStoreUInt(0xCDEF, 16). EndCell(), ). EndCell() if err := dict.Set(key, value); err != nil { panic(err) } root := dict.AsCell() proofBuilder := cell.NewMerkleProofBuilder(root) observed := proofBuilder.Root().AsDict(32) loaded, err := observed.LoadValue(key) if err != nil { panic(err) } // LoadValue marks the dictionary path and the terminal cell with the value as used. // LoadRef calls BeginParse on the child ref, so this ref will also stay ordinary in proof. _, err = loaded.LoadRef() if err != nil { panic(err) } proof, err := proofBuilder.CreateProof() if err != nil { panic(err) } proofBody, err := cell.UnwrapProof(proof, root.Hash()) if err != nil { panic(err) } loadedFromProof, err := proofBody.AsDict(32).LoadValue(key) if err != nil { panic(err) } fmt.Println(loadedFromProof.MustLoadUInt(8)) // 171 child, err := loadedFromProof.LoadRef() if err != nil { panic(err) } fmt.Println(child.MustLoadUInt(16)) // 52719 ``` -------------------------------- ### Call Smart Contract GET Method Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/README.md Executes a 'GET' method on a smart contract, retrieves the result, and extracts a cell from the first output. This is useful for querying contract state without transactions. ```go result, _ := api.RunGetMethod(ctx, block, contractAddr, "method_name") cell := result.MustCell(0) ``` -------------------------------- ### Create and Populate a Cell Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Use BeginCell to start building a new cell, then chain MustStoreUInt to add unsigned integers of specified bit lengths. Finally, call EndCell to finalize the immutable cell. ```go cell := cell.BeginCell(). MustStoreUInt(42, 8). MustStoreUInt(1000, 64). EndCell() ``` -------------------------------- ### Initialize API Client Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Creates a new API client using a connection pool and a specified proof check policy. The `ProofCheckPolicyFast` is the default, offering basic validation without master block checks. ```go api := ton.NewAPIClient(pool, ton.ProofCheckPolicyFast) ``` -------------------------------- ### GetBlockchainConfig Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Gets blockchain configuration parameters. ```APIDOC ## GetBlockchainConfig ### Description Gets blockchain configuration parameters. ### Method `GetBlockchainConfig` ### Parameters #### Path Parameters - **ctx** (`context.Context`) - Required - Request context - **block** (`*BlockIDExt`) - Required - Block for config - **onlyParams** (`...int32`) - Optional - Specific config param IDs to fetch ### Returns - `(*tlb.BlockchainConfig, error)` — Configuration and error ``` -------------------------------- ### Create and Configure Lite Client Connection Pool Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-liteclient.md Initializes a new connection pool and adds lite servers from a remote configuration URL. Ensure to defer the Stop() method for proper cleanup. ```go client := liteclient.NewConnectionPool() defer client.Stop() // Add liteservers from TON config err := client.AddConnectionsFromConfigUrl(context.Background(), "https://ton-blockchain.github.io/testnet-global.config.json") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Send Transaction to Update Wallet Record Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-dns.md Sends a transaction to update a domain's wallet record. This example shows how to use the `BuildSetWalletRecordPayload` to send an update via an owner wallet. ```go newWallet := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") body := domain.BuildSetWalletRecordPayload(newWallet) // Send via wallet err := ownerWallet.Send(ctx, &wallet.Message{ Mode: 1, InternalMessage: &tlb.InternalMessage{ Bounce: true, DstAddr: domain.GetNFTAddress(), Amount: tlb.MustFromTON("0.03"), Body: body, }, }, true) if err != nil { log.Fatal(err) } ``` -------------------------------- ### GetTransaction Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Gets a specific transaction by logical time. ```APIDOC ## GetTransaction ### Description Gets a specific transaction by logical time. ### Method `GetTransaction` ### Parameters #### Path Parameters - **ctx** (`context.Context`) - Required - Request context - **block** (`*BlockIDExt`) - Required - Block for lookup - **addr** (`*address.Address`) - Required - Account address - **lt** (`uint64`) - Required - Logical time ### Returns - `(*tlb.Transaction, error)` — Transaction and error ``` -------------------------------- ### GetJettonWallet Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Gets the jetton wallet address for an owner and returns a client for it. ```APIDOC ## GetJettonWallet ### Description Gets the jetton wallet address for an owner and returns a client for it. ### Method Go Function ### Parameters #### Path Parameters - `ctx` (context.Context) - Required - Request context - `owner` (*address.Address) - Required - Owner account address ### Returns - `(*JettonWalletClient, error)` - Jetton wallet client and error ### Example ```go owner := address.MustParseAddr("EQC9bWZd29foipyPOGWlVNVCQzpGAjvi1rGWF7EbNcSVClpA") wallet, err := master.GetJettonWallet(ctx, owner) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Create Wallet from Seed with Options Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Initializes a wallet instance from a seed phrase with custom workchain and subwallet IDs. This allows for more specific wallet configurations. ```go w, err := wallet.FromSeedWithOptions(ctx, api, seed, wallet.V5R1Final, wallet.WithWorkchain(0), wallet.WithSubwallet(0), ) ``` -------------------------------- ### Configure Context with Timeout Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Sets a per-request timeout for context. This is recommended for various operations like balance queries, GET method calls, sending transactions, and block queries to prevent indefinite waiting. ```go // Per-request timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := api.CurrentMasterchainInfo(ctx) ``` -------------------------------- ### Deploy a Smart Contract Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md This function deploys a new smart contract. Provide the contract's code, initial data, and an initial balance. Optional send options can be specified. ```go func (w Wallet) DeployContract(ctx context.Context, msgBody, contractCode, contractData *cell.Cell, amount *big.Int, opts ...SendOption) error ``` -------------------------------- ### GetBlockData Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Gets complete block data (header, transactions, state updates). ```APIDOC ## GetBlockData ### Description Gets complete block data (header, transactions, state updates). ### Method `GetBlockData` ### Parameters #### Path Parameters - **ctx** (`context.Context`) - Required - Request context - **block** (`*BlockIDExt`) - Required - Block ID ### Returns - `(*tlb.Block, error)` — Full block and error ``` -------------------------------- ### CreateProofSkeleton Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Creates a low-level proof skeleton for manual proof construction. ```APIDOC ## CreateProofSkeleton ### Description Creates a low-level proof skeleton for manual proof construction. ### Method CreateProofSkeleton ### Returns - **(*ProofSkeleton)** - New skeleton ``` -------------------------------- ### GetCollectionData Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Gets collection metadata including owner, next item index, and content. ```APIDOC ## GetCollectionData ### Description Gets collection metadata including owner, next item index, and content. ### Method Go Function ### Parameters #### Path Parameters - `ctx` (context.Context) - Required - Request context ### Returns - `(*CollectionData, error)` - Collection data and error ### Example ```go collectionAddr := address.MustParseAddr("EQDnxWxVdW0nEY0K5LuWrC3e2HCeEwJCHj62uxLLKk_9dPMg") collectionClient := nft.NewCollectionClient(api, collectionAddr) data, err := collectionClient.GetCollectionData(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Owner: %s\n", data.OwnerAddress.String()) fmt.Printf("Next Item Index: %d\n", data.NextItemIndex) ``` ``` -------------------------------- ### Create and Populate a Dictionary Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Initialize a dictionary with a specific key size using NewDict. Use BeginCell and EndCell to create key and value cells, then use the Set method to add them to the dictionary. ```go dict := cell.NewDict(256) key := cell.BeginCell().MustStoreUInt(1, 256).EndCell() value := cell.BeginCell().MustStoreUInt(42, 32).EndCell() dict.Set(key, value) ``` -------------------------------- ### GetJettonData Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Gets jetton master contract data including total supply, admin, and metadata. ```APIDOC ## GetJettonData ### Description Gets jetton master contract data including total supply, admin, and metadata. ### Method Go Function ### Parameters #### Path Parameters - `ctx` (context.Context) - Required - Request context ### Returns - `(*JettonData, error)` - Jetton data and error ### Example ```go masterAddr := address.MustParseAddr("EQAbMQzuuGiCne0R7QEj9nrXsjM7gNjeVmrlBZouyC-SCLlO") master := jetton.NewJettonMasterClient(api, masterAddr) data, err := master.GetJettonData(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Total Supply: %s\n", data.TotalSupply.String()) fmt.Printf("Mintable: %v\n", data.Mintable) fmt.Printf("Admin: %s\n", data.AdminAddress.String()) ``` ``` -------------------------------- ### Create Proof Skeleton Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Initializes and returns a new, low-level proof skeleton. This is used as a base for manually constructing proofs in TON. ```go func CreateProofSkeleton() *ProofSkeleton ``` -------------------------------- ### Add Lite Servers from Configuration URL Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-liteclient.md Downloads TON global configuration from a URL and adds all listed lite servers to the connection pool. Handles potential download or connection errors. ```go err := client.AddConnectionsFromConfigUrl(context.Background(), "https://ton-blockchain.github.io/testnet-global.config.json") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create and Use TON Wallet Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/integration-guide.md Demonstrates creating a wallet from a seed phrase, checking its balance, and sending a transfer. Ensure you replace "your seed phrase here (12 or 24 words)" with your actual seed phrase. ```go package main import ( "context" "log" "strings" "time" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/liteclient" "github.com/xssnick/tonutils-go/tlb" "github.com/xssnick/tonutils-go/ton" "github.com/xssnick/tonutils-go/ton/wallet" ) func main() { // Setup API client := liteclient.NewConnectionPool() defer client.Stop() ctx := context.Background() client.AddConnectionsFromConfigUrl(ctx, "https://ton-blockchain.github.io/testnet-global.config.json") api := ton.NewAPIClient(client).WithRetryTimeout(3, 5*time.Second) // Create wallet from seed phrase seed := strings.Split("your seed phrase here (12 or 24 words)", " ") w, err := wallet.FromSeed(ctx, api, seed, wallet.V4R2) if err != nil { log.Fatal(err) } walletAddr := w.GetAddress() log.Printf("Wallet address: %s\n", walletAddr.String()) // Get current state block, err := api.CurrentMasterchainInfo(ctx) if err != nil { log.Fatal(err) } // Check balance balance, err := w.GetBalance(ctx, block) if err != nil { log.Fatal(err) } log.Printf("Balance: %s\n", tlb.FromNanotonsBig(balance).String()) // Send transfer if balance sufficient recipient, err := address.ParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") if err != nil { log.Fatal(err) } amount := tlb.MustFromTON("0.5") err = w.Transfer(ctx, recipient, amount, "Hello from tonutils-go!") if err != nil { log.Fatal(err) } log.Println("Transfer sent successfully") } ``` -------------------------------- ### RunGetMethod Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Executes a GET method of a smart contract and returns the result. Parameters can be integers, cells, or slices. ```APIDOC ## RunGetMethod ### Description Executes a GET method of a smart contract and returns the result. Parameters can be integers, cells, or slices. ### Method POST (Assumed, as it modifies state or performs complex operations) ### Endpoint /runGetMethod (Assumed, based on function name) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (`context.Context`) - Required - Request context - **blockInfo** (`*BlockIDExt`) - Required - Block for state - **addr** (`*address.Address`) - Required - Contract address - **method** (`string`) - Required - Method name (or ID as "method_id") - **params** (`...interface{}`) - Optional - Method parameters (int, []byte, *cell.Cell, *cell.Slice) ### Response #### Success Response (200) - **ExecutionResult** (`*ExecutionResult`) - Execution result #### Error Response - **error** (`error`) - Contract execution failed or method not found - **ContractExecError** (`ContractExecError`) - Contract returned non-zero exit code ``` -------------------------------- ### Get Address Workchain ID Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-address.md The Workchain method returns the workchain identifier for standard and variable addresses. ```go func (a *Address) Workchain() int32 ``` -------------------------------- ### Create Jetton Wallet Client Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Initializes a client for interacting with a Jetton wallet contract. Requires a TON API client and the Jetton wallet address. ```go func NewJettonWalletClient(api *ton.APIClient, addr *address.Address) *JettonWalletClient ``` -------------------------------- ### ListTransactions Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Gets a list of recent transactions for an account. Use the LT and hash from the previous transaction to paginate backwards. ```APIDOC ## ListTransactions ### Description Gets a list of recent transactions for an account. Use the LT and hash from the previous transaction to paginate backwards. ### Method `ListTransactions` ### Parameters #### Path Parameters - **ctx** (`context.Context`) - Required - Request context - **addr** (`*address.Address`) - Required - Account address - **num** (`uint32`) - Required - Number of transactions to fetch - **lt** (`uint64`) - Required - Logical time of last known transaction (0 to start from latest) - **txHash** (`[]byte`) - Required - Hash of last known transaction (empty to start from latest) ### Returns - `([]*tlb.Transaction, error)` — Transaction list (newest first) and error ### Example ```go addr := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") block, _ := api.CurrentMasterchainInfo(ctx) account, _ := api.GetAccount(ctx, block, addr) txList, err := api.ListTransactions(ctx, addr, 10, account.LastTxLT, account.LastTxHash) if err != nil { log.Fatal(err) } for _, tx := range txList { fmt.Printf("LT: %d, Hash: %x\n", tx.LT, tx.Hash()) } ``` ``` -------------------------------- ### Creating Dictionaries with Specified Key Sizes Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Initialize a dictionary with a specific key size, such as 256 bits. Other common key sizes like 8, 64, or 128 bits can also be used. ```go // Create dictionary with 256-bit keys dict := cell.NewDict(256) // Create dictionary with other key sizes dict8 := cell.NewDict(8) dict64 := cell.NewDict(64) ``` -------------------------------- ### Get Wallet Address Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md Retrieves the address associated with a wallet instance. This is a common operation after creating or loading a wallet. ```go func (w Wallet) GetAddress() *address.Address ``` ```go addr := w.GetAddress() fmt.Println(addr.String()) ``` -------------------------------- ### Get Jetton Wallet Balance Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Retrieves the balance of jettons held by a specific wallet. Ensure the context is valid. ```go balance, err := wallet.GetBalance(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Balance: %s\n", balance.String()) ``` -------------------------------- ### Create Wallet from Seed Phrase Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md Initializes a wallet using a BIP39 seed phrase and a specified wallet version. Requires a TON API client and context. ```go import ( "strings" "github.com/xssnick/tonutils-go/ton/wallet" ) seed := strings.Split("your twelve word seed phrase here", " ") w, err := wallet.FromSeed(ctx, api, seed, wallet.V3R2) if err != nil { log.Fatal(err) } addr := w.GetAddress() fmt.Println("Wallet address:", addr.String()) ``` -------------------------------- ### Create TON API Client Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-ton-client.md Initializes a new APIClient by wrapping a LiteClient connection pool. Proof check policy defaults to `ProofCheckPolicyFast`. ```go import ( "github.com/xssnick/tonutils-go/liteclient" "github.com/xssnick/tonutils-go/ton" ) pool := liteclient.NewConnectionPool() err := pool.AddConnectionsFromConfigUrl(ctx, "https://ton-blockchain.github.io/testnet-global.config.json") if err != nil { log.Fatal(err) } api := ton.NewAPIClient(pool) ``` -------------------------------- ### RefsCount Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Returns the number of cell references contained within the cell. The count ranges from 0 to 4. ```go func (c *Cell) RefsCount() int ``` -------------------------------- ### ToBOC Example Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Serializes the cell into BOC (Bag of Cells) format bytes, suitable for network transmission or storage. ```go boc := myCell.ToBOC() // Send boc over network or store to file ``` ```go func (c *Cell) ToBOC() []byte ``` -------------------------------- ### Create Jetton Master Client Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Initializes a client for interacting with a Jetton master contract. Requires a TON API client and the Jetton master address. ```go func NewJettonMasterClient(api *ton.APIClient, addr *address.Address) *JettonMasterClient ``` -------------------------------- ### FromPrivateKeyWithOptions Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-wallet.md Creates a wallet from a private key with additional custom configuration options. It takes the context, API client, private key, wallet version, and a variadic list of options. ```APIDOC ## FromPrivateKeyWithOptions ### Description Creates a wallet from a private key with custom options. ### Method ```go func FromPrivateKeyWithOptions(ctx context.Context, api *ton.APIClient, key ed25519.PrivateKey, version Version, options ...wallet.Option) (Wallet, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Request context - **api** (*ton.APIClient) - Required - TON API client - **key** (ed25519.PrivateKey) - Required - Private key - **version** (Version) - Required - Wallet contract version - **options** (...wallet.Option) - Optional - Configuration options ### Response #### Success Response - **Wallet** (Wallet) - Configured wallet instance - **error** (error) - Error if creation fails ``` -------------------------------- ### StoreRef and MustStoreRef Examples Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-cells.md Stores a reference to another cell. Cells can have up to 4 references. MustStoreRef panics on error. ```go innerCell := cell.BeginCell().MustStoreUInt(42, 32).EndCell() outerCell := cell.BeginCell(). MustStoreUInt(1, 8). MustStoreRef(innerCell). EndCell() ``` ```go func (b *Builder) StoreRef(cell *Cell) (*Builder, error) ``` ```go func (b *Builder) MustStoreRef(cell *Cell) *Builder ``` -------------------------------- ### Download and Parse TON Global Configuration from URL Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-liteclient.md Fetches TON global configuration from a specified URL and parses it. Requires a context for the request. ```go cfg, err := liteclient.GetConfigFromUrl(ctx, "https://ton-blockchain.github.io/global.config.json") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Coins Methods for Amount Handling Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-tlb.md Provides methods for the Coins type to get string representation, nanotons, or float values. ```go func (c *Coins) String() string func (c *Coins) Nano() *big.Int func (c *Coins) NanoInt64() int64 func (c *Coins) ToFloat() float64 ``` -------------------------------- ### Initialize New Connection Pool Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Creates a new connection pool with default settings. Default settings include a randomly generated authentication key, a reconnection policy of 3 retries with 3-second backoff, a 5-second ping interval, and round-robin load balancing with fallback. ```go pool := liteclient.NewConnectionPool() ``` -------------------------------- ### Get NFT Data and Display Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-nft-jetton.md Retrieves NFT data including owner and content. Handles offchain content display. ```go itemAddr := address.MustParseAddr("EQDuPc-3EoqH72Gd6M45vmFsktQ8AzqaN14mweJhCjxg0d_b") itemClient := nft.NewItemClient(api, itemAddr) nftData, err := itemClient.GetNFTData(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Owner: %s\n", nftData.OwnerAddress.String()) fmt.Printf("Index: %d\n", nftData.Index) if content, ok := nftData.Content.(*nft.ContentOffchain); ok { fmt.Printf("Content URL: %s\n", content.URI) } ``` -------------------------------- ### Loading Public Lite Server Configurations Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/configuration-reference.md Load network configurations from public URLs for mainnet or testnet. These URLs provide the addresses of public lite servers. ```go config := "https://ton-blockchain.github.io/global.config.json" // Public testnet servers config := "https://ton-blockchain.github.io/testnet-global.config.json" ``` -------------------------------- ### Get Address Type Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-address.md The Type method returns a constant indicating the address's classification (e.g., NoneAddress, ExtAddress). ```go func (a *Address) Type() AddrType ``` -------------------------------- ### Handle Config Download Failed Error Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/errors-reference.md When `AddConnectionsFromConfigUrl()` or `GetConfigFromUrl()` fail to download the TON global configuration due to network issues. Consider using cached configurations or a fallback URL. ```go err := pool.AddConnectionsFromConfigUrl(ctx, configUrl) if err != nil { log.Printf("Config download failed: %v\n", err) // Use cached config or fallback URL } ``` -------------------------------- ### Get Raw Address String Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-address.md The StringRaw method returns the address in the format 'workchain:hex', providing the raw components. ```go addr := address.MustParseAddr("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N") fmt.Println(addr.StringRaw()) // 0:03dfb552e637aeb4dffb083f60e87edb8207d34e4599fe83968f0d0769d69d9b ``` -------------------------------- ### Build and Parse Custom TLB Structures Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/integration-guide.md Demonstrates building a custom payload structure using TLB tags and serializing it into a cell. It also shows how to parse this cell back into the Go struct, including accessing nested cells. ```go package main import ( "log" "github.com/xssnick/tonutils-go/tlb" "github.com/xssnick/tonutils-go/tvm/cell" ) type MyPayload struct { Magic tlb.Magic `tlb:"#a1b2c3d4"` QueryID uint64 `tlb:"## 64"` Flags uint8 `tlb:"## 8"` Body *cell.Cell `tlb:"^"` } func main() { // Build payload using TLB payload := MyPayload{ QueryID: 123, Flags: 7, Body: cell.BeginCell(). MustStoreUInt(0xCAFE, 16). EndCell(), } // Serialize to cell payloadCell, err := tlb.ToCell(payload) if err != nil { log.Fatal(err) } log.Printf("Serialized: %s\n", payloadCell.Dump()) // Parse back from cell var decoded MyPayload err = tlb.Parse(&decoded, payloadCell) if err != nil { log.Fatal(err) } log.Printf("QueryID: %d\n", decoded.QueryID) log.Printf("Flags: %d\n", decoded.Flags) // Access referenced cell bodySlice, _ := decoded.Body.BeginParse() val, _ := bodySlice.LoadUInt(16) log.Printf("Body value: 0x%x\n", val) } ``` -------------------------------- ### GetRootContractAddr Source: https://github.com/xssnick/tonutils-go/blob/master/_autodocs/api-reference-dns.md Gets the address of the TON DNS root contract by querying the masterchain configuration. This is a prerequisite for initializing a DNS client. ```APIDOC ## GetRootContractAddr ### Description Gets the address of the TON DNS root contract by querying the masterchain configuration. ### Method GET (conceptual, as it queries blockchain config) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (`context.Context`) - Required - Request context - **api** (`*ton.APIClient`) - Required - TON API client ### Returns - **(*address.Address, error)** - Root contract address and error ### Example: ```go import ( "github.com/xssnick/tonutils-go/ton/dns" ) root, err := dns.GetRootContractAddr(ctx, api) if err != nil { log.Fatal(err) } fmt.Printf("DNS Root: %s\n", root.String()) ``` ```