In ethers.js, one can wait for a transaction to be mined with wait()
. Is there a way to do this when using ethclient
from go-ethereum
as a package? I would like to wait for the result before moving on in the program.
2 Answers
I think the function you are looking for is waitMined.
bind.WaitMined(context.Background(), client, signedTx)
Created this function that polls the client for a transaction, returns a channel that only unblocks once the transaction is confirmed (and sends said transaction over the channel)
// Returns a channel that blocks until the transaction is confirmed
func waitTxConfirmed(ctx context.Context, c *ethclient.Client, hash common.Hash) <-chan *types.Transaction {
ch := make(chan *types.Transaction)
go func() {
for {
tx, pending, _ := c.TransactionByHash(ctx, hash)
if !pending {
ch <- tx
}
time.Sleep(time.Millisecond * 500)
}
}()
return ch
}