Solidity

如何在 Solidity 合約中讀取 Struct 的值?

  • May 1, 2018

我開發了以下智能合約並嘗試通過 truffle js 控制台對其進行測試:

pragma solidity ^0.4.2;

contract AddressRatings {

struct Rating {
   mapping ( address => uint8 ) ratings;
   uint256 amtOfRatings;
   uint256 sumOfRatings;
   uint8 average;
}

mapping ( address => Rating ) public ratings;

function rateAddress (address _addr, uint8 _rating) external {
   require(_rating > 0 && _rating < 6); // only ratings from 1 to 5 are allowed
   require(ratings[_addr].ratings[msg.sender] == 0); // a sender can rate someone else only once
   ratings[_addr].ratings[msg.sender] = _rating;
   ratings[_addr].amtOfRatings++;
   ratings[_addr].sumOfRatings += _rating;
   ratings[_addr].average = uint8(ratings[_addr].sumOfRatings/ratings[_addr].amtOfRatings);
}

}

我能夠獲取契約的實例並呼叫方法 rateAddress。我也可以檢索評級映射的對象。但是,我不知道如何讀取返回的 Rating 結構的屬性。

無論我嘗試返回未定義,例如 ratingsObj 1 , ratingsObj

$$ ‘average’ $$, ratingObj.average 在此處輸入圖像描述

此外,結構內的映射似乎不起作用,儘管它可以編譯……

任何提示表示讚賞!

PS:非常歡迎提出如何使這個契約更有效率的建議。

使用 promise 來檢索 Rating 對象,允許我使用索引訪問屬性。toNumber 函式最終返回值:)

在此處輸入圖像描述

問題是您struct Rating包含一個mapping. Solidity 不能從函式返回映射,因為它不知道它有多大。但是,它可以返回提供密鑰的各個條目。您可能應該跟踪地址是否以另一種方式對地址進行了評級。這是我的做法:

pragma solidity ^0.4.23;

contract AddressRatings {

   struct Rating {
       uint256 amtOfRatings;
       uint256 sumOfRatings;
       uint8 average;
   }

   mapping(address => mapping(address => uint8)) public ratingsPerAddress;

   mapping (address => Rating ) public ratings;

   function rateAddress (address _addr, uint8 _rating) external {
       require(_rating > 0 && _rating < 6); // only ratings from 1 to 5 are allowed
       require(ratingsPerAddress[_addr][msg.sender] == 0); // a sender can rate someone else only once

       ratingsPerAddress[_addr][msg.sender] = _rating;

       ratings[_addr].amtOfRatings++;
       ratings[_addr].sumOfRatings += _rating;
       ratings[_addr].average = uint8(ratings[_addr].sumOfRatings/ratings[_addr].amtOfRatings);
   }

}

引用自:https://ethereum.stackexchange.com/questions/47192