区块链开发:JS/TS本地|项目环境搭建
- 本地环境搭建
- VSCode Solidity扩展
- 全局安装Solc,corepack
- VSCode配置本地Solc
- 安装Ganache搭建JS虚拟环境
- 项目测试
- 安装依赖
- 编写代码
- 部署合约`test_blockchain.ts`
- 设置Script
- 部署查看
- 报错说明
- 1. Error:missing revert data
- 2.Error: could not coalesce error
本地环境搭建
VSCode Solidity扩展
添加如下两种扩展到VSCode中
全局安装Solc,corepack
Solc用于编译智能合约(.sol)
npm install -g solc
npm install -g corepack
solcjs --version
corepack --version
VSCode配置本地Solc
打开settings搜索Solidity,设置编译版本
C:\Users\用户目录\.vscode\extensions\juanblanco.solidity-0.0.165\node_modules\solc\soljson.js
修改默认编译为localFile
安装Ganache搭建JS虚拟环境
地址:https://trufflesuite.com/ganache/
官网下载速度很慢,推荐挂个vpn,或者去Github下
Github:https://github.com/trufflesuite/ganache-ui
启动
项目测试
安装依赖
安装solc,ethers
npm i solc -S
npm i ethers@5.7.2 -S
npm i --save-dev @types/fs-extra
npm i typescript -S
npm i ts-node -S
npm i fs-extra -S
编写代码
其中rpc地址是从Ganache中来的
部署合约test_blockchain.ts
import { ethers } from "ethers";
import { readFileSync } from "fs-extra";
// main fn
const main = async () => {
// http://127.0.0.1:7545
// init rpc provider
const provider = new ethers.providers.JsonRpcProvider(
"http://127.0.0.1:7545"
);
// your wallet
// Get from Ganache
// PrimaryKey : ...
// Address : ...
// Not recommended you use primary key here
// But this just a test
const primary_key: string =
"0x290042e98e1afdbe0f88d2e1146bf7116a1793aa9fa1f315264e5319247bc6ae";
const wallet = new ethers.Wallet(primary_key, provider);
const abi = readFileSync(
"src/binary/src_smart_contract_SimpleStorage_sol_SimpleStorage.abi",
"utf8"
);
const binary = readFileSync(
"src/binary/src_smart_contract_SimpleStorage_sol_SimpleStorage.bin",
"utf8"
);
const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
//deploy
const contract = await contractFactory.deploy({ gasLimit: 3000000 });
};
const methods = {
main,
};
const linearRunner = () => {
methods
.main()
.then(() => {
// exit program
process.exit(0);
})
.catch((e) => {
console.error(e);
process.exit(1);
});
};
linearRunner();
设置Script
这里的compile用来编译solidity写的智能合约,deploy则是进行合约部署
{
"dependencies": {
"ethers": "^5.7.2",
"fs-extra": "^11.1.1",
"solc": "^0.8.20",
"ts-node": "^10.9.1",
"typescript": "^5.1.6"
},
"scripts": {
"compile": "solcjs --bin --abi --include-path node_modules/ --base-path . -o ./src/binary src/smart_contract/SimpleStorage.sol",
"deploy": "ts-node src/test_blockchain.ts"
},
"devDependencies": {
"@types/fs-extra": "^11.0.1"
}
}
部署查看
报错说明
1. Error:missing revert data
这个错误起初我以为只出现6+的版本,去Github上查看无果,别人也遇到这个问题,解决的方法最后在我修改到5.7.2版本后解决,但是这不是正确的解决方法而是在deploy的时候添加Gas限制以保证Gas足够就解决了,无论6+版本还是5.7.2都OK
const contract = await contractFactory.deploy({ gasLimit: 3000000 });
2.Error: could not coalesce error
出现 “could not coalesce error” 错误通常表示在处理交易期间发生了无法合并的错误,但从结果看智能合约确实被部署了。