Created
December 3, 2024 08:46
-
-
Save korrio/fa3e7353d31140406d7669e6bd7ac858 to your computer and use it in GitHub Desktop.
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
const { Connection, PublicKey, Keypair } = require('@solana/web3.js'); | |
const { Liquidity, Percent, Token } = require('@raydium-io/raydium-sdk'); | |
async function swap() { | |
// Setup connection | |
const connection = new Connection('https://api.mainnet-beta.solana.com'); | |
const wallet = Keypair.generate(); // ในการใช้งานจริงใช้ wallet จริง | |
// Setup pool และ tokens | |
const SOL_USDC_POOL_ID = new PublicKey('58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2'); | |
const inputMint = new PublicKey('So11111111111111111111111111111111111111112'); // SOL | |
const outputMint = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC | |
try { | |
// ดึงข้อมูล Pool | |
const poolInfo = await Liquidity.fetchInfo({ | |
connection, | |
poolId: SOL_USDC_POOL_ID | |
}); | |
// สร้าง swap transaction | |
const { transaction, signers } = await Liquidity.makeSwapTransaction({ | |
connection, | |
wallet, | |
poolInfo, | |
amountIn: 1 * 10 ** 9, // 1 SOL | |
amountOutMin: 0, // ระวัง! ควรคำนวณ minimum amount ที่ยอมรับได้ | |
fixedSide: 'in', // swap จากจำนวน input ที่แน่นอน | |
tokenIn: new Token(inputMint, 9), // SOL has 9 decimals | |
tokenOut: new Token(outputMint, 6), // USDC has 6 decimals | |
}); | |
// ส่ง transaction | |
const txid = await connection.sendTransaction(transaction, [wallet, ...signers]); | |
console.log('Swap transaction sent:', txid); | |
// รอ confirmation | |
const confirmation = await connection.confirmTransaction(txid); | |
console.log('Transaction confirmed:', confirmation); | |
} catch (error) { | |
console.error('Error:', error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment