상세 컨텐츠

본문 제목

KlaySwap V3 풀에서 토큰 스왑하기

백도 황도지사

by 아서킴 2024. 4. 8. 10:40

본문

728x90

 

- Hardhat, Typescript 환경

- IKlayswapV3SwapRouter ABI(출처 KlayswapDocs )

pragma solidity ^0.8.0;

interface IKlayswapV3SwapRouter {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external returns (uint256 amountOut);
}

 

교환하기

const klayswapV3SwapRouterAddress = "0x6c14e2e4bae412137437a8ec9e57263212d141a0"

async function swapInKlayswapV3(fromToken: string, 
				toToken: string, 
                                fee: string, 
                                amount: BigNumber, 
                                minAmountOut: BigNumber, 
                                signer: SignerWithAddress) {
    
    const klayswapV3swapRouter = await ethers.getContractAt('IKlayswapV3SwapRouter', klayswapV3SwapRouterAddress)
    const blocktimestamp = await utils.currentTime()

    const params: ExactInputSingleParams = {
        tokenIn: fromToken,
        tokenOut: toToken,
        fee: fee, //수수료 0.2% 풀이면 "2000"
        recipient: signer.address,
        deadline: blocktimestamp + 100,
        amountIn: amount,
        amountOutMinimum: minAmountOut,
        sqrtPriceLimitX96: BigNumber.from(0) // 잘 몰라서 0
    }
    const result = await klayswapV3swapRouter.exactInputSingle(
        params,
        { gasLimit: 3000000 })
}

 

 

wKlay를 Klay 로 전환하기

const tokenABI = [
    {
        "inputs": [
            {
                "internalType": "address",
                "name": "account",
                "type": "address"
            }
        ],
        "name": "balanceOf",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
]
    
interface IWKLAY {
    function deposit ( ) external payable;
    function decimals (  ) external view returns ( uint8 );
    function transfer ( address to, uint value ) external returns ( bool );
    function withdraw ( uint ) external;
    function balanceOf ( address ) external view returns ( uint );
    function approve ( address spender, uint256 amount ) external returns ( bool );
}

const wklayAddress = "0x19Aac5f612f524B754CA7e7c41cbFa2E981A4432"

async function wklayToKlay(signer: SignerWithAddress) {
    const wklayToken = await ethers.getContractAt(tokenABI, wklayAddress)
    const balance = await wklayToken.balanceOf(signer.address)

    const wklay = await ethers.getContractAt('IWKLAY', wklayAddress)
    await wklay.withdraw(balance, { gasLimit: 3000000 })

}

관련글 더보기