truffle开发配置

Posted by 姚飞亮 on 2020-11-01

truffle开发配置

1.安装

sudo npm install -g truffle --unsafe-perm=true --allow-root

2.初始化

truffle init

配置部署账号

1
2
3
4
5
6
> //secrets.json 助记词
> {
> "mnemonic": "window habit dragon snake *** *** *** clock hold bar public dust",
> "projectId": "272c7dbe1460492b804fdbeffb36cab4"
> }
>

3.修改 truffle-config.js 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const path = require("path");
const { projectId, mnemonic } = require('./secrets.json');
const HDWalletProvider = require('@truffle/hdwallet-provider');
module.exports = {
contracts_build_directory: path.join(__dirname, "client/src/contracts"),
networks: {
rinkeby: {
provider: () => new HDWalletProvider(
mnemonic, `https://rinkeby.infura.io/v3/0c23855fdde64855986fd08b858f1906`
),
network_id:4,
gas: 8500000, // Gas sent with each transaction (default: ~6700000)
gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
production: true // Treats this network as if it was a public net. (default: false)
},
},
compilers: {
solc: {
version: "0.6.2", // A version or constraint - Ex. "^0.5.0"

}
}
};

4.编译合约

truffle compile

5.部署合约

truffle migrate --network rinkeby //--reset

6.调用合约

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
truffle console --network rinkeby
Migrations.deployed().then((i) => { instance = i})
//let instance = await Migrations.deployed()
//let instance = await Migrations.new()
//let instance = await MetaCoin.at("0x1234...");//指定合约地址
//写入
instance.setCompleted(12)
//读取
instance.last_completed_migration()
//instance.sendTransaction({...}).then(function(result) {
//// 处理交易结果
//});
//instance.send(web3.utils.toWei(1, "ether")).then(function(result) {
//// 处理交易结果
//});

7.调试合约

1
2
3
4
5
6
7
8
9
10
//暂时没debug成功
truffle debug
truffle debug <transaction hash>
truffle debug 0xeff68eb3a569cd0e48d5c6a28c8d9eecc2035dea748c7e3d7cfa4789a6628adb
truffle debug <transaction hash> --network <network>
//test测试成功
//truffle test --debug
//truffle console --network rinkeby
//truffle test ./test/TestMigrations.js
truffle test ./test/TestMigrations.js --network rinkeby

8.外部脚本

1
2
3
truffle console --network rinkeby 
//truffle exec <path/to/file.js>
truffle exec ./test/ExecMigrations.js

9.MetaMask

1
2
3
4
5
6
7
8
9
// Is there is an injected web3 instance?
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// If no injected web3 instance is detected, fallback to Ganache.
App.web3Provider = new web3.providers.HttpProvider('http://127.0.0.1:7545');
web3 = new Web3(App.web3Provider);
}


Ω