github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/accounts/abi/bind/base.go (about)

     1  // Copyright 2022 Commercium
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package bind
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  
    26  	"github.com/CommerciumBlockchain/go-commercium"
    27  	"github.com/CommerciumBlockchain/go-commercium/accounts/abi"
    28  	"github.com/CommerciumBlockchain/go-commercium/common"
    29  	"github.com/CommerciumBlockchain/go-commercium/core/types"
    30  	"github.com/CommerciumBlockchain/go-commercium/crypto"
    31  	"github.com/CommerciumBlockchain/go-commercium/event"
    32  )
    33  
    34  // SignerFn is a signer function callback when a contract requires a method to
    35  // sign the transaction before submission.
    36  type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
    37  
    38  // CallOpts is the collection of options to fine tune a contract call request.
    39  type CallOpts struct {
    40  	Pending     bool            // Whether to operate on the pending state or the last known one
    41  	From        common.Address  // Optional the sender address, otherwise the first account is used
    42  	BlockNumber *big.Int        // Optional the block number on which the call should be performed
    43  	Context     context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    44  }
    45  
    46  // TransactOpts is the collection of authorization data required to create a
    47  // valid Ethereum transaction.
    48  type TransactOpts struct {
    49  	From   common.Address // Ethereum account to send the transaction from
    50  	Nonce  *big.Int       // Nonce to use for the transaction execution (nil = use pending state)
    51  	Signer SignerFn       // Method to use for signing the transaction (mandatory)
    52  
    53  	Value    *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
    54  
    55  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    56  }
    57  
    58  // FilterOpts is the collection of options to fine tune filtering for events
    59  // within a bound contract.
    60  type FilterOpts struct {
    61  	Start uint64  // Start of the queried range
    62  	End   *uint64 // End of the range (nil = latest)
    63  
    64  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    65  }
    66  
    67  // WatchOpts is the collection of options to fine tune subscribing for events
    68  // within a bound contract.
    69  type WatchOpts struct {
    70  	Start   *uint64         // Start of the queried range (nil = latest)
    71  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    72  }
    73  
    74  // BoundContract is the base wrapper object that reflects a contract on the
    75  // Ethereum network. It contains a collection of methods that are used by the
    76  // higher level contract bindings to operate.
    77  type BoundContract struct {
    78  	address    common.Address     // Deployment address of the contract on the Ethereum blockchain
    79  	abi        abi.ABI            // Reflect based ABI to access the correct Ethereum methods
    80  	caller     ContractCaller     // Read interface to interact with the blockchain
    81  	transactor ContractTransactor // Write interface to interact with the blockchain
    82  	filterer   ContractFilterer   // Event filtering to interact with the blockchain
    83  }
    84  
    85  // NewBoundContract creates a low level contract interface through which calls
    86  // and transactions may be made through.
    87  func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
    88  	return &BoundContract{
    89  		address:    address,
    90  		abi:        abi,
    91  		caller:     caller,
    92  		transactor: transactor,
    93  		filterer:   filterer,
    94  	}
    95  }
    96  
    97  // DeployContract deploys a contract onto the Ethereum blockchain and binds the
    98  // deployment address with a Go wrapper.
    99  func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
   100  	// Otherwise try to deploy the contract
   101  	c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
   102  
   103  	input, err := c.abi.Pack("", params...)
   104  	if err != nil {
   105  		return common.Address{}, nil, nil, err
   106  	}
   107  	tx, err := c.transact(opts, nil, append(bytecode, input...))
   108  	if err != nil {
   109  		return common.Address{}, nil, nil, err
   110  	}
   111  	c.address = crypto.CreateAddress(opts.From, tx.Nonce())
   112  	return c.address, tx, c, nil
   113  }
   114  
   115  // Call invokes the (constant) contract method with params as input values and
   116  // sets the output to result. The result type might be a single field for simple
   117  // returns, a slice of interfaces for anonymous returns and a struct for named
   118  // returns.
   119  func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
   120  	// Don't crash on a lazy user
   121  	if opts == nil {
   122  		opts = new(CallOpts)
   123  	}
   124  	if results == nil {
   125  		results = new([]interface{})
   126  	}
   127  	// Pack the input, call and unpack the results
   128  	input, err := c.abi.Pack(method, params...)
   129  	if err != nil {
   130  		return err
   131  	}
   132  	var (
   133  		msg    = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
   134  		ctx    = ensureContext(opts.Context)
   135  		code   []byte
   136  		output []byte
   137  	)
   138  	if opts.Pending {
   139  		pb, ok := c.caller.(PendingContractCaller)
   140  		if !ok {
   141  			return ErrNoPendingState
   142  		}
   143  		output, err = pb.PendingCallContract(ctx, msg)
   144  		if err == nil && len(output) == 0 {
   145  			// Make sure we have a contract to operate on, and bail out otherwise.
   146  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   147  				return err
   148  			} else if len(code) == 0 {
   149  				return ErrNoCode
   150  			}
   151  		}
   152  	} else {
   153  		output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
   154  		if err != nil {
   155  			return err
   156  		}
   157  		if len(output) == 0 {
   158  			// Make sure we have a contract to operate on, and bail out otherwise.
   159  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   160  				return err
   161  			} else if len(code) == 0 {
   162  				return ErrNoCode
   163  			}
   164  		}
   165  	}
   166  
   167  	if len(*results) == 0 {
   168  		res, err := c.abi.Unpack(method, output)
   169  		*results = res
   170  		return err
   171  	}
   172  	res := *results
   173  	return c.abi.UnpackIntoInterface(res[0], method, output)
   174  }
   175  
   176  // Transact invokes the (paid) contract method with params as input values.
   177  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   178  	// Otherwise pack up the parameters and invoke the contract
   179  	input, err := c.abi.Pack(method, params...)
   180  	if err != nil {
   181  		return nil, err
   182  	}
   183  	// todo(rjl493456442) check the method is payable or not,
   184  	// reject invalid transaction at the first place
   185  	return c.transact(opts, &c.address, input)
   186  }
   187  
   188  // RawTransact initiates a transaction with the given raw calldata as the input.
   189  // It's usually used to initiate transactions for invoking **Fallback** function.
   190  func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
   191  	// todo(rjl493456442) check the method is payable or not,
   192  	// reject invalid transaction at the first place
   193  	return c.transact(opts, &c.address, calldata)
   194  }
   195  
   196  // Transfer initiates a plain transaction to move funds to the contract, calling
   197  // its default method if one is available.
   198  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   199  	// todo(rjl493456442) check the payable fallback or receive is defined
   200  	// or not, reject invalid transaction at the first place
   201  	return c.transact(opts, &c.address, nil)
   202  }
   203  
   204  // transact executes an actual transaction invocation, first deriving any missing
   205  // authorization fields, and then scheduling the transaction for execution.
   206  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   207  	var err error
   208  
   209  	// Ensure a valid value field and resolve the account nonce
   210  	value := opts.Value
   211  	if value == nil {
   212  		value = new(big.Int)
   213  	}
   214  	var nonce uint64
   215  	if opts.Nonce == nil {
   216  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   217  		if err != nil {
   218  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   219  		}
   220  	} else {
   221  		nonce = opts.Nonce.Uint64()
   222  	}
   223  	// Create the transaction, sign it and schedule it for execution
   224  	var rawTx *types.Transaction
   225  	if contract == nil {
   226  		rawTx = types.NewContractCreation(nonce, value, input)
   227  	} else {
   228  		rawTx = types.NewTransaction(nonce, c.address, value, input)
   229  	}
   230  	if opts.Signer == nil {
   231  		return nil, errors.New("no signer to authorize the transaction with")
   232  	}
   233  	signedTx, err := opts.Signer(opts.From, rawTx)
   234  	if err != nil {
   235  		return nil, err
   236  	}
   237  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   238  		return nil, err
   239  	}
   240  	return signedTx, nil
   241  }
   242  
   243  // FilterLogs filters contract logs for past blocks, returning the necessary
   244  // channels to construct a strongly typed bound iterator on top of them.
   245  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   246  	// Don't crash on a lazy user
   247  	if opts == nil {
   248  		opts = new(FilterOpts)
   249  	}
   250  	// Append the event selector to the query parameters and construct the topic set
   251  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   252  
   253  	topics, err := abi.MakeTopics(query...)
   254  	if err != nil {
   255  		return nil, nil, err
   256  	}
   257  	// Start the background filtering
   258  	logs := make(chan types.Log, 128)
   259  
   260  	config := ethereum.FilterQuery{
   261  		Addresses: []common.Address{c.address},
   262  		Topics:    topics,
   263  		FromBlock: new(big.Int).SetUint64(opts.Start),
   264  	}
   265  	if opts.End != nil {
   266  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   267  	}
   268  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   269  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   270  	*/
   271  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   272  	if err != nil {
   273  		return nil, nil, err
   274  	}
   275  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   276  		for _, log := range buff {
   277  			select {
   278  			case logs <- log:
   279  			case <-quit:
   280  				return nil
   281  			}
   282  		}
   283  		return nil
   284  	}), nil
   285  
   286  	if err != nil {
   287  		return nil, nil, err
   288  	}
   289  	return logs, sub, nil
   290  }
   291  
   292  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   293  // subscription object that can be used to tear down the watcher.
   294  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   295  	// Don't crash on a lazy user
   296  	if opts == nil {
   297  		opts = new(WatchOpts)
   298  	}
   299  	// Append the event selector to the query parameters and construct the topic set
   300  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   301  
   302  	topics, err := abi.MakeTopics(query...)
   303  	if err != nil {
   304  		return nil, nil, err
   305  	}
   306  	// Start the background filtering
   307  	logs := make(chan types.Log, 128)
   308  
   309  	config := ethereum.FilterQuery{
   310  		Addresses: []common.Address{c.address},
   311  		Topics:    topics,
   312  	}
   313  	if opts.Start != nil {
   314  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   315  	}
   316  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   317  	if err != nil {
   318  		return nil, nil, err
   319  	}
   320  	return logs, sub, nil
   321  }
   322  
   323  // UnpackLog unpacks a retrieved log into the provided output structure.
   324  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   325  	if len(log.Data) > 0 {
   326  		if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
   327  			return err
   328  		}
   329  	}
   330  	var indexed abi.Arguments
   331  	for _, arg := range c.abi.Events[event].Inputs {
   332  		if arg.Indexed {
   333  			indexed = append(indexed, arg)
   334  		}
   335  	}
   336  	return abi.ParseTopics(out, indexed, log.Topics[1:])
   337  }
   338  
   339  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   340  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   341  	if len(log.Data) > 0 {
   342  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   343  			return err
   344  		}
   345  	}
   346  	var indexed abi.Arguments
   347  	for _, arg := range c.abi.Events[event].Inputs {
   348  		if arg.Indexed {
   349  			indexed = append(indexed, arg)
   350  		}
   351  	}
   352  	return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
   353  }
   354  
   355  // ensureContext is a helper method to ensure a context is not nil, even if the
   356  // user specified it as such.
   357  func ensureContext(ctx context.Context) context.Context {
   358  	if ctx == nil {
   359  		return context.TODO()
   360  	}
   361  	return ctx
   362  }