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