forked from raydium-io/raydium-sdk-V1-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapOnlyAmm.ts
88 lines (78 loc) · 2.42 KB
/
swapOnlyAmm.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
import assert from 'assert';
import {
jsonInfo2PoolKeys,
Liquidity,
LiquidityPoolKeys,
Percent,
Token,
TokenAmount,
} from '@raydium-io/raydium-sdk';
import { Keypair } from '@solana/web3.js';
import {
connection,
DEFAULT_TOKEN,
makeTxVersion,
wallet
} from '../config';
import { formatAmmKeysById } from './formatAmmKeysById';
import {
buildAndSendTx,
getWalletTokenAccount,
} from './util';
type WalletTokenAccounts = Awaited<ReturnType<typeof getWalletTokenAccount>>
type TestTxInputInfo = {
outputToken: Token
targetPool: string
inputTokenAmount: TokenAmount
slippage: Percent
walletTokenAccounts: WalletTokenAccounts
wallet: Keypair
}
async function swapOnlyAmm(input: TestTxInputInfo) {
// -------- pre-action: get pool info --------
const targetPoolInfo = await formatAmmKeysById(input.targetPool)
assert(targetPoolInfo, 'cannot find the target pool')
const poolKeys = jsonInfo2PoolKeys(targetPoolInfo) as LiquidityPoolKeys
// -------- step 1: coumpute amount out --------
const { amountOut, minAmountOut } = Liquidity.computeAmountOut({
poolKeys: poolKeys,
poolInfo: await Liquidity.fetchInfo({ connection, poolKeys }),
amountIn: input.inputTokenAmount,
currencyOut: input.outputToken,
slippage: input.slippage,
})
// -------- step 2: create instructions by SDK function --------
const { innerTransactions } = await Liquidity.makeSwapInstructionSimple({
connection,
poolKeys,
userKeys: {
tokenAccounts: input.walletTokenAccounts,
owner: input.wallet.publicKey,
},
amountIn: input.inputTokenAmount,
amountOut: minAmountOut,
fixedSide: 'in',
makeTxVersion,
})
console.log('amountOut:', amountOut.toFixed(), ' minAmountOut: ', minAmountOut.toFixed())
return { txids: await buildAndSendTx(innerTransactions) }
}
async function howToUse() {
const inputToken = DEFAULT_TOKEN.USDC // USDC
const outputToken = DEFAULT_TOKEN.RAY // RAY
const targetPool = 'EVzLJhqMtdC1nPmz8rNd6xGfVjDPxpLZgq7XJuNfMZ6' // USDC-RAY pool
const inputTokenAmount = new TokenAmount(inputToken, 10000)
const slippage = new Percent(1, 100)
const walletTokenAccounts = await getWalletTokenAccount(connection, wallet.publicKey)
swapOnlyAmm({
outputToken,
targetPool,
inputTokenAmount,
slippage,
walletTokenAccounts,
wallet: wallet,
}).then(({ txids }) => {
/** continue with txids */
console.log('txids', txids)
})
}