2022/05/11 Solidity_Hardhat_Day2

# 2022/05/11 Hardhat之TypeScript支持

### 配置`Hardhat`的`TypeScript`设置

- 使用`yarn test`安装依赖项
- 修改配置文件,将`hardhat.config.js` -> `hardhat.config.ts`

**需要修改的三个地方:**

1. 加载插件使用`import`不是`require`
2. 需要显示导入`Hardhat`配置函数
3. 自定义任务需要明确地访问`Hardhat`运行时环境,作为一个参数

**示例修改配置项:**

1. `javascript`

`
require("@nomiclabs/hardhat-waffle");

task("accounts", "Prints the list of accounts", async () => {
const accounts = await ethers.getSigners();

for (const account of accounts) {
console.log(await account.address);
}
});

module.exports = {
solidity: "0.7.3",
};
`

2. `typescript`

`
import { task } from "hardhat/config";
import "@nomiclabs/hardhat-waffle";

task("accounts", "Prints the list of accounts", async (args, hre) => {
const accounts = await hre.ethers.getSigners();

for (const account of accounts) {
console.log(await account.address);
}
});

export default {
solidity: "0.7.3",
};
`

**区别点:**

1. task显示导入
2. `module.exports` -> `export default`
3. `task`声明`hre`参数等

### 使用`TypeScript`编写测试和脚本

**注意:**

`js`的`hre`中的所有属性都会被注入到全局作用域当中,可以通过显式获取`hre`

`ts`需要显示地导入所有变量

**测试示例:**

`
import { ethers } from "hardhat";
import { Signer } from "ethers";

describe("Token", function () {
let accounts: Signer[];

beforeEach(async function () {
accounts = await ethers.getSigners();
});

it("should do something right", async function () {

});
});
`

**脚本示例:**

`
import { run, ethers } from "hardhat";

async function main() {
await run("compile");

const accounts = await ethers.getSigners();

console.log("Accounts:", accounts.map(a => a.address));
}

main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
`

### 类型安全配置

`ts`当中会将合约编译成一个类:

`
import { HardhatUserConfig } from "hardhat/config";

const config: HardhatUserConfig = {
// Your type-safe config goes here
};

export default config;
`

posted @ 2022-08-10 18:51  俊king  阅读(57)  评论(0)    收藏  举报