安装truffle
npm install -g truffle
创建一个文件夹,并初始化truffle生成基本文件
truffle init
生成的文件简介
1、contracts
用于存放合约文件
2、migrations
**migrations:**使用solidity编写智能合约的文件夹,编写文件解释truffle 如何部署智能合约,用的是node.js
3、test
编写测试文件
4、truffle-config.js
配置网络和rpc,以及部署时使用的密钥
编写合约
1、示例
新建合约文件 ERC721Token.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract ERC721Token is ERC721{
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
/**
* Mints Bored Apes
*/
function mintDomain(uint numberOfTokens) public payable {
uint256 newItemId = _tokenIds.current();
for(uint i = 0; i < numberOfTokens; i++) {
_safeMint(msg.sender, newItemId);
_tokenIds.increment();
}
}
}
2、编译
truffle compile
编译后生成build文件
部署合约
1、在migrations文件中创建migration文件
创建文件 1_initial_migration.js
const ERC721Token = artifacts.require('ERC721Token.sol');
module.exports = function (deployer) {
deployer.deploy(ERC721Token);
};
2、安装ganache-cli
npm i -g ganache-cli
3、新建一个终端
部署合约,此时还是部署在local chain上
truffle migrate
4、创建一个metamask钱包
5、注册INFURA: https://infura.io
6、创建.env文件
存放密钥地址
PRIVATE_KEY_0=xxx
PRIVATE_KEY_1=xxx
7、安装env
npm i dotenv
8、配置truffle-config.js
require('dotenv').config()
const HDWalletProvider = require('@truffle/hdwallet-provider')
//
const privateKey = process.env.PRIVATE_KEY_1
module.exports = {
networks: {
goerli: {
provider: function () {
return new HDWalletProvider(privateKey,
'https://goerli.infura.io/v3/*')
},
network_id: '5',
},
},
compilers: {
solc: {
version: "^0.8.0"
}
}
}
9、部署合约
truffle migrate --network goerli
报错提示:
如遇到@truffle/hdwallet-provider未安装,使用命令:
npm i @truffle/hdwallet-provider
如遇到@openzeppelin/contracts未安装,使用命令:
npm i @openzeppelin/contracts