【区块链】以太坊Solidity编写一个简单的Hello World合约

【区块链】以太坊Solidity编写一个简单的Hello World合约,第1张

熟悉一门语言得从Hello World! 开始,因为这是最简单的一个输出形式。
我们先在contracts目录下建立一个helloworld.sol文件
进入编辑

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract helloworld {
  uint public balance;

/********** Begin **********/
// 函数名:sayHelloWorld
  function sayHelloWorld() public pure returns (string memory){
      return ("Hello World!");
    }
/********** End **********/
}


保存退出
在migrations下新建一个部署合约的js文件:3_initial_migration.js
名字可以变动

                        
//const Migrations = artifacts.require("Migrations");

var helloworld = artifacts.require("helloworld");	//这里是你要部署的合约

module.exports = function (deployer) {
  deployer.deploy(helloworld);
};

接下来在test中使用js调用智能合约

var helloworld=artifacts.require("helloworld")
contract('helloworld',function(accounts){
        it("first",function(){
                return helloworld.deployed().then(function(instance){
                        console.log(instance.address)	//输出合约地址
                        instance.sayHelloWorld().then(function(result) {
                                console.log(result);		//输出hello world
                        })
                })
        })
        /*这里理论上不需要,但是我这不再输出一行无法显示前一行,有解决方案可以评论区留言*/
        it("sencode",function(){
                return helloworld.deployed().then(function(instance){
                        console.log(instance.address)
                })
        })
})

在另一个窗口打开ganache

ganache-cli

运行智能合约并调用

truffle compile
truffle migrate
truffle test ./test/helloworld.js

就可以在控制台看到运行结果了

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/925043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存