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

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

Logo

为所有Web3兴趣爱好者提供学习成长、分享交流、生态实践、资源工具等服务,作为Anome Land原住民可不断优先享受各种福利,共同打造全球最大的Web3 UGC游戏平台。

更多推荐