github.com/ethereum/go-ethereum@v1.16.1/accounts/abi/abi_test.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/hex"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"reflect"
    26  	"strings"
    27  	"testing"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/math"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/internal/testrand"
    33  )
    34  
    35  const jsondata = `
    36  [
    37  	{ "type" : "function", "name" : ""},
    38  	{ "type" : "function", "name" : "balance", "stateMutability" : "view" },
    39  	{ "type" : "function", "name" : "send", "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
    40  	{ "type" : "function", "name" : "test", "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
    41  	{ "type" : "function", "name" : "string", "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
    42  	{ "type" : "function", "name" : "bool", "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
    43  	{ "type" : "function", "name" : "address", "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
    44  	{ "type" : "function", "name" : "uint64[2]", "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
    45  	{ "type" : "function", "name" : "uint64[]", "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
    46  	{ "type" : "function", "name" : "int8", "inputs" : [ { "name" : "inputs", "type" : "int8" } ] },
    47  	{ "type" : "function", "name" : "bytes32", "inputs" : [ { "name" : "inputs", "type" : "bytes32" } ] },
    48  	{ "type" : "function", "name" : "foo", "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
    49  	{ "type" : "function", "name" : "bar", "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
    50  	{ "type" : "function", "name" : "slice", "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
    51  	{ "type" : "function", "name" : "slice256", "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
    52  	{ "type" : "function", "name" : "sliceAddress", "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
    53  	{ "type" : "function", "name" : "sliceMultiAddress", "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] },
    54  	{ "type" : "function", "name" : "nestedArray", "inputs" : [ { "name" : "a", "type" : "uint256[2][2]" }, { "name" : "b", "type" : "address[]" } ] },
    55  	{ "type" : "function", "name" : "nestedArray2", "inputs" : [ { "name" : "a", "type" : "uint8[][2]" } ] },
    56  	{ "type" : "function", "name" : "nestedSlice", "inputs" : [ { "name" : "a", "type" : "uint8[][]" } ] },
    57  	{ "type" : "function", "name" : "receive", "inputs" : [ { "name" : "memo", "type" : "bytes" }], "outputs" : [], "payable" : true, "stateMutability" : "payable" },
    58  	{ "type" : "function", "name" : "fixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
    59  	{ "type" : "function", "name" : "fixedArrBytes", "stateMutability" : "view", "inputs" : [ { "name" : "bytes", "type" : "bytes" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
    60  	{ "type" : "function", "name" : "mixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" }, { "name" : "dynArr", "type" : "uint256[]" } ] },
    61  	{ "type" : "function", "name" : "doubleFixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type" : "uint256[2]" }, { "name" : "fixedArr2", "type" : "uint256[3]" } ] },
    62  	{ "type" : "function", "name" : "multipleMixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type" : "uint256[2]" }, { "name" : "dynArr", "type" : "uint256[]" }, { "name" : "fixedArr2", "type" : "uint256[3]" } ] },
    63  	{ "type" : "function", "name" : "overloadedNames", "stateMutability" : "view", "inputs": [ { "components": [ { "internalType": "uint256", "name": "_f",	"type": "uint256" }, { "internalType": "uint256", "name": "__f", "type": "uint256"}, { "internalType": "uint256", "name": "f", "type": "uint256"}],"internalType": "struct Overloader.F", "name": "f","type": "tuple"}]}
    64  ]`
    65  
    66  var (
    67  	Uint256, _    = NewType("uint256", "", nil)
    68  	Uint32, _     = NewType("uint32", "", nil)
    69  	Uint16, _     = NewType("uint16", "", nil)
    70  	String, _     = NewType("string", "", nil)
    71  	Bool, _       = NewType("bool", "", nil)
    72  	Bytes, _      = NewType("bytes", "", nil)
    73  	Bytes32, _    = NewType("bytes32", "", nil)
    74  	Address, _    = NewType("address", "", nil)
    75  	Uint64Arr, _  = NewType("uint64[]", "", nil)
    76  	AddressArr, _ = NewType("address[]", "", nil)
    77  	Int8, _       = NewType("int8", "", nil)
    78  	// Special types for testing
    79  	Uint32Arr2, _       = NewType("uint32[2]", "", nil)
    80  	Uint64Arr2, _       = NewType("uint64[2]", "", nil)
    81  	Uint256Arr, _       = NewType("uint256[]", "", nil)
    82  	Uint256Arr2, _      = NewType("uint256[2]", "", nil)
    83  	Uint256Arr3, _      = NewType("uint256[3]", "", nil)
    84  	Uint256ArrNested, _ = NewType("uint256[2][2]", "", nil)
    85  	Uint8ArrNested, _   = NewType("uint8[][2]", "", nil)
    86  	Uint8SliceNested, _ = NewType("uint8[][]", "", nil)
    87  	TupleF, _           = NewType("tuple", "struct Overloader.F", []ArgumentMarshaling{
    88  		{Name: "_f", Type: "uint256"},
    89  		{Name: "__f", Type: "uint256"},
    90  		{Name: "f", Type: "uint256"}})
    91  )
    92  
    93  var methods = map[string]Method{
    94  	"":                    NewMethod("", "", Function, "", false, false, nil, nil),
    95  	"balance":             NewMethod("balance", "balance", Function, "view", false, false, nil, nil),
    96  	"send":                NewMethod("send", "send", Function, "", false, false, []Argument{{"amount", Uint256, false}}, nil),
    97  	"test":                NewMethod("test", "test", Function, "", false, false, []Argument{{"number", Uint32, false}}, nil),
    98  	"string":              NewMethod("string", "string", Function, "", false, false, []Argument{{"inputs", String, false}}, nil),
    99  	"bool":                NewMethod("bool", "bool", Function, "", false, false, []Argument{{"inputs", Bool, false}}, nil),
   100  	"address":             NewMethod("address", "address", Function, "", false, false, []Argument{{"inputs", Address, false}}, nil),
   101  	"uint64[]":            NewMethod("uint64[]", "uint64[]", Function, "", false, false, []Argument{{"inputs", Uint64Arr, false}}, nil),
   102  	"uint64[2]":           NewMethod("uint64[2]", "uint64[2]", Function, "", false, false, []Argument{{"inputs", Uint64Arr2, false}}, nil),
   103  	"int8":                NewMethod("int8", "int8", Function, "", false, false, []Argument{{"inputs", Int8, false}}, nil),
   104  	"bytes32":             NewMethod("bytes32", "bytes32", Function, "", false, false, []Argument{{"inputs", Bytes32, false}}, nil),
   105  	"foo":                 NewMethod("foo", "foo", Function, "", false, false, []Argument{{"inputs", Uint32, false}}, nil),
   106  	"bar":                 NewMethod("bar", "bar", Function, "", false, false, []Argument{{"inputs", Uint32, false}, {"string", Uint16, false}}, nil),
   107  	"slice":               NewMethod("slice", "slice", Function, "", false, false, []Argument{{"inputs", Uint32Arr2, false}}, nil),
   108  	"slice256":            NewMethod("slice256", "slice256", Function, "", false, false, []Argument{{"inputs", Uint256Arr2, false}}, nil),
   109  	"sliceAddress":        NewMethod("sliceAddress", "sliceAddress", Function, "", false, false, []Argument{{"inputs", AddressArr, false}}, nil),
   110  	"sliceMultiAddress":   NewMethod("sliceMultiAddress", "sliceMultiAddress", Function, "", false, false, []Argument{{"a", AddressArr, false}, {"b", AddressArr, false}}, nil),
   111  	"nestedArray":         NewMethod("nestedArray", "nestedArray", Function, "", false, false, []Argument{{"a", Uint256ArrNested, false}, {"b", AddressArr, false}}, nil),
   112  	"nestedArray2":        NewMethod("nestedArray2", "nestedArray2", Function, "", false, false, []Argument{{"a", Uint8ArrNested, false}}, nil),
   113  	"nestedSlice":         NewMethod("nestedSlice", "nestedSlice", Function, "", false, false, []Argument{{"a", Uint8SliceNested, false}}, nil),
   114  	"receive":             NewMethod("receive", "receive", Function, "payable", false, true, []Argument{{"memo", Bytes, false}}, []Argument{}),
   115  	"fixedArrStr":         NewMethod("fixedArrStr", "fixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr", Uint256Arr2, false}}, nil),
   116  	"fixedArrBytes":       NewMethod("fixedArrBytes", "fixedArrBytes", Function, "view", false, false, []Argument{{"bytes", Bytes, false}, {"fixedArr", Uint256Arr2, false}}, nil),
   117  	"mixedArrStr":         NewMethod("mixedArrStr", "mixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr", Uint256Arr2, false}, {"dynArr", Uint256Arr, false}}, nil),
   118  	"doubleFixedArrStr":   NewMethod("doubleFixedArrStr", "doubleFixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr1", Uint256Arr2, false}, {"fixedArr2", Uint256Arr3, false}}, nil),
   119  	"multipleMixedArrStr": NewMethod("multipleMixedArrStr", "multipleMixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr1", Uint256Arr2, false}, {"dynArr", Uint256Arr, false}, {"fixedArr2", Uint256Arr3, false}}, nil),
   120  	"overloadedNames":     NewMethod("overloadedNames", "overloadedNames", Function, "view", false, false, []Argument{{"f", TupleF, false}}, nil),
   121  }
   122  
   123  func TestReader(t *testing.T) {
   124  	t.Parallel()
   125  	abi := ABI{
   126  		Methods: methods,
   127  	}
   128  
   129  	exp, err := JSON(strings.NewReader(jsondata))
   130  	if err != nil {
   131  		t.Fatal(err)
   132  	}
   133  
   134  	for name, expM := range exp.Methods {
   135  		gotM, exist := abi.Methods[name]
   136  		if !exist {
   137  			t.Errorf("Missing expected method %v", name)
   138  		}
   139  		if !reflect.DeepEqual(gotM, expM) {
   140  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
   141  		}
   142  	}
   143  
   144  	for name, gotM := range abi.Methods {
   145  		expM, exist := exp.Methods[name]
   146  		if !exist {
   147  			t.Errorf("Found extra method %v", name)
   148  		}
   149  		if !reflect.DeepEqual(gotM, expM) {
   150  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
   151  		}
   152  	}
   153  }
   154  
   155  func TestInvalidABI(t *testing.T) {
   156  	t.Parallel()
   157  	json := `[{ "type" : "function", "name" : "", "constant" : fals }]`
   158  	_, err := JSON(strings.NewReader(json))
   159  	if err == nil {
   160  		t.Fatal("invalid json should produce error")
   161  	}
   162  	json2 := `[{ "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "typ" : "uint256" } ] }]`
   163  	_, err = JSON(strings.NewReader(json2))
   164  	if err == nil {
   165  		t.Fatal("invalid json should produce error")
   166  	}
   167  }
   168  
   169  // TestConstructor tests a constructor function.
   170  // The test is based on the following contract:
   171  //
   172  //	contract TestConstructor {
   173  //		constructor(uint256 a, uint256 b) public{}
   174  //	}
   175  func TestConstructor(t *testing.T) {
   176  	t.Parallel()
   177  	json := `[{	"inputs": [{"internalType": "uint256","name": "a","type": "uint256"	},{	"internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]`
   178  	method := NewMethod("", "", Constructor, "nonpayable", false, false, []Argument{{"a", Uint256, false}, {"b", Uint256, false}}, nil)
   179  	// Test from JSON
   180  	abi, err := JSON(strings.NewReader(json))
   181  	if err != nil {
   182  		t.Fatal(err)
   183  	}
   184  	if !reflect.DeepEqual(abi.Constructor, method) {
   185  		t.Error("Missing expected constructor")
   186  	}
   187  	// Test pack/unpack
   188  	packed, err := abi.Pack("", big.NewInt(1), big.NewInt(2))
   189  	if err != nil {
   190  		t.Error(err)
   191  	}
   192  	unpacked, err := abi.Constructor.Inputs.Unpack(packed)
   193  	if err != nil {
   194  		t.Error(err)
   195  	}
   196  
   197  	if !reflect.DeepEqual(unpacked[0], big.NewInt(1)) {
   198  		t.Error("Unable to pack/unpack from constructor")
   199  	}
   200  	if !reflect.DeepEqual(unpacked[1], big.NewInt(2)) {
   201  		t.Error("Unable to pack/unpack from constructor")
   202  	}
   203  }
   204  
   205  func TestTestNumbers(t *testing.T) {
   206  	t.Parallel()
   207  	abi, err := JSON(strings.NewReader(jsondata))
   208  	if err != nil {
   209  		t.Fatal(err)
   210  	}
   211  
   212  	if _, err := abi.Pack("balance"); err != nil {
   213  		t.Error(err)
   214  	}
   215  
   216  	if _, err := abi.Pack("balance", 1); err == nil {
   217  		t.Error("expected error for balance(1)")
   218  	}
   219  
   220  	if _, err := abi.Pack("doesntexist", nil); err == nil {
   221  		t.Errorf("doesntexist shouldn't exist")
   222  	}
   223  
   224  	if _, err := abi.Pack("doesntexist", 1); err == nil {
   225  		t.Errorf("doesntexist(1) shouldn't exist")
   226  	}
   227  
   228  	if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
   229  		t.Error(err)
   230  	}
   231  
   232  	i := new(int)
   233  	*i = 1000
   234  	if _, err := abi.Pack("send", i); err == nil {
   235  		t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
   236  	}
   237  
   238  	if _, err := abi.Pack("test", uint32(1000)); err != nil {
   239  		t.Error(err)
   240  	}
   241  }
   242  
   243  func TestMethodSignature(t *testing.T) {
   244  	t.Parallel()
   245  	m := NewMethod("foo", "foo", Function, "", false, false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil)
   246  	exp := "foo(string,string)"
   247  	if m.Sig != exp {
   248  		t.Error("signature mismatch", exp, "!=", m.Sig)
   249  	}
   250  
   251  	idexp := crypto.Keccak256([]byte(exp))[:4]
   252  	if !bytes.Equal(m.ID, idexp) {
   253  		t.Errorf("expected ids to match %x != %x", m.ID, idexp)
   254  	}
   255  
   256  	m = NewMethod("foo", "foo", Function, "", false, false, []Argument{{"bar", Uint256, false}}, nil)
   257  	exp = "foo(uint256)"
   258  	if m.Sig != exp {
   259  		t.Error("signature mismatch", exp, "!=", m.Sig)
   260  	}
   261  
   262  	// Method with tuple arguments
   263  	s, _ := NewType("tuple", "", []ArgumentMarshaling{
   264  		{Name: "a", Type: "int256"},
   265  		{Name: "b", Type: "int256[]"},
   266  		{Name: "c", Type: "tuple[]", Components: []ArgumentMarshaling{
   267  			{Name: "x", Type: "int256"},
   268  			{Name: "y", Type: "int256"},
   269  		}},
   270  		{Name: "d", Type: "tuple[2]", Components: []ArgumentMarshaling{
   271  			{Name: "x", Type: "int256"},
   272  			{Name: "y", Type: "int256"},
   273  		}},
   274  	})
   275  	m = NewMethod("foo", "foo", Function, "", false, false, []Argument{{"s", s, false}, {"bar", String, false}}, nil)
   276  	exp = "foo((int256,int256[],(int256,int256)[],(int256,int256)[2]),string)"
   277  	if m.Sig != exp {
   278  		t.Error("signature mismatch", exp, "!=", m.Sig)
   279  	}
   280  }
   281  
   282  func TestOverloadedMethodSignature(t *testing.T) {
   283  	t.Parallel()
   284  	json := `[{"constant":true,"inputs":[{"name":"i","type":"uint256"},{"name":"j","type":"uint256"}],"name":"foo","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"i","type":"uint256"}],"name":"foo","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"i","type":"uint256"}],"name":"bar","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"i","type":"uint256"},{"indexed":false,"name":"j","type":"uint256"}],"name":"bar","type":"event"}]`
   285  	abi, err := JSON(strings.NewReader(json))
   286  	if err != nil {
   287  		t.Fatal(err)
   288  	}
   289  	check := func(name string, expect string, method bool) {
   290  		if method {
   291  			if abi.Methods[name].Sig != expect {
   292  				t.Fatalf("The signature of overloaded method mismatch, want %s, have %s", expect, abi.Methods[name].Sig)
   293  			}
   294  		} else {
   295  			if abi.Events[name].Sig != expect {
   296  				t.Fatalf("The signature of overloaded event mismatch, want %s, have %s", expect, abi.Events[name].Sig)
   297  			}
   298  		}
   299  	}
   300  	check("foo", "foo(uint256,uint256)", true)
   301  	check("foo0", "foo(uint256)", true)
   302  	check("bar", "bar(uint256)", false)
   303  	check("bar0", "bar(uint256,uint256)", false)
   304  }
   305  
   306  func TestCustomErrors(t *testing.T) {
   307  	t.Parallel()
   308  	json := `[{ "inputs": [	{ "internalType": "uint256", "name": "", "type": "uint256" } ],"name": "MyError", "type": "error"} ]`
   309  	abi, err := JSON(strings.NewReader(json))
   310  	if err != nil {
   311  		t.Fatal(err)
   312  	}
   313  	check := func(name string, expect string) {
   314  		if abi.Errors[name].Sig != expect {
   315  			t.Fatalf("The signature of overloaded method mismatch, want %s, have %s", expect, abi.Methods[name].Sig)
   316  		}
   317  	}
   318  	check("MyError", "MyError(uint256)")
   319  }
   320  
   321  func TestCustomErrorUnpackIntoInterface(t *testing.T) {
   322  	t.Parallel()
   323  	errorName := "MyError"
   324  	json := fmt.Sprintf(`[{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"}],"name":"%s","type":"error"}]`, errorName)
   325  	abi, err := JSON(strings.NewReader(json))
   326  	if err != nil {
   327  		t.Fatal(err)
   328  	}
   329  	type MyError struct {
   330  		Sender  common.Address
   331  		Balance *big.Int
   332  	}
   333  
   334  	sender := testrand.Address()
   335  	balance := new(big.Int).SetBytes(testrand.Bytes(8))
   336  	encoded, err := abi.Errors[errorName].Inputs.Pack(sender, balance)
   337  	if err != nil {
   338  		t.Fatal(err)
   339  	}
   340  	result := MyError{}
   341  	err = abi.UnpackIntoInterface(&result, errorName, encoded)
   342  	if err != nil {
   343  		t.Fatal(err)
   344  	}
   345  	if result.Sender != sender {
   346  		t.Errorf("expected %x got %x", sender, result.Sender)
   347  	}
   348  	if result.Balance.Cmp(balance) != 0 {
   349  		t.Errorf("expected %v got %v", balance, result.Balance)
   350  	}
   351  }
   352  
   353  func TestMultiPack(t *testing.T) {
   354  	t.Parallel()
   355  	abi, err := JSON(strings.NewReader(jsondata))
   356  	if err != nil {
   357  		t.Fatal(err)
   358  	}
   359  
   360  	sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
   361  	sig = append(sig, make([]byte, 64)...)
   362  	sig[35] = 10
   363  	sig[67] = 11
   364  
   365  	packed, err := abi.Pack("bar", uint32(10), uint16(11))
   366  	if err != nil {
   367  		t.Fatal(err)
   368  	}
   369  	if !bytes.Equal(packed, sig) {
   370  		t.Errorf("expected %x got %x", sig, packed)
   371  	}
   372  }
   373  
   374  func ExampleJSON() {
   375  	const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
   376  
   377  	abi, err := JSON(strings.NewReader(definition))
   378  	if err != nil {
   379  		panic(err)
   380  	}
   381  	out, err := abi.Pack("isBar", common.HexToAddress("01"))
   382  	if err != nil {
   383  		panic(err)
   384  	}
   385  
   386  	fmt.Printf("%x\n", out)
   387  	// Output:
   388  	// 1f2c40920000000000000000000000000000000000000000000000000000000000000001
   389  }
   390  
   391  func TestInputVariableInputLength(t *testing.T) {
   392  	t.Parallel()
   393  	const definition = `[
   394  	{ "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
   395  	{ "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
   396  	{ "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
   397  	]`
   398  
   399  	abi, err := JSON(strings.NewReader(definition))
   400  	if err != nil {
   401  		t.Fatal(err)
   402  	}
   403  
   404  	// test one string
   405  	strin := "hello world"
   406  	strpack, err := abi.Pack("strOne", strin)
   407  	if err != nil {
   408  		t.Error(err)
   409  	}
   410  
   411  	offset := make([]byte, 32)
   412  	offset[31] = 32
   413  	length := make([]byte, 32)
   414  	length[31] = byte(len(strin))
   415  	value := common.RightPadBytes([]byte(strin), 32)
   416  	exp := append(offset, append(length, value...)...)
   417  
   418  	// ignore first 4 bytes of the output. This is the function identifier
   419  	strpack = strpack[4:]
   420  	if !bytes.Equal(strpack, exp) {
   421  		t.Errorf("expected %x, got %x\n", exp, strpack)
   422  	}
   423  
   424  	// test one bytes
   425  	btspack, err := abi.Pack("bytesOne", []byte(strin))
   426  	if err != nil {
   427  		t.Error(err)
   428  	}
   429  	// ignore first 4 bytes of the output. This is the function identifier
   430  	btspack = btspack[4:]
   431  	if !bytes.Equal(btspack, exp) {
   432  		t.Errorf("expected %x, got %x\n", exp, btspack)
   433  	}
   434  
   435  	//  test two strings
   436  	str1 := "hello"
   437  	str2 := "world"
   438  	str2pack, err := abi.Pack("strTwo", str1, str2)
   439  	if err != nil {
   440  		t.Error(err)
   441  	}
   442  
   443  	offset1 := make([]byte, 32)
   444  	offset1[31] = 64
   445  	length1 := make([]byte, 32)
   446  	length1[31] = byte(len(str1))
   447  	value1 := common.RightPadBytes([]byte(str1), 32)
   448  
   449  	offset2 := make([]byte, 32)
   450  	offset2[31] = 128
   451  	length2 := make([]byte, 32)
   452  	length2[31] = byte(len(str2))
   453  	value2 := common.RightPadBytes([]byte(str2), 32)
   454  
   455  	exp2 := append(offset1, offset2...)
   456  	exp2 = append(exp2, append(length1, value1...)...)
   457  	exp2 = append(exp2, append(length2, value2...)...)
   458  
   459  	// ignore first 4 bytes of the output. This is the function identifier
   460  	str2pack = str2pack[4:]
   461  	if !bytes.Equal(str2pack, exp2) {
   462  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   463  	}
   464  
   465  	// test two strings, first > 32, second < 32
   466  	str1 = strings.Repeat("a", 33)
   467  	str2pack, err = abi.Pack("strTwo", str1, str2)
   468  	if err != nil {
   469  		t.Error(err)
   470  	}
   471  
   472  	offset1 = make([]byte, 32)
   473  	offset1[31] = 64
   474  	length1 = make([]byte, 32)
   475  	length1[31] = byte(len(str1))
   476  	value1 = common.RightPadBytes([]byte(str1), 64)
   477  	offset2[31] = 160
   478  
   479  	exp2 = append(offset1, offset2...)
   480  	exp2 = append(exp2, append(length1, value1...)...)
   481  	exp2 = append(exp2, append(length2, value2...)...)
   482  
   483  	// ignore first 4 bytes of the output. This is the function identifier
   484  	str2pack = str2pack[4:]
   485  	if !bytes.Equal(str2pack, exp2) {
   486  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   487  	}
   488  
   489  	// test two strings, first > 32, second >32
   490  	str1 = strings.Repeat("a", 33)
   491  	str2 = strings.Repeat("a", 33)
   492  	str2pack, err = abi.Pack("strTwo", str1, str2)
   493  	if err != nil {
   494  		t.Error(err)
   495  	}
   496  
   497  	offset1 = make([]byte, 32)
   498  	offset1[31] = 64
   499  	length1 = make([]byte, 32)
   500  	length1[31] = byte(len(str1))
   501  	value1 = common.RightPadBytes([]byte(str1), 64)
   502  
   503  	offset2 = make([]byte, 32)
   504  	offset2[31] = 160
   505  	length2 = make([]byte, 32)
   506  	length2[31] = byte(len(str2))
   507  	value2 = common.RightPadBytes([]byte(str2), 64)
   508  
   509  	exp2 = append(offset1, offset2...)
   510  	exp2 = append(exp2, append(length1, value1...)...)
   511  	exp2 = append(exp2, append(length2, value2...)...)
   512  
   513  	// ignore first 4 bytes of the output. This is the function identifier
   514  	str2pack = str2pack[4:]
   515  	if !bytes.Equal(str2pack, exp2) {
   516  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   517  	}
   518  }
   519  
   520  func TestInputFixedArrayAndVariableInputLength(t *testing.T) {
   521  	t.Parallel()
   522  	abi, err := JSON(strings.NewReader(jsondata))
   523  	if err != nil {
   524  		t.Error(err)
   525  	}
   526  
   527  	// test string, fixed array uint256[2]
   528  	strin := "hello world"
   529  	arrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   530  	fixedArrStrPack, err := abi.Pack("fixedArrStr", strin, arrin)
   531  	if err != nil {
   532  		t.Error(err)
   533  	}
   534  
   535  	// generate expected output
   536  	offset := make([]byte, 32)
   537  	offset[31] = 96
   538  	length := make([]byte, 32)
   539  	length[31] = byte(len(strin))
   540  	strvalue := common.RightPadBytes([]byte(strin), 32)
   541  	arrinvalue1 := common.LeftPadBytes(arrin[0].Bytes(), 32)
   542  	arrinvalue2 := common.LeftPadBytes(arrin[1].Bytes(), 32)
   543  	exp := append(offset, arrinvalue1...)
   544  	exp = append(exp, arrinvalue2...)
   545  	exp = append(exp, append(length, strvalue...)...)
   546  
   547  	// ignore first 4 bytes of the output. This is the function identifier
   548  	fixedArrStrPack = fixedArrStrPack[4:]
   549  	if !bytes.Equal(fixedArrStrPack, exp) {
   550  		t.Errorf("expected %x, got %x\n", exp, fixedArrStrPack)
   551  	}
   552  
   553  	// test byte array, fixed array uint256[2]
   554  	bytesin := []byte(strin)
   555  	arrin = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   556  	fixedArrBytesPack, err := abi.Pack("fixedArrBytes", bytesin, arrin)
   557  	if err != nil {
   558  		t.Error(err)
   559  	}
   560  
   561  	// generate expected output
   562  	offset = make([]byte, 32)
   563  	offset[31] = 96
   564  	length = make([]byte, 32)
   565  	length[31] = byte(len(strin))
   566  	strvalue = common.RightPadBytes([]byte(strin), 32)
   567  	arrinvalue1 = common.LeftPadBytes(arrin[0].Bytes(), 32)
   568  	arrinvalue2 = common.LeftPadBytes(arrin[1].Bytes(), 32)
   569  	exp = append(offset, arrinvalue1...)
   570  	exp = append(exp, arrinvalue2...)
   571  	exp = append(exp, append(length, strvalue...)...)
   572  
   573  	// ignore first 4 bytes of the output. This is the function identifier
   574  	fixedArrBytesPack = fixedArrBytesPack[4:]
   575  	if !bytes.Equal(fixedArrBytesPack, exp) {
   576  		t.Errorf("expected %x, got %x\n", exp, fixedArrBytesPack)
   577  	}
   578  
   579  	// test string, fixed array uint256[2], dynamic array uint256[]
   580  	strin = "hello world"
   581  	fixedarrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   582  	dynarrin := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   583  	mixedArrStrPack, err := abi.Pack("mixedArrStr", strin, fixedarrin, dynarrin)
   584  	if err != nil {
   585  		t.Error(err)
   586  	}
   587  
   588  	// generate expected output
   589  	stroffset := make([]byte, 32)
   590  	stroffset[31] = 128
   591  	strlength := make([]byte, 32)
   592  	strlength[31] = byte(len(strin))
   593  	strvalue = common.RightPadBytes([]byte(strin), 32)
   594  	fixedarrinvalue1 := common.LeftPadBytes(fixedarrin[0].Bytes(), 32)
   595  	fixedarrinvalue2 := common.LeftPadBytes(fixedarrin[1].Bytes(), 32)
   596  	dynarroffset := make([]byte, 32)
   597  	dynarroffset[31] = byte(160 + ((len(strin)/32)+1)*32)
   598  	dynarrlength := make([]byte, 32)
   599  	dynarrlength[31] = byte(len(dynarrin))
   600  	dynarrinvalue1 := common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   601  	dynarrinvalue2 := common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   602  	dynarrinvalue3 := common.LeftPadBytes(dynarrin[2].Bytes(), 32)
   603  	exp = append(stroffset, fixedarrinvalue1...)
   604  	exp = append(exp, fixedarrinvalue2...)
   605  	exp = append(exp, dynarroffset...)
   606  	exp = append(exp, append(strlength, strvalue...)...)
   607  	dynarrarg := append(dynarrlength, dynarrinvalue1...)
   608  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   609  	dynarrarg = append(dynarrarg, dynarrinvalue3...)
   610  	exp = append(exp, dynarrarg...)
   611  
   612  	// ignore first 4 bytes of the output. This is the function identifier
   613  	mixedArrStrPack = mixedArrStrPack[4:]
   614  	if !bytes.Equal(mixedArrStrPack, exp) {
   615  		t.Errorf("expected %x, got %x\n", exp, mixedArrStrPack)
   616  	}
   617  
   618  	// test string, fixed array uint256[2], fixed array uint256[3]
   619  	strin = "hello world"
   620  	fixedarrin1 := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   621  	fixedarrin2 := [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   622  	doubleFixedArrStrPack, err := abi.Pack("doubleFixedArrStr", strin, fixedarrin1, fixedarrin2)
   623  	if err != nil {
   624  		t.Error(err)
   625  	}
   626  
   627  	// generate expected output
   628  	stroffset = make([]byte, 32)
   629  	stroffset[31] = 192
   630  	strlength = make([]byte, 32)
   631  	strlength[31] = byte(len(strin))
   632  	strvalue = common.RightPadBytes([]byte(strin), 32)
   633  	fixedarrin1value1 := common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   634  	fixedarrin1value2 := common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   635  	fixedarrin2value1 := common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   636  	fixedarrin2value2 := common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   637  	fixedarrin2value3 := common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   638  	exp = append(stroffset, fixedarrin1value1...)
   639  	exp = append(exp, fixedarrin1value2...)
   640  	exp = append(exp, fixedarrin2value1...)
   641  	exp = append(exp, fixedarrin2value2...)
   642  	exp = append(exp, fixedarrin2value3...)
   643  	exp = append(exp, append(strlength, strvalue...)...)
   644  
   645  	// ignore first 4 bytes of the output. This is the function identifier
   646  	doubleFixedArrStrPack = doubleFixedArrStrPack[4:]
   647  	if !bytes.Equal(doubleFixedArrStrPack, exp) {
   648  		t.Errorf("expected %x, got %x\n", exp, doubleFixedArrStrPack)
   649  	}
   650  
   651  	// test string, fixed array uint256[2], dynamic array uint256[], fixed array uint256[3]
   652  	strin = "hello world"
   653  	fixedarrin1 = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   654  	dynarrin = []*big.Int{big.NewInt(1), big.NewInt(2)}
   655  	fixedarrin2 = [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   656  	multipleMixedArrStrPack, err := abi.Pack("multipleMixedArrStr", strin, fixedarrin1, dynarrin, fixedarrin2)
   657  	if err != nil {
   658  		t.Error(err)
   659  	}
   660  
   661  	// generate expected output
   662  	stroffset = make([]byte, 32)
   663  	stroffset[31] = 224
   664  	strlength = make([]byte, 32)
   665  	strlength[31] = byte(len(strin))
   666  	strvalue = common.RightPadBytes([]byte(strin), 32)
   667  	fixedarrin1value1 = common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   668  	fixedarrin1value2 = common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   669  	dynarroffset = math.U256Bytes(big.NewInt(int64(256 + ((len(strin)/32)+1)*32)))
   670  	dynarrlength = make([]byte, 32)
   671  	dynarrlength[31] = byte(len(dynarrin))
   672  	dynarrinvalue1 = common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   673  	dynarrinvalue2 = common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   674  	fixedarrin2value1 = common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   675  	fixedarrin2value2 = common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   676  	fixedarrin2value3 = common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   677  	exp = append(stroffset, fixedarrin1value1...)
   678  	exp = append(exp, fixedarrin1value2...)
   679  	exp = append(exp, dynarroffset...)
   680  	exp = append(exp, fixedarrin2value1...)
   681  	exp = append(exp, fixedarrin2value2...)
   682  	exp = append(exp, fixedarrin2value3...)
   683  	exp = append(exp, append(strlength, strvalue...)...)
   684  	dynarrarg = append(dynarrlength, dynarrinvalue1...)
   685  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   686  	exp = append(exp, dynarrarg...)
   687  
   688  	// ignore first 4 bytes of the output. This is the function identifier
   689  	multipleMixedArrStrPack = multipleMixedArrStrPack[4:]
   690  	if !bytes.Equal(multipleMixedArrStrPack, exp) {
   691  		t.Errorf("expected %x, got %x\n", exp, multipleMixedArrStrPack)
   692  	}
   693  }
   694  
   695  func TestDefaultFunctionParsing(t *testing.T) {
   696  	t.Parallel()
   697  	const definition = `[{ "name" : "balance", "type" : "function" }]`
   698  
   699  	abi, err := JSON(strings.NewReader(definition))
   700  	if err != nil {
   701  		t.Fatal(err)
   702  	}
   703  
   704  	if _, ok := abi.Methods["balance"]; !ok {
   705  		t.Error("expected 'balance' to be present")
   706  	}
   707  }
   708  
   709  func TestBareEvents(t *testing.T) {
   710  	t.Parallel()
   711  	const definition = `[
   712  	{ "type" : "event", "name" : "balance" },
   713  	{ "type" : "event", "name" : "anon", "anonymous" : true},
   714  	{ "type" : "event", "name" : "args", "inputs" : [{ "indexed":false, "name":"arg0", "type":"uint256" }, { "indexed":true, "name":"arg1", "type":"address" }] },
   715  	{ "type" : "event", "name" : "tuple", "inputs" : [{ "indexed":false, "name":"t", "type":"tuple", "components":[{"name":"a", "type":"uint256"}] }, { "indexed":true, "name":"arg1", "type":"address" }] }
   716  	]`
   717  
   718  	tuple, _ := NewType("tuple", "", []ArgumentMarshaling{{Name: "a", Type: "uint256"}})
   719  
   720  	expectedEvents := map[string]struct {
   721  		Anonymous bool
   722  		Args      []Argument
   723  	}{
   724  		"balance": {false, nil},
   725  		"anon":    {true, nil},
   726  		"args": {false, []Argument{
   727  			{Name: "arg0", Type: Uint256, Indexed: false},
   728  			{Name: "arg1", Type: Address, Indexed: true},
   729  		}},
   730  		"tuple": {false, []Argument{
   731  			{Name: "t", Type: tuple, Indexed: false},
   732  			{Name: "arg1", Type: Address, Indexed: true},
   733  		}},
   734  	}
   735  
   736  	abi, err := JSON(strings.NewReader(definition))
   737  	if err != nil {
   738  		t.Fatal(err)
   739  	}
   740  
   741  	if len(abi.Events) != len(expectedEvents) {
   742  		t.Fatalf("invalid number of events after parsing, want %d, got %d", len(expectedEvents), len(abi.Events))
   743  	}
   744  
   745  	for name, exp := range expectedEvents {
   746  		got, ok := abi.Events[name]
   747  		if !ok {
   748  			t.Errorf("could not found event %s", name)
   749  			continue
   750  		}
   751  		if got.Anonymous != exp.Anonymous {
   752  			t.Errorf("invalid anonymous indication for event %s, want %v, got %v", name, exp.Anonymous, got.Anonymous)
   753  		}
   754  		if len(got.Inputs) != len(exp.Args) {
   755  			t.Errorf("invalid number of args, want %d, got %d", len(exp.Args), len(got.Inputs))
   756  			continue
   757  		}
   758  		for i, arg := range exp.Args {
   759  			if arg.Name != got.Inputs[i].Name {
   760  				t.Errorf("events[%s].Input[%d] has an invalid name, want %s, got %s", name, i, arg.Name, got.Inputs[i].Name)
   761  			}
   762  			if arg.Indexed != got.Inputs[i].Indexed {
   763  				t.Errorf("events[%s].Input[%d] has an invalid indexed indication, want %v, got %v", name, i, arg.Indexed, got.Inputs[i].Indexed)
   764  			}
   765  			if arg.Type.T != got.Inputs[i].Type.T {
   766  				t.Errorf("events[%s].Input[%d] has an invalid type, want %x, got %x", name, i, arg.Type.T, got.Inputs[i].Type.T)
   767  			}
   768  		}
   769  	}
   770  }
   771  
   772  // TestUnpackEvent is based on this contract:
   773  //
   774  //	contract T {
   775  //		event received(address sender, uint amount, bytes memo);
   776  //		event receivedAddr(address sender);
   777  //		function receive(bytes memo) external payable {
   778  //			received(msg.sender, msg.value, memo);
   779  //			receivedAddr(msg.sender);
   780  //		}
   781  //	}
   782  //
   783  // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
   784  //
   785  //	receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
   786  func TestUnpackEvent(t *testing.T) {
   787  	t.Parallel()
   788  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   789  	abi, err := JSON(strings.NewReader(abiJSON))
   790  	if err != nil {
   791  		t.Fatal(err)
   792  	}
   793  
   794  	const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   795  	data, err := hex.DecodeString(hexdata)
   796  	if err != nil {
   797  		t.Fatal(err)
   798  	}
   799  	if len(data)%32 == 0 {
   800  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   801  	}
   802  
   803  	type ReceivedEvent struct {
   804  		Sender common.Address
   805  		Amount *big.Int
   806  		Memo   []byte
   807  	}
   808  	var ev ReceivedEvent
   809  
   810  	err = abi.UnpackIntoInterface(&ev, "received", data)
   811  	if err != nil {
   812  		t.Error(err)
   813  	}
   814  
   815  	type ReceivedAddrEvent struct {
   816  		Sender common.Address
   817  	}
   818  	var receivedAddrEv ReceivedAddrEvent
   819  	err = abi.UnpackIntoInterface(&receivedAddrEv, "receivedAddr", data)
   820  	if err != nil {
   821  		t.Error(err)
   822  	}
   823  }
   824  
   825  func TestUnpackEventIntoMap(t *testing.T) {
   826  	t.Parallel()
   827  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   828  	abi, err := JSON(strings.NewReader(abiJSON))
   829  	if err != nil {
   830  		t.Fatal(err)
   831  	}
   832  
   833  	const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   834  	data, err := hex.DecodeString(hexdata)
   835  	if err != nil {
   836  		t.Fatal(err)
   837  	}
   838  	if len(data)%32 == 0 {
   839  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   840  	}
   841  
   842  	receivedMap := map[string]interface{}{}
   843  	expectedReceivedMap := map[string]interface{}{
   844  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   845  		"amount": big.NewInt(1),
   846  		"memo":   []byte{88},
   847  	}
   848  	if err := abi.UnpackIntoMap(receivedMap, "received", data); err != nil {
   849  		t.Error(err)
   850  	}
   851  	if len(receivedMap) != 3 {
   852  		t.Error("unpacked `received` map expected to have length 3")
   853  	}
   854  	if receivedMap["sender"] != expectedReceivedMap["sender"] {
   855  		t.Error("unpacked `received` map does not match expected map")
   856  	}
   857  	if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 {
   858  		t.Error("unpacked `received` map does not match expected map")
   859  	}
   860  	if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) {
   861  		t.Error("unpacked `received` map does not match expected map")
   862  	}
   863  
   864  	receivedAddrMap := map[string]interface{}{}
   865  	if err = abi.UnpackIntoMap(receivedAddrMap, "receivedAddr", data); err != nil {
   866  		t.Error(err)
   867  	}
   868  	if len(receivedAddrMap) != 1 {
   869  		t.Error("unpacked `receivedAddr` map expected to have length 1")
   870  	}
   871  	if receivedAddrMap["sender"] != expectedReceivedMap["sender"] {
   872  		t.Error("unpacked `receivedAddr` map does not match expected map")
   873  	}
   874  }
   875  
   876  func TestUnpackMethodIntoMap(t *testing.T) {
   877  	t.Parallel()
   878  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"send","outputs":[{"name":"amount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"get","outputs":[{"name":"hash","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"function"}]`
   879  	abi, err := JSON(strings.NewReader(abiJSON))
   880  	if err != nil {
   881  		t.Fatal(err)
   882  	}
   883  	const hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001580000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158`
   884  	data, err := hex.DecodeString(hexdata)
   885  	if err != nil {
   886  		t.Fatal(err)
   887  	}
   888  	if len(data)%32 != 0 {
   889  		t.Errorf("len(data) is %d, want a multiple of 32", len(data))
   890  	}
   891  
   892  	// Tests a method with no outputs
   893  	receiveMap := map[string]interface{}{}
   894  	if err = abi.UnpackIntoMap(receiveMap, "receive", data); err != nil {
   895  		t.Error(err)
   896  	}
   897  	if len(receiveMap) > 0 {
   898  		t.Error("unpacked `receive` map expected to have length 0")
   899  	}
   900  
   901  	// Tests a method with only outputs
   902  	sendMap := map[string]interface{}{}
   903  	if err = abi.UnpackIntoMap(sendMap, "send", data); err != nil {
   904  		t.Error(err)
   905  	}
   906  	if len(sendMap) != 1 {
   907  		t.Error("unpacked `send` map expected to have length 1")
   908  	}
   909  	if sendMap["amount"].(*big.Int).Cmp(big.NewInt(1)) != 0 {
   910  		t.Error("unpacked `send` map expected `amount` value of 1")
   911  	}
   912  
   913  	// Tests a method with outputs and inputs
   914  	getMap := map[string]interface{}{}
   915  	if err = abi.UnpackIntoMap(getMap, "get", data); err != nil {
   916  		t.Error(err)
   917  	}
   918  	if len(getMap) != 1 {
   919  		t.Error("unpacked `get` map expected to have length 1")
   920  	}
   921  	expectedBytes := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0}
   922  	if !bytes.Equal(getMap["hash"].([]byte), expectedBytes) {
   923  		t.Errorf("unpacked `get` map expected `hash` value of %v", expectedBytes)
   924  	}
   925  }
   926  
   927  func TestUnpackIntoMapNamingConflict(t *testing.T) {
   928  	t.Parallel()
   929  	// Two methods have the same name
   930  	var abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"get","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"send","outputs":[{"name":"amount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"get","outputs":[{"name":"hash","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"function"}]`
   931  	abi, err := JSON(strings.NewReader(abiJSON))
   932  	if err != nil {
   933  		t.Fatal(err)
   934  	}
   935  	var hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   936  	data, err := hex.DecodeString(hexdata)
   937  	if err != nil {
   938  		t.Fatal(err)
   939  	}
   940  	if len(data)%32 == 0 {
   941  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   942  	}
   943  	getMap := map[string]interface{}{}
   944  	if err = abi.UnpackIntoMap(getMap, "get", data); err == nil {
   945  		t.Error("naming conflict between two methods; error expected")
   946  	}
   947  
   948  	// Two events have the same name
   949  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"received","type":"event"}]`
   950  	abi, err = JSON(strings.NewReader(abiJSON))
   951  	if err != nil {
   952  		t.Fatal(err)
   953  	}
   954  	hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   955  	data, err = hex.DecodeString(hexdata)
   956  	if err != nil {
   957  		t.Fatal(err)
   958  	}
   959  	if len(data)%32 == 0 {
   960  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   961  	}
   962  	receivedMap := map[string]interface{}{}
   963  	if err = abi.UnpackIntoMap(receivedMap, "received", data); err != nil {
   964  		t.Error("naming conflict between two events; no error expected")
   965  	}
   966  
   967  	// Method and event have the same name
   968  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"received","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   969  	abi, err = JSON(strings.NewReader(abiJSON))
   970  	if err != nil {
   971  		t.Fatal(err)
   972  	}
   973  	if len(data)%32 == 0 {
   974  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   975  	}
   976  	if err = abi.UnpackIntoMap(receivedMap, "received", data); err == nil {
   977  		t.Error("naming conflict between an event and a method; error expected")
   978  	}
   979  
   980  	// Conflict is case sensitive
   981  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"received","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"Received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   982  	abi, err = JSON(strings.NewReader(abiJSON))
   983  	if err != nil {
   984  		t.Fatal(err)
   985  	}
   986  	if len(data)%32 == 0 {
   987  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   988  	}
   989  	expectedReceivedMap := map[string]interface{}{
   990  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   991  		"amount": big.NewInt(1),
   992  		"memo":   []byte{88},
   993  	}
   994  	if err = abi.UnpackIntoMap(receivedMap, "Received", data); err != nil {
   995  		t.Error(err)
   996  	}
   997  	if len(receivedMap) != 3 {
   998  		t.Error("unpacked `received` map expected to have length 3")
   999  	}
  1000  	if receivedMap["sender"] != expectedReceivedMap["sender"] {
  1001  		t.Error("unpacked `received` map does not match expected map")
  1002  	}
  1003  	if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 {
  1004  		t.Error("unpacked `received` map does not match expected map")
  1005  	}
  1006  	if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) {
  1007  		t.Error("unpacked `received` map does not match expected map")
  1008  	}
  1009  }
  1010  
  1011  func TestABI_MethodById(t *testing.T) {
  1012  	t.Parallel()
  1013  	abi, err := JSON(strings.NewReader(jsondata))
  1014  	if err != nil {
  1015  		t.Fatal(err)
  1016  	}
  1017  	for name, m := range abi.Methods {
  1018  		a := fmt.Sprintf("%v", m)
  1019  		m2, err := abi.MethodById(m.ID)
  1020  		if err != nil {
  1021  			t.Fatalf("Failed to look up ABI method: %v", err)
  1022  		}
  1023  		b := fmt.Sprintf("%v", m2)
  1024  		if a != b {
  1025  			t.Errorf("Method %v (id %x) not 'findable' by id in ABI", name, m.ID)
  1026  		}
  1027  	}
  1028  	// test unsuccessful lookups
  1029  	if _, err = abi.MethodById(crypto.Keccak256()); err == nil {
  1030  		t.Error("Expected error: no method with this id")
  1031  	}
  1032  	// Also test empty
  1033  	if _, err := abi.MethodById([]byte{0x00}); err == nil {
  1034  		t.Errorf("Expected error, too short to decode data")
  1035  	}
  1036  	if _, err := abi.MethodById([]byte{}); err == nil {
  1037  		t.Errorf("Expected error, too short to decode data")
  1038  	}
  1039  	if _, err := abi.MethodById(nil); err == nil {
  1040  		t.Errorf("Expected error, nil is short to decode data")
  1041  	}
  1042  }
  1043  
  1044  func TestABI_EventById(t *testing.T) {
  1045  	t.Parallel()
  1046  	tests := []struct {
  1047  		name  string
  1048  		json  string
  1049  		event string
  1050  	}{
  1051  		{
  1052  			name: "",
  1053  			json: `[
  1054  			{"type":"event","name":"received","anonymous":false,"inputs":[
  1055  				{"indexed":false,"name":"sender","type":"address"},
  1056  				{"indexed":false,"name":"amount","type":"uint256"},
  1057  				{"indexed":false,"name":"memo","type":"bytes"}
  1058  				]
  1059  			}]`,
  1060  			event: "received(address,uint256,bytes)",
  1061  		}, {
  1062  			name: "",
  1063  			json: `[
  1064  				{ "constant": true, "inputs": [], "name": "name", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1065  				{ "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "approve", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1066  				{ "constant": true, "inputs": [], "name": "totalSupply", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1067  				{ "constant": false, "inputs": [ { "name": "_from", "type": "address" }, { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1068  				{ "constant": true, "inputs": [], "name": "decimals", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1069  				{ "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1070  				{ "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1071  				{ "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1072  				{ "constant": true, "inputs": [ { "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1073  				{ "payable": true, "stateMutability": "payable", "type": "fallback" },
  1074  				{ "anonymous": false, "inputs": [ { "indexed": true, "name": "owner", "type": "address" }, { "indexed": true, "name": "spender", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" },
  1075  				{ "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "address" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }
  1076  			]`,
  1077  			event: "Transfer(address,address,uint256)",
  1078  		},
  1079  	}
  1080  
  1081  	for testnum, test := range tests {
  1082  		abi, err := JSON(strings.NewReader(test.json))
  1083  		if err != nil {
  1084  			t.Error(err)
  1085  		}
  1086  
  1087  		topic := test.event
  1088  		topicID := crypto.Keccak256Hash([]byte(topic))
  1089  
  1090  		event, err := abi.EventByID(topicID)
  1091  		if err != nil {
  1092  			t.Fatalf("Failed to look up ABI method: %v, test #%d", err, testnum)
  1093  		}
  1094  		if event == nil {
  1095  			t.Errorf("We should find a event for topic %s, test #%d", topicID.Hex(), testnum)
  1096  		} else if event.ID != topicID {
  1097  			t.Errorf("Event id %s does not match topic %s, test #%d", event.ID.Hex(), topicID.Hex(), testnum)
  1098  		}
  1099  
  1100  		unknowntopicID := crypto.Keccak256Hash([]byte("unknownEvent"))
  1101  		unknownEvent, err := abi.EventByID(unknowntopicID)
  1102  		if err == nil {
  1103  			t.Errorf("EventByID should return an error if a topic is not found, test #%d", testnum)
  1104  		}
  1105  		if unknownEvent != nil {
  1106  			t.Errorf("We should not find any event for topic %s, test #%d", unknowntopicID.Hex(), testnum)
  1107  		}
  1108  	}
  1109  }
  1110  
  1111  func TestABI_ErrorByID(t *testing.T) {
  1112  	t.Parallel()
  1113  	abi, err := JSON(strings.NewReader(`[
  1114  		{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"MyError1","type":"error"},
  1115  		{"inputs":[{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"x","type":"tuple"},{"internalType":"address","name":"y","type":"address"},{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"z","type":"tuple"}],"name":"MyError2","type":"error"},
  1116  		{"inputs":[{"internalType":"uint256[]","name":"x","type":"uint256[]"}],"name":"MyError3","type":"error"}
  1117  	]`))
  1118  	if err != nil {
  1119  		t.Fatal(err)
  1120  	}
  1121  	for name, m := range abi.Errors {
  1122  		a := fmt.Sprintf("%v", &m)
  1123  		var id [4]byte
  1124  		copy(id[:], m.ID[:4])
  1125  		m2, err := abi.ErrorByID(id)
  1126  		if err != nil {
  1127  			t.Fatalf("Failed to look up ABI error: %v", err)
  1128  		}
  1129  		b := fmt.Sprintf("%v", m2)
  1130  		if a != b {
  1131  			t.Errorf("Error %v (id %x) not 'findable' by id in ABI", name, id)
  1132  		}
  1133  	}
  1134  	// test unsuccessful lookups
  1135  	if _, err = abi.ErrorByID([4]byte{}); err == nil {
  1136  		t.Error("Expected error: no error with this id")
  1137  	}
  1138  }
  1139  
  1140  // TestDoubleDuplicateMethodNames checks that if transfer0 already exists, there won't be a name
  1141  // conflict and that the second transfer method will be renamed transfer1.
  1142  func TestDoubleDuplicateMethodNames(t *testing.T) {
  1143  	t.Parallel()
  1144  	abiJSON := `[{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"transfer0","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"},{"name":"customFallback","type":"string"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]`
  1145  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1146  	if err != nil {
  1147  		t.Fatal(err)
  1148  	}
  1149  	if _, ok := contractAbi.Methods["transfer"]; !ok {
  1150  		t.Fatalf("Could not find original method")
  1151  	}
  1152  	if _, ok := contractAbi.Methods["transfer0"]; !ok {
  1153  		t.Fatalf("Could not find duplicate method")
  1154  	}
  1155  	if _, ok := contractAbi.Methods["transfer1"]; !ok {
  1156  		t.Fatalf("Could not find duplicate method")
  1157  	}
  1158  	if _, ok := contractAbi.Methods["transfer2"]; ok {
  1159  		t.Fatalf("Should not have found extra method")
  1160  	}
  1161  }
  1162  
  1163  // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name
  1164  // conflict and that the second send event will be renamed send1.
  1165  // The test runs the abi of the following contract.
  1166  //
  1167  //	contract DuplicateEvent {
  1168  //		event send(uint256 a);
  1169  //		event send0();
  1170  //		event send();
  1171  //	}
  1172  func TestDoubleDuplicateEventNames(t *testing.T) {
  1173  	t.Parallel()
  1174  	abiJSON := `[{"anonymous": false,"inputs": [{"indexed": false,"internalType": "uint256","name": "a","type": "uint256"}],"name": "send","type": "event"},{"anonymous": false,"inputs": [],"name": "send0","type": "event"},{	"anonymous": false,	"inputs": [],"name": "send","type": "event"}]`
  1175  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1176  	if err != nil {
  1177  		t.Fatal(err)
  1178  	}
  1179  	if _, ok := contractAbi.Events["send"]; !ok {
  1180  		t.Fatalf("Could not find original event")
  1181  	}
  1182  	if _, ok := contractAbi.Events["send0"]; !ok {
  1183  		t.Fatalf("Could not find duplicate event")
  1184  	}
  1185  	if _, ok := contractAbi.Events["send1"]; !ok {
  1186  		t.Fatalf("Could not find duplicate event")
  1187  	}
  1188  	if _, ok := contractAbi.Events["send2"]; ok {
  1189  		t.Fatalf("Should not have found extra event")
  1190  	}
  1191  }
  1192  
  1193  // TestUnnamedEventParam checks that an event with unnamed parameters is
  1194  // correctly handled.
  1195  // The test runs the abi of the following contract.
  1196  //
  1197  //	contract TestEvent {
  1198  //		event send(uint256, uint256);
  1199  //	}
  1200  func TestUnnamedEventParam(t *testing.T) {
  1201  	t.Parallel()
  1202  	abiJSON := `[{ "anonymous": false, "inputs": [{	"indexed": false,"internalType": "uint256",	"name": "","type": "uint256"},{"indexed": false,"internalType": "uint256","name": "","type": "uint256"}],"name": "send","type": "event"}]`
  1203  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1204  	if err != nil {
  1205  		t.Fatal(err)
  1206  	}
  1207  
  1208  	event, ok := contractAbi.Events["send"]
  1209  	if !ok {
  1210  		t.Fatalf("Could not find event")
  1211  	}
  1212  	if event.Inputs[0].Name != "arg0" {
  1213  		t.Fatalf("Could not find input")
  1214  	}
  1215  	if event.Inputs[1].Name != "arg1" {
  1216  		t.Fatalf("Could not find input")
  1217  	}
  1218  }
  1219  
  1220  func TestUnpackRevert(t *testing.T) {
  1221  	t.Parallel()
  1222  
  1223  	var cases = []struct {
  1224  		input     string
  1225  		expect    string
  1226  		expectErr error
  1227  	}{
  1228  		{"", "", errors.New("invalid data for unpacking")},
  1229  		{"08c379a1", "", errors.New("invalid data for unpacking")},
  1230  		{"08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000", "revert reason", nil},
  1231  		{"4e487b710000000000000000000000000000000000000000000000000000000000000000", "generic panic", nil},
  1232  		{"4e487b7100000000000000000000000000000000000000000000000000000000000000ff", "unknown panic code: 0xff", nil},
  1233  	}
  1234  	for index, c := range cases {
  1235  		t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) {
  1236  			t.Parallel()
  1237  			got, err := UnpackRevert(common.Hex2Bytes(c.input))
  1238  			if c.expectErr != nil {
  1239  				if err == nil {
  1240  					t.Fatalf("Expected non-nil error")
  1241  				}
  1242  				if err.Error() != c.expectErr.Error() {
  1243  					t.Fatalf("Expected error mismatch, want %v, got %v", c.expectErr, err)
  1244  				}
  1245  				return
  1246  			}
  1247  			if c.expect != got {
  1248  				t.Fatalf("Output mismatch, want %v, got %v", c.expect, got)
  1249  			}
  1250  		})
  1251  	}
  1252  }
  1253  
  1254  func TestInternalContractType(t *testing.T) {
  1255  	jsonData := `[{"inputs":[{"components":[{"internalType":"uint256","name":"dailyLimit","type":"uint256"},{"internalType":"uint256","name":"txLimit","type":"uint256"},{"internalType":"uint256","name":"accountDailyLimit","type":"uint256"},{"internalType":"uint256","name":"minAmount","type":"uint256"},{"internalType":"bool","name":"onlyWhitelisted","type":"bool"}],"internalType":"struct IMessagePassingBridge.BridgeLimits","name":"bridgeLimits","type":"tuple"},{"components":[{"internalType":"uint256","name":"lastTransferReset","type":"uint256"},{"internalType":"uint256","name":"bridged24Hours","type":"uint256"}],"internalType":"struct IMessagePassingBridge.AccountLimit","name":"accountDailyLimit","type":"tuple"},{"components":[{"internalType":"uint256","name":"lastTransferReset","type":"uint256"},{"internalType":"uint256","name":"bridged24Hours","type":"uint256"}],"internalType":"struct IMessagePassingBridge.BridgeDailyLimit","name":"bridgeDailyLimit","type":"tuple"},{"internalType":"contract INameService","name":"nameService","type":"INameService"},{"internalType":"bool","name":"isClosed","type":"bool"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"canBridge","outputs":[{"internalType":"bool","name":"isWithinLimit","type":"bool"},{"internalType":"string","name":"error","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint8","name":"decimals","type":"uint8"}],"name":"normalizeFrom18ToTokenDecimals","outputs":[{"internalType":"uint256","name":"normalized","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint8","name":"decimals","type":"uint8"}],"name":"normalizeFromTokenTo18Decimals","outputs":[{"internalType":"uint256","name":"normalized","type":"uint256"}],"stateMutability":"pure","type":"function"}]`
  1256  	if _, err := JSON(strings.NewReader(jsonData)); err != nil {
  1257  		t.Fatal(err)
  1258  	}
  1259  }