github.com/core-coin/go-core/v2@v2.1.9/accounts/abi/bind/base.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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  	core "github.com/core-coin/go-core/v2"
    26  	"github.com/core-coin/go-core/v2/accounts/abi"
    27  	"github.com/core-coin/go-core/v2/common"
    28  	"github.com/core-coin/go-core/v2/core/types"
    29  	"github.com/core-coin/go-core/v2/crypto"
    30  	"github.com/core-coin/go-core/v2/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(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 Core transaction.
    47  type TransactOpts struct {
    48  	From   common.Address // Core 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  	EnergyPrice *big.Int // Energy price to use for the transaction execution (nil = energy price oracle)
    54  	EnergyLimit uint64   // Energy 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  // Core 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 Core blockchain
    80  	abi        abi.ABI            // Reflect based ABI to access the correct Core 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 Core 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    = core.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 {
   156  			return err
   157  		}
   158  		if len(output) == 0 {
   159  			// Make sure we have a contract to operate on, and bail out otherwise.
   160  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   161  				return err
   162  			} else if len(code) == 0 {
   163  				return ErrNoCode
   164  			}
   165  		}
   166  	}
   167  
   168  	if len(*results) == 0 {
   169  		res, err := c.abi.Unpack(method, output)
   170  		*results = res
   171  		return err
   172  	}
   173  	res := *results
   174  	return c.abi.UnpackIntoInterface(res[0], method, output)
   175  }
   176  
   177  // Transact invokes the (paid) contract method with params as input values.
   178  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   179  	// Otherwise pack up the parameters and invoke the contract
   180  	input, err := c.abi.Pack(method, params...)
   181  	if err != nil {
   182  		return nil, err
   183  	}
   184  	// todo(raisty) check the method is payable or not,
   185  	// reject invalid transaction at the first place
   186  	return c.transact(opts, &c.address, input)
   187  }
   188  
   189  // RawTransact initiates a transaction with the given raw calldata as the input.
   190  // It's usually used to initiate transactions for invoking **Fallback** function.
   191  func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
   192  	// todo(raisty) check the method is payable or not,
   193  	// reject invalid transaction at the first place
   194  	return c.transact(opts, &c.address, calldata)
   195  }
   196  
   197  // Transfer initiates a plain transaction to move funds to the contract, calling
   198  // its default method if one is available.
   199  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   200  	// todo(raisty) check the payable fallback or receive is defined
   201  	// or not, reject invalid transaction at the first place
   202  	return c.transact(opts, &c.address, nil)
   203  }
   204  
   205  // transact executes an actual transaction invocation, first deriving any missing
   206  // authorization fields, and then scheduling the transaction for execution.
   207  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   208  	var err error
   209  
   210  	// Ensure a valid value field and resolve the account nonce
   211  	value := opts.Value
   212  	if value == nil {
   213  		value = new(big.Int)
   214  	}
   215  	var nonce uint64
   216  	if opts.Nonce == nil {
   217  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   218  		if err != nil {
   219  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   220  		}
   221  	} else {
   222  		nonce = opts.Nonce.Uint64()
   223  	}
   224  	// Figure out the energy allowance and energy price values
   225  	energyPrice := opts.EnergyPrice
   226  	if energyPrice == nil {
   227  		energyPrice, err = c.transactor.SuggestEnergyPrice(ensureContext(opts.Context))
   228  		if err != nil {
   229  			return nil, fmt.Errorf("failed to suggest energy price: %v", err)
   230  		}
   231  	}
   232  	energyLimit := opts.EnergyLimit
   233  	if energyLimit == 0 {
   234  		// Energy estimation cannot succeed without code for method invocations
   235  		if contract != nil {
   236  			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   237  				return nil, err
   238  			} else if len(code) == 0 {
   239  				return nil, ErrNoCode
   240  			}
   241  		}
   242  		// If the contract surely has code (or code is not needed), estimate the transaction
   243  		msg := core.CallMsg{From: opts.From, To: contract, EnergyPrice: energyPrice, Value: value, Data: input}
   244  		energyLimit, err = c.transactor.EstimateEnergy(ensureContext(opts.Context), msg)
   245  		if err != nil {
   246  			return nil, fmt.Errorf("failed to estimate energy needed: %v", err)
   247  		}
   248  	}
   249  	// Create the transaction, sign it and schedule it for execution
   250  	var rawTx *types.Transaction
   251  	if contract == nil {
   252  		rawTx = types.NewContractCreation(nonce, value, energyLimit, energyPrice, input)
   253  	} else {
   254  		rawTx = types.NewTransaction(nonce, c.address, value, energyLimit, energyPrice, input)
   255  	}
   256  	if opts.Signer == nil {
   257  		return nil, errors.New("no signer to authorize the transaction with")
   258  	}
   259  	signedTx, err := opts.Signer(opts.From, rawTx)
   260  	if err != nil {
   261  		return nil, err
   262  	}
   263  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   264  		return nil, err
   265  	}
   266  	return signedTx, nil
   267  }
   268  
   269  // FilterLogs filters contract logs for past blocks, returning the necessary
   270  // channels to construct a strongly typed bound iterator on top of them.
   271  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   272  	// Don't crash on a lazy user
   273  	if opts == nil {
   274  		opts = new(FilterOpts)
   275  	}
   276  	// Append the event selector to the query parameters and construct the topic set
   277  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   278  
   279  	topics, err := abi.MakeTopics(query...)
   280  	if err != nil {
   281  		return nil, nil, err
   282  	}
   283  	// Start the background filtering
   284  	logs := make(chan types.Log, 128)
   285  
   286  	config := core.FilterQuery{
   287  		Addresses: []common.Address{c.address},
   288  		Topics:    topics,
   289  		FromBlock: new(big.Int).SetUint64(opts.Start),
   290  	}
   291  	if opts.End != nil {
   292  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   293  	}
   294  	/* TODO(raisty): Replace the rest of the method below with this when supported
   295  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   296  	*/
   297  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   298  	if err != nil {
   299  		return nil, nil, err
   300  	}
   301  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   302  		for _, log := range buff {
   303  			select {
   304  			case logs <- log:
   305  			case <-quit:
   306  				return nil
   307  			}
   308  		}
   309  		return nil
   310  	}), nil
   311  
   312  	if err != nil {
   313  		return nil, nil, err
   314  	}
   315  	return logs, sub, nil
   316  }
   317  
   318  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   319  // subscription object that can be used to tear down the watcher.
   320  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   321  	// Don't crash on a lazy user
   322  	if opts == nil {
   323  		opts = new(WatchOpts)
   324  	}
   325  	// Append the event selector to the query parameters and construct the topic set
   326  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   327  
   328  	topics, err := abi.MakeTopics(query...)
   329  	if err != nil {
   330  		return nil, nil, err
   331  	}
   332  	// Start the background filtering
   333  	logs := make(chan types.Log, 128)
   334  
   335  	config := core.FilterQuery{
   336  		Addresses: []common.Address{c.address},
   337  		Topics:    topics,
   338  	}
   339  	if opts.Start != nil {
   340  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   341  	}
   342  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   343  	if err != nil {
   344  		return nil, nil, err
   345  	}
   346  	return logs, sub, nil
   347  }
   348  
   349  // UnpackLog unpacks a retrieved log into the provided output structure.
   350  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   351  	if len(log.Data) > 0 {
   352  		if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
   353  			return err
   354  		}
   355  	}
   356  	var indexed abi.Arguments
   357  	for _, arg := range c.abi.Events[event].Inputs {
   358  		if arg.Indexed {
   359  			indexed = append(indexed, arg)
   360  		}
   361  	}
   362  	return abi.ParseTopics(out, indexed, log.Topics[1:])
   363  }
   364  
   365  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   366  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   367  	if len(log.Data) > 0 {
   368  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   369  			return err
   370  		}
   371  	}
   372  	var indexed abi.Arguments
   373  	for _, arg := range c.abi.Events[event].Inputs {
   374  		if arg.Indexed {
   375  			indexed = append(indexed, arg)
   376  		}
   377  	}
   378  	return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
   379  }
   380  
   381  // ensureContext is a helper method to ensure a context is not nil, even if the
   382  // user specified it as such.
   383  func ensureContext(ctx context.Context) context.Context {
   384  	if ctx == nil {
   385  		return context.TODO()
   386  	}
   387  	return ctx
   388  }