gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:18:17 26 4
gpt4 key购买 nike

有一个简单的可靠契约:

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 调用的返回类型有关,因此我尝试将其转换为 string:web3.utils.toWei(stuffPrice.toString(),"ether") ;但这给出了错误:数字最多只能安全存储 53 位。
不确定我是否需要简单地从 uint256 更改类中的 var 或者是否有更好的方法来转换 toWei 返回变量?

最佳答案

toWei()方法接受 String|BN作为第一个论点。你正在传递它 stuffPrice作为 Number .

快速修复是定义 stuffPriceString :

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'
);

关于casting - Solidity: 错误:请将数字作为字符串或 BN 对象传递以避免精度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67898627/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com