-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathRaydiumSwap.ts
281 lines (248 loc) · 8.86 KB
/
RaydiumSwap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { Connection, PublicKey, Keypair, Transaction, VersionedTransaction, TransactionMessage } from '@solana/web3.js'
import {
Liquidity,
LiquidityPoolKeys,
jsonInfo2PoolKeys,
LiquidityPoolJsonInfo,
TokenAccount,
Token,
TokenAmount,
TOKEN_PROGRAM_ID,
Percent,
SPL_ACCOUNT_LAYOUT,
} from '@raydium-io/raydium-sdk'
import { Wallet } from '@coral-xyz/anchor'
import bs58 from 'bs58'
import fs from 'fs';
import path from 'path';
/**
* Class representing a Raydium Swap operation.
*/
class RaydiumSwap {
allPoolKeysJson: LiquidityPoolJsonInfo[]
connection: Connection
wallet: Wallet
/**
* Create a RaydiumSwap instance.
* @param {string} RPC_URL - The RPC URL for connecting to the Solana blockchain.
* @param {string} WALLET_PRIVATE_KEY - The private key of the wallet in base58 format.
*/
constructor(RPC_URL: string, WALLET_PRIVATE_KEY: string) {
this.connection = new Connection(RPC_URL
, { commitment: 'confirmed' })
this.wallet = new Wallet(Keypair.fromSecretKey(Uint8Array.from(bs58.decode(WALLET_PRIVATE_KEY))))
}
/**
* Loads all the pool keys available from a JSON configuration file.
* @async
* @returns {Promise<void>}
*/
async loadPoolKeys(liquidityFile: string) {
let liquidityJson;
if (liquidityFile.startsWith('http')) {
const liquidityJsonResp = await fetch(liquidityFile);
if (!liquidityJsonResp.ok) return;
liquidityJson = await liquidityJsonResp.json();
} else {
liquidityJson = JSON.parse(fs.readFileSync(path.join(__dirname, liquidityFile), 'utf-8'));
}
const allPoolKeysJson = [...(liquidityJson?.official ?? []), ...(liquidityJson?.unOfficial ?? [])]
this.allPoolKeysJson = allPoolKeysJson
}
/**
* Finds pool information for the given token pair.
* @param {string} mintA - The mint address of the first token.
* @param {string} mintB - The mint address of the second token.
* @returns {LiquidityPoolKeys | null} The liquidity pool keys if found, otherwise null.
*/
findPoolInfoForTokens(mintA: string, mintB: string) {
const poolData = this.allPoolKeysJson.find(
(i) => (i.baseMint === mintA && i.quoteMint === mintB) || (i.baseMint === mintB && i.quoteMint === mintA)
)
if (!poolData) return null
return jsonInfo2PoolKeys(poolData) as LiquidityPoolKeys
}
/**
* Retrieves token accounts owned by the wallet.
* @async
* @returns {Promise<TokenAccount[]>} An array of token accounts.
*/
async getOwnerTokenAccounts() {
const walletTokenAccount = await this.connection.getTokenAccountsByOwner(this.wallet.publicKey, {
programId: TOKEN_PROGRAM_ID,
})
return walletTokenAccount.value.map((i) => ({
pubkey: i.pubkey,
programId: i.account.owner,
accountInfo: SPL_ACCOUNT_LAYOUT.decode(i.account.data),
}))
}
/**
* Builds a swap transaction.
* @async
* @param {string} toToken - The mint address of the token to receive.
* @param {number} amount - The amount of the token to swap.
* @param {LiquidityPoolKeys} poolKeys - The liquidity pool keys.
* @param {number} [maxLamports=100000] - The maximum lamports to use for transaction fees.
* @param {boolean} [useVersionedTransaction=true] - Whether to use a versioned transaction.
* @param {'in' | 'out'} [fixedSide='in'] - The fixed side of the swap ('in' or 'out').
* @returns {Promise<Transaction | VersionedTransaction>} The constructed swap transaction.
*/
async getSwapTransaction(
toToken: string,
// fromToken: string,
amount: number,
poolKeys: LiquidityPoolKeys,
maxLamports: number = 100000,
useVersionedTransaction = true,
fixedSide: 'in' | 'out' = 'in'
): Promise<Transaction | VersionedTransaction> {
const directionIn = poolKeys.quoteMint.toString() == toToken
const { minAmountOut, amountIn } = await this.calcAmountOut(poolKeys, amount, directionIn)
console.log({ minAmountOut, amountIn });
const userTokenAccounts = await this.getOwnerTokenAccounts()
const swapTransaction = await Liquidity.makeSwapInstructionSimple({
connection: this.connection,
makeTxVersion: useVersionedTransaction ? 0 : 1,
poolKeys: {
...poolKeys,
},
userKeys: {
tokenAccounts: userTokenAccounts,
owner: this.wallet.publicKey,
},
amountIn: amountIn,
amountOut: minAmountOut,
fixedSide: fixedSide,
config: {
bypassAssociatedCheck: false,
},
computeBudgetConfig: {
microLamports: maxLamports,
},
})
const recentBlockhashForSwap = await this.connection.getLatestBlockhash()
const instructions = swapTransaction.innerTransactions[0].instructions.filter(Boolean)
if (useVersionedTransaction) {
const versionedTransaction = new VersionedTransaction(
new TransactionMessage({
payerKey: this.wallet.publicKey,
recentBlockhash: recentBlockhashForSwap.blockhash,
instructions: instructions,
}).compileToV0Message()
)
versionedTransaction.sign([this.wallet.payer])
return versionedTransaction
}
const legacyTransaction = new Transaction({
blockhash: recentBlockhashForSwap.blockhash,
lastValidBlockHeight: recentBlockhashForSwap.lastValidBlockHeight,
feePayer: this.wallet.publicKey,
})
legacyTransaction.add(...instructions)
return legacyTransaction
}
/**
* Sends a legacy transaction.
* @async
* @param {Transaction} tx - The transaction to send.
* @returns {Promise<string>} The transaction ID.
*/
async sendLegacyTransaction(tx: Transaction, maxRetries?: number) {
const txid = await this.connection.sendTransaction(tx, [this.wallet.payer], {
skipPreflight: true,
maxRetries: maxRetries,
})
return txid
}
/**
* Sends a versioned transaction.
* @async
* @param {VersionedTransaction} tx - The versioned transaction to send.
* @returns {Promise<string>} The transaction ID.
*/
async sendVersionedTransaction(tx: VersionedTransaction, maxRetries?: number) {
const txid = await this.connection.sendTransaction(tx, {
skipPreflight: true,
maxRetries: maxRetries,
})
return txid
}
/**
* Simulates a versioned transaction.
* @async
* @param {VersionedTransaction} tx - The versioned transaction to simulate.
* @returns {Promise<any>} The simulation result.
*/
async simulateLegacyTransaction(tx: Transaction) {
const txid = await this.connection.simulateTransaction(tx, [this.wallet.payer])
return txid
}
/**
* Simulates a versioned transaction.
* @async
* @param {VersionedTransaction} tx - The versioned transaction to simulate.
* @returns {Promise<any>} The simulation result.
*/
async simulateVersionedTransaction(tx: VersionedTransaction) {
const txid = await this.connection.simulateTransaction(tx)
return txid
}
/**
* Gets a token account by owner and mint address.
* @param {PublicKey} mint - The mint address of the token.
* @returns {TokenAccount} The token account.
*/
getTokenAccountByOwnerAndMint(mint: PublicKey) {
return {
programId: TOKEN_PROGRAM_ID,
pubkey: PublicKey.default,
accountInfo: {
mint: mint,
amount: 0,
},
} as unknown as TokenAccount
}
/**
* Calculates the amount out for a swap.
* @async
* @param {LiquidityPoolKeys} poolKeys - The liquidity pool keys.
* @param {number} rawAmountIn - The raw amount of the input token.
* @param {boolean} swapInDirection - The direction of the swap (true for in, false for out).
* @returns {Promise<Object>} The swap calculation result.
*/
async calcAmountOut(poolKeys: LiquidityPoolKeys, rawAmountIn: number, swapInDirection: boolean) {
const poolInfo = await Liquidity.fetchInfo({ connection: this.connection, poolKeys })
let currencyInMint = poolKeys.baseMint
let currencyInDecimals = poolInfo.baseDecimals
let currencyOutMint = poolKeys.quoteMint
let currencyOutDecimals = poolInfo.quoteDecimals
if (!swapInDirection) {
currencyInMint = poolKeys.quoteMint
currencyInDecimals = poolInfo.quoteDecimals
currencyOutMint = poolKeys.baseMint
currencyOutDecimals = poolInfo.baseDecimals
}
const currencyIn = new Token(TOKEN_PROGRAM_ID, currencyInMint, currencyInDecimals)
const amountIn = new TokenAmount(currencyIn, rawAmountIn, false)
const currencyOut = new Token(TOKEN_PROGRAM_ID, currencyOutMint, currencyOutDecimals)
const slippage = new Percent(5, 100) // 5% slippage
const { amountOut, minAmountOut, currentPrice, executionPrice, priceImpact, fee } = Liquidity.computeAmountOut({
poolKeys,
poolInfo,
amountIn,
currencyOut,
slippage,
})
return {
amountIn,
amountOut,
minAmountOut,
currentPrice,
executionPrice,
priceImpact,
fee,
}
}
}
export default RaydiumSwap