github.com/aswedchain/aswed@v1.0.1/accounts/abi/bind/base.go (about)

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