github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/accounts/abi/abi.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package abi 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "errors" 23 "fmt" 24 "io" 25 26 "github.com/ethereum-optimism/optimism/l2geth/common" 27 "github.com/ethereum-optimism/optimism/l2geth/crypto" 28 ) 29 30 // The ABI holds information about a contract's context and available 31 // invokable methods. It will allow you to type check function calls and 32 // packs data accordingly. 33 type ABI struct { 34 Constructor Method 35 Methods map[string]Method 36 Events map[string]Event 37 } 38 39 // JSON returns a parsed ABI interface and error if it failed. 40 func JSON(reader io.Reader) (ABI, error) { 41 dec := json.NewDecoder(reader) 42 43 var abi ABI 44 if err := dec.Decode(&abi); err != nil { 45 return ABI{}, err 46 } 47 48 return abi, nil 49 } 50 51 // Pack the given method name to conform the ABI. Method call's data 52 // will consist of method_id, args0, arg1, ... argN. Method id consists 53 // of 4 bytes and arguments are all 32 bytes. 54 // Method ids are created from the first 4 bytes of the hash of the 55 // methods string signature. (signature = baz(uint32,string32)) 56 func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { 57 // Fetch the ABI of the requested method 58 if name == "" { 59 // constructor 60 arguments, err := abi.Constructor.Inputs.Pack(args...) 61 if err != nil { 62 return nil, err 63 } 64 return arguments, nil 65 } 66 method, exist := abi.Methods[name] 67 if !exist { 68 return nil, fmt.Errorf("method '%s' not found", name) 69 } 70 arguments, err := method.Inputs.Pack(args...) 71 if err != nil { 72 return nil, err 73 } 74 // Pack up the method ID too if not a constructor and return 75 return append(method.ID(), arguments...), nil 76 } 77 78 // Unpack output in v according to the abi specification 79 func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) { 80 // since there can't be naming collisions with contracts and events, 81 // we need to decide whether we're calling a method or an event 82 if method, ok := abi.Methods[name]; ok { 83 if len(data)%32 != 0 { 84 return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data) 85 } 86 return method.Outputs.Unpack(v, data) 87 } 88 if event, ok := abi.Events[name]; ok { 89 return event.Inputs.Unpack(v, data) 90 } 91 return fmt.Errorf("abi: could not locate named method or event") 92 } 93 94 // UnpackIntoMap unpacks a log into the provided map[string]interface{} 95 func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) { 96 // since there can't be naming collisions with contracts and events, 97 // we need to decide whether we're calling a method or an event 98 if method, ok := abi.Methods[name]; ok { 99 if len(data)%32 != 0 { 100 return fmt.Errorf("abi: improperly formatted output") 101 } 102 return method.Outputs.UnpackIntoMap(v, data) 103 } 104 if event, ok := abi.Events[name]; ok { 105 return event.Inputs.UnpackIntoMap(v, data) 106 } 107 return fmt.Errorf("abi: could not locate named method or event") 108 } 109 110 // UnmarshalJSON implements json.Unmarshaler interface 111 func (abi *ABI) UnmarshalJSON(data []byte) error { 112 var fields []struct { 113 Type string 114 Name string 115 Constant bool 116 StateMutability string 117 Anonymous bool 118 Inputs []Argument 119 Outputs []Argument 120 } 121 if err := json.Unmarshal(data, &fields); err != nil { 122 return err 123 } 124 abi.Methods = make(map[string]Method) 125 abi.Events = make(map[string]Event) 126 for _, field := range fields { 127 switch field.Type { 128 case "constructor": 129 abi.Constructor = Method{ 130 Inputs: field.Inputs, 131 } 132 // empty defaults to function according to the abi spec 133 case "function", "": 134 name := field.Name 135 _, ok := abi.Methods[name] 136 for idx := 0; ok; idx++ { 137 name = fmt.Sprintf("%s%d", field.Name, idx) 138 _, ok = abi.Methods[name] 139 } 140 isConst := field.Constant || field.StateMutability == "pure" || field.StateMutability == "view" 141 abi.Methods[name] = Method{ 142 Name: name, 143 RawName: field.Name, 144 Const: isConst, 145 Inputs: field.Inputs, 146 Outputs: field.Outputs, 147 } 148 case "event": 149 name := field.Name 150 _, ok := abi.Events[name] 151 for idx := 0; ok; idx++ { 152 name = fmt.Sprintf("%s%d", field.Name, idx) 153 _, ok = abi.Events[name] 154 } 155 abi.Events[name] = Event{ 156 Name: name, 157 RawName: field.Name, 158 Anonymous: field.Anonymous, 159 Inputs: field.Inputs, 160 } 161 } 162 } 163 164 return nil 165 } 166 167 // MethodById looks up a method by the 4-byte id 168 // returns nil if none found 169 func (abi *ABI) MethodById(sigdata []byte) (*Method, error) { 170 if len(sigdata) < 4 { 171 return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata)) 172 } 173 for _, method := range abi.Methods { 174 if bytes.Equal(method.ID(), sigdata[:4]) { 175 return &method, nil 176 } 177 } 178 return nil, fmt.Errorf("no method with id: %#x", sigdata[:4]) 179 } 180 181 // EventByID looks an event up by its topic hash in the 182 // ABI and returns nil if none found. 183 func (abi *ABI) EventByID(topic common.Hash) (*Event, error) { 184 for _, event := range abi.Events { 185 if bytes.Equal(event.ID().Bytes(), topic.Bytes()) { 186 return &event, nil 187 } 188 } 189 return nil, fmt.Errorf("no event with id: %#x", topic.Hex()) 190 } 191 192 // UsingOVM 193 // Both RevertSelector and UnpackRevert were pulled from upstream 194 // geth as they were not present in the version of geth that this 195 // codebase was forked from. These are useful for displaying revert 196 // messages to users when they use `eth_call` 197 // RevertSelector is a special function selector for revert reason unpacking. 198 var RevertSelector = crypto.Keccak256([]byte("Error(string)"))[:4] 199 200 // UnpackRevert resolves the abi-encoded revert reason. According to the solidity 201 // docs https://docs.soliditylang.org/en/v0.8.4/control-structures.html#revert, 202 // the provided revert reason is abi-encoded as if it were a call to a function 203 // `Error(string)`. So it's a special tool for it. 204 func UnpackRevert(data []byte) (string, error) { 205 if len(data) < 4 { 206 return "", errors.New("invalid data for unpacking") 207 } 208 if !bytes.Equal(data[:4], RevertSelector) { 209 return "", errors.New("invalid data for unpacking") 210 } 211 typ, _ := NewType("string", "", nil) 212 unpacked, err := (Arguments{{Type: typ}}).UnpackValues(data[4:]) 213 if err != nil { 214 return "", err 215 } 216 return unpacked[0].(string), nil 217 }