github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/accounts/abi/error.go (about) 1 // Copyright 2016 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 "errors" 22 "fmt" 23 "strings" 24 25 "github.com/tirogen/go-ethereum/common" 26 "github.com/tirogen/go-ethereum/crypto" 27 ) 28 29 type Error struct { 30 Name string 31 Inputs Arguments 32 str string 33 34 // Sig contains the string signature according to the ABI spec. 35 // e.g. error foo(uint32 a, int b) = "foo(uint32,int256)" 36 // Please note that "int" is substitute for its canonical representation "int256" 37 Sig string 38 39 // ID returns the canonical representation of the error's signature used by the 40 // abi definition to identify event names and types. 41 ID common.Hash 42 } 43 44 func NewError(name string, inputs Arguments) Error { 45 // sanitize inputs to remove inputs without names 46 // and precompute string and sig representation. 47 names := make([]string, len(inputs)) 48 types := make([]string, len(inputs)) 49 for i, input := range inputs { 50 if input.Name == "" { 51 inputs[i] = Argument{ 52 Name: fmt.Sprintf("arg%d", i), 53 Indexed: input.Indexed, 54 Type: input.Type, 55 } 56 } else { 57 inputs[i] = input 58 } 59 // string representation 60 names[i] = fmt.Sprintf("%v %v", input.Type, inputs[i].Name) 61 if input.Indexed { 62 names[i] = fmt.Sprintf("%v indexed %v", input.Type, inputs[i].Name) 63 } 64 // sig representation 65 types[i] = input.Type.String() 66 } 67 68 str := fmt.Sprintf("error %v(%v)", name, strings.Join(names, ", ")) 69 sig := fmt.Sprintf("%v(%v)", name, strings.Join(types, ",")) 70 id := common.BytesToHash(crypto.Keccak256([]byte(sig))) 71 72 return Error{ 73 Name: name, 74 Inputs: inputs, 75 str: str, 76 Sig: sig, 77 ID: id, 78 } 79 } 80 81 func (e *Error) String() string { 82 return e.str 83 } 84 85 func (e *Error) Unpack(data []byte) (interface{}, error) { 86 if len(data) < 4 { 87 return "", errors.New("invalid data for unpacking") 88 } 89 if !bytes.Equal(data[:4], e.ID[:4]) { 90 return "", errors.New("invalid data for unpacking") 91 } 92 return e.Inputs.Unpack(data[4:]) 93 }