1
摘要
开发实战|3步教你在以太坊上开一家宠物店(附流程+代码)介绍了如何获取宠物商店的TRUFLLE框架代码,并完成部署的过程。
但是这个是已经成熟的代码框架,一般用户要开发自己的项目。那如何借用宠物商店成熟框架完成自有DAPP的搭建呢?我们以tiny熊老师的一个姓名/年龄智能合约用例来呈现方法。
2
需求描述
我们要实现一个用户姓名和年纪的输入和呈现页面,能更新智能合约上的用户名和年龄。重新输入用户名和年纪,点击按钮可更新智能合约的这2个变量信息。
3
操作步骤
3.1 创建目录,下载框架
首先创建好目录,下载宠物商店的代码框架。
duncanwang@ubuntu:~/work$ mkdir name-age
duncanwang@ubuntu:~/work$ cd name-age
duncanwang@ubuntu:~/work/name-age$ truffle unbox pet-shop
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!
Commands:
Compile: truffle compile
Migrate: truffle migrate
Test contracts: truffle test
Run dev server: npm run
devduncanwang@ubuntu:~/work/name-age$
3.2 创建智能合约代码
新建一个InfoContract.sol智能合约文件,并把它更新到./contracts目录下。
pragma solidity ^0.4.24;
contract InfoContract {
string name;
uint age;
event Instructor(string name, uint age);
function setInfo(string _name, uint _age) public {
name = _name;
age = _age;
emit Instructor(name, age);
}
function getInfo() public view returns(string, uint) {
return (name, age);
}
}
3.3 增加合约相关的部署和测试代码
1) 增加合约部署测试
文件2_info_contract.js到./migrations目录,代码如下,表示contract InfoContract合约部署。
var MyContract = artifacts.require("./InfoContract.sol");
module.exports = function(deployer) {
// deployment steps
deployer.deploy(MyContract);
};
2) 增加测试文件
pragma solidity ^0.4.24;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/InfoContract.sol";
contract TestInfoContract {
InfoContract info = InfoContract(DeployedAddresses.InfoContract());
string name;
uint age;
function testInfo() {
info.setInfo("ABC", 10);