예를들어 아래와 같이 토큰을 스왑하는 상황을 가정해보자
const result = await tokenContract.approve(
routerAddress,
utils.parseEther("100"),
{
maxPriorityFeePerGas: gasPrice,
maxFeePerGas: gasPrice,
}
);
// 스왑
const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
const swapValue = await routerContract.swapExactTokensForETH(
utils.parseEther("1"),
0,
["0x123...","0x123...","0x123..."],
to,
deadline,
{
maxPriorityFeePerGas: gasPrice,
maxFeePerGas: gasPrice,
}
);
console.log("스왑 결과 :", swapValue);
token을 스왑하기 위해 approve를 먼저 해주고 있는 모습이다
하지만 이렇게 하면 오류가 발생할 수 있다
왜냐하면 먼저 rpc 요청을 보냈다고 먼저 보낸 요청이 뒤에 보낸 요청보다 먼저 마이닝 될 거라는 보장을 할 수 없기 때문이다
트렌젝션의 순서는 채굴자가 정한다. 즉, 채굴자에 따라서 블럭 안의 트랜젝션의 순서가 정해진다는 것이다 (이로인해 MEV라는 것도 있음)
그럼 비동기와 같이 특정 rpc요청이 마이닝 될 때까지 await해주려면 무엇을 사용해야 할까?
이미지의 트랜젝션 객체 맨 아래를 보면 wait이라는 function을 볼 수 있다
이것을 쓰면 된다
const result = await tokenContract.approve(
routerAddress,
utils.parseEther("100"),
{
maxPriorityFeePerGas: gasPrice,
maxFeePerGas: gasPrice,
}
);
// 트랜잭션이 성공적으로 처리되었는지 확인
const receipt = await result.wait();
if (receipt.status === 1) { // status가 1인 경우 트랜잭션 성공
console.log("approve 결과: 성공");
// 스왑
const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
const swapValue = await routerContract.swapExactTokensForETH(
utils.parseEther("1"),
0,
["0x123...","0x123...","0x123..."],
to,
deadline,
{
maxPriorityFeePerGas: gasPrice,
maxFeePerGas: gasPrice,
}
);
console.log("스왑 결과 :", swapValue);
} else {
console.log("approve 결과: 실패");
}
굳
'BlockChain' 카테고리의 다른 글
Byzantine Failure란? ( 비잔틴 장군 문제 ) (0) | 2022.11.13 |
---|---|
비트코인 채굴, POW는 낭비인가 (0) | 2022.09.17 |
비트코인의 채굴 난이도 조절 방식 (POW) +실습 (1) | 2022.09.17 |