Forsage魔豹联盟DAPP系统开发方案

2022-10-27 14:07:54 浏览数 (1)

编写合约代码

现在我们来开始编写第一个智能合约代码,solidity代码如下:

代码语言:javascript复制
pragma solidity ^0.4.2;
contract hello {
    string greeting;
    
    function hello(string _greeting) public {
        greeting = _greeting;
    }

    function say() constant public returns (string) {
        return greeting;
    }
}
123456789101112

在编写完成代码,IDE进行编译时会出现错误,注意要选择正确的编译器版本,如图:

简单解释下,我们定义了一个名为hello的合约,在合约初始化时保存了一个字符串(我们会传入hello world),每次调用say返回字符串。 把这段代码写(拷贝)到Browser-Solidity,如果没有错误,点击Details获取部署代码,如:

部署合约

Browser-Solidity生成的代码,拷贝到编辑器里修改后的代码如下:

代码语言:javascript复制
var _greeting = "Hello World";
var helloContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function","stateMutability":"view"},{"inputs":[{"name":"_greeting","type":"string"}],"type":"constructor","payable":true,"stateMutability":"payable"}]);
var hello = helloContract.new(
   _greeting,
   {
     from: web3.eth.accounts[2], 
     data: '0x6060604052604051610250380380610250833981016040528080518201919060200150505b8060006000509080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10607157805160ff1916838001178555609f565b82800160010185558215609f579182015b82811115609e5782518260005055916020019190600101906082565b5b50905060c6919060aa565b8082111560c2576000818150600090555060010160aa565b5090565b50505b50610178806100d86000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063954ab4b21461003c57610037565b610002565b346100025761004e60048050506100bc565b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600302600f01f150905090810190601f1680156100ae5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b602060405190810160405280600081526020015060006000508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101695780601f1061013e57610100808354040283529160200191610169565b820191906000526020600020905b81548152906001019060200180831161014c57829003601f168201915b50505050509050610175565b9056', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: '   contract.address   ' transactionHash: '   contract.transactionHash);
    }
 })

0 人点赞