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



在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);
}
}

并运行如下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")); 
});
});
});

但我得到了以下错误:

Error: Please pass numbers as string or BN objects to avoid precision errors.

这似乎与web3.utils.toWei调用的返回类型有关,所以我尝试将其强制转换为字符串:web3.utils.coWei(stuffPrice.toString((,"醚"(;但这给出了错误:数字只能安全地存储多达53位。

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

错误在这里:

web3.utils.toWei(stuffPrice,'ether')

stuffPrice应为字符串。

web3.utils.toWei(String(stuffPrice),'ether')
toWei((方法接受String|BN作为第一个参数。您将其作为Number传递给stuffPrice

快速解决方案是将stuffPrice定义为String:

var stuffPrice = '10'; // corrected code, String

而不是

var stuffPrice = 10; // original code, Number

另一种方法是将BN对象传递给它。

var stuffPrice = 10; // original code, Number
web3.utils.toWei(
web3.utils.toBN(stuffPrice), // converts Number to BN, which is accepted by `toWei()`
'ether'
);

您需要将状态变量声明为字符串,在这种情况下可以使用。

反应中:

state = { playerEthervalue: ''};
const accounts = await web3.eth.getAccounts();
// Send the ethers to transaction, initiate the transaction
await lottery.methods.getPlayersAddress().send({ from: accounts[0], 
value: web3.utils.toWei(this.state.playerEthervalue, 'ether') });

固体(.sol(:

function getPlayersAddress() public payable {    
require(msg.value >= 0.00000001 ether);
players.push(msg.sender); 
}

最新更新