solidity - 在我修改它后,solidity 语言合同中的数组保持为空
问题描述
我已经用solidity 语言编写了一份合约,并在remix.ethereum.org 中对其进行了测试,并且所有功能都可以正常工作,但是当我尝试使用ganache 使用nodejs 和web3 库对其进行测试时,出现了一个无法正常工作的场景。我在合同中修改了一个数组,然后调用了一个函数来返回该数组,但我得到的是一个空数组,我不知道为什么并试图搜索类似的问题,但没有找到。
合约代码
pragma solidity ^0.4.17;
contract web2decentorage {
address public decentorage;
address public webUser;
address[] public storageNodes;
uint userValue; //this value in wei
uint storageNodeValue;
function web2decentorage(uint UV, uint SNV) public {
userValue = UV;
storageNodeValue = SNV;
decentorage = msg.sender; //decentorage ID that will manage this contract
}
function getPaidByUser() public payable {
require(msg.value > userValue); //here we should put the amount of money the user shoudl pay
webUser = msg.sender; //save the user ID
}
function addStorageNode(address A) public restricted {
storageNodes.push(A);
}
function payStorageNode(address A) public restricted {
for(uint i=0; i<storageNodes.length; i++){
if(storageNodes[i] == A){
storageNodes[i].transfer(storageNodeValue); //amount of money should be sent to a storage node
}
}
}
function getStorageNodes() public restricted returns(address[]) {
return storageNodes;
}
function getDecentorage() public restricted view returns(address) {
return decentorage;
}
function getwebUser() public restricted view returns(address) {
return webUser;
}
modifier restricted() {
require(msg.sender == decentorage);
_;
}
}
测试代码
beforeEach(async () => {
accounts = await web3.eth.getAccounts();
console.log(accounts);
//deploy to ganache network the contract
web2decentorage = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data:bytecode , arguments: [499,100]})
.send({from: accounts[0], gas: '1000000'});
});
describe('web2decentorage', ()=>{
it('a storage node will be part of this contract and be added as one of the storage nodes that stores the data', async() => {
await web2decentorage.methods.addStorageNode(accounts[1]).call({
from: accounts[0]
});
const returnVal = await web2decentorage.methods.getStorageNodes().call({
from: accounts[0]
});
console.log(returnVal);
//assert.equal(accounts[2],storageNodes[0]);
});
});
我添加了一个节点,然后检查数组是否有添加的节点,我发现它是空的。
解决方案
await web2decentorage.methods.addStorageNode(accounts[1]).call({
from: accounts[0]
});
您需要使用.send()
函数 (not .call()
) 来进行会产生状态更改的交易(在您的情况下,将新项目推storageNodes
送到合同存储)。
Call 用于只读操作,因此您可以安全地用于与之交互getStorageNodes()
。
推荐阅读
- ravendb - Ravendb 尝试查询子对象导致“无法索引未索引字段”
- angular - Primeng 组件不使用 ngx-translate 更新翻译
- javascript - 使用 0.01 - 0.05 之间的不同随机数自动重复增加值
- mysql - Case 语句变量声明和在 MS SQL SERVER 中的使用
- php - 拉拉维尔 5.6。将状态附加到队列工作者
- tabs - PhpStorm - 关闭调试时打开的选项卡
- can-bus - candump如何显示发送、接收和时间戳
- c++ - 将已经存在的 cudaTextureObject 绑定到 OpenSceneGraph(OpenGL) 中的纹理以进行渲染
- java - 如何在 Java 中使用搜索和替换自定义 HTML 标签?
- sql-server - SQL Server,在单个查询中显示来自多个表的总量