【问题标题】:Solidity - return struct array vs uint arraySolidity - 返回结构数组与 uint 数组
【发布时间】:2022-01-11 08:49:02
【问题描述】:

我只是在学习稳固性。以前,solidity 不允许我们返回结构数组。但是我们可以在较新的版本中做到这一点。您更喜欢以下哪种架构来获取用户发布的帖子列表? (我想在客户端显示列表)

合同样本:

contract Post {
  // State variables
  uint256 private currentIndex = 0;

  /// ... another variables

  struct PostStruct {
    uint256 id;
    address user;
    string title;
    string body;
    string thumbnail;
    PostStatusEnum status;
    bool deleted;
  }

  PostStruct[] private posts;
  mapping(address => uint256[]) postIndexesByUser; // example: 0x01234 => [3, 5, 24, 112, 448]

  /// METHOD 1 OR METHOD 2 ?

}

方法一:

  /// @notice This function returns post by user address.
  /// @dev We will get _page and _perPage for pagination
  function getPostsByUser(
    address _user,
    uint256 _page,
    uint256 _perPage
  )
    external
    view
    onlyValidPostPage(_page)
    onlyValidPostPerPage(_perPage)
    returns (PostStruct[] memory)
  {
    uint256[] memory allPostIds = postIndexesByUser[_user];
    PostStruct[] memory result = new PostStruct[](_perPage);
    uint256 index = 0;

    require(
      _page * _perPage - _perPage < allPostIds.length,
      "There is no data to display."
    );

    for (uint256 i = _perPage * _page - _perPage; i < _perPage * _page; i++) {
      if (i < allPostIds.length) {
        result[index] = posts[allPostIds[i]];
        index++;
      }
    }
    return result;
  }

方法二: Just return the post IDs and then call the posts on the client side.

【问题讨论】:

    标签: blockchain ethereum solidity smartcontracts truffle


    【解决方案1】:

    使用方法2。尽量不要对合约代码进行大量计算,因为这会花费你大量的 gas 费用。假设您有 1000 个帖子,并且您必须为每次计算付费。

    【讨论】:

    • 谢谢@Yilmaz,即使有分页,第一种方法还是不行?
    • @MiladJafari 你说的分页是什么意思?
    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2013-08-02
    • 2014-06-02
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多