github.com/ava-labs/subnet-evm@v0.6.4/accounts/abi/abi_test.go (about)

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