Skip to content

Commit

Permalink
Wait for Tx in Block
Browse files Browse the repository at this point in the history
  • Loading branch information
joelsmith-2019 committed Oct 28, 2024
1 parent b13aefc commit cc25e64
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions node/pkg/wormconn/send_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package wormconn
import (
"context"
"fmt"
"time"

txclient "github.com/cosmos/cosmos-sdk/client/tx"
sdktypes "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -92,12 +93,35 @@ func (c *ClientConn) SignAndBroadcastTx(ctx context.Context, msg sdktypes.Msg) (
return nil, fmt.Errorf("failed to broadcast tx: %w", err)
}

res, err := client.GetTx(ctx, &sdktx.GetTxRequest{Hash: txResp.TxResponse.TxHash})
if err == nil {
fmt.Printf("JOEL - Tx response: %v\n", res.TxResponse)
// Wait for the tx to be included in a block (13 seconds for 2 blocks minimum)
res, err := waitForBlockInclusion(ctx, client, txResp.TxResponse.TxHash, 13*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to wait for tx inclusion: %w", err)
} else {
fmt.Printf("JOEL - Failed to fetch tx: %v\n", err)
// update the response with the final result
txResp.TxResponse = res.TxResponse
}

return txResp, nil
}

// waitForBlockInclusion waits for the tx to be included in a block, or times out after a given duration.
func waitForBlockInclusion(ctx context.Context, client sdktx.ServiceClient, txHash string, waitTimeout time.Duration) (*sdktx.GetTxResponse, error) {
exitAfter := time.After(waitTimeout)
for {
select {
// check if wait timeout is exceeded
case <-exitAfter:
return nil, fmt.Errorf("timed out after: %d; wait for tx %s to be included in a block", waitTimeout, txHash)
// check if in block every second
case <-time.After(1 * time.Second):
res, err := client.GetTx(ctx, &sdktx.GetTxRequest{Hash: txHash})
if err == nil {
return res, nil
}
// check if context is done
case <-ctx.Done():
return nil, ctx.Err()
}
}
}

0 comments on commit cc25e64

Please sign in to comment.