testnet
GitHub

ParseStructFromAbi

func ParseStructFromAbi[T any](in *T, args any) error

Parses generic input arguments (typically from ABI unpacking) into a specific Go struct using JSON as an intermediate format. This function simplifies input validation and type conversion for precompile methods.

Parameters

Name Type Required Description
in *T Pointer to the target Go struct where data will be unmarshaled. The struct should have json tags matching the input data keys.
args any The input data to parse, typically a map[string]interface{} or a struct resulting from ABI unpacking.

Returns

Type: error

Returns nil on success, or a JSON marshaling/unmarshaling error if the data types are incompatible.

Errors

Code Name Description
json.MarshalError Marshal Error Occurs if `args` contains types that cannot be marshaled to JSON (e.g., channels, functions).
json.UnmarshalError Unmarshal Error Occurs if the JSON structure of `args` does not match the definition of struct `T`.

Examples

Basic Struct Parsing

Demonstrates converting unpacked ABI arguments into a `CreatePolicyArgs` struct.

type CreatePolicyArgs struct {
    Name        string `json:"name"`
    Description string `json:"description"`
}

func (p *Precompile) Run(evm *vm.EVM, contract *vm.Contract, readonly bool) ([]byte, error) {
    // Assume 'args' comes from method.Inputs.Unpack(input)
    var inputArgs CreatePolicyArgs
    
    // Parse generic args into typed struct
    if err := utils.ParseStructFromAbi(&inputArgs, args); err != nil {
        return nil, err
    }
    
    fmt.Printf("Policy Name: %s", inputArgs.Name)
    return nil, nil
}
ESC
Type to search