Solidity:错误:请将数字作为字符串或 BN 对象传递,以避免精度错误

Jee*_*ves 3 javascript blockchain ethereum solidity smartcontracts

有一个简单的 Solidity 合约:

contract SellStuff{

    address seller;
    string name;
    string description;
    uint256 price;

    function sellStuff(string memory _name, string memory _description, uint256 _price) public{
        seller = msg.sender;
        name = _name;
        description = _description;
        price = _price;
    }
    function getStuff() public view returns (
        address _seller, 
        string memory _name, 
        string memory _description, 
        uint256 _price){
            return(seller, name, description, price);
    }
}
Run Code Online (Sandbox Code Playgroud)

并运行 javascript 测试,如下所示:

var SellStuff= artifacts.require("./SellStuff.sol");

// Testing
contract('SellStuff', function(accounts){

    var sellStuffInstance;
    var seller = accounts[1];
    var stuffName = "stuff 1";
    var stuffDescription = "Description for stuff 1";
    var stuffPrice = 10;

    it("should sell stuff", function(){
        return SellStuff.deployed().then(function(instance){
            sellStuffInstance= instance;
            return sellStuffInstance.sellStuff(stuffName, stuffDescription, web3.utils.toWei(stuffPrice,'ether'), {from: seller});
        }).then(function(){
            //the state of the block should be updated from the last promise
            return sellStuffInstance.getStuff();
        }).then(function(data){
                assert.equal(data[0], seller, "seller must be " + seller);
                assert.equal(data[1], stuffName, "stuff name must be " +  stuffName);
                assert.equal(data[2], stuffDescription, "stuff description must be " + stuffDescription);
                assert.equal(data[3].toNumber(), web3.utils.toWei(stuffPrice,"ether"), "stuff price must be " + web3.utils.toWei(stuffPrice,"ether")); 
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Error: Please pass numbers as string or BN objects to avoid precision errors.
Run Code Online (Sandbox Code Playgroud)

这看起来像是与 web3.utils.toWei 调用的返回类型有关,所以我尝试将其转换为字符串:web3.utils.toWei(stuffPrice.toString(),"ether"); 但这给出了错误:数字只能安全地存储最多 53 位。

不确定我是否需要简单地从 uint256 更改类中的 var,或者是否有更好的方法来转换 toWei 返回变量?

Yil*_*maz 9

错误在这里:

web3.utils.toWei(stuffPrice,'ether')
Run Code Online (Sandbox Code Playgroud)

stuffPrice应该是字符串。

 web3.utils.toWei(String(stuffPrice),'ether')
Run Code Online (Sandbox Code Playgroud)


Pet*_*jda 5

toWei ()方法接受String|BN第一个参数。您将其stuffPrice作为Number.


一个快速解决方法是将其定义stuffPriceString

var stuffPrice = '10'; // corrected code, String
Run Code Online (Sandbox Code Playgroud)

代替

var stuffPrice = 10; // original code, Number
Run Code Online (Sandbox Code Playgroud)

另一种方法是向其传递一个BN对象。

var stuffPrice = 10; // original code, Number

web3.utils.toWei(
    web3.utils.toBN(stuffPrice), // converts Number to BN, which is accepted by `toWei()`
    'ether'
);
Run Code Online (Sandbox Code Playgroud)