Solidity开发框架搭建与HelloWorld合约部署调用
本篇主要介绍使用truffle框架来开发以太坊solidity智能合约。机器环境为ubuntu 16.04,默认已经安装好node和npm等工具命令。
开发框架搭建
Truffle安装
$ npm install -g truffle
以太坊仿真节点安装
$ npm install -g ganache-cli
HelloWorld合约编写与部署调用
新建helloworld项目
$ truffle init helloworld
项目目录如下:
在contracts目录下新建HelloWorld.sol文件,并编写合约:
pragma solidity >=0.4.22 <0.9.0;
contract HelloWorld {
function print() pure public returns (string memory) {
return 'HelloWorld';
}
}
修改migrations/1_inital_migration.js文件:
const hello = artifacts.require("HelloWorld");
module.exports = function (deployer) {
deployer.deploy(hello);
};
把truffle-config.js的网络注释去掉:
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
编译合约
$ truffle compile
启动轻节点
$ ganache-cli
部署合约
$ truffle migrate
调用合约
进入控制台
truffle console
获取合约实例
$ HelloWorld.deployed().then(instance => contract = instance)
$ contract.print.call()