【发布时间】:2021-07-09 10:03:12
【问题描述】:
我已经在 AWS 中构建并运行了一个后端 golang 项目,我添加了 geth 以实现部分区块链功能。到目前为止,我已经编写了一个智能合约,它的 go 文件由 geth 自动生成,名为 orderContract.go。现在,我需要运行代码。正下方是我当前的项目文件结构
H&H
/main.go(package main)
/controller(folder, package controller)
____/A.go
____/B.go
____/orderContract.go(auto generated using abi)
A.go 从 orderContract.go 调用一个函数,该函数将值设置为 orderContract 中定义的结构对象。下面是我的代码
orderContract.sol
pragma solidity ^0.8.5;
contract OrderContract {
struct OrderInfo{
uint64 _orderId;
string _orderName;
uint64 _addressId;
string _pickUpTime;
string _status;
string _orderType;
}
OrderInfo _orderInfo;
event SetOrderInfo(OrderInfo orderInfo);
function setOrderInfo(uint64 orderId, string memory orderName, uint64 addressId, string memory pickUpTime, string memory status, string memory orderType) external {
_orderInfo._orderId = orderId;
_orderInfo._orderName = orderName;
_orderInfo._addressId = addressId;
_orderInfo._pickUpTime = pickUpTime;
_orderInfo._status = status;
_orderInfo._orderType = orderType;
emit SetOrderInfo(_orderInfo);
}
function getOrderInfo() public view returns(OrderInfo memory) {
return _orderInfo;
}
}
从 A.go 获取代码
conn, err := ethclient.Dial("HTTP://127.0.0.1:7545")
if err != nil {
log.Fatal(err)
}
privateKey, err := crypto.HexToECDSA("90df3126cb5b982d72d9909dea5a5e93306be0df4197c40b5f33b565ad950ee5")
if err != nil {
log.Fatal(err)
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("error casting public key to ECDSA")
}
fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
nonce, err := conn.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
log.Fatal(err)
}
gasPrice, err := conn.SuggestGasPrice(context.Background())
if err != nil {
log.Fatal(err)
}
auth := bind.NewKeyedTransactor(privateKey)
auth.Nonce = big.NewInt(int64(nonce))
auth.Value = big.NewInt(0) // in wei
auth.GasLimit = uint64(300000) // in units
auth.GasPrice = gasPrice
contract, err := NewController1(common.HexToAddress("0x902eb38dFab584EBef7570D33978b3D644bcfce7"), conn)
if err != nil {
log.Fatalf("Failed to instantiate contract : %v", err)
}
//set order info
tx, err := contract.SetOrderInfo(&bind.TransactOpts{}, 1, "orderName1", 1, "2019-11-10", "approved", "donation")
if err != nil {
fmt.Println("Here we go")
log.Fatal(err)
}
fmt.Printf("tx sent: %s", tx.Hash().Hex())
我正在使用Ganache来保存一个本地区块链环境,这个项目是后端项目。 A.go 包含将被调用的 API,上面显示的 A.go 的 snap 代码是 API 的一部分。
当我运行 go run main.go 时,一切似乎都很好,但是当我在 A.go 中调用包含 snap 代码部分的 API 时,它会显示错误
net/http: nil Context
一行
tx, err := contract.SetOrderInfo(&bind.TransactOpts{}, 1, "orderName1", 1, "2019-11-10", "approved", "donation")
有人可以帮我吗?谢谢!
【问题讨论】:
标签: go backend go-ethereum geth