github.com/0xsequence/ethkit@v1.25.0/go-ethereum/interfaces.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 ethereum defines interfaces for interacting with Ethereum.
    18  package ethereum
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"math/big"
    24  
    25  	"github.com/0xsequence/ethkit/go-ethereum/common"
    26  	"github.com/0xsequence/ethkit/go-ethereum/core/types"
    27  )
    28  
    29  // NotFound is returned by API methods if the requested item does not exist.
    30  var NotFound = errors.New("not found")
    31  
    32  // TODO: move subscription to package event
    33  
    34  // Subscription represents an event subscription where events are
    35  // delivered on a data channel.
    36  type Subscription interface {
    37  	// Unsubscribe cancels the sending of events to the data channel
    38  	// and closes the error channel.
    39  	Unsubscribe()
    40  	// Err returns the subscription error channel. The error channel receives
    41  	// a value if there is an issue with the subscription (e.g. the network connection
    42  	// delivering the events has been closed). Only one value will ever be sent.
    43  	// The error channel is closed by Unsubscribe.
    44  	Err() <-chan error
    45  }
    46  
    47  // ChainReader provides access to the blockchain. The methods in this interface access raw
    48  // data from either the canonical chain (when requesting by block number) or any
    49  // blockchain fork that was previously downloaded and processed by the node. The block
    50  // number argument can be nil to select the latest canonical block. Reading block headers
    51  // should be preferred over full blocks whenever possible.
    52  //
    53  // The returned error is NotFound if the requested item does not exist.
    54  type ChainReader interface {
    55  	BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
    56  	BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
    57  	HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
    58  	HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
    59  	TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error)
    60  	TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error)
    61  
    62  	// This method subscribes to notifications about changes of the head block of
    63  	// the canonical chain.
    64  	SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (Subscription, error)
    65  }
    66  
    67  // TransactionReader provides access to past transactions and their receipts.
    68  // Implementations may impose arbitrary restrictions on the transactions and receipts that
    69  // can be retrieved. Historic transactions may not be available.
    70  //
    71  // Avoid relying on this interface if possible. Contract logs (through the LogFilterer
    72  // interface) are more reliable and usually safer in the presence of chain
    73  // reorganisations.
    74  //
    75  // The returned error is NotFound if the requested item does not exist.
    76  type TransactionReader interface {
    77  	// TransactionByHash checks the pool of pending transactions in addition to the
    78  	// blockchain. The isPending return value indicates whether the transaction has been
    79  	// mined yet. Note that the transaction may not be part of the canonical chain even if
    80  	// it's not pending.
    81  	TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error)
    82  	// TransactionReceipt returns the receipt of a mined transaction. Note that the
    83  	// transaction may not be included in the current canonical chain even if a receipt
    84  	// exists.
    85  	TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
    86  }
    87  
    88  // ChainStateReader wraps access to the state trie of the canonical blockchain. Note that
    89  // implementations of the interface may be unable to return state values for old blocks.
    90  // In many cases, using CallContract can be preferable to reading raw contract storage.
    91  type ChainStateReader interface {
    92  	BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
    93  	StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error)
    94  	CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
    95  	NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
    96  }
    97  
    98  // SyncProgress gives progress indications when the node is synchronising with
    99  // the Ethereum network.
   100  type SyncProgress struct {
   101  	StartingBlock uint64 // Block number where sync began
   102  	CurrentBlock  uint64 // Current block number where sync is at
   103  	HighestBlock  uint64 // Highest alleged block number in the chain
   104  
   105  	// "fast sync" fields. These used to be sent by geth, but are no longer used
   106  	// since version v1.10.
   107  	PulledStates uint64 // Number of state trie entries already downloaded
   108  	KnownStates  uint64 // Total number of state trie entries known about
   109  
   110  	// "snap sync" fields.
   111  	SyncedAccounts      uint64 // Number of accounts downloaded
   112  	SyncedAccountBytes  uint64 // Number of account trie bytes persisted to disk
   113  	SyncedBytecodes     uint64 // Number of bytecodes downloaded
   114  	SyncedBytecodeBytes uint64 // Number of bytecode bytes downloaded
   115  	SyncedStorage       uint64 // Number of storage slots downloaded
   116  	SyncedStorageBytes  uint64 // Number of storage trie bytes persisted to disk
   117  
   118  	HealedTrienodes     uint64 // Number of state trie nodes downloaded
   119  	HealedTrienodeBytes uint64 // Number of state trie bytes persisted to disk
   120  	HealedBytecodes     uint64 // Number of bytecodes downloaded
   121  	HealedBytecodeBytes uint64 // Number of bytecodes persisted to disk
   122  
   123  	HealingTrienodes uint64 // Number of state trie nodes pending
   124  	HealingBytecode  uint64 // Number of bytecodes pending
   125  }
   126  
   127  // ChainSyncReader wraps access to the node's current sync status. If there's no
   128  // sync currently running, it returns nil.
   129  type ChainSyncReader interface {
   130  	SyncProgress(ctx context.Context) (*SyncProgress, error)
   131  }
   132  
   133  // CallMsg contains parameters for contract calls.
   134  type CallMsg struct {
   135  	From      common.Address  // the sender of the 'transaction'
   136  	To        *common.Address // the destination contract (nil for contract creation)
   137  	Gas       uint64          // if 0, the call executes with near-infinite gas
   138  	GasPrice  *big.Int        // wei <-> gas exchange ratio
   139  	GasFeeCap *big.Int        // EIP-1559 fee cap per gas.
   140  	GasTipCap *big.Int        // EIP-1559 tip per gas.
   141  	Value     *big.Int        // amount of wei sent along with the call
   142  	Data      []byte          // input data, usually an ABI-encoded contract method invocation
   143  
   144  	AccessList types.AccessList // EIP-2930 access list.
   145  }
   146  
   147  // A ContractCaller provides contract calls, essentially transactions that are executed by
   148  // the EVM but not mined into the blockchain. ContractCall is a low-level method to
   149  // execute such calls. For applications which are structured around specific contracts,
   150  // the abigen tool provides a nicer, properly typed way to perform calls.
   151  type ContractCaller interface {
   152  	CallContract(ctx context.Context, call CallMsg, blockNumber *big.Int) ([]byte, error)
   153  }
   154  
   155  // FilterQuery contains options for contract log filtering.
   156  type FilterQuery struct {
   157  	BlockHash *common.Hash     // used by eth_getLogs, return logs only from block with this hash
   158  	FromBlock *big.Int         // beginning of the queried range, nil means genesis block
   159  	ToBlock   *big.Int         // end of the range, nil means latest block
   160  	Addresses []common.Address // restricts matches to events created by specific contracts
   161  
   162  	// The Topic list restricts matches to particular event topics. Each event has a list
   163  	// of topics. Topics matches a prefix of that list. An empty element slice matches any
   164  	// topic. Non-empty elements represent an alternative that matches any of the
   165  	// contained topics.
   166  	//
   167  	// Examples:
   168  	// {} or nil          matches any topic list
   169  	// {{A}}              matches topic A in first position
   170  	// {{}, {B}}          matches any topic in first position AND B in second position
   171  	// {{A}, {B}}         matches topic A in first position AND B in second position
   172  	// {{A, B}, {C, D}}   matches topic (A OR B) in first position AND (C OR D) in second position
   173  	Topics [][]common.Hash
   174  }
   175  
   176  // LogFilterer provides access to contract log events using a one-off query or continuous
   177  // event subscription.
   178  //
   179  // Logs received through a streaming query subscription may have Removed set to true,
   180  // indicating that the log was reverted due to a chain reorganisation.
   181  type LogFilterer interface {
   182  	FilterLogs(ctx context.Context, q FilterQuery) ([]types.Log, error)
   183  	SubscribeFilterLogs(ctx context.Context, q FilterQuery, ch chan<- types.Log) (Subscription, error)
   184  }
   185  
   186  // TransactionSender wraps transaction sending. The SendTransaction method injects a
   187  // signed transaction into the pending transaction pool for execution. If the transaction
   188  // was a contract creation, the TransactionReceipt method can be used to retrieve the
   189  // contract address after the transaction has been mined.
   190  //
   191  // The transaction must be signed and have a valid nonce to be included. Consumers of the
   192  // API can use package accounts to maintain local private keys and need can retrieve the
   193  // next available nonce using PendingNonceAt.
   194  type TransactionSender interface {
   195  	SendTransaction(ctx context.Context, tx *types.Transaction) error
   196  }
   197  
   198  // GasPricer wraps the gas price oracle, which monitors the blockchain to determine the
   199  // optimal gas price given current fee market conditions.
   200  type GasPricer interface {
   201  	SuggestGasPrice(ctx context.Context) (*big.Int, error)
   202  }
   203  
   204  // FeeHistory provides recent fee market data that consumers can use to determine
   205  // a reasonable maxPriorityFeePerGas value.
   206  type FeeHistory struct {
   207  	OldestBlock  *big.Int     // block corresponding to first response value
   208  	Reward       [][]*big.Int // list every txs priority fee per block
   209  	BaseFee      []*big.Int   // list of each block's base fee
   210  	GasUsedRatio []float64    // ratio of gas used out of the total available limit
   211  }
   212  
   213  // A PendingStateReader provides access to the pending state, which is the result of all
   214  // known executable transactions which have not yet been included in the blockchain. It is
   215  // commonly used to display the result of ’unconfirmed’ actions (e.g. wallet value
   216  // transfers) initiated by the user. The PendingNonceAt operation is a good way to
   217  // retrieve the next available transaction nonce for a specific account.
   218  type PendingStateReader interface {
   219  	PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error)
   220  	PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error)
   221  	PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
   222  	PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
   223  	PendingTransactionCount(ctx context.Context) (uint, error)
   224  }
   225  
   226  // PendingContractCaller can be used to perform calls against the pending state.
   227  type PendingContractCaller interface {
   228  	PendingCallContract(ctx context.Context, call CallMsg) ([]byte, error)
   229  }
   230  
   231  // GasEstimator wraps EstimateGas, which tries to estimate the gas needed to execute a
   232  // specific transaction based on the pending state. There is no guarantee that this is the
   233  // true gas limit requirement as other transactions may be added or removed by miners, but
   234  // it should provide a basis for setting a reasonable default.
   235  type GasEstimator interface {
   236  	EstimateGas(ctx context.Context, call CallMsg) (uint64, error)
   237  }
   238  
   239  // A PendingStateEventer provides access to real time notifications about changes to the
   240  // pending state.
   241  type PendingStateEventer interface {
   242  	SubscribePendingTransactions(ctx context.Context, ch chan<- *types.Transaction) (Subscription, error)
   243  }