Golang实现solidity的abi.encodePack方法

1、int类型、address、string进行打包:

import (
	"encoding/hex"
	"github.com/ethereum/go-ethereum/accounts/abi"
)
...
addressTy, _ := abi.NewType("address", "string", []abi.ArgumentMarshaling{})
bytesTy, _ := abi.NewType("bytes", "string", nil)
uint256Ty, _ := abi.NewType("uint256", "uint64", []abi.ArgumentMarshaling{})

	args := abi.Arguments{
		{Type: addressTy},
		{Type: bytesTy},
		{Type: uint256Ty}
	}
//尤其注意这里,当string转bytes的时候一定要用hex.DecodeString进行16进制转bytes
	_params2, _ := hex.DecodeString(params2)
	packed, err := args.Pack(
		common.HexToAddress(params1),
		_params2,
		big.NewInt(_params3)
	)
...
argPacked := hexutil.Encode(packed)

2、结构体数组的打包;

import (
	"encoding/hex"
	"github.com/ethereum/go-ethereum/accounts/abi"
)
...

type Transaction struct {
	To    common.Address `json:"to"`
	Value *big.Int       `json:"value"`
	Data  []byte         `json:"data"`
}
...

//golang数组的打包,在生成新类型的时候,中括号"[]"应该在类型名的后边
	structTy, _ := abi.NewType("tuple[]", "struct ty", []abi.ArgumentMarshaling{
		{Name: "params1", Type: "address"},
		{Name: "params2", Type: "uint256"},
		{Name: "params3", Type: "bytes"},
	})

	args := abi.Arguments{
		{Type: structTy},
	}

        _params3, _ := hex.DecodeString(params3)
        transactions := []Transaction{
          {
            common.HexToAddress(params1), 
            big.NewInt(params2), 
            params3
          }
        }

	packed, err := args.Pack(
		transactions,
	)

	argPacked := hexutil.Encode(packed)
Subscribe to daxiong
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.