drizzle 和 react 学习( 二 )


保持终端窗口打开,您可以观察稍后与之交互时发生的情况
3.2 指定网络
我们需要让我们的项目知道如何连接到这个区块链 。要做到这一点,我们需要将以下内容放在 -.js中 :
module.exports = {networks: {development: {host: "localhost",port: 8545,network_id: "*" // Match any network id}}};
4. 编译和移植智能合约
现在我们准备编译和移植合约
4.1 编译
在终端中,确保您位于项目目录的根目录中并输入:
truffle compile
如果您使用的是并且在运行此命令时遇到问题,请参阅文档on
您应该看到类似于以下输出内容:
Compiling ./contracts/Migrations.sol...Compiling ./contracts/MyStringStore.sol...Writing artifacts to ./build/contracts
4.2 移植
现在我们已经成功编译了合约,是时候将它们移植到区块链了!
注意:关于移植
创建移植脚本
在 / 目录中创建名为 .js 的新文件
文件中添加如下内容:
const MyStringStore = artifacts.require("MyStringStore");module.exports = function(deployer) {deployer.deploy(MyStringStore);};
返回终端,移植合约到区块链
truffle migrate
你可以看到如下类似输出:
Using network 'development'.Running migration: 1_initial_migration.jsDeploying Migrations...... 0xcc1a5aea7c0a8257ba3ae366b83af2d257d73a5772e84393b0576065bf24aedfMigrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0Saving successful migration to network...... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956Saving artifacts...Running migration: 2_deploy_contracts.jsDeploying MyStringStore...... 0x43b6a6888c90c38568d4f9ea494b9e2a22f55e506a8197938fb1bb6e5eaa5d34MyStringStore: 0x345ca3e014aaf5dca488057592ee47305d9b3e10Saving successful migration to network...... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0Saving artifacts...
您可以按顺序查看正在执行的移植,然后是每个已部署合同的区块链地址(您的地址将有所不同) 。
5. 测试智能合约
在我们继续之前,我们应该编写几个测试来确保合约按预期工作 。
在 test/ 目录中创建一个名为 .js 的新文件 。
将以下内容添加到 .js 文件:
const MyStringStore = artifacts.require("./MyStringStore.sol");contract("MyStringStore", accounts => {it("should store the string 'Hey there!'", async () => {const myStringStore = await MyStringStore.deployed();// Set myString to "Hey there!"await myStringStore.set("Hey there!", { from: accounts[0] });// Get myString from public variable getterconst storedString = await myStringStore.myString.call();assert.equal(storedString, "Hey there!", "The string was not stored");});});
5.1 运行测试
返回终端,运行测试:
truffle test
如果所有测试都通过,您将在控制台看到与此类似的输出:
Using network 'development'.Contract: MyStringStore? should store the value 'Hey there!' (3085ms)1 passing (3s)
真棒! 现在我们知道合同确实有效 。
6. 创建 React.js 项目
现在我们完成了智能合约,我们可以用 React.js 编写我们的前端客户端! 为此,只需运行此命令(如果您有NPM 5.2或更高版本):