github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/chain/accounts/abi/pack.go (about)

     1  package abi
     2  
     3  import (
     4  	"math/big"
     5  	"reflect"
     6  
     7  	"github.com/neatio-net/neatio/utilities/common"
     8  	"github.com/neatio-net/neatio/utilities/common/math"
     9  )
    10  
    11  func packBytesSlice(bytes []byte, l int) []byte {
    12  	len := packNum(reflect.ValueOf(l))
    13  	return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...)
    14  }
    15  
    16  func packElement(t Type, reflectValue reflect.Value) []byte {
    17  	switch t.T {
    18  	case IntTy, UintTy:
    19  		return packNum(reflectValue)
    20  	case StringTy:
    21  		return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len())
    22  	case AddressTy:
    23  		if reflectValue.Kind() == reflect.Array {
    24  			reflectValue = mustArrayToByteSlice(reflectValue)
    25  		}
    26  
    27  		return common.LeftPadBytes(reflectValue.Bytes(), 32)
    28  	case BoolTy:
    29  		if reflectValue.Bool() {
    30  			return math.PaddedBigBytes(common.Big1, 32)
    31  		}
    32  		return math.PaddedBigBytes(common.Big0, 32)
    33  	case BytesTy:
    34  		if reflectValue.Kind() == reflect.Array {
    35  			reflectValue = mustArrayToByteSlice(reflectValue)
    36  		}
    37  		return packBytesSlice(reflectValue.Bytes(), reflectValue.Len())
    38  	case FixedBytesTy, FunctionTy:
    39  		if reflectValue.Kind() == reflect.Array {
    40  			reflectValue = mustArrayToByteSlice(reflectValue)
    41  		}
    42  		return common.RightPadBytes(reflectValue.Bytes(), 32)
    43  	default:
    44  		panic("abi: fatal error")
    45  	}
    46  }
    47  
    48  func packNum(value reflect.Value) []byte {
    49  	switch kind := value.Kind(); kind {
    50  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
    51  		return U256(new(big.Int).SetUint64(value.Uint()))
    52  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    53  		return U256(big.NewInt(value.Int()))
    54  	case reflect.Ptr:
    55  		return U256(new(big.Int).Set(value.Interface().(*big.Int)))
    56  	default:
    57  		panic("abi: fatal error")
    58  	}
    59  
    60  }