github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/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/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/accounts/abi"
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  )
    31  
    32  // SignerFn is a signer function callback when a contract requires a method to
    33  // sign the transaction before submission.
    34  type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error)
    35  
    36  // CallOpts is the collection of options to fine tune a contract call request.
    37  type CallOpts struct {
    38  	Pending bool           // Whether to operate on the pending state or the last known one
    39  	From    common.Address // Optional the sender address, otherwise the first account is used
    40  
    41  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    42  }
    43  
    44  // TransactOpts is the collection of authorization data required to create a
    45  // valid Ethereum transaction.
    46  type TransactOpts struct {
    47  	From   common.Address // Ethereum account to send the transaction from
    48  	Nonce  *big.Int       // Nonce to use for the transaction execution (nil = use pending state)
    49  	Signer SignerFn       // Method to use for signing the transaction (mandatory)
    50  
    51  	Value    *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds)
    52  	GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
    53  	GasLimit *big.Int // Gas limit to set for the transaction execution (nil = estimate + 10%)
    54  
    55  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    56  }
    57  
    58  // BoundContract is the base wrapper object that reflects a contract on the
    59  // Ethereum network. It contains a collection of methods that are used by the
    60  // higher level contract bindings to operate.
    61  type BoundContract struct {
    62  	address    common.Address     // Deployment address of the contract on the Ethereum blockchain
    63  	abi        abi.ABI            // Reflect based ABI to access the correct Ethereum methods
    64  	caller     ContractCaller     // Read interface to interact with the blockchain
    65  	transactor ContractTransactor // Write interface to interact with the blockchain
    66  }
    67  
    68  // NewBoundContract creates a low level contract interface through which calls
    69  // and transactions may be made through.
    70  func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract {
    71  	return &BoundContract{
    72  		address:    address,
    73  		abi:        abi,
    74  		caller:     caller,
    75  		transactor: transactor,
    76  	}
    77  }
    78  
    79  // DeployContract deploys a contract onto the Ethereum blockchain and binds the
    80  // deployment address with a Go wrapper.
    81  func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
    82  	// Otherwise try to deploy the contract
    83  	c := NewBoundContract(common.Address{}, abi, backend, backend)
    84  
    85  	input, err := c.abi.Pack("", params...)
    86  	if err != nil {
    87  		return common.Address{}, nil, nil, err
    88  	}
    89  	tx, err := c.transact(opts, nil, append(bytecode, input...))
    90  	if err != nil {
    91  		return common.Address{}, nil, nil, err
    92  	}
    93  	c.address = crypto.CreateAddress(opts.From, tx.Nonce())
    94  	return c.address, tx, c, nil
    95  }
    96  
    97  // Call invokes the (constant) contract method with params as input values and
    98  // sets the output to result. The result type might be a single field for simple
    99  // returns, a slice of interfaces for anonymous returns and a struct for named
   100  // returns.
   101  func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error {
   102  	// Don't crash on a lazy user
   103  	if opts == nil {
   104  		opts = new(CallOpts)
   105  	}
   106  	// Pack the input, call and unpack the results
   107  	input, err := c.abi.Pack(method, params...)
   108  	if err != nil {
   109  		return err
   110  	}
   111  	var (
   112  		msg    = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
   113  		ctx    = ensureContext(opts.Context)
   114  		code   []byte
   115  		output []byte
   116  	)
   117  	if opts.Pending {
   118  		pb, ok := c.caller.(PendingContractCaller)
   119  		if !ok {
   120  			return ErrNoPendingState
   121  		}
   122  		output, err = pb.PendingCallContract(ctx, msg)
   123  		if err == nil && len(output) == 0 {
   124  			// Make sure we have a contract to operate on, and bail out otherwise.
   125  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   126  				return err
   127  			} else if len(code) == 0 {
   128  				return ErrNoCode
   129  			}
   130  		}
   131  	} else {
   132  		output, err = c.caller.CallContract(ctx, msg, nil)
   133  		if err == nil && len(output) == 0 {
   134  			// Make sure we have a contract to operate on, and bail out otherwise.
   135  			if code, err = c.caller.CodeAt(ctx, c.address, nil); err != nil {
   136  				return err
   137  			} else if len(code) == 0 {
   138  				return ErrNoCode
   139  			}
   140  		}
   141  	}
   142  	if err != nil {
   143  		return err
   144  	}
   145  	return c.abi.Unpack(result, method, output)
   146  }
   147  
   148  // Transact invokes the (paid) contract method with params as input values.
   149  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   150  	// Otherwise pack up the parameters and invoke the contract
   151  	input, err := c.abi.Pack(method, params...)
   152  	if err != nil {
   153  		return nil, err
   154  	}
   155  	return c.transact(opts, &c.address, input)
   156  }
   157  
   158  // Transfer initiates a plain transaction to move funds to the contract, calling
   159  // its default method if one is available.
   160  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   161  	return c.transact(opts, &c.address, nil)
   162  }
   163  
   164  // transact executes an actual transaction invocation, first deriving any missing
   165  // authorization fields, and then scheduling the transaction for execution.
   166  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   167  	var err error
   168  
   169  	// Ensure a valid value field and resolve the account nonce
   170  	value := opts.Value
   171  	if value == nil {
   172  		value = new(big.Int)
   173  	}
   174  	var nonce uint64
   175  	if opts.Nonce == nil {
   176  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   177  		if err != nil {
   178  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   179  		}
   180  	} else {
   181  		nonce = opts.Nonce.Uint64()
   182  	}
   183  	// Figure out the gas allowance and gas price values
   184  	gasPrice := opts.GasPrice
   185  	if gasPrice == nil {
   186  		gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
   187  		if err != nil {
   188  			return nil, fmt.Errorf("failed to suggest gas price: %v", err)
   189  		}
   190  	}
   191  	gasLimit := opts.GasLimit
   192  	if gasLimit == nil {
   193  		// Gas estimation cannot succeed without code for method invocations
   194  		if contract != nil {
   195  			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   196  				return nil, err
   197  			} else if len(code) == 0 {
   198  				return nil, ErrNoCode
   199  			}
   200  		}
   201  		// If the contract surely has code (or code is not needed), estimate the transaction
   202  		msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input}
   203  		gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   204  		if err != nil {
   205  			return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
   206  		}
   207  	}
   208  	// Create the transaction, sign it and schedule it for execution
   209  	var rawTx *types.Transaction
   210  	if contract == nil {
   211  		rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
   212  	} else {
   213  		rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
   214  	}
   215  	if opts.Signer == nil {
   216  		return nil, errors.New("no signer to authorize the transaction with")
   217  	}
   218  	signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
   219  	if err != nil {
   220  		return nil, err
   221  	}
   222  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   223  		return nil, err
   224  	}
   225  	return signedTx, nil
   226  }
   227  
   228  func ensureContext(ctx context.Context) context.Context {
   229  	if ctx == nil {
   230  		return context.TODO()
   231  	}
   232  	return ctx
   233  }