github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/accounts/abi/method.go (about) 1 // Copyright 2015 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package abi 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/SmartMeshFoundation/Spectrum/crypto" 24 ) 25 26 // Method represents a callable given a `Name` and whether the method is a constant. 27 // If the method is `Const` no transaction needs to be created for this 28 // particular Method call. It can easily be simulated using a local VM. 29 // For example a `Balance()` method only needs to retrieve something 30 // from the storage and therefor requires no Tx to be send to the 31 // network. A method such as `Transact` does require a Tx and thus will 32 // be flagged `true`. 33 // Input specifies the required input parameters for this gives method. 34 type Method struct { 35 Name string 36 Const bool 37 Inputs Arguments 38 Outputs Arguments 39 } 40 41 // Sig returns the methods string signature according to the ABI spec. 42 // 43 // Example 44 // 45 // function foo(uint32 a, int b) = "foo(uint32,int256)" 46 // 47 // Please note that "int" is substitute for its canonical representation "int256" 48 func (method Method) Sig() string { 49 types := make([]string, len(method.Inputs)) 50 i := 0 51 for _, input := range method.Inputs { 52 types[i] = input.Type.String() 53 i++ 54 } 55 return fmt.Sprintf("%v(%v)", method.Name, strings.Join(types, ",")) 56 } 57 58 func (method Method) String() string { 59 inputs := make([]string, len(method.Inputs)) 60 for i, input := range method.Inputs { 61 inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type) 62 } 63 outputs := make([]string, len(method.Outputs)) 64 for i, output := range method.Outputs { 65 if len(output.Name) > 0 { 66 outputs[i] = fmt.Sprintf("%v ", output.Name) 67 } 68 outputs[i] += output.Type.String() 69 } 70 constant := "" 71 if method.Const { 72 constant = "constant " 73 } 74 return fmt.Sprintf("function %v(%v) %sreturns(%v)", method.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", ")) 75 } 76 77 func (method Method) Id() []byte { 78 return crypto.Keccak256([]byte(method.Sig()))[:4] 79 }