github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/evm/types/abi.go (about)

     1  package types
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/ethereum/go-ethereum/accounts/abi"
     9  )
    10  
    11  type ABI struct {
    12  	*abi.ABI
    13  }
    14  
    15  func NewABI(data string) (*ABI, error) {
    16  	parsed, err := abi.JSON(strings.NewReader(data))
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	return &ABI{ABI: &parsed}, nil
    21  }
    22  
    23  func (a *ABI) DecodeInputParam(methodName string, data []byte) ([]interface{}, error) {
    24  	if len(data) <= 4 {
    25  		return nil, fmt.Errorf("method %s data is nil", methodName)
    26  	}
    27  	method, ok := a.Methods[methodName]
    28  	if !ok {
    29  		return nil, fmt.Errorf("method %s is not exist in abi", methodName)
    30  	}
    31  	return method.Inputs.Unpack(data[4:])
    32  }
    33  
    34  func (a *ABI) IsMatchFunction(methodName string, data []byte) bool {
    35  	if len(data) < 4 {
    36  		return false
    37  	}
    38  	method, ok := a.Methods[methodName]
    39  	if !ok {
    40  		return false
    41  	}
    42  	if bytes.Equal(method.ID, data[:4]) {
    43  		return true
    44  	}
    45  	return false
    46  }
    47  
    48  func (a *ABI) EncodeOutput(methodName string, data []byte) ([]byte, error) {
    49  	method, ok := a.Methods[methodName]
    50  	if !ok {
    51  		return nil, fmt.Errorf("method %s is not exist in abi", methodName)
    52  	}
    53  	return method.Outputs.PackValues([]interface{}{string(data)})
    54  }