熟悉一門語(yǔ)言得從Hello World! 開(kāi)始,因?yàn)檫@是最簡(jiǎn)單的一個(gè)輸出形式。
我們先在contracts目錄下建立一個(gè)helloworld.sol文件
進(jìn)入編輯
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
contract helloworld {
uint public balance;
/********** Begin **********/
// 函數(shù)名:sayHelloWorld
function sayHelloWorld() public pure returns (string memory){
return ("Hello World!");
}
/********** End **********/
}
保存退出
在migrations下新建一個(gè)部署合約的js文件:3_initial_migration.js
名字可以變動(dòng)
//const Migrations = artifacts.require("Migrations");
var helloworld = artifacts.require("helloworld"); //這里是你要部署的合約
module.exports = function (deployer) {
deployer.deploy(helloworld);
};
接下來(lái)在test中使用js調(diào)用智能合約
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
})
})
})
/*這里理論上不需要,但是我這不再輸出一行無(wú)法顯示前一行,有解決方案可以評(píng)論區(qū)留言*/
it("sencode",function(){
return helloworld.deployed().then(function(instance){
console.log(instance.address)
})
})
})
在另一個(gè)窗口打開(kāi)ganache
ganache-cli
運(yùn)行智能合約并調(diào)用文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-608798.html
truffle compile
truffle migrate
truffle test ./test/helloworld.js
就可以在控制臺(tái)看到運(yùn)行結(jié)果了文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-608798.html
到了這里,關(guān)于【區(qū)塊鏈】以太坊Solidity編寫一個(gè)簡(jiǎn)單的Hello World合約的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!