github.com/bcnmy/go-ethereum@v1.10.27/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  // GetTransactionSender returns the sender address of a transaction. The transaction must
    81  // be included in blockchain at the given block and index.
    82  func (ec *EthereumClient) GetTransactionSender(ctx *Context, tx *Transaction, blockhash *Hash, index int) (sender *Address, _ error) {
    83  	addr, err := ec.client.TransactionSender(ctx.context, tx.tx, blockhash.hash, uint(index))
    84  	return &Address{addr}, err
    85  }
    86  
    87  // GetTransactionCount returns the total number of transactions in the given block.
    88  func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count int, _ error) {
    89  	rawCount, err := ec.client.TransactionCount(ctx.context, hash.hash)
    90  	return int(rawCount), err
    91  }
    92  
    93  // GetTransactionInBlock returns a single transaction at index in the given block.
    94  func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
    95  	rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
    96  	return &Transaction{rawTx}, err
    97  }
    98  
    99  // GetTransactionReceipt returns the receipt of a transaction by transaction hash.
   100  // Note that the receipt is not available for pending transactions.
   101  func (ec *EthereumClient) GetTransactionReceipt(ctx *Context, hash *Hash) (receipt *Receipt, _ error) {
   102  	rawReceipt, err := ec.client.TransactionReceipt(ctx.context, hash.hash)
   103  	return &Receipt{rawReceipt}, err
   104  }
   105  
   106  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   107  // no sync currently running, it returns nil.
   108  func (ec *EthereumClient) SyncProgress(ctx *Context) (progress *SyncProgress, _ error) {
   109  	rawProgress, err := ec.client.SyncProgress(ctx.context)
   110  	if rawProgress == nil {
   111  		return nil, err
   112  	}
   113  	return &SyncProgress{*rawProgress}, err
   114  }
   115  
   116  // NewHeadHandler is a client-side subscription callback to invoke on events and
   117  // subscription failure.
   118  type NewHeadHandler interface {
   119  	OnNewHead(header *Header)
   120  	OnError(failure string)
   121  }
   122  
   123  // SubscribeNewHead subscribes to notifications about the current blockchain head
   124  // on the given channel.
   125  func (ec *EthereumClient) SubscribeNewHead(ctx *Context, handler NewHeadHandler, buffer int) (sub *Subscription, _ error) {
   126  	// Subscribe to the event internally
   127  	ch := make(chan *types.Header, buffer)
   128  	rawSub, err := ec.client.SubscribeNewHead(ctx.context, ch)
   129  	if err != nil {
   130  		return nil, err
   131  	}
   132  	// Start up a dispatcher to feed into the callback
   133  	go func() {
   134  		for {
   135  			select {
   136  			case header := <-ch:
   137  				handler.OnNewHead(&Header{header})
   138  
   139  			case err := <-rawSub.Err():
   140  				if err != nil {
   141  					handler.OnError(err.Error())
   142  				}
   143  				return
   144  			}
   145  		}
   146  	}()
   147  	return &Subscription{rawSub}, nil
   148  }
   149  
   150  // State Access
   151  
   152  // GetBalanceAt returns the wei balance of the given account.
   153  // The block number can be <0, in which case the balance is taken from the latest known block.
   154  func (ec *EthereumClient) GetBalanceAt(ctx *Context, account *Address, number int64) (balance *BigInt, _ error) {
   155  	if number < 0 {
   156  		rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, nil)
   157  		return &BigInt{rawBalance}, err
   158  	}
   159  	rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, big.NewInt(number))
   160  	return &BigInt{rawBalance}, err
   161  }
   162  
   163  // GetStorageAt returns the value of key in the contract storage of the given account.
   164  // The block number can be <0, in which case the value is taken from the latest known block.
   165  func (ec *EthereumClient) GetStorageAt(ctx *Context, account *Address, key *Hash, number int64) (storage []byte, _ error) {
   166  	if number < 0 {
   167  		return ec.client.StorageAt(ctx.context, account.address, key.hash, nil)
   168  	}
   169  	return ec.client.StorageAt(ctx.context, account.address, key.hash, big.NewInt(number))
   170  }
   171  
   172  // GetCodeAt returns the contract code of the given account.
   173  // The block number can be <0, in which case the code is taken from the latest known block.
   174  func (ec *EthereumClient) GetCodeAt(ctx *Context, account *Address, number int64) (code []byte, _ error) {
   175  	if number < 0 {
   176  		return ec.client.CodeAt(ctx.context, account.address, nil)
   177  	}
   178  	return ec.client.CodeAt(ctx.context, account.address, big.NewInt(number))
   179  }
   180  
   181  // GetNonceAt returns the account nonce of the given account.
   182  // The block number can be <0, in which case the nonce is taken from the latest known block.
   183  func (ec *EthereumClient) GetNonceAt(ctx *Context, account *Address, number int64) (nonce int64, _ error) {
   184  	if number < 0 {
   185  		rawNonce, err := ec.client.NonceAt(ctx.context, account.address, nil)
   186  		return int64(rawNonce), err
   187  	}
   188  	rawNonce, err := ec.client.NonceAt(ctx.context, account.address, big.NewInt(number))
   189  	return int64(rawNonce), err
   190  }
   191  
   192  // Filters
   193  
   194  // FilterLogs executes a filter query.
   195  func (ec *EthereumClient) FilterLogs(ctx *Context, query *FilterQuery) (logs *Logs, _ error) {
   196  	rawLogs, err := ec.client.FilterLogs(ctx.context, query.query)
   197  	if err != nil {
   198  		return nil, err
   199  	}
   200  	// Temp hack due to vm.Logs being []*vm.Log
   201  	res := make([]*types.Log, len(rawLogs))
   202  	for i := range rawLogs {
   203  		res[i] = &rawLogs[i]
   204  	}
   205  	return &Logs{res}, nil
   206  }
   207  
   208  // FilterLogsHandler is a client-side subscription callback to invoke on events and
   209  // subscription failure.
   210  type FilterLogsHandler interface {
   211  	OnFilterLogs(log *Log)
   212  	OnError(failure string)
   213  }
   214  
   215  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   216  func (ec *EthereumClient) SubscribeFilterLogs(ctx *Context, query *FilterQuery, handler FilterLogsHandler, buffer int) (sub *Subscription, _ error) {
   217  	// Subscribe to the event internally
   218  	ch := make(chan types.Log, buffer)
   219  	rawSub, err := ec.client.SubscribeFilterLogs(ctx.context, query.query, ch)
   220  	if err != nil {
   221  		return nil, err
   222  	}
   223  	// Start up a dispatcher to feed into the callback
   224  	go func() {
   225  		for {
   226  			select {
   227  			case log := <-ch:
   228  				handler.OnFilterLogs(&Log{&log})
   229  
   230  			case err := <-rawSub.Err():
   231  				if err != nil {
   232  					handler.OnError(err.Error())
   233  				}
   234  				return
   235  			}
   236  		}
   237  	}()
   238  	return &Subscription{rawSub}, nil
   239  }
   240  
   241  // Pending State
   242  
   243  // GetPendingBalanceAt returns the wei balance of the given account in the pending state.
   244  func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
   245  	rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
   246  	return &BigInt{rawBalance}, err
   247  }
   248  
   249  // GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   250  func (ec *EthereumClient) GetPendingStorageAt(ctx *Context, account *Address, key *Hash) (storage []byte, _ error) {
   251  	return ec.client.PendingStorageAt(ctx.context, account.address, key.hash)
   252  }
   253  
   254  // GetPendingCodeAt returns the contract code of the given account in the pending state.
   255  func (ec *EthereumClient) GetPendingCodeAt(ctx *Context, account *Address) (code []byte, _ error) {
   256  	return ec.client.PendingCodeAt(ctx.context, account.address)
   257  }
   258  
   259  // GetPendingNonceAt returns the account nonce of the given account in the pending state.
   260  // This is the nonce that should be used for the next transaction.
   261  func (ec *EthereumClient) GetPendingNonceAt(ctx *Context, account *Address) (nonce int64, _ error) {
   262  	rawNonce, err := ec.client.PendingNonceAt(ctx.context, account.address)
   263  	return int64(rawNonce), err
   264  }
   265  
   266  // GetPendingTransactionCount returns the total number of transactions in the pending state.
   267  func (ec *EthereumClient) GetPendingTransactionCount(ctx *Context) (count int, _ error) {
   268  	rawCount, err := ec.client.PendingTransactionCount(ctx.context)
   269  	return int(rawCount), err
   270  }
   271  
   272  // Contract Calling
   273  
   274  // CallContract executes a message call transaction, which is directly executed in the VM
   275  // of the node, but never mined into the blockchain.
   276  //
   277  // blockNumber selects the block height at which the call runs. It can be <0, in which
   278  // case the code is taken from the latest known block. Note that state from very old
   279  // blocks might not be available.
   280  func (ec *EthereumClient) CallContract(ctx *Context, msg *CallMsg, number int64) (output []byte, _ error) {
   281  	if number < 0 {
   282  		return ec.client.CallContract(ctx.context, msg.msg, nil)
   283  	}
   284  	return ec.client.CallContract(ctx.context, msg.msg, big.NewInt(number))
   285  }
   286  
   287  // PendingCallContract executes a message call transaction using the EVM.
   288  // The state seen by the contract call is the pending state.
   289  func (ec *EthereumClient) PendingCallContract(ctx *Context, msg *CallMsg) (output []byte, _ error) {
   290  	return ec.client.PendingCallContract(ctx.context, msg.msg)
   291  }
   292  
   293  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   294  // execution of a transaction.
   295  func (ec *EthereumClient) SuggestGasPrice(ctx *Context) (price *BigInt, _ error) {
   296  	rawPrice, err := ec.client.SuggestGasPrice(ctx.context)
   297  	return &BigInt{rawPrice}, err
   298  }
   299  
   300  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   301  // the current pending state of the backend blockchain. There is no guarantee that this is
   302  // the true gas limit requirement as other transactions may be added or removed by miners,
   303  // but it should provide a basis for setting a reasonable default.
   304  func (ec *EthereumClient) EstimateGas(ctx *Context, msg *CallMsg) (gas int64, _ error) {
   305  	rawGas, err := ec.client.EstimateGas(ctx.context, msg.msg)
   306  	return int64(rawGas), err
   307  }
   308  
   309  // SendTransaction injects a signed transaction into the pending pool for execution.
   310  //
   311  // If the transaction was a contract creation use the TransactionReceipt method to get the
   312  // contract address after the transaction has been mined.
   313  func (ec *EthereumClient) SendTransaction(ctx *Context, tx *Transaction) error {
   314  	return ec.client.SendTransaction(ctx.context, tx.tx)
   315  }