github.com/amazechain/amc@v0.1.3/interfaces.go (about)

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