如何使用golang生成raw transaction的input data?

之前使用java代码调用合约时,通过一下方法来生成input data。

new Function(functionName, argumentList, Collections.<TypeReference<?>>emptyList());
FunctionEncoder.encode(functionCall);

这种方法之用输入合约名称和合约的参数,没有使用abi.json信息,我想知道如何使用golang来达到类似的效果。我只有合约地址,账户公私钥,合约代码信息。
研究过一段时间这个方法,但是他一致没有正常运行。

name := "add"
rawName := "add"
funType := 0
mutability := "view"
param1, err := abi.NewType("value", "int", nil)
inputs := abi.Arguments{
    abi.Argument{
        Name:    "value",
        Type:    param1,
        Indexed: false,
    },
}

method := abi.NewMethod(name, rawName, abi.FunctionType(funType), mutability, false, false, inputs, nil)

input, err := method.Inputs.Pack(1)
if err != nil {
    log.Fatal(err)
}

log.Println(common.Bytes2Hex(input))

在没有合约abi.json的情况下,如何生成input data信息呢?

请先 登录 后评论

3 个回答

YGCool

拿erc20转账构造data举例:

import (
    ethcommon "github.com/ethereum/go-ethereum/common"
)

const (
    TRANSFER_METHOD_ID  = "0xa9059cbb"
)

func MakeERC20TransferData(toAddress string, amount *big.Int) ([]byte, error) {
	var data []byte
	methodId, err := hexutil.Decode(TRANSFER_METHOD_ID)
	if err != nil {
		return methodId, err
	}
	data = append(data, methodId...)
	paddedAddress := ethcommon.LeftPadBytes(ethcommon.HexToAddress(toAddress).Bytes(), 32)
	data = append(data, paddedAddress...)
	paddedAmount := ethcommon.LeftPadBytes(amount.Bytes(), 32)
	data = append(data, paddedAmount...)
	return data, nil
}

// use:
data, err := MakeERC20TransferData(toAddress, big.NewInt(1000000000))
if err != nil {
    panic(err)
}
请先 登录 后评论
zen
// Pack the given method name to conform the ABI. Method call's data
// will consist of method_id, args0, arg1, ... argN. Method id consists
// of 4 bytes and arguments are all 32 bytes.
// Method ids are created from the first 4 bytes of the hash of the
// methods string signature. (signature = baz(uint32,string32))
func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
请先 登录 后评论
筷子

如果功能单一的话,通过历史数据分析,然后拼接参数即可。

请先 登录 后评论
  • 1 关注
  • 0 收藏,2516 浏览
  • zhyyao 提出于 2023-08-29 18:34