在 Solidity 中部署智能合约后调用智能合约的功能

问题描述

我在 solidity 中有简单的智能合约。我想在部署智能合约后调用函数 getHello()(查看已部署合约中的变量,而无需自己调用它)。我可以这样做吗?

    pragma solidity 0.5.12;

    contract Hello {
    
    string public helloStr = "Hello,world 2!";
    
    uint[] public nums = [10,20,30];
    
    function getHello() public view returns (string memory) {
        
        
        return helloStr;
        
    }
    
    function pushNewElement(uint newElement) public returns (uint) {
        
        nums.push(newElement);
        
    }
    
    function popLastElement () public returns (uint) {
        
        nums.pop();
        
    }
    
   
    function setHello(string memory newHello) public {
        
        
        helloStr = newHello;
        
    }
    
    
}

解决方法

为了获取公共变量,编译器自动形成函数。 在你的情况下,你可以得到带有哈希函数的 hello 字符串 c660ab0e

enter image description here

或者使用你的函数 getHello()。

对于调用函数(例如,helloStr()),您应该使用:

{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"解决你的智能合约","data":"0xc660ab0e"},"latest"],"id":1}

或者使用 web3 调用:

https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html#call

,

是的,部署合约后您将看到“hello world 2”,但您将永远无法看到“newHello”输出。因为每当您使用 setHello() 函数时,它都会设置空字符串。