Last active
July 14, 2022 09:37
-
-
Save x3r0s/1221e2d086cf2cd5679f11b1ff927100 to your computer and use it in GitHub Desktop.
TDI 프로젝트 Web3 1inch API 예제 코드에 설명 주석을 추가한 JS 문서입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 모듈 Import, 실제 사용에서는 fetch, yesno 모듈은 제거되며 Web3 Module은 etherjs 모듈로 Migration 됨 | |
// Migration 방법에 관련된 문서는 https://docs.ethers.io/v5/migration/web3/ 참고 | |
const Web3 = require('web3'); // Migration to etherjs | |
const fetch = require('node-fetch'); // Migration to Axios | |
// 네트워크 체인 ID 설정 | |
const chainId = 56; | |
// Web3 RPC URL 설정, 추후 web3 provider에 인자로 들어감 | |
const web3RpcUrl = 'https://bsc-dataseed.binance.org'; | |
// 유저 지갑 주소 | |
const walletAddress = '0x...xxx'; | |
// 유저 지갑 Private key | |
const privateKey = '0x...xxx'; | |
// Swap 트랜잭션을 발생시킬 기본 파라미터 | |
const swapParams = { | |
fromTokenAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1INCH // Swap할 원본 토큰 Contract Address | |
toTokenAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI // Swap될 토큰 Contract Address | |
amount: '100000000000000000', // Swap할 수량 | |
fromAddress: walletAddress, // 유저 지갑 주소 | |
slippage: 1, // Slippage 설정 (0.1, 0.5, 1) | |
disableEstimate: false, | |
allowPartialFill: false, | |
}; | |
// 트랜잭션을 전송할 API URL | |
const broadcastApiUrl = 'https://tx-gateway.1inch.io/v1.1/' + chainId + '/broadcast'; | |
// API Base URL 생성 | |
const apiBaseUrl = 'https://api.1inch.io/v4.0/' + chainId; | |
// Web3 Provider 생성 | |
const web3 = new Web3(web3RpcUrl); | |
// API 요청 URL을 생성하는 함수 | |
function apiRequestUrl(methodName, queryParams) { | |
return apiBaseUrl + methodName + '?' + (new URLSearchParams(queryParams)).toString(); | |
} | |
// 트랜잭션을 실행하는 함수 | |
async function broadCastRawTransaction(rawTransaction) { | |
return fetch(broadcastApiUrl, { | |
method: 'post', | |
body: JSON.stringify({rawTransaction}), | |
headers: {'Content-Type': 'application/json'} | |
}) | |
.then(res => res.json()) | |
.then(res => { | |
return res.transactionHash; | |
}); | |
} | |
// unsigned transaction을 Sign 하고 전송(발생)하는 함수 | |
async function signAndSendTransaction(transaction) { | |
// 트랜잭션 Sign 처리 진행 | |
const {rawTransaction} = await web3.eth.accounts.signTransaction(transaction, privateKey); | |
// Sign 처리된 트랜잭션을 broadCastRawTransaction 함수에 인자로 넣어 트랜잭션 실행 | |
return await broadCastRawTransaction(rawTransaction); | |
} | |
// 트랜잭션 파라미터를 인자로 받아 최종적으로 실행하기 직전의 트랜잭션(unsigned transaction)을 생성하는 함수 | |
async function buildTxForSwap(swapParams) { | |
const url = apiRequestUrl('/swap', swapParams); | |
return fetch(url).then(res => res.json()).then(res => res.tx); | |
} | |
// **********************************************// | |
// 위에 선언된 함수를 이용하여 실제 트랜젝션을 실행하는 파트 ↓ // | |
// **********************************************// | |
// 선언해두었던 swapParams를 인자값으로 buildTxForSwap() 함수에 넣어 트랜잭션을 생성함 | |
const swapTransaction = await buildTxForSwap(swapParams); | |
console.log('Transaction for swap: ', swapTransaction); | |
// 생성된 unsigned transaction을 인자로 넣어 SignAndSendTransaction() 함수를 실행해 signed transaction을 생성하고 트랜잭션 해시를 반환받음 | |
const swapTxHash = await signAndSendTransaction(swapTransaction); | |
// 반환받은 트랜잭션 해시를 출력함 | |
console.log('Swap transaction hash: ', swapTxHash); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment