首页 > 解决方案 > 在我修改它后,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]);
    });

    
});

我添加了一个节点,然后检查数组是否有添加的节点,我发现它是空的。

标签: solidityweb3

解决方案


await web2decentorage.methods.addStorageNode(accounts[1]).call({
    from: accounts[0]
});

您需要使用.send()函数 (not .call()) 来进行会产生状态更改的交易(在您的情况下,将新项目推storageNodes送到合同存储)。

Call 用于只读操作,因此您可以安全地用于与之交互getStorageNodes()


推荐阅读