github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/accounts/abi/bind/base.go (about)

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