Day 3

链上数据读取

初级阶段 · 预计学习时间 2-3 小时

学习目标
  • 查询区块链高度
  • 查询账户余额和 Nonce
  • 根据哈希查询交易详情
查询区块高度

区块高度表示当前最新的区块编号。

package main

import (
    "fmt"
    "log"

    "github.com/aeternity/aepp-sdk-go/v9/naet"
)

func main() {
    node := naet.NewNode("https://testnet.aeternity.io", false)

    // 获取区块高度
    height, err := node.GetHeight()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("当前区块高度: %d\n", height)
}
查询账户余额

账户余额以 aettos(最小单位)返回,1 AE = 1018 aettos。

// 替换为你的地址
address := "ak_2a1j2Mk9YSmC1gioUq4PWRm3bsv887MbuRVwyv4KaUGoR1eiKi"

accountInfo, err := node.GetAccount(address)
if err != nil {
    log.Printf("账户未找到或查询错误: %v\n", err)
} else {
    fmt.Printf("地址: %s\n", address)
    fmt.Printf("余额: %s aettos\n", accountInfo.Balance)
    fmt.Printf("Nonce: %d\n", accountInfo.Nonce)
}
余额格式化
import (
    "math/big"
)

// 将 aettos 转换为 AE
func aettosToAE(aettos *big.Int) *big.Float {
    ae := new(big.Float).SetInt(aettos)
    divisor := new(big.Float).SetInt(big.NewInt(1e18))
    return new(big.Float).Quo(ae, divisor)
}

// 使用
balance := new(big.Int)
balance.SetString(accountInfo.Balance.String(), 10)
aeBalance := aettosToAE(balance)
fmt.Printf("余额: %s AE\n", aeBalance.Text('f', 6))
查询交易详情

通过交易哈希(th_...)查询交易详情。

// 替换为有效的交易哈希
txHash := "th_2Rkmk..."

tx, err := node.GetTransactionByHash(txHash)
if err != nil {
    log.Println("交易未找到:", err)
} else {
    fmt.Println("=== 交易详情 ===")
    fmt.Printf("哈希: %s\n", tx.Hash)
    fmt.Printf("区块高度: %d\n", tx.BlockHeight)
    fmt.Printf("区块哈希: %s\n", tx.BlockHash)
}
完整示例:链上数据浏览器
package main

import (
    "fmt"
    "log"
    "math/big"

    "github.com/aeternity/aepp-sdk-go/v9/naet"
)

func main() {
    node := naet.NewNode("https://testnet.aeternity.io", false)

    fmt.Println("=== Aeternity 链上数据读取 ===\n")

    // 1. 区块高度
    height, err := node.GetHeight()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("📦 当前区块高度: %d\n", height)

    // 2. 账户查询
    testAddress := "ak_fUq2NesPXcYZ1CcqBcGC3StpdnQw3iVxMA3YSeCNAwfN4myQk"
    
    accInfo, err := node.GetAccount(testAddress)
    if err != nil {
        fmt.Printf("❌ 账户查询失败: %v\n", err)
    } else {
        // 转换余额
        balance := new(big.Int)
        balance.SetString(accInfo.Balance.String(), 10)
        
        ae := new(big.Float).SetInt(balance)
        ae.Quo(ae, big.NewFloat(1e18))
        
        fmt.Printf("\n👤 账户信息:\n")
        fmt.Printf("   地址: %s\n", testAddress[:20]+"...")
        fmt.Printf("   余额: %s AE\n", ae.Text('f', 4))
        fmt.Printf("   Nonce: %d\n", accInfo.Nonce)
    }

    fmt.Println("\n✅ 数据读取完成!")
}
知识检查点

完成 Day 3 后,你应该能够: