github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/blockchain/clients/zksync.go (about)

     1  package clients
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/ethereum/go-ethereum"
     7  	"github.com/ethereum/go-ethereum/common"
     8  	"github.com/pkg/errors"
     9  	"github.com/zksync-sdk/zksync2-go/clients"
    10  
    11  	"github.com/machinefi/w3bstream/pkg/enums"
    12  )
    13  
    14  type (
    15  	// ZKSyncClient is a client for zksync chain
    16  	ZKSyncClient struct {
    17  		*EthClient
    18  	}
    19  )
    20  
    21  // NewZKSyncClient creates a new ZKSyncClient
    22  func NewZKSyncClient(endpoint string) *ZKSyncClient {
    23  	return &ZKSyncClient{
    24  		EthClient: NewEthClient(endpoint),
    25  	}
    26  }
    27  
    28  // TransactionByHash returns transaction by hash
    29  func (c *ZKSyncClient) TransactionByHash(ctx context.Context, hash string) (any, error) {
    30  	client, err := clients.Dial(c.endpoint)
    31  	if err != nil {
    32  		return nil, errors.Wrap(err, "dial chain address failed")
    33  	}
    34  
    35  	tx, _, err := client.TransactionByHash(ctx, common.HexToHash(hash))
    36  	if err != nil {
    37  		return nil, errors.Wrap(err, "query transaction failed")
    38  	}
    39  	return tx, nil
    40  }
    41  
    42  // TransactionState returns transaction state
    43  func (c *ZKSyncClient) TransactionState(ctx context.Context, hash string) (enums.TransactionState, error) {
    44  	client, err := clients.Dial(c.endpoint)
    45  	if err != nil {
    46  		return enums.TRANSACTION_STATE_UNKNOWN, errors.Wrap(err, "dial chain failed")
    47  	}
    48  	nh := common.HexToHash(hash)
    49  
    50  	_, p, err := client.TransactionByHash(ctx, nh)
    51  	if err != nil {
    52  		if err == ethereum.NotFound {
    53  			return enums.TRANSACTION_STATE__FAILED, nil
    54  		}
    55  		return enums.TRANSACTION_STATE_UNKNOWN, errors.Wrap(err, "get transaction by hash failed")
    56  	}
    57  	if p {
    58  		return enums.TRANSACTION_STATE__PENDING, nil
    59  	}
    60  
    61  	receipt, err := client.TransactionReceipt(ctx, nh)
    62  	if err != nil {
    63  		if err == ethereum.NotFound {
    64  			return enums.TRANSACTION_STATE__IN_BLOCK, nil
    65  		}
    66  		return enums.TRANSACTION_STATE_UNKNOWN, errors.Wrap(err, "get transaction receipt failed")
    67  	}
    68  	if receipt.Status == 0 {
    69  		return enums.TRANSACTION_STATE__FAILED, nil
    70  	}
    71  	return enums.TRANSACTION_STATE__CONFIRMED, nil
    72  }