1
// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// @return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
    uint [] results;
    for(uint i = 0 ; i<homes.length; i++) {
        if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
            results.push(homes[i].id);
        }
    }
    return results;    
}

结果应该是与输入的物理地址匹配的 id 列表,但它不会过滤,而是返回所有可用的房屋。当我更改为使用 String utils 时,没有任何变化。

这是整个代码:

pragma solidity ^0.4.0;

import "browser/StringUtils.sol";

// @title HomeListing

contract HomeListing {

    struct Home {
        uint id;
        string physicalAddress;
        bool available;
    }

    Home[] public homes;
    mapping (address => Home) hostToHome;
    event HomeEvent(uint _id);
    event Test(uint length);

    constructor() {

    }

    // @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
    function addHome(string _physicalAddress) public {
        uint _id = uint(keccak256(_physicalAddress, msg.sender));
        homes.push(Home(_id, _physicalAddress, true));
    }

    // @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
    // @return _id - list of ids for homes
    function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
        uint [] results;
        for(uint i = 0 ; i<homes.length; i++) {
            string location = homes[i].physicalAddress;
            if(StringUtils.equal(location,_physicalAddress )) {
                results.push(homes[i].id);
            }
        }
        return results;
    }
}
4

1 回答 1

2

给你带来麻烦的部分是线路uint[] results;。默认情况下,声明为局部变量storage的数组引用内存。来自Solidity 文档的“内存关键字是什么”部分:

存储位置有默认值,具体取决于它涉及的变量类型:

  • 状态变量总是在存储中
  • 函数参数默认在内存中
  • 结构、数组或映射类型的局部变量默认引用存储
  • 值类型的局部变量(即既不是数组,也不是结构,也不是映射)存储在堆栈中

结果是您引用了合约的第一个存储槽,恰好是Home[] public homes. 这就是为什么您要恢复整个阵列的原因。

要解决此问题,您需要使用memory数组。但是,您还有一个额外的问题,即您不能在 Solidity 中使用动态内存数组。一种解决方法是确定结果大小限制并静态声明您的数组。

示例(限于 10 个结果):

function listHomesByAddress(string _physicalAddress) public view returns(uint[10]) {
    uint [10] memory results;
    uint j = 0;
    for(uint i = 0 ; i<homes.length && j < 10; i++) {
        if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
            results[j++] = homes[i].id;
        }
    }
    return results;

} 
于 2018-07-04T19:44:36.120 回答