golang geth 调用智能合约查询及转账ABI

  • lovo1
  • 更新于 2024-10-31 21:32
  • 阅读 154

golang geth 调用智能合约查询及转账ABI


import (
    "context"
    "fmt"
    constract "go-contract-demo/part3/contract"
    "math/big"
    "os"

    "github.com/ethereum/go-ethereum/accounts/abi/bind"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/ethclient"
)

const (
    privateKey      = "503f38a9c967ed597e47fe25643985f032b072db8075426a92110f82df48dfcb"
    contractAddress = "0x1F5b157d46276E0f7f8108A82a2a518084E2E0F5"
    toAddress       = "0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db"
)

var url string = "http://localhost:8545"

func main() {
    client, err := ethclient.Dial(url)
    if err != nil {
        fmt.Println("ethclient.Dial error : ", err)
        os.Exit(0)
    }
    token, err := constract.NewHello(common.HexToAddress(contractAddress), client)
    if err != nil {
        fmt.Println("NewToken error : ", err)
    }

    // 获取当前区块链的ChainID
    chainID, err := client.ChainID(context.Background())
    if err != nil {
        fmt.Println("获取ChainID失败:", err)
        return
    }
    privateKeyECDSA, err := crypto.HexToECDSA(privateKey)
    if err != nil {
        fmt.Println("crypto.HexToECDSA error ,", err)
        return
    }

    gasTipCap, _ := client.SuggestGasTipCap(context.Background())

    //构建参数对象
    opts, err := bind.NewKeyedTransactorWithChainID(privateKeyECDSA, chainID)
    if err != nil {
        fmt.Println("bind.NewKeyedTransactorWithChainID error ,", err)
        return
    }
    //设置参数
    opts.GasFeeCap = big.NewInt(108694000460)
    opts.GasLimit = uint64(100000)
    opts.GasTipCap = gasTipCap

    //调用合约Store方法
    tx, err := token.Store(opts, big.NewInt(11))
    if err != nil {
        fmt.Println("token.Transfer error ,", err)
        return
    }

    fmt.Println("使用go调用智能合约:Store tx : ", tx.Hash().Hex())

    number, err := token.GetNumber(nil)

    if err != nil {
        fmt.Println(" GetNumber failed ", err)
    }

    fmt.Println("number ", number)

    amount, _ := new(big.Int).SetString("10", 10)
    tx2, err := token.Transfer(opts, common.HexToAddress(toAddress), amount)
    if err != nil {
        fmt.Println("token.Transfer error ,", err)
        return
    }

    fmt.Println(":transfer tx2 : ", tx2.Hash().Hex())

    blance, err := token.GetBalance(nil, common.HexToAddress(toAddress))

    if err != nil {
        fmt.Println(" blance failed ", err)
    }

    fmt.Println("blance ", blance)

}
  • 原创
  • 学分: 0
  • 分类: Go
  • 标签:
点赞 0
收藏 0
分享

0 条评论

请先 登录 后评论
lovo1
lovo1
0x604B...4E95
MY