創(chuàng)建錢(qián)包
func TestAccount(t *testing.T) {
//Create an account
key, err := crypto.GenerateKey()
if err != nil {
fmt.Println("Error: ", err.Error())
}
//Get the address
address := crypto.PubkeyToAddress(key.PublicKey).Hex()
fmt.Printf("address[%d][%v]\n", len(address), address)
//Get the private key
privateKey := hex.EncodeToString(key.D.Bytes())
fmt.Printf("privateKey[%d][%v]\n", len(privateKey), privateKey)
}
- 讀取合約
var avaxRpc = "https://api.avax-test.network/ext/bc/C/rpc"
var contractAddr = "0x18E99DA3649f3a027B4cDE362EeA596318a2169f"
func TestRetrieve(t *testing.T) {
cli, err := ethclient.Dial(avaxRpc)
if err != nil {
t.Fatal(err)
}
store, err := NewStore(ethcommon.HexToAddress(contractAddr), cli)
if err != nil {
t.Fatal(err)
}
opts := &bind.CallOpts{}
retrieve, err := store.Retrieve(opts)
if err != nil {
t.Fatal(err)
}
fmt.Println(retrieve)
}
- 寫(xiě)數(shù)據(jù)
func MakeAuth(ctx context.Context, privateKey, rpc, from string, chainId uint64) (*bind.TransactOpts, error) {
pk, pkErr := crypto.HexToECDSA(privateKey)
if pkErr != nil {
return nil, pkErr
}
auth, authErr := bind.NewKeyedTransactorWithChainID(pk, big.NewInt(int64(chainId)))
if authErr != nil {
return nil, authErr
}
// 合約地址
nonce, gas, err := block.GetLastNonceAndPrice(ctx, chainId, rpc, from)
if err != nil {
return nil, err
}
auth.Nonce = big.NewInt(int64(nonce))
auth.GasPrice = block.StringToBigInt(gas)
auth.Value = big.NewInt(0)
auth.GasLimit = uint64(600000)
return auth, nil
}
func TestStore(t *testing.T) {
cli, err := ethclient.Dial(avaxRpc)
if err != nil {
t.Fatal(err)
}
store, err := NewStore(ethcommon.HexToAddress(contractAddr), cli)
if err != nil {
t.Fatal(err)
}
pri := "" // 私鑰
addr := "0x335D7380e77ecd5bB35611D0A34EC44c12283990" // 錢(qián)包地址
auth, err := MakeAuth(context.Background(), pri, avaxRpc, addr, 43113)
if err != nil {
t.Fatal(err)
}
transaction, err := store.Store(auth, big.NewInt(100))
if err != nil {
t.Fatal(err)
}
fmt.Println(transaction.Hash().Hex())
}