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

熟悉一门语言得从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

就可以在控制台看到运行结果了
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值