当我使用golang调用合约方法时,如何确认该交易的状态?

huangapple go评论78阅读模式
英文:

When I use golang call the contract method,how can I confirm this trx status?

问题

我将为您翻译以下内容:

我将代币铸造到我的账户,并返回交易哈希,但我想知道这个哈希的状态。就像JavaScript可以使用回调函数等待此交易完成一样。

var promise = await token.mint("my account", 1)
console.log(promise.transactionHash)

Golang代码:

transaction, err := erc721.Mint(trx, common.HexToAddress("my account"), big.NewInt(int64(i)))
if err != nil {
    fmt.Println(err)
}
fmt.Println(transaction.Hash().String())
英文:

I mint the token to my account and it return transaction hash ,but I wnat to now this hash status .Like js can use callback function to wait this trx finished

     var promise = await token.mint("my account",1)
     console.log(promise.transactionHash)

golang

transaction, err := erc721.Mint(trx, common.HexToAddress("my account"), big.NewInt(int64(i)))
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(transaction.Hash().String())

答案1

得分: 0

根据评论中提到的,你需要监听事件日志(最好筛选出你的地址),并在确认后调用收据。

注意:这个示例只是为了演示必要的步骤。

func waitForReceipt(c *ethclient.Client, hash, addr string) (*types.Receipt, error) {
    query := ethereum.FilterQuery{
        Addresses: []common.Address{addr},
    }
    var ch = make(chan types.Log)
    sub, err := c.SubscribeFilterLogs(ctx, query, ch) // 订阅地址的所有日志
    if err != nil {
        return nil, err
    }

    for confirmed := false; !confirmed; { // 等待区块链上的确认
        select {
        case err := <-sub.Err():
            return nil, err
        case vLog := <-ch:
            if vLog.TxHash.Hex() == hash {
                confirmed = true
            }
        }

    }
    return c.TransactionReceipt(ctx, hash) // 调用收据
}
英文:

As mentioned in comment, you have to listen for event logs (preferably filtered for your address), and call for receipt after confirmation.

NOTE: Example is just to demonstrate necessary steps.

func waitForReceipt(c *ethclient.Client, hash, addr string) (*types.Receipt, error) {
	query := ethereum.FilterQuery{
		Addresses: []common.Address{addr},
	}
	var ch = make(chan types.Log)
	sub, err := c.SubscribeFilterLogs(ctx, query, ch) // subscribe to all logs for addr
	if err != nil {
		return nil, err
	}

	for confirmed := false; !confirmed;  { // wait for confirmation on blockchain
		select {
		case err := &lt;-sub.Err():
			return nil, err
		case vLog := &lt;-ch:
			if vLog.TxHash.Hex() == hash {
				confirmed = true
			}
		}

	}
	return c.TransactionReceipt(ctx, hash) // call for receipt
}

huangapple
  • 本文由 发表于 2022年6月13日 16:20:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72599694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定