|
| 1 | +import "dotenv/config"; |
| 2 | +import { ethers } from "ethers"; |
| 3 | +import UniswapV3SwapRouterArtifact from "@uniswap/v3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json"; |
| 4 | +import ERC20ABI from "../abis/ERC20.json"; |
| 5 | +import { address } from "./address"; |
| 6 | +// 유니스왑 V3 Router 주소 (Arbitrum) |
| 7 | +const swapRouterAddress = address.swapRouterAddress; |
| 8 | + |
| 9 | +// Uniswap V3 Router의 ABI (swapExactInputSingle 함수) |
| 10 | +const { abi: uniswapV3SwapRouterABI } = UniswapV3SwapRouterArtifact; |
| 11 | + |
| 12 | +async function swapTokens() { |
| 13 | + // RPC 노드 연결 |
| 14 | + const provider = new ethers.JsonRpcProvider("https://arb1.arbitrum.io/rpc"); |
| 15 | + |
| 16 | + // 사용자의 지갑 |
| 17 | + const privateKey = "YOUR_PRIVATE_KEY"; // 사용자 개인키 |
| 18 | + const wallet = new ethers.Wallet(privateKey, provider); |
| 19 | + |
| 20 | + // 유니스왑 V3 Router 컨트랙트 객체 생성 |
| 21 | + const routerContract = new ethers.Contract(swapRouterAddress, uniswapV3SwapRouterABI, wallet); |
| 22 | + |
| 23 | + // 스왑할 토큰 정보 (예: WETH -> USDC) |
| 24 | + const tokenIn = ""; // WETH 주소 |
| 25 | + const tokenOut = ""; // USDC 주소 |
| 26 | + const fee = 3000; // 0.3% 풀 사용 |
| 27 | + const recipient = wallet.address; // 스왑 결과를 받을 주소 (보통 사용자 본인의 주소) |
| 28 | + const deadline = Math.floor(Date.now() / 1000) + 60 * 10; // 10분 후 트랜잭션 마감 |
| 29 | + const amountIn = ethers.parseUnits("0.1", 18); // 스왑할 0.1 WETH (단위: 18 decimals) |
| 30 | + const amountOutMinimum = ethers.parseUnits("1", 6); // 최소 1 USDC 수령 (단위: 6 decimals) |
| 31 | + |
| 32 | + try { |
| 33 | + // 토큰 승인: 먼저 WETH를 유니스왑 V3 Router에 사용하도록 승인 |
| 34 | + const tokenInContract = new ethers.Contract(tokenIn, ERC20ABI, wallet); |
| 35 | + |
| 36 | + const approvalTx = await tokenInContract.approve(swapRouterAddress, amountIn); |
| 37 | + await approvalTx.wait(); |
| 38 | + console.log("Token approved"); |
| 39 | + |
| 40 | + // 스왑 트랜잭션 생성 |
| 41 | + const swapTx = await routerContract.exactInputSingle({ |
| 42 | + tokenIn, |
| 43 | + tokenOut, |
| 44 | + fee, |
| 45 | + recipient, |
| 46 | + deadline, |
| 47 | + amountIn, |
| 48 | + amountOutMinimum, |
| 49 | + sqrtPriceLimitX96: 0, // 가격 제한 없음 |
| 50 | + }); |
| 51 | + |
| 52 | + // 트랜잭션 대기 |
| 53 | + const receipt = await swapTx.wait(); |
| 54 | + console.log("Swap completed: ", receipt); |
| 55 | + } catch (error) { |
| 56 | + console.error("An error occured during swap:", error); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +swapTokens(); |
0 commit comments