github.com/lmittmann/w3@v0.20.0/w3types/interfaces_test.go (about)

     1  package w3types_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/ethereum/go-ethereum/common"
     7  	"github.com/ethereum/go-ethereum/rpc"
     8  	"github.com/lmittmann/w3"
     9  	"github.com/lmittmann/w3/w3types"
    10  )
    11  
    12  // TxBySenderAndNonceFactory requests the senders transaction hash by the nonce.
    13  func TxBySenderAndNonceFactory(sender common.Address, nonce uint64) w3types.RPCCallerFactory[common.Hash] {
    14  	return &getTransactionBySenderAndNonceFactory{
    15  		sender: sender,
    16  		nonce:  nonce,
    17  	}
    18  }
    19  
    20  // getTransactionBySenderAndNonceFactory implements the w3types.RPCCaller and
    21  // w3types.RPCCallerFactory interfaces. It stores the method parameters and
    22  // the reference to the return value.
    23  type getTransactionBySenderAndNonceFactory struct {
    24  	// params
    25  	sender common.Address
    26  	nonce  uint64
    27  
    28  	// returns
    29  	returns *common.Hash
    30  }
    31  
    32  // Returns sets the reference to the return value.
    33  //
    34  // Return implements the [w3types.RPCCallerFactory] interface.
    35  func (f *getTransactionBySenderAndNonceFactory) Returns(txHash *common.Hash) w3types.RPCCaller {
    36  	f.returns = txHash
    37  	return f
    38  }
    39  
    40  // CreateRequest creates a batch request element for the Otterscan getTransactionBySenderAndNonce method.
    41  //
    42  // CreateRequest implements the [w3types.RPCCaller] interface.
    43  func (f *getTransactionBySenderAndNonceFactory) CreateRequest() (rpc.BatchElem, error) {
    44  	return rpc.BatchElem{
    45  		Method: "ots_getTransactionBySenderAndNonce",
    46  		Args:   []any{f.sender, f.nonce},
    47  		Result: f.returns,
    48  	}, nil
    49  }
    50  
    51  // HandleResponse handles the response of the Otterscan getTransactionBySenderAndNonce method.
    52  //
    53  // HandleResponse implements the [w3types.RPCCaller] interface.
    54  func (f *getTransactionBySenderAndNonceFactory) HandleResponse(elem rpc.BatchElem) error {
    55  	if err := elem.Error; err != nil {
    56  		return err
    57  	}
    58  	return nil
    59  }
    60  
    61  func ExampleRPCCaller_getTransactionBySenderAndNonce() {
    62  	client := w3.MustDial("https://docs-demo.quiknode.pro")
    63  	defer client.Close()
    64  
    65  	addr := w3.A("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")
    66  
    67  	var firstTxHash common.Hash
    68  	if err := client.Call(
    69  		TxBySenderAndNonceFactory(addr, 0).Returns(&firstTxHash),
    70  	); err != nil {
    71  		fmt.Printf("Request failed: %v\n", err)
    72  		return
    73  	}
    74  
    75  	fmt.Printf("First Tx Hash: %s\n", firstTxHash)
    76  	// Output:
    77  	// First Tx Hash: 0x6ff0860e202c61189cb2a3a38286bffd694acbc50577df6cb5a7ff40e21ea074
    78  }