BlockChain
tx.wait()으로 트랜젝션 마이닝 기다려주기
pangyoelon
2023. 8. 22. 15:27
예를들어 아래와 같이 토큰을 스왑하는 상황을 가정해보자
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 결과: 실패");
}
굳