github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/mobile/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  // Contains a wrapper for the Ethereum client.
    18  
    19  package geth
    20  
    21  import (
    22  	"math/big"
    23  
    24  	"github.com/ethereum/go-ethereum/core/types"
    25  	"github.com/ethereum/go-ethereum/ethclient"
    26  )
    27  
    28  // EthereumClient provides access to the Ethereum APIs.
    29  type EthereumClient struct {
    30  	client *ethclient.Client
    31  }
    32  
    33  // NewEthereumClient connects a client to the given URL.
    34  func NewEthereumClient(rawurl string) (client *EthereumClient, _ error) {
    35  	rawClient, err := ethclient.Dial(rawurl)
    36  	return &EthereumClient{rawClient}, err
    37  }
    38  
    39  // GetBlockByHash returns the given full block.
    40  func (ec *EthereumClient) GetBlockByHash(ctx *Context, hash *Hash) (block *Block, _ error) {
    41  	rawBlock, err := ec.client.BlockByHash(ctx.context, hash.hash)
    42  	return &Block{rawBlock}, err
    43  }
    44  
    45  // GetBlockByNumber returns a block from the current canonical chain. If number is <0, the
    46  // latest known block is returned.
    47  func (ec *EthereumClient) GetBlockByNumber(ctx *Context, number int64) (block *Block, _ error) {
    48  	if number < 0 {
    49  		rawBlock, err := ec.client.BlockByNumber(ctx.context, nil)
    50  		return &Block{rawBlock}, err
    51  	}
    52  	rawBlock, err := ec.client.BlockByNumber(ctx.context, big.NewInt(number))
    53  	return &Block{rawBlock}, err
    54  }
    55  
    56  // GetHeaderByHash returns the block header with the given hash.
    57  func (ec *EthereumClient) GetHeaderByHash(ctx *Context, hash *Hash) (header *Header, _ error) {
    58  	rawHeader, err := ec.client.HeaderByHash(ctx.context, hash.hash)
    59  	return &Header{rawHeader}, err
    60  }
    61  
    62  // GetHeaderByNumber returns a block header from the current canonical chain. If number is <0,
    63  // the latest known header is returned.
    64  func (ec *EthereumClient) GetHeaderByNumber(ctx *Context, number int64) (header *Header, _ error) {
    65  	if number < 0 {
    66  		rawHeader, err := ec.client.HeaderByNumber(ctx.context, nil)
    67  		return &Header{rawHeader}, err
    68  	}
    69  	rawHeader, err := ec.client.HeaderByNumber(ctx.context, big.NewInt(number))
    70  	return &Header{rawHeader}, err
    71  }
    72  
    73  // GetTransactionByHash returns the transaction with the given hash.
    74  func (ec *EthereumClient) GetTransactionByHash(ctx *Context, hash *Hash) (tx *Transaction, _ error) {
    75  	// TODO(karalabe): handle isPending
    76  	rawTx, _, err := ec.client.TransactionByHash(ctx.context, hash.hash)
    77  	return &Transaction{rawTx}, err
    78  }
    79  
    80  // GetTransactionCount returns the total number of transactions in the given block.
    81  func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count int, _ error) {
    82  	rawCount, err := ec.client.TransactionCount(ctx.context, hash.hash)
    83  	return int(rawCount), err
    84  }
    85  
    86  // GetTransactionInBlock returns a single transaction at index in the given block.
    87  func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
    88  	rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
    89  	return &Transaction{rawTx}, err
    90  
    91  }
    92  
    93  // GetTransactionReceipt returns the receipt of a transaction by transaction hash.
    94  // Note that the receipt is not available for pending transactions.
    95  func (ec *EthereumClient) GetTransactionReceipt(ctx *Context, hash *Hash) (receipt *Receipt, _ error) {
    96  	rawReceipt, err := ec.client.TransactionReceipt(ctx.context, hash.hash)
    97  	return &Receipt{rawReceipt}, err
    98  }
    99  
   100  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   101  // no sync currently running, it returns nil.
   102  func (ec *EthereumClient) SyncProgress(ctx *Context) (progress *SyncProgress, _ error) {
   103  	rawProgress, err := ec.client.SyncProgress(ctx.context)
   104  	if rawProgress == nil {
   105  		return nil, err
   106  	}
   107  	return &SyncProgress{*rawProgress}, err
   108  }
   109  
   110  // NewHeadHandler is a client-side subscription callback to invoke on events and
   111  // subscription failure.
   112  type NewHeadHandler interface {
   113  	OnNewHead(header *Header)
   114  	OnError(failure string)
   115  }
   116  
   117  // SubscribeNewHead subscribes to notifications about the current blockchain head
   118  // on the given channel.
   119  func (ec *EthereumClient) SubscribeNewHead(ctx *Context, handler NewHeadHandler, buffer int) (sub *Subscription, _ error) {
   120  	// Subscribe to the event internally
   121  	ch := make(chan *types.Header, buffer)
   122  	rawSub, err := ec.client.SubscribeNewHead(ctx.context, ch)
   123  	if err != nil {
   124  		return nil, err
   125  	}
   126  	// Start up a dispatcher to feed into the callback
   127  	go func() {
   128  		for {
   129  			select {
   130  			case header := <-ch:
   131  				handler.OnNewHead(&Header{header})
   132  
   133  			case err := <-rawSub.Err():
   134  				handler.OnError(err.Error())
   135  				return
   136  			}
   137  		}
   138  	}()
   139  	return &Subscription{rawSub}, nil
   140  }
   141  
   142  // State Access
   143  
   144  // GetBalanceAt returns the wei balance of the given account.
   145  // The block number can be <0, in which case the balance is taken from the latest known block.
   146  func (ec *EthereumClient) GetBalanceAt(ctx *Context, account *Address, number int64) (balance *BigInt, _ error) {
   147  	if number < 0 {
   148  		rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, nil)
   149  		return &BigInt{rawBalance}, err
   150  	}
   151  	rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, big.NewInt(number))
   152  	return &BigInt{rawBalance}, err
   153  }
   154  
   155  // GetStorageAt returns the value of key in the contract storage of the given account.
   156  // The block number can be <0, in which case the value is taken from the latest known block.
   157  func (ec *EthereumClient) GetStorageAt(ctx *Context, account *Address, key *Hash, number int64) (storage []byte, _ error) {
   158  	if number < 0 {
   159  		return ec.client.StorageAt(ctx.context, account.address, key.hash, nil)
   160  	}
   161  	return ec.client.StorageAt(ctx.context, account.address, key.hash, big.NewInt(number))
   162  }
   163  
   164  // GetCodeAt returns the contract code of the given account.
   165  // The block number can be <0, in which case the code is taken from the latest known block.
   166  func (ec *EthereumClient) GetCodeAt(ctx *Context, account *Address, number int64) (code []byte, _ error) {
   167  	if number < 0 {
   168  		return ec.client.CodeAt(ctx.context, account.address, nil)
   169  	}
   170  	return ec.client.CodeAt(ctx.context, account.address, big.NewInt(number))
   171  }
   172  
   173  // GetNonceAt returns the account nonce of the given account.
   174  // The block number can be <0, in which case the nonce is taken from the latest known block.
   175  func (ec *EthereumClient) GetNonceAt(ctx *Context, account *Address, number int64) (nonce int64, _ error) {
   176  	if number < 0 {
   177  		rawNonce, err := ec.client.NonceAt(ctx.context, account.address, nil)
   178  		return int64(rawNonce), err
   179  	}
   180  	rawNonce, err := ec.client.NonceAt(ctx.context, account.address, big.NewInt(number))
   181  	return int64(rawNonce), err
   182  }
   183  
   184  // Filters
   185  
   186  // FilterLogs executes a filter query.
   187  func (ec *EthereumClient) FilterLogs(ctx *Context, query *FilterQuery) (logs *Logs, _ error) {
   188  	rawLogs, err := ec.client.FilterLogs(ctx.context, query.query)
   189  	if err != nil {
   190  		return nil, err
   191  	}
   192  	// Temp hack due to vm.Logs being []*vm.Log
   193  	res := make([]*types.Log, len(rawLogs))
   194  	for i, log := range rawLogs {
   195  		res[i] = &log
   196  	}
   197  	return &Logs{res}, nil
   198  }
   199  
   200  // FilterLogsHandler is a client-side subscription callback to invoke on events and
   201  // subscription failure.
   202  type FilterLogsHandler interface {
   203  	OnFilterLogs(log *Log)
   204  	OnError(failure string)
   205  }
   206  
   207  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   208  func (ec *EthereumClient) SubscribeFilterLogs(ctx *Context, query *FilterQuery, handler FilterLogsHandler, buffer int) (sub *Subscription, _ error) {
   209  	// Subscribe to the event internally
   210  	ch := make(chan types.Log, buffer)
   211  	rawSub, err := ec.client.SubscribeFilterLogs(ctx.context, query.query, ch)
   212  	if err != nil {
   213  		return nil, err
   214  	}
   215  	// Start up a dispatcher to feed into the callback
   216  	go func() {
   217  		for {
   218  			select {
   219  			case log := <-ch:
   220  				handler.OnFilterLogs(&Log{&log})
   221  
   222  			case err := <-rawSub.Err():
   223  				handler.OnError(err.Error())
   224  				return
   225  			}
   226  		}
   227  	}()
   228  	return &Subscription{rawSub}, nil
   229  }
   230  
   231  // Pending State
   232  
   233  // GetPendingBalanceAt returns the wei balance of the given account in the pending state.
   234  func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
   235  	rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
   236  	return &BigInt{rawBalance}, err
   237  }
   238  
   239  // GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   240  func (ec *EthereumClient) GetPendingStorageAt(ctx *Context, account *Address, key *Hash) (storage []byte, _ error) {
   241  	return ec.client.PendingStorageAt(ctx.context, account.address, key.hash)
   242  }
   243  
   244  // GetPendingCodeAt returns the contract code of the given account in the pending state.
   245  func (ec *EthereumClient) GetPendingCodeAt(ctx *Context, account *Address) (code []byte, _ error) {
   246  	return ec.client.PendingCodeAt(ctx.context, account.address)
   247  }
   248  
   249  // GetPendingNonceAt returns the account nonce of the given account in the pending state.
   250  // This is the nonce that should be used for the next transaction.
   251  func (ec *EthereumClient) GetPendingNonceAt(ctx *Context, account *Address) (nonce int64, _ error) {
   252  	rawNonce, err := ec.client.PendingNonceAt(ctx.context, account.address)
   253  	return int64(rawNonce), err
   254  }
   255  
   256  // GetPendingTransactionCount returns the total number of transactions in the pending state.
   257  func (ec *EthereumClient) GetPendingTransactionCount(ctx *Context) (count int, _ error) {
   258  	rawCount, err := ec.client.PendingTransactionCount(ctx.context)
   259  	return int(rawCount), err
   260  }
   261  
   262  // Contract Calling
   263  
   264  // CallContract executes a message call transaction, which is directly executed in the VM
   265  // of the node, but never mined into the blockchain.
   266  //
   267  // blockNumber selects the block height at which the call runs. It can be <0, in which
   268  // case the code is taken from the latest known block. Note that state from very old
   269  // blocks might not be available.
   270  func (ec *EthereumClient) CallContract(ctx *Context, msg *CallMsg, number int64) (output []byte, _ error) {
   271  	if number < 0 {
   272  		return ec.client.CallContract(ctx.context, msg.msg, nil)
   273  	}
   274  	return ec.client.CallContract(ctx.context, msg.msg, big.NewInt(number))
   275  }
   276  
   277  // PendingCallContract executes a message call transaction using the EVM.
   278  // The state seen by the contract call is the pending state.
   279  func (ec *EthereumClient) PendingCallContract(ctx *Context, msg *CallMsg) (output []byte, _ error) {
   280  	return ec.client.PendingCallContract(ctx.context, msg.msg)
   281  }
   282  
   283  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   284  // execution of a transaction.
   285  func (ec *EthereumClient) SuggestGasPrice(ctx *Context) (price *BigInt, _ error) {
   286  	rawPrice, err := ec.client.SuggestGasPrice(ctx.context)
   287  	return &BigInt{rawPrice}, err
   288  }
   289  
   290  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   291  // the current pending state of the backend blockchain. There is no guarantee that this is
   292  // the true gas limit requirement as other transactions may be added or removed by miners,
   293  // but it should provide a basis for setting a reasonable default.
   294  func (ec *EthereumClient) EstimateGas(ctx *Context, msg *CallMsg) (gas *BigInt, _ error) {
   295  	rawGas, err := ec.client.EstimateGas(ctx.context, msg.msg)
   296  	return &BigInt{rawGas}, err
   297  }
   298  
   299  // SendTransaction injects a signed transaction into the pending pool for execution.
   300  //
   301  // If the transaction was a contract creation use the TransactionReceipt method to get the
   302  // contract address after the transaction has been mined.
   303  func (ec *EthereumClient) SendTransaction(ctx *Context, tx *Transaction) error {
   304  	return ec.client.SendTransaction(ctx.context, tx.tx)
   305  }