github.com/phillinzzz/newBsc@v1.1.6/ethclient/ethclient.go (about)

     1  // Copyright 2016 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 ethclient provides a client for the Ethereum RPC API.
    18  package ethclient
    19  
    20  import (
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  
    27  	"github.com/phillinzzz/newBsc"
    28  	"github.com/phillinzzz/newBsc/common"
    29  	"github.com/phillinzzz/newBsc/common/hexutil"
    30  	"github.com/phillinzzz/newBsc/core/types"
    31  	"github.com/phillinzzz/newBsc/rpc"
    32  )
    33  
    34  // Client defines typed wrappers for the Ethereum RPC API.
    35  type Client struct {
    36  	c *rpc.Client
    37  }
    38  
    39  // Dial connects a client to the given URL.
    40  func Dial(rawurl string) (*Client, error) {
    41  	return DialContext(context.Background(), rawurl)
    42  }
    43  
    44  func DialContext(ctx context.Context, rawurl string) (*Client, error) {
    45  	c, err := rpc.DialContext(ctx, rawurl)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	return NewClient(c), nil
    50  }
    51  
    52  // NewClient creates a client that uses the given RPC client.
    53  func NewClient(c *rpc.Client) *Client {
    54  	return &Client{c}
    55  }
    56  
    57  func (ec *Client) Close() {
    58  	ec.c.Close()
    59  }
    60  
    61  // Blockchain Access
    62  
    63  // ChainId retrieves the current chain ID for transaction replay protection.
    64  func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {
    65  	var result hexutil.Big
    66  	err := ec.c.CallContext(ctx, &result, "eth_chainId")
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	return (*big.Int)(&result), err
    71  }
    72  
    73  // BlockByHash returns the given full block.
    74  //
    75  // Note that loading full blocks requires two requests. Use HeaderByHash
    76  // if you don't need all transactions or uncle headers.
    77  func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
    78  	return ec.getBlock(ctx, "eth_getBlockByHash", hash, true)
    79  }
    80  
    81  // BlockByNumber returns a block from the current canonical chain. If number is nil, the
    82  // latest known block is returned.
    83  //
    84  // Note that loading full blocks requires two requests. Use HeaderByNumber
    85  // if you don't need all transactions or uncle headers.
    86  func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
    87  	return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
    88  }
    89  
    90  // BlockNumber returns the most recent block number
    91  func (ec *Client) BlockNumber(ctx context.Context) (uint64, error) {
    92  	var result hexutil.Uint64
    93  	err := ec.c.CallContext(ctx, &result, "eth_blockNumber")
    94  	return uint64(result), err
    95  }
    96  
    97  type rpcBlock struct {
    98  	Hash         common.Hash      `json:"hash"`
    99  	Transactions []rpcTransaction `json:"transactions"`
   100  	UncleHashes  []common.Hash    `json:"uncles"`
   101  }
   102  
   103  func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) {
   104  	var raw json.RawMessage
   105  	err := ec.c.CallContext(ctx, &raw, method, args...)
   106  	if err != nil {
   107  		return nil, err
   108  	} else if len(raw) == 0 {
   109  		return nil, ethereum.NotFound
   110  	}
   111  	// Decode header and transactions.
   112  	var head *types.Header
   113  	var body rpcBlock
   114  	if err := json.Unmarshal(raw, &head); err != nil {
   115  		return nil, err
   116  	}
   117  	if err := json.Unmarshal(raw, &body); err != nil {
   118  		return nil, err
   119  	}
   120  	// Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
   121  	if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
   122  		return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
   123  	}
   124  	if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
   125  		return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles")
   126  	}
   127  	if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
   128  		return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions")
   129  	}
   130  	if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
   131  		return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions")
   132  	}
   133  	// Load uncles because they are not included in the block response.
   134  	var uncles []*types.Header
   135  	if len(body.UncleHashes) > 0 {
   136  		uncles = make([]*types.Header, len(body.UncleHashes))
   137  		reqs := make([]rpc.BatchElem, len(body.UncleHashes))
   138  		for i := range reqs {
   139  			reqs[i] = rpc.BatchElem{
   140  				Method: "eth_getUncleByBlockHashAndIndex",
   141  				Args:   []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
   142  				Result: &uncles[i],
   143  			}
   144  		}
   145  		if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
   146  			return nil, err
   147  		}
   148  		for i := range reqs {
   149  			if reqs[i].Error != nil {
   150  				return nil, reqs[i].Error
   151  			}
   152  			if uncles[i] == nil {
   153  				return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:])
   154  			}
   155  		}
   156  	}
   157  	// Fill the sender cache of transactions in the block.
   158  	txs := make([]*types.Transaction, len(body.Transactions))
   159  	for i, tx := range body.Transactions {
   160  		if tx.From != nil {
   161  			setSenderFromServer(tx.tx, *tx.From, body.Hash)
   162  		}
   163  		txs[i] = tx.tx
   164  	}
   165  	return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil
   166  }
   167  
   168  // HeaderByHash returns the block header with the given hash.
   169  func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   170  	var head *types.Header
   171  	err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false)
   172  	if err == nil && head == nil {
   173  		err = ethereum.NotFound
   174  	}
   175  	return head, err
   176  }
   177  
   178  // HeaderByNumber returns a block header from the current canonical chain. If number is
   179  // nil, the latest known header is returned.
   180  func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
   181  	var head *types.Header
   182  	err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
   183  	if err == nil && head == nil {
   184  		err = ethereum.NotFound
   185  	}
   186  	return head, err
   187  }
   188  
   189  // GetDiffAccounts returns changed accounts in a specific block number.
   190  func (ec *Client) GetDiffAccounts(ctx context.Context, number *big.Int) ([]common.Address, error) {
   191  	accounts := make([]common.Address, 0)
   192  	err := ec.c.CallContext(ctx, &accounts, "eth_getDiffAccounts", toBlockNumArg(number))
   193  	return accounts, err
   194  }
   195  
   196  // GetDiffAccountsWithScope returns detailed changes of some interested accounts in a specific block number.
   197  func (ec *Client) GetDiffAccountsWithScope(ctx context.Context, number *big.Int, accounts []common.Address) (*types.DiffAccountsInBlock, error) {
   198  	var result types.DiffAccountsInBlock
   199  	err := ec.c.CallContext(ctx, &result, "eth_getDiffAccountsWithScope", toBlockNumArg(number), accounts)
   200  	return &result, err
   201  }
   202  
   203  type rpcTransaction struct {
   204  	tx *types.Transaction
   205  	txExtraInfo
   206  }
   207  
   208  type txExtraInfo struct {
   209  	BlockNumber *string         `json:"blockNumber,omitempty"`
   210  	BlockHash   *common.Hash    `json:"blockHash,omitempty"`
   211  	From        *common.Address `json:"from,omitempty"`
   212  }
   213  
   214  func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error {
   215  	if err := json.Unmarshal(msg, &tx.tx); err != nil {
   216  		return err
   217  	}
   218  	return json.Unmarshal(msg, &tx.txExtraInfo)
   219  }
   220  
   221  // TransactionByHash returns the transaction with the given hash.
   222  func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
   223  	var json *rpcTransaction
   224  	err = ec.c.CallContext(ctx, &json, "eth_getTransactionByHash", hash)
   225  	if err != nil {
   226  		return nil, false, err
   227  	} else if json == nil {
   228  		return nil, false, ethereum.NotFound
   229  	} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   230  		return nil, false, fmt.Errorf("server returned transaction without signature")
   231  	}
   232  	if json.From != nil && json.BlockHash != nil {
   233  		setSenderFromServer(json.tx, *json.From, *json.BlockHash)
   234  	}
   235  	return json.tx, json.BlockNumber == nil, nil
   236  }
   237  
   238  // TransactionSender returns the sender address of the given transaction. The transaction
   239  // must be known to the remote node and included in the blockchain at the given block and
   240  // index. The sender is the one derived by the protocol at the time of inclusion.
   241  //
   242  // There is a fast-path for transactions retrieved by TransactionByHash and
   243  // TransactionInBlock. Getting their sender address can be done without an RPC interaction.
   244  func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) {
   245  	// Try to load the address from the cache.
   246  	sender, err := types.Sender(&senderFromServer{blockhash: block}, tx)
   247  	if err == nil {
   248  		return sender, nil
   249  	}
   250  	var meta struct {
   251  		Hash common.Hash
   252  		From common.Address
   253  	}
   254  	if err = ec.c.CallContext(ctx, &meta, "eth_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil {
   255  		return common.Address{}, err
   256  	}
   257  	if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() {
   258  		return common.Address{}, errors.New("wrong inclusion block/index")
   259  	}
   260  	return meta.From, nil
   261  }
   262  
   263  // TransactionCount returns the total number of transactions in the given block.
   264  func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
   265  	var num hexutil.Uint
   266  	err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByHash", blockHash)
   267  	return uint(num), err
   268  }
   269  
   270  // TransactionInBlock returns a single transaction at index in the given block.
   271  func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
   272  	var json *rpcTransaction
   273  	err := ec.c.CallContext(ctx, &json, "eth_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index))
   274  	if err != nil {
   275  		return nil, err
   276  	}
   277  	if json == nil {
   278  		return nil, ethereum.NotFound
   279  	} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   280  		return nil, fmt.Errorf("server returned transaction without signature")
   281  	}
   282  	if json.From != nil && json.BlockHash != nil {
   283  		setSenderFromServer(json.tx, *json.From, *json.BlockHash)
   284  	}
   285  	return json.tx, err
   286  }
   287  
   288  // TransactionInBlock returns a single transaction at index in the given block.
   289  func (ec *Client) TransactionsInBlock(ctx context.Context, number *big.Int) ([]*types.Transaction, error) {
   290  	var rpcTxs []*rpcTransaction
   291  	err := ec.c.CallContext(ctx, &rpcTxs, "eth_getTransactionsByBlockNumber", toBlockNumArg(number))
   292  	if err != nil {
   293  		return nil, err
   294  	}
   295  	fmt.Println(len(rpcTxs))
   296  	txs := make([]*types.Transaction, 0, len(rpcTxs))
   297  	for _, tx := range rpcTxs {
   298  		txs = append(txs, tx.tx)
   299  	}
   300  	return txs, err
   301  }
   302  
   303  // TransactionInBlock returns a single transaction at index in the given block.
   304  func (ec *Client) TransactionRecipientsInBlock(ctx context.Context, number *big.Int) ([]*types.Receipt, error) {
   305  	var rs []*types.Receipt
   306  	err := ec.c.CallContext(ctx, &rs, "eth_getTransactionReceiptsByBlockNumber", toBlockNumArg(number))
   307  	if err != nil {
   308  		return nil, err
   309  	}
   310  	return rs, err
   311  }
   312  
   313  // TransactionDataAndReceipt returns the original data and receipt of a transaction by transaction hash.
   314  // Note that the receipt is not available for pending transactions.
   315  func (ec *Client) TransactionDataAndReceipt(ctx context.Context, txHash common.Hash) (*types.OriginalDataAndReceipt, error) {
   316  	var r *types.OriginalDataAndReceipt
   317  	err := ec.c.CallContext(ctx, &r, "eth_getTransactionDataAndReceipt", txHash)
   318  	if err == nil {
   319  		if r == nil {
   320  			return nil, ethereum.NotFound
   321  		}
   322  	}
   323  	return r, err
   324  }
   325  
   326  // TransactionReceipt returns the receipt of a transaction by transaction hash.
   327  // Note that the receipt is not available for pending transactions.
   328  func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   329  	var r *types.Receipt
   330  	err := ec.c.CallContext(ctx, &r, "eth_getTransactionReceipt", txHash)
   331  	if err == nil {
   332  		if r == nil {
   333  			return nil, ethereum.NotFound
   334  		}
   335  	}
   336  	return r, err
   337  }
   338  
   339  func toBlockNumArg(number *big.Int) string {
   340  	if number == nil {
   341  		return "latest"
   342  	}
   343  	pending := big.NewInt(-1)
   344  	if number.Cmp(pending) == 0 {
   345  		return "pending"
   346  	}
   347  	return hexutil.EncodeBig(number)
   348  }
   349  
   350  type rpcProgress struct {
   351  	StartingBlock hexutil.Uint64
   352  	CurrentBlock  hexutil.Uint64
   353  	HighestBlock  hexutil.Uint64
   354  	PulledStates  hexutil.Uint64
   355  	KnownStates   hexutil.Uint64
   356  }
   357  
   358  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   359  // no sync currently running, it returns nil.
   360  func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) {
   361  	var raw json.RawMessage
   362  	if err := ec.c.CallContext(ctx, &raw, "eth_syncing"); err != nil {
   363  		return nil, err
   364  	}
   365  	// Handle the possible response types
   366  	var syncing bool
   367  	if err := json.Unmarshal(raw, &syncing); err == nil {
   368  		return nil, nil // Not syncing (always false)
   369  	}
   370  	var progress *rpcProgress
   371  	if err := json.Unmarshal(raw, &progress); err != nil {
   372  		return nil, err
   373  	}
   374  	return &ethereum.SyncProgress{
   375  		StartingBlock: uint64(progress.StartingBlock),
   376  		CurrentBlock:  uint64(progress.CurrentBlock),
   377  		HighestBlock:  uint64(progress.HighestBlock),
   378  		PulledStates:  uint64(progress.PulledStates),
   379  		KnownStates:   uint64(progress.KnownStates),
   380  	}, nil
   381  }
   382  
   383  // SubscribeNewHead subscribes to notifications about the current blockchain head
   384  // on the given channel.
   385  func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
   386  	return ec.c.EthSubscribe(ctx, ch, "newHeads")
   387  }
   388  
   389  // State Access
   390  
   391  // NetworkID returns the network ID (also known as the chain ID) for this chain.
   392  func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) {
   393  	version := new(big.Int)
   394  	var ver string
   395  	if err := ec.c.CallContext(ctx, &ver, "net_version"); err != nil {
   396  		return nil, err
   397  	}
   398  	if _, ok := version.SetString(ver, 10); !ok {
   399  		return nil, fmt.Errorf("invalid net_version result %q", ver)
   400  	}
   401  	return version, nil
   402  }
   403  
   404  // BalanceAt returns the wei balance of the given account.
   405  // The block number can be nil, in which case the balance is taken from the latest known block.
   406  func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
   407  	var result hexutil.Big
   408  	err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber))
   409  	return (*big.Int)(&result), err
   410  }
   411  
   412  // StorageAt returns the value of key in the contract storage of the given account.
   413  // The block number can be nil, in which case the value is taken from the latest known block.
   414  func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   415  	var result hexutil.Bytes
   416  	err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, toBlockNumArg(blockNumber))
   417  	return result, err
   418  }
   419  
   420  // CodeAt returns the contract code of the given account.
   421  // The block number can be nil, in which case the code is taken from the latest known block.
   422  func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
   423  	var result hexutil.Bytes
   424  	err := ec.c.CallContext(ctx, &result, "eth_getCode", account, toBlockNumArg(blockNumber))
   425  	return result, err
   426  }
   427  
   428  // NonceAt returns the account nonce of the given account.
   429  // The block number can be nil, in which case the nonce is taken from the latest known block.
   430  func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
   431  	var result hexutil.Uint64
   432  	err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, toBlockNumArg(blockNumber))
   433  	return uint64(result), err
   434  }
   435  
   436  // Filters
   437  
   438  // FilterLogs executes a filter query.
   439  func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
   440  	var result []types.Log
   441  	arg, err := toFilterArg(q)
   442  	if err != nil {
   443  		return nil, err
   444  	}
   445  	err = ec.c.CallContext(ctx, &result, "eth_getLogs", arg)
   446  	return result, err
   447  }
   448  
   449  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   450  func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   451  	arg, err := toFilterArg(q)
   452  	if err != nil {
   453  		return nil, err
   454  	}
   455  	return ec.c.EthSubscribe(ctx, ch, "logs", arg)
   456  }
   457  
   458  func toFilterArg(q ethereum.FilterQuery) (interface{}, error) {
   459  	arg := map[string]interface{}{
   460  		"address": q.Addresses,
   461  		"topics":  q.Topics,
   462  	}
   463  	if q.BlockHash != nil {
   464  		arg["blockHash"] = *q.BlockHash
   465  		if q.FromBlock != nil || q.ToBlock != nil {
   466  			return nil, fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
   467  		}
   468  	} else {
   469  		if q.FromBlock == nil {
   470  			arg["fromBlock"] = "0x0"
   471  		} else {
   472  			arg["fromBlock"] = toBlockNumArg(q.FromBlock)
   473  		}
   474  		arg["toBlock"] = toBlockNumArg(q.ToBlock)
   475  	}
   476  	return arg, nil
   477  }
   478  
   479  // Pending State
   480  
   481  // PendingBalanceAt returns the wei balance of the given account in the pending state.
   482  func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {
   483  	var result hexutil.Big
   484  	err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending")
   485  	return (*big.Int)(&result), err
   486  }
   487  
   488  // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   489  func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) {
   490  	var result hexutil.Bytes
   491  	err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, "pending")
   492  	return result, err
   493  }
   494  
   495  // PendingCodeAt returns the contract code of the given account in the pending state.
   496  func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
   497  	var result hexutil.Bytes
   498  	err := ec.c.CallContext(ctx, &result, "eth_getCode", account, "pending")
   499  	return result, err
   500  }
   501  
   502  // PendingNonceAt returns the account nonce of the given account in the pending state.
   503  // This is the nonce that should be used for the next transaction.
   504  func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   505  	var result hexutil.Uint64
   506  	err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending")
   507  	return uint64(result), err
   508  }
   509  
   510  // PendingTransactionCount returns the total number of transactions in the pending state.
   511  func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
   512  	var num hexutil.Uint
   513  	err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByNumber", "pending")
   514  	return uint(num), err
   515  }
   516  
   517  // TODO: SubscribePendingTransactions (needs server side)
   518  
   519  // Contract Calling
   520  
   521  // CallContract executes a message call transaction, which is directly executed in the VM
   522  // of the node, but never mined into the blockchain.
   523  //
   524  // blockNumber selects the block height at which the call runs. It can be nil, in which
   525  // case the code is taken from the latest known block. Note that state from very old
   526  // blocks might not be available.
   527  func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   528  	var hex hexutil.Bytes
   529  	err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), toBlockNumArg(blockNumber))
   530  	if err != nil {
   531  		return nil, err
   532  	}
   533  	return hex, nil
   534  }
   535  
   536  // PendingCallContract executes a message call transaction using the EVM.
   537  // The state seen by the contract call is the pending state.
   538  func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
   539  	var hex hexutil.Bytes
   540  	err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), "pending")
   541  	if err != nil {
   542  		return nil, err
   543  	}
   544  	return hex, nil
   545  }
   546  
   547  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   548  // execution of a transaction.
   549  func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   550  	var hex hexutil.Big
   551  	if err := ec.c.CallContext(ctx, &hex, "eth_gasPrice"); err != nil {
   552  		return nil, err
   553  	}
   554  	return (*big.Int)(&hex), nil
   555  }
   556  
   557  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   558  // the current pending state of the backend blockchain. There is no guarantee that this is
   559  // the true gas limit requirement as other transactions may be added or removed by miners,
   560  // but it should provide a basis for setting a reasonable default.
   561  func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
   562  	var hex hexutil.Uint64
   563  	err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg))
   564  	if err != nil {
   565  		return 0, err
   566  	}
   567  	return uint64(hex), nil
   568  }
   569  
   570  // SendTransaction injects a signed transaction into the pending pool for execution.
   571  //
   572  // If the transaction was a contract creation use the TransactionReceipt method to get the
   573  // contract address after the transaction has been mined.
   574  func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   575  	data, err := tx.MarshalBinary()
   576  	if err != nil {
   577  		return err
   578  	}
   579  	return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(data))
   580  }
   581  
   582  func toCallArg(msg ethereum.CallMsg) interface{} {
   583  	arg := map[string]interface{}{
   584  		"from": msg.From,
   585  		"to":   msg.To,
   586  	}
   587  	if len(msg.Data) > 0 {
   588  		arg["data"] = hexutil.Bytes(msg.Data)
   589  	}
   590  	if msg.Value != nil {
   591  		arg["value"] = (*hexutil.Big)(msg.Value)
   592  	}
   593  	if msg.Gas != 0 {
   594  		arg["gas"] = hexutil.Uint64(msg.Gas)
   595  	}
   596  	if msg.GasPrice != nil {
   597  		arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
   598  	}
   599  	return arg
   600  }