github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/accounts/abi/bind/base.go (about)

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