github.com/0xsequence/ethkit@v1.25.0/go-ethereum/accounts/abi/abi.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 abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  
    26  	"github.com/0xsequence/ethkit/go-ethereum/common"
    27  	"github.com/0xsequence/ethkit/go-ethereum/crypto"
    28  )
    29  
    30  // The ABI holds information about a contract's context and available
    31  // invokable methods. It will allow you to type check function calls and
    32  // packs data accordingly.
    33  type ABI struct {
    34  	Constructor Method
    35  	Methods     map[string]Method
    36  	Events      map[string]Event
    37  	Errors      map[string]Error
    38  
    39  	// Additional "special" functions introduced in solidity v0.6.0.
    40  	// It's separated from the original default fallback. Each contract
    41  	// can only define one fallback and receive function.
    42  	Fallback Method // Note it's also used to represent legacy fallback before v0.6.0
    43  	Receive  Method
    44  }
    45  
    46  // JSON returns a parsed ABI interface and error if it failed.
    47  func JSON(reader io.Reader) (ABI, error) {
    48  	dec := json.NewDecoder(reader)
    49  
    50  	var abi ABI
    51  	if err := dec.Decode(&abi); err != nil {
    52  		return ABI{}, err
    53  	}
    54  	return abi, nil
    55  }
    56  
    57  // Pack the given method name to conform the ABI. Method call's data
    58  // will consist of method_id, args0, arg1, ... argN. Method id consists
    59  // of 4 bytes and arguments are all 32 bytes.
    60  // Method ids are created from the first 4 bytes of the hash of the
    61  // methods string signature. (signature = baz(uint32,string32))
    62  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    63  	// Fetch the ABI of the requested method
    64  	if name == "" {
    65  		// constructor
    66  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    67  		if err != nil {
    68  			return nil, err
    69  		}
    70  		return arguments, nil
    71  	}
    72  	method, exist := abi.Methods[name]
    73  	if !exist {
    74  		return nil, fmt.Errorf("method '%s' not found", name)
    75  	}
    76  	arguments, err := method.Inputs.Pack(args...)
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  	// Pack up the method ID too if not a constructor and return
    81  	return append(method.ID, arguments...), nil
    82  }
    83  
    84  func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
    85  	// since there can't be naming collisions with contracts and events,
    86  	// we need to decide whether we're calling a method or an event
    87  	var args Arguments
    88  	if method, ok := abi.Methods[name]; ok {
    89  		if len(data)%32 != 0 {
    90  			return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
    91  		}
    92  		args = method.Outputs
    93  	}
    94  	if event, ok := abi.Events[name]; ok {
    95  		args = event.Inputs
    96  	}
    97  	if args == nil {
    98  		return nil, fmt.Errorf("abi: could not locate named method or event: %s", name)
    99  	}
   100  	return args, nil
   101  }
   102  
   103  // Unpack unpacks the output according to the abi specification.
   104  func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
   105  	args, err := abi.getArguments(name, data)
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  	return args.Unpack(data)
   110  }
   111  
   112  // UnpackIntoInterface unpacks the output in v according to the abi specification.
   113  // It performs an additional copy. Please only use, if you want to unpack into a
   114  // structure that does not strictly conform to the abi structure (e.g. has additional arguments)
   115  func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
   116  	args, err := abi.getArguments(name, data)
   117  	if err != nil {
   118  		return err
   119  	}
   120  	unpacked, err := args.Unpack(data)
   121  	if err != nil {
   122  		return err
   123  	}
   124  	return args.Copy(v, unpacked)
   125  }
   126  
   127  // UnpackIntoMap unpacks a log into the provided map[string]interface{}.
   128  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
   129  	args, err := abi.getArguments(name, data)
   130  	if err != nil {
   131  		return err
   132  	}
   133  	return args.UnpackIntoMap(v, data)
   134  }
   135  
   136  // UnmarshalJSON implements json.Unmarshaler interface.
   137  func (abi *ABI) UnmarshalJSON(data []byte) error {
   138  	var fields []struct {
   139  		Type    string
   140  		Name    string
   141  		Inputs  []Argument
   142  		Outputs []Argument
   143  
   144  		// Status indicator which can be: "pure", "view",
   145  		// "nonpayable" or "payable".
   146  		StateMutability string
   147  
   148  		// Deprecated Status indicators, but removed in v0.6.0.
   149  		Constant bool // True if function is either pure or view
   150  		Payable  bool // True if function is payable
   151  
   152  		// Event relevant indicator represents the event is
   153  		// declared as anonymous.
   154  		Anonymous bool
   155  	}
   156  	if err := json.Unmarshal(data, &fields); err != nil {
   157  		return err
   158  	}
   159  	abi.Methods = make(map[string]Method)
   160  	abi.Events = make(map[string]Event)
   161  	abi.Errors = make(map[string]Error)
   162  	for _, field := range fields {
   163  		switch field.Type {
   164  		case "constructor":
   165  			abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
   166  		case "function":
   167  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok })
   168  			abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
   169  		case "fallback":
   170  			// New introduced function type in v0.6.0, check more detail
   171  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   172  			if abi.HasFallback() {
   173  				return errors.New("only single fallback is allowed")
   174  			}
   175  			abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
   176  		case "receive":
   177  			// New introduced function type in v0.6.0, check more detail
   178  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   179  			if abi.HasReceive() {
   180  				return errors.New("only single receive is allowed")
   181  			}
   182  			if field.StateMutability != "payable" {
   183  				return errors.New("the statemutability of receive can only be payable")
   184  			}
   185  			abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
   186  		case "event":
   187  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok })
   188  			abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
   189  		case "error":
   190  			// Errors cannot be overloaded or overridden but are inherited,
   191  			// no need to resolve the name conflict here.
   192  			abi.Errors[field.Name] = NewError(field.Name, field.Inputs)
   193  		default:
   194  			return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
   195  		}
   196  	}
   197  	return nil
   198  }
   199  
   200  // MethodById looks up a method by the 4-byte id,
   201  // returns nil if none found.
   202  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   203  	if len(sigdata) < 4 {
   204  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   205  	}
   206  	for _, method := range abi.Methods {
   207  		if bytes.Equal(method.ID, sigdata[:4]) {
   208  			return &method, nil
   209  		}
   210  	}
   211  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   212  }
   213  
   214  // EventByID looks an event up by its topic hash in the
   215  // ABI and returns nil if none found.
   216  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   217  	for _, event := range abi.Events {
   218  		if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
   219  			return &event, nil
   220  		}
   221  	}
   222  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   223  }
   224  
   225  // HasFallback returns an indicator whether a fallback function is included.
   226  func (abi *ABI) HasFallback() bool {
   227  	return abi.Fallback.Type == Fallback
   228  }
   229  
   230  // HasReceive returns an indicator whether a receive function is included.
   231  func (abi *ABI) HasReceive() bool {
   232  	return abi.Receive.Type == Receive
   233  }
   234  
   235  // revertSelector is a special function selector for revert reason unpacking.
   236  var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
   237  
   238  // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
   239  // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
   240  // the provided revert reason is abi-encoded as if it were a call to a function
   241  // `Error(string)`. So it's a special tool for it.
   242  func UnpackRevert(data []byte) (string, error) {
   243  	if len(data) < 4 {
   244  		return "", errors.New("invalid data for unpacking")
   245  	}
   246  	if !bytes.Equal(data[:4], revertSelector) {
   247  		return "", errors.New("invalid data for unpacking")
   248  	}
   249  	typ, _ := NewType("string", "", nil)
   250  	unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
   251  	if err != nil {
   252  		return "", err
   253  	}
   254  	return unpacked[0].(string), nil
   255  }