You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在调用Hedera智能合约时传递结构体等复杂类型?

使用Hedera SDK调用带结构体参数的Solidity合约

问题描述

用户编写了如下Solidity合约:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8;
pragma abicoder v2;

contract testStruct {

    struct Example {
        uint256 number;
        address user;
    }

    Example public example;

    function set_struct(Example memory _example) public {
        example = _example;
    }
}

尝试用Hedera SDK调用时,错误地尝试手动传递字节数组:

//Create the transaction
const transaction = new ContractExecuteTransaction()
     .setContractId(newContractId)
     .setGas(100_000_000)
     .setFunction("set_struct", new ContractFunctionParameters()
           .addBytesArray(byte[][] structInBytes)

遇到SDK类型匹配问题,不清楚如何正确传递结构体这类复杂参数。

解决方案

Hedera SDK已经封装了Solidity ABI的编码逻辑,不需要手动将结构体转换为字节数组,直接按照结构体的字段顺序,使用ContractFunctionParameters的对应类型方法逐个添加字段值即可:

  1. 明确结构体字段类型:Example结构体包含uint256类型的number和address类型的user两个字段。
  2. 按字段顺序添加参数:调用set_struct时,依次添加对应类型的参数,SDK会自动将其编码为结构体格式。

正确的调用代码示例:

// 创建交易
const transaction = new ContractExecuteTransaction()
    .setContractId(newContractId)
    .setGas(100_000_000)
    .setFunction("set_struct", new ContractFunctionParameters()
        .addUint256(123) // 对应结构体的number字段
        .addAddress("0x1234567890abcdef1234567890abcdef12345678") // 对应结构体的user字段
    );

补充说明

如果需要传递结构体数组(比如Example[]),可以使用addArray方法结合对应类型的包装器,示例如下:

// 假设要传递两个Example结构体组成的数组
const structArray = [
    { number: 123, user: "0x123..." },
    { number: 456, user: "0x456..." }
];

const params = new ContractFunctionParameters();
params.addArray(structArray.map(item => 
    new ContractFunctionParameters()
        .addUint256(item.number)
        .addAddress(item.user)
));

const transaction = new ContractExecuteTransaction()
    .setContractId(newContractId)
    .setGas(100_000_000)
    .setFunction("set_struct_array", params);

内容的提问来源于stack exchange,提问作者Raphaël Messian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:20:41