Go-Ethereum

如何從 go-ethereum 中的 bind 包中實現 ContractTransactor 介面?

  • April 27, 2019

嘿伙計們提前謝謝!

這裡是bin包中go-ethereum庫提供的介面。我需要一個關於如何實現這個介面的例子:)

// ContractTransactor defines the methods needed to allow operating with contract
// on a write only basis. Beside the transacting method, the remainder are helpers
// used when the user does not provide some needed values, but rather leaves it up
// to the transactor to decide.
type ContractTransactor interface {
   // PendingCodeAt returns the code of the given account in the pending state.
   PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
   // PendingNonceAt retrieves the current pending nonce associated with an account.
   PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
   // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   // execution of a transaction.
   SuggestGasPrice(ctx context.Context) (*big.Int, error)
   // EstimateGas tries to estimate the gas needed to execute a specific
   // transaction based on the current pending state of the backend blockchain.
   // There is no guarantee that this is the true gas limit requirement as other
   // transactions may be added or removed by miners, but it should provide a basis
   // for setting a reasonable default.
   EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error)
   // SendTransaction injects the transaction into the pending pool for execution.
   SendTransaction(ctx context.Context, tx *types.Transaction) error
}

我這裡有一些基本的入門程式碼,這樣人們就可以看到我需要在哪裡應用介面。

package main

import (
   "MyProject/constants"
   "MyProject/contracts"
   "fmt"
   "github.com/ethereum/go-ethereum/accounts/abi"
   "github.com/ethereum/go-ethereum/accounts/abi/bind"
   "github.com/ethereum/go-ethereum/common"
   "math/big"
   "strings"
)

func main() {
   contractAddress,err:=common.NewMixedcaseAddressFromString("hexFun")
   if err != nil {
       panic(err)
   }
   userAddress,err:=common.NewMixedcaseAddressFromString("hexFun")

   if err != nil {
       panic(err)
   }

   userMainAddress := userAddress.Address()
   mainConctractAddress := contractAddress.Address()
   if err != nil {
       panic(err)
   }
   fmt.Println(abiObj)
   //LOOOOOOOK HERE PEOPLE THANK YOU --------------------------------------

   var one bind.ContractTransactor
   transactor, err:=contracts.NewERC721Transactor(mainConctractAddress,one)
   if err != nil {
       panic(err)
   }
   auth, err := bind.NewTransactor(strings.NewReader(constants.GetEthKey()),constants.GetEthParaphrase())
   trans, err:=transactor.Mint(auth,userMainAddress,big.NewInt(123))

   if err != nil {
       panic(err)
   }
   fmt.Println(trans.Hash())

}

ethclient包實現了ContractTransactor介面,因此您只需實例化客戶端:

client, err := ethclient.Dial("https://mainnet.infura.io")

然後你可以將它傳遞給你的合約交易者方法:

transactor, err:= contracts.NewERC721Transactor(mainContractAddress, client)

引用自:https://ethereum.stackexchange.com/questions/66097