Typescript에서 hardhat 사용하기 - task 사용하는법, config파일 밖으로 꺼내서 코드 가독성 높이는 법
하드햇에서 실행 스크립트를 만들때 변수화 시켜서 깔끔하게 만들려면 task를 사용해서 만드는 방법이 있다고 한다.
그러나 온라인상에서 예시 코드가 없어서 여기에 기록해두고자 한다.
https://hardhat.org/hardhat-runner/docs/advanced/create-task#creating-a-task
Hardhat | Ethereum development environment for professionals by Nomic Foundation
Hardhat is an Ethereum development environment. Compile your contracts and run them on a development network. Get Solidity stack traces, console.log and more.
hardhat.org
타입스크립트 기반으로 이를 만들어주는 코드가 잘 보이지 않아서 구글링 한 결과 다른 소스코드에서 가져온 부분을 발견할 수 있었다.
typescript source code of hardhat.config
www.programcreek.com
import { task } from 'hardhat/config';
// This is a sample Buidler task. To learn how to create your own go to
// https://buidler.dev/guides/create-task.html
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.getAddress());
}
});
이런식으로 task를 config에서 정의해주면 된다.
문제는 config안에서 모든것을 다 해주어야 된다는 것이긴 한데
공식 문서를 보니
1. config안에서 변수를 받아서 함수로 만들어 주거나
2. 스크립트 파일을 만들어서 해당 경로에서 실행해 주거나 2가지중 택 1을 하라고 한다.
근데 이걸 config에 모두 넣으면 정말 말도 안되게 지저분해진다.
그래서 이걸 모듈로 한번 분리시켜봤다.
디버깅 과정을 거쳐 아래처럼 하니 결국 모듈로 분리하고 가독성을 높이는데 성공할 수 있었다.
1. 먼저 scripts 문서 하위에 task를 정의 한 후 export 해버린다.
import { task } from 'hardhat/config';
export const getTotalSupply = task('getTotalSupply', 'getTotalSupplyOftheToken')
.addParam("address", "address of the token")
.setAction(async (taskArgs, hre) => {
console.log("taskArgs.address >>", taskArgs.address)
const TestCoin = await hre.ethers.getContractAt("TestCoin", taskArgs.address);
const totalSupply = await TestCoin.totalSupply()
console.log(totalSupply)
})
이렇게 하고 나서
hardhat.config.ts 안에서
import { getTotalSupply } from './scripts/taskScripts'
getTotalSupply
요것만 넣어주면?
npx hardhat --network matic getTotalSupply --address 컨트렉트주소
이렇게 실행시켜주게 되면 config 안에서 실행되는것과 똑같이 실행이 되게 된다.
이러면 각 task 별로 파일을 분리해서 스크립트를 실행시켜버릴 수가 있다!
근데 이걸 또 scripts 밑에 넣으니 안이쁘다
그래서 따로 task 폴더를 만들어 줬다.
이제 하드햇에서 말하는 2가지 케이스 모두 경로를 나누어서
변수가 있는 경우에는 task를 쓰고 없는 경우에는 scripts를 써서 더 이쁘게 사용할 수 있다