truffle unbox react 下載項目
打開Ganache啓動私有鏈,同時修改truffle-config.js中的端口號,使之與Ganache的端口號7545保持一致,或者改ganache的端口爲8545
const path = require("path");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
contracts_build_directory: path.join(__dirname, "client/src/contracts"),
networks: {
develop: {
host: 'localhost',
port: '7545',
network_id: '*' // Match any network id
}
}
};
進入控制檯
編譯智能合約
遷移到區塊鏈上
truffle(develop)> migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'develop'
> Network id: 5777
> Block gas limit: 0x6691b7
1_initial_migration.js
======================
Deploying 'Migrations'
----------------------
> transaction hash: 0xaa0788f7bd013dec3d999f543c20d6ac5c7d3cf6cf4756b6656f313fecf90034
> Blocks: 0 Seconds: 0
> contract address: 0x7bdD98D5f749941a4928af0f8c1A9cC184749A57
> block number: 1
> block timestamp: 1580287418
> account: 0x59e747a0c6315d4ac024FB2dD8a67d14907e19Bf
> balance: 99.99623034
> gas used: 188483
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.00376966 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.00376966 ETH
2_deploy_contracts.js
=====================
Deploying 'SimpleStorage'
-------------------------
> transaction hash: 0x78a01569782ccb26d8463c4431f791f93674c7ace8af55dcf667899b4427d547
> Blocks: 0 Seconds: 0
> contract address: 0x6c9F6cA9ed18D2A530bE3C3242d582a42ce3042B
> block number: 3
> block timestamp: 1580287419
> account: 0x59e747a0c6315d4ac024FB2dD8a67d14907e19Bf
> balance: 99.99324294
> gas used: 107369
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.00214738 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.00214738 ETH
Summary
=======
> Total deployments: 2
> Final cost: 0.00591704 ETH
ganache上第一個賬戶的以太幣確實發生了減少
control+ - +d退出控制檯
cd client,然後執行npm run start啓動項目,發現加載失敗
項目默認監聽的端口爲8545,實際上Ganache的端口爲7545,需要在getWeb3.js中修改端口號(或者修改Ganache的端口爲8545,那麼這裏就不用修改了)
示例合約
pragma solidity >=0.4.21 <0.7.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
示例App.js,實現載入頁面時,向區塊鏈中寫入一個數字5,並回顯的功能
最後成功部署示例項目
下面修改App.js,實現輸入數字、提交儲存並回顯展示的功能
import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";
import "./App.css";
class App extends Component {
state = { storageValue: 0, web3: null, accounts: null, contract: null,inputValue:0};
componentDidMount = async () => {
try {
// Get network provider and web3 instance.
const web3 = await getWeb3();
// Use web3 to get the user's accounts.
const accounts = await web3.eth.getAccounts();
// Get the contract instance.
const networkId = await web3.eth.net.getId();
const deployedNetwork = SimpleStorageContract.networks[networkId];
const instance = new web3.eth.Contract(
SimpleStorageContract.abi,
deployedNetwork && deployedNetwork.address,
);
const response = await instance.methods.get().call();
this.setState({ web3, accounts, storageValue: response,contract: instance });
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
};
run = async (i) => {
const { accounts, contract } = this.state;
// Stores a given value, 5 by default.
await contract.methods.set(i).send({ from: accounts[0] });
// Get the value from the contract to prove it worked.
const response = await contract.methods.get().call();
// Update state with the result.
this.setState({ storageValue: response });
};
handleInputChange=(e)=>{
this.setState({
inputValue:parseInt(e.currentTarget.value)
})
}
render() {
if (!this.state.web3) {
return <div>Loading Web3, accounts, and contract...</div>;
}
return (
<div className="App">
<h1>Good to Go!</h1>
<p>Your Truffle Box is installed and ready.</p>
<h2>Smart Contract Example</h2>
<p>
If your contracts compiled and migrated successfully, below will show
a stored value of 5 (by default).
</p>
<p>
Try changing the value stored on <strong>line 40</strong> of App.js.
</p>
<div>The stored value is: {this.state.storageValue}</div>
<input type="text" value={this.state.inputValue} onChange={this.handleInputChange}></input>
<div> <button onClick={this.run.bind(this,this.state.inputValue)}>提交</button></div>
</div>
);
}
}
export default App;
安裝一個MetaMask的錢包插件,導入Ganache的賬號,此時向區塊鏈中儲存數據的時候,即執行set方法時需要產生交易費用,此時點擊確認即可調用智能合約中的set方法
例如需要存儲數字50:
點擊確認之後執行合約,而從區塊鏈中讀取數據並不需要費用,可以直接調用智能合約的get方法,此時可見儲存的值已被設置爲50