github.com/0xsequence/ethkit@v1.25.0/go-ethereum/ethclient/gethclient/gethclient.go (about)

     1  // Copyright 2021 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package gethclient provides an RPC client for geth-specific APIs.
    18  package gethclient
    19  
    20  import (
    21  	"context"
    22  	"math/big"
    23  	"runtime"
    24  	"runtime/debug"
    25  
    26  	"github.com/0xsequence/ethkit/go-ethereum"
    27  	"github.com/0xsequence/ethkit/go-ethereum/common"
    28  	"github.com/0xsequence/ethkit/go-ethereum/common/hexutil"
    29  	"github.com/0xsequence/ethkit/go-ethereum/core/types"
    30  	"github.com/0xsequence/ethkit/go-ethereum/rpc"
    31  )
    32  
    33  // Client is a wrapper around rpc.Client that implements geth-specific functionality.
    34  //
    35  // If you want to use the standardized Ethereum RPC functionality, use ethclient.Client instead.
    36  type Client struct {
    37  	c *rpc.Client
    38  }
    39  
    40  // New creates a client that uses the given RPC client.
    41  func New(c *rpc.Client) *Client {
    42  	return &Client{c}
    43  }
    44  
    45  // CreateAccessList tries to create an access list for a specific transaction based on the
    46  // current pending state of the blockchain.
    47  func (ec *Client) CreateAccessList(ctx context.Context, msg ethereum.CallMsg) (*types.AccessList, uint64, string, error) {
    48  	type accessListResult struct {
    49  		Accesslist *types.AccessList `json:"accessList"`
    50  		Error      string            `json:"error,omitempty"`
    51  		GasUsed    hexutil.Uint64    `json:"gasUsed"`
    52  	}
    53  	var result accessListResult
    54  	if err := ec.c.CallContext(ctx, &result, "eth_createAccessList", toCallArg(msg)); err != nil {
    55  		return nil, 0, "", err
    56  	}
    57  	return result.Accesslist, uint64(result.GasUsed), result.Error, nil
    58  }
    59  
    60  // AccountResult is the result of a GetProof operation.
    61  type AccountResult struct {
    62  	Address      common.Address  `json:"address"`
    63  	AccountProof []string        `json:"accountProof"`
    64  	Balance      *big.Int        `json:"balance"`
    65  	CodeHash     common.Hash     `json:"codeHash"`
    66  	Nonce        uint64          `json:"nonce"`
    67  	StorageHash  common.Hash     `json:"storageHash"`
    68  	StorageProof []StorageResult `json:"storageProof"`
    69  }
    70  
    71  // StorageResult provides a proof for a key-value pair.
    72  type StorageResult struct {
    73  	Key   string   `json:"key"`
    74  	Value *big.Int `json:"value"`
    75  	Proof []string `json:"proof"`
    76  }
    77  
    78  // GetProof returns the account and storage values of the specified account including the Merkle-proof.
    79  // The block number can be nil, in which case the value is taken from the latest known block.
    80  func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*AccountResult, error) {
    81  	type storageResult struct {
    82  		Key   string       `json:"key"`
    83  		Value *hexutil.Big `json:"value"`
    84  		Proof []string     `json:"proof"`
    85  	}
    86  
    87  	type accountResult struct {
    88  		Address      common.Address  `json:"address"`
    89  		AccountProof []string        `json:"accountProof"`
    90  		Balance      *hexutil.Big    `json:"balance"`
    91  		CodeHash     common.Hash     `json:"codeHash"`
    92  		Nonce        hexutil.Uint64  `json:"nonce"`
    93  		StorageHash  common.Hash     `json:"storageHash"`
    94  		StorageProof []storageResult `json:"storageProof"`
    95  	}
    96  
    97  	var res accountResult
    98  	err := ec.c.CallContext(ctx, &res, "eth_getProof", account, keys, toBlockNumArg(blockNumber))
    99  	// Turn hexutils back to normal datatypes
   100  	storageResults := make([]StorageResult, 0, len(res.StorageProof))
   101  	for _, st := range res.StorageProof {
   102  		storageResults = append(storageResults, StorageResult{
   103  			Key:   st.Key,
   104  			Value: st.Value.ToInt(),
   105  			Proof: st.Proof,
   106  		})
   107  	}
   108  	result := AccountResult{
   109  		Address:      res.Address,
   110  		AccountProof: res.AccountProof,
   111  		Balance:      res.Balance.ToInt(),
   112  		Nonce:        uint64(res.Nonce),
   113  		CodeHash:     res.CodeHash,
   114  		StorageHash:  res.StorageHash,
   115  		StorageProof: storageResults,
   116  	}
   117  	return &result, err
   118  }
   119  
   120  // OverrideAccount specifies the state of an account to be overridden.
   121  type OverrideAccount struct {
   122  	Nonce     uint64                      `json:"nonce"`
   123  	Code      []byte                      `json:"code"`
   124  	Balance   *big.Int                    `json:"balance"`
   125  	State     map[common.Hash]common.Hash `json:"state"`
   126  	StateDiff map[common.Hash]common.Hash `json:"stateDiff"`
   127  }
   128  
   129  // CallContract executes a message call transaction, which is directly executed in the VM
   130  // of the node, but never mined into the blockchain.
   131  //
   132  // blockNumber selects the block height at which the call runs. It can be nil, in which
   133  // case the code is taken from the latest known block. Note that state from very old
   134  // blocks might not be available.
   135  //
   136  // overrides specifies a map of contract states that should be overwritten before executing
   137  // the message call.
   138  // Please use ethclient.CallContract instead if you don't need the override functionality.
   139  func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int, overrides *map[common.Address]OverrideAccount) ([]byte, error) {
   140  	var hex hexutil.Bytes
   141  	err := ec.c.CallContext(
   142  		ctx, &hex, "eth_call", toCallArg(msg),
   143  		toBlockNumArg(blockNumber), toOverrideMap(overrides),
   144  	)
   145  	return hex, err
   146  }
   147  
   148  // GCStats retrieves the current garbage collection stats from a geth node.
   149  func (ec *Client) GCStats(ctx context.Context) (*debug.GCStats, error) {
   150  	var result debug.GCStats
   151  	err := ec.c.CallContext(ctx, &result, "debug_gcStats")
   152  	return &result, err
   153  }
   154  
   155  // MemStats retrieves the current memory stats from a geth node.
   156  func (ec *Client) MemStats(ctx context.Context) (*runtime.MemStats, error) {
   157  	var result runtime.MemStats
   158  	err := ec.c.CallContext(ctx, &result, "debug_memStats")
   159  	return &result, err
   160  }
   161  
   162  // SetHead sets the current head of the local chain by block number.
   163  // Note, this is a destructive action and may severely damage your chain.
   164  // Use with extreme caution.
   165  func (ec *Client) SetHead(ctx context.Context, number *big.Int) error {
   166  	return ec.c.CallContext(ctx, nil, "debug_setHead", toBlockNumArg(number))
   167  }
   168  
   169  // SubscribePendingTransactions subscribes to new pending transactions.
   170  func (ec *Client) SubscribePendingTransactions(ctx context.Context, ch chan<- common.Hash) (*rpc.ClientSubscription, error) {
   171  	return ec.c.EthSubscribe(ctx, ch, "newPendingTransactions")
   172  }
   173  
   174  func toBlockNumArg(number *big.Int) string {
   175  	if number == nil {
   176  		return "latest"
   177  	}
   178  	pending := big.NewInt(-1)
   179  	if number.Cmp(pending) == 0 {
   180  		return "pending"
   181  	}
   182  	return hexutil.EncodeBig(number)
   183  }
   184  
   185  func toCallArg(msg ethereum.CallMsg) interface{} {
   186  	arg := map[string]interface{}{
   187  		"from": msg.From,
   188  		"to":   msg.To,
   189  	}
   190  	if len(msg.Data) > 0 {
   191  		arg["data"] = hexutil.Bytes(msg.Data)
   192  	}
   193  	if msg.Value != nil {
   194  		arg["value"] = (*hexutil.Big)(msg.Value)
   195  	}
   196  	if msg.Gas != 0 {
   197  		arg["gas"] = hexutil.Uint64(msg.Gas)
   198  	}
   199  	if msg.GasPrice != nil {
   200  		arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
   201  	}
   202  	return arg
   203  }
   204  
   205  func toOverrideMap(overrides *map[common.Address]OverrideAccount) interface{} {
   206  	if overrides == nil {
   207  		return nil
   208  	}
   209  	type overrideAccount struct {
   210  		Nonce     hexutil.Uint64              `json:"nonce"`
   211  		Code      hexutil.Bytes               `json:"code"`
   212  		Balance   *hexutil.Big                `json:"balance"`
   213  		State     map[common.Hash]common.Hash `json:"state"`
   214  		StateDiff map[common.Hash]common.Hash `json:"stateDiff"`
   215  	}
   216  	result := make(map[common.Address]overrideAccount)
   217  	for addr, override := range *overrides {
   218  		result[addr] = overrideAccount{
   219  			Nonce:     hexutil.Uint64(override.Nonce),
   220  			Code:      override.Code,
   221  			Balance:   (*hexutil.Big)(override.Balance),
   222  			State:     override.State,
   223  			StateDiff: override.StateDiff,
   224  		}
   225  	}
   226  	return &result
   227  }