github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/accounts/abi/bind/base.go (about)

     1  // Copyright 2019 The ebakus/go-ebakus Authors
     2  // This file is part of the ebakus/go-ebakus library.
     3  //
     4  // The ebakus/go-ebakus 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 ebakus/go-ebakus 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 ebakus/go-ebakus 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  	ebakus "github.com/ebakus/go-ebakus"
    26  	"github.com/ebakus/go-ebakus/accounts/abi"
    27  	"github.com/ebakus/go-ebakus/common"
    28  	"github.com/ebakus/go-ebakus/core/types"
    29  	"github.com/ebakus/go-ebakus/crypto"
    30  	"github.com/ebakus/go-ebakus/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 Ebakus transaction.
    47  type TransactOpts struct {
    48  	From   common.Address // Ebakus 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 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  // Ebakus 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 Ebakus blockchain
    80  	abi        abi.ABI            // Reflect based ABI to access the correct Ebakus 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 Ebakus 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, result interface{}, method string, params ...interface{}) error {
   121  	// Don't crash on a lazy user
   122  	if opts == nil {
   123  		opts = new(CallOpts)
   124  	}
   125  	// Pack the input, call and unpack the results
   126  	input, err := c.abi.Pack(method, params...)
   127  	if err != nil {
   128  		return err
   129  	}
   130  	var (
   131  		msg    = ebakus.CallMsg{From: opts.From, To: &c.address, Data: input}
   132  		ctx    = ensureContext(opts.Context)
   133  		code   []byte
   134  		output []byte
   135  	)
   136  	if opts.Pending {
   137  		pb, ok := c.caller.(PendingContractCaller)
   138  		if !ok {
   139  			return ErrNoPendingState
   140  		}
   141  		output, err = pb.PendingCallContract(ctx, msg)
   142  		if err == nil && len(output) == 0 {
   143  			// Make sure we have a contract to operate on, and bail out otherwise.
   144  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   145  				return err
   146  			} else if len(code) == 0 {
   147  				return ErrNoCode
   148  			}
   149  		}
   150  	} else {
   151  		output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
   152  		if err == nil && len(output) == 0 {
   153  			// Make sure we have a contract to operate on, and bail out otherwise.
   154  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   155  				return err
   156  			} else if len(code) == 0 {
   157  				return ErrNoCode
   158  			}
   159  		}
   160  	}
   161  	if err != nil {
   162  		return err
   163  	}
   164  	return c.abi.Unpack(result, method, output)
   165  }
   166  
   167  // Transact invokes the (paid) contract method with params as input values.
   168  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   169  	// Otherwise pack up the parameters and invoke the contract
   170  	input, err := c.abi.Pack(method, params...)
   171  	if err != nil {
   172  		return nil, err
   173  	}
   174  	return c.transact(opts, &c.address, input)
   175  }
   176  
   177  // Transfer initiates a plain transaction to move funds to the contract, calling
   178  // its default method if one is available.
   179  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   180  	return c.transact(opts, &c.address, nil)
   181  }
   182  
   183  // transact executes an actual transaction invocation, first deriving any missing
   184  // authorization fields, and then scheduling the transaction for execution.
   185  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   186  	var err error
   187  
   188  	// Ensure a valid value field and resolve the account nonce
   189  	value := opts.Value
   190  	if value == nil {
   191  		value = new(big.Int)
   192  	}
   193  	var nonce uint64
   194  	if opts.Nonce == nil {
   195  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   196  		if err != nil {
   197  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   198  		}
   199  	} else {
   200  		nonce = opts.Nonce.Uint64()
   201  	}
   202  	gasLimit := opts.GasLimit
   203  	if gasLimit == 0 {
   204  		// Gas estimation cannot succeed without code for method invocations
   205  		if contract != nil {
   206  			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   207  				return nil, err
   208  			} else if len(code) == 0 {
   209  				return nil, ErrNoCode
   210  			}
   211  		}
   212  		// If the contract surely has code (or code is not needed), estimate the transaction
   213  		msg := ebakus.CallMsg{From: opts.From, To: contract, Value: value, Data: input}
   214  		gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   215  		if err != nil {
   216  			return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
   217  		}
   218  	}
   219  	// Create the transaction, sign it and schedule it for execution
   220  	var rawTx *types.Transaction
   221  	if contract == nil {
   222  		// TODO: calculate actual work
   223  		rawTx = types.NewContractCreation(0, nonce, value, gasLimit, input)
   224  	} else {
   225  		rawTx = types.NewTransaction(0, nonce, c.address, value, gasLimit, input)
   226  	}
   227  	if opts.Signer == nil {
   228  		return nil, errors.New("no signer to authorize the transaction with")
   229  	}
   230  	signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
   231  	if err != nil {
   232  		return nil, err
   233  	}
   234  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   235  		return nil, err
   236  	}
   237  	return signedTx, nil
   238  }
   239  
   240  // FilterLogs filters contract logs for past blocks, returning the necessary
   241  // channels to construct a strongly typed bound iterator on top of them.
   242  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   243  	// Don't crash on a lazy user
   244  	if opts == nil {
   245  		opts = new(FilterOpts)
   246  	}
   247  	// Append the event selector to the query parameters and construct the topic set
   248  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   249  
   250  	topics, err := makeTopics(query...)
   251  	if err != nil {
   252  		return nil, nil, err
   253  	}
   254  	// Start the background filtering
   255  	logs := make(chan types.Log, 128)
   256  
   257  	config := ebakus.FilterQuery{
   258  		Addresses: []common.Address{c.address},
   259  		Topics:    topics,
   260  		FromBlock: new(big.Int).SetUint64(opts.Start),
   261  	}
   262  	if opts.End != nil {
   263  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   264  	}
   265  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   266  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   267  	*/
   268  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   269  	if err != nil {
   270  		return nil, nil, err
   271  	}
   272  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   273  		for _, log := range buff {
   274  			select {
   275  			case logs <- log:
   276  			case <-quit:
   277  				return nil
   278  			}
   279  		}
   280  		return nil
   281  	}), nil
   282  
   283  	if err != nil {
   284  		return nil, nil, err
   285  	}
   286  	return logs, sub, nil
   287  }
   288  
   289  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   290  // subscription object that can be used to tear down the watcher.
   291  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   292  	// Don't crash on a lazy user
   293  	if opts == nil {
   294  		opts = new(WatchOpts)
   295  	}
   296  	// Append the event selector to the query parameters and construct the topic set
   297  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   298  
   299  	topics, err := makeTopics(query...)
   300  	if err != nil {
   301  		return nil, nil, err
   302  	}
   303  	// Start the background filtering
   304  	logs := make(chan types.Log, 128)
   305  
   306  	config := ebakus.FilterQuery{
   307  		Addresses: []common.Address{c.address},
   308  		Topics:    topics,
   309  	}
   310  	if opts.Start != nil {
   311  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   312  	}
   313  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   314  	if err != nil {
   315  		return nil, nil, err
   316  	}
   317  	return logs, sub, nil
   318  }
   319  
   320  // UnpackLog unpacks a retrieved log into the provided output structure.
   321  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   322  	if len(log.Data) > 0 {
   323  		if err := c.abi.Unpack(out, event, log.Data); err != nil {
   324  			return err
   325  		}
   326  	}
   327  	var indexed abi.Arguments
   328  	for _, arg := range c.abi.Events[event].Inputs {
   329  		if arg.Indexed {
   330  			indexed = append(indexed, arg)
   331  		}
   332  	}
   333  	return parseTopics(out, indexed, log.Topics[1:])
   334  }
   335  
   336  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   337  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   338  	if len(log.Data) > 0 {
   339  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   340  			return err
   341  		}
   342  	}
   343  	var indexed abi.Arguments
   344  	for _, arg := range c.abi.Events[event].Inputs {
   345  		if arg.Indexed {
   346  			indexed = append(indexed, arg)
   347  		}
   348  	}
   349  	return parseTopicsIntoMap(out, indexed, log.Topics[1:])
   350  }
   351  
   352  // ensureContext is a helper method to ensure a context is not nil, even if the
   353  // user specified it as such.
   354  func ensureContext(ctx context.Context) context.Context {
   355  	if ctx == nil {
   356  		return context.TODO()
   357  	}
   358  	return ctx
   359  }