Skip to content

Commit

Permalink
add: swap with api and ins demo
Browse files Browse the repository at this point in the history
  • Loading branch information
cruzshia committed Nov 25, 2024
1 parent 514d513 commit 23fe65c
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Raydium SDK V2 demo.",
"license": "GPL-3.0",
"dependencies": {
"@raydium-io/raydium-sdk-v2": "0.1.73-alpha",
"@raydium-io/raydium-sdk-v2": "0.1.92-alpha",
"@solana/spl-token": "^0.4.6",
"@types/jsonfile": "^6.1.4",
"bs58": "^5.0.0",
Expand Down
1 change: 1 addition & 0 deletions src/api/swapBaseOut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const apiSwapBaseOut = async () => {
const [isInputSol, isOutputSol] = [inputMint === NATIVE_MINT.toBase58(), outputMint === NATIVE_MINT.toBase58()]

const { tokenAccounts } = await fetchTokenAccountData()

const inputTokenAcc = tokenAccounts.find((a) => a.mint.toBase58() === inputMint)?.publicKey
const outputTokenAcc = tokenAccounts.find((a) => a.mint.toBase58() === outputMint)?.publicKey

Expand Down
12 changes: 7 additions & 5 deletions src/clmm/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const swap = async () => {
const raydium = await initSdk()
let poolInfo: ApiV3PoolInfoConcentratedItem
// RAY-USDC pool
const poolId = '61R1ndXxvsWXXkWSyNkCxnzwd3zUNB8Q2ibmkiLPC8ht'
const poolId = 'DiwsGxJYoRZURvyCtMsJVyxR86yZBBbSYeeWNm7YCmT6'
const inputMint = RAYMint.toBase58()
let poolKeys: ClmmKeys | undefined
let clmmPoolInfo: ComputeClmmPoolInfo
Expand Down Expand Up @@ -46,6 +46,8 @@ export const swap = async () => {
tickCache = data.tickData
}

console.log(123123444, clmmPoolInfo.observationId)

if (inputMint !== poolInfo.mintA.address && inputMint !== poolInfo.mintB.address)
throw new Error('input mint does not match pool')

Expand Down Expand Up @@ -81,10 +83,10 @@ export const swap = async () => {
})

printSimulateInfo()
const { txId } = await execute()
console.log('swapped in clmm pool:', { txId: `https://explorer.solana.com/tx/${txId}` })
process.exit() // if you don't want to end up node execution, comment this line
// const { txId } = await execute()
// console.log('swapped in clmm pool:', { txId: `https://explorer.solana.com/tx/${txId}` })
// process.exit() // if you don't want to end up node execution, comment this line
}

/** uncomment code below to execute */
// swap()
swap()
82 changes: 82 additions & 0 deletions src/trade/swapBaseInInstruction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Transaction, PublicKey } from '@solana/web3.js'
import { NATIVE_MINT } from '@solana/spl-token'
import axios, { AxiosResponse } from 'axios'
import { connection, owner } from '../config'
import {
API_URLS,
ApiSwapV1Out,
USDCMint,
PoolKeys,
getATAAddress,
swapBaseInAutoAccount,
ALL_PROGRAM_ID,
printSimulate,
addComputeBudget,
} from '@raydium-io/raydium-sdk-v2'
import BN from 'bn.js'

export const apiSwap = async () => {
// const inputMint = NATIVE_MINT.toBase58()
// const outputMint = USDCMint.toBase58()

const inputMint = USDCMint.toBase58()
const outputMint = NATIVE_MINT.toBase58()
const amount = 1000000
const slippage = 0.5 // in percent, for this example, 0.5 means 0.5%
const txVersion: 'LEGACY' | 'VO' = 'LEGACY'

const { data: swapResponse } = await axios.get<ApiSwapV1Out>(
`${
API_URLS.SWAP_HOST
}/compute/swap-base-out?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=${
slippage * 100
}&txVersion=${txVersion}`
)

if (!swapResponse.success) {
throw new Error(swapResponse.msg)
}

const res = await axios.get<AxiosResponse<PoolKeys[]>>(
API_URLS.BASE_HOST + API_URLS.POOL_KEY_BY_ID + `?ids=${swapResponse.data.routePlan.map((r) => r.poolId).join(',')}`
)

const allMints = res.data.data.map((r) => [r.mintA, r.mintB]).flat()
const [mintAProgram, mintBProgram] = [
allMints.find((m) => m.address === inputMint)!.programId,
allMints.find((m) => m.address === outputMint)!.programId,
]

// get input/output token account ata
// please ensure your input token account has balance
const inputAccount = getATAAddress(owner.publicKey, new PublicKey(inputMint), new PublicKey(mintAProgram)).publicKey
const outputAccount = getATAAddress(owner.publicKey, new PublicKey(outputMint), new PublicKey(mintBProgram)).publicKey

const ins = swapBaseInAutoAccount({
programId: ALL_PROGRAM_ID.Router,
wallet: owner.publicKey,
amount: new BN(amount),
inputAccount,
outputAccount,
routeInfo: swapResponse,
poolKeys: res.data.data,
})

const recentBlockhash = (await connection.getLatestBlockhash()).blockhash
const tx = new Transaction()

// set up compute units
const { instructions } = addComputeBudget({
units: 600000,
microLamports: 6000000,
})
instructions.forEach((ins) => tx.add(ins))

tx.add(ins)
tx.feePayer = owner.publicKey
tx.recentBlockhash = recentBlockhash
tx.sign(owner)

printSimulate([tx])
}
apiSwap()
74 changes: 74 additions & 0 deletions src/trade/swapBaseOutInstruction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { Transaction, PublicKey } from '@solana/web3.js'
import { NATIVE_MINT } from '@solana/spl-token'
import axios, { AxiosResponse } from 'axios'
import { connection, owner } from '../config'
import {
API_URLS,
ApiSwapV1Out,
USDCMint,
PoolKeys,
getATAAddress,
swapBaseOutAutoAccount,
ALL_PROGRAM_ID,
printSimulate,
addComputeBudget,
} from '@raydium-io/raydium-sdk-v2'
import BN from 'bn.js'

export const swapBaseOutInstruction = async () => {
const inputMint = USDCMint.toBase58()
const outputMint = NATIVE_MINT.toBase58()
const amount = 1000000
const slippage = 0.5 // in percent, for this example, 0.5 means 0.5%
const txVersion: 'LEGACY' | 'VO' = 'LEGACY'

const { data: swapResponse } = await axios.get<ApiSwapV1Out>(
`${
API_URLS.SWAP_HOST
}/compute/swap-base-out?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amount}&slippageBps=${
slippage * 100
}&txVersion=${txVersion}`
)

if (!swapResponse.success) {
throw new Error(swapResponse.msg)
}

const res = await axios.get<AxiosResponse<PoolKeys[]>>(
API_URLS.BASE_HOST + API_URLS.POOL_KEY_BY_ID + `?ids=${swapResponse.data.routePlan.map((r) => r.poolId).join(',')}`
)

const allMints = res.data.data.map((r) => [r.mintA, r.mintB]).flat()
const [mintAProgram, mintBProgram] = [
allMints.find((m) => m.address === inputMint)!.programId,
allMints.find((m) => m.address === outputMint)!.programId,
]

// get input/output token account ata
const inputAccount = getATAAddress(owner.publicKey, new PublicKey(inputMint), new PublicKey(mintAProgram)).publicKey
const outputAccount = getATAAddress(owner.publicKey, new PublicKey(outputMint), new PublicKey(mintBProgram)).publicKey

const ins = swapBaseOutAutoAccount({
programId: ALL_PROGRAM_ID.Router,
wallet: owner.publicKey,
inputAccount,
outputAccount,
routeInfo: swapResponse,
poolKeys: res.data.data,
})

const { instructions } = addComputeBudget({
units: 600000,
microLamports: 6000000,
})
const recentBlockhash = (await connection.getLatestBlockhash()).blockhash
const tx = new Transaction()
instructions.forEach((ins) => tx.add(ins))
tx.add(ins)
tx.feePayer = owner.publicKey
tx.recentBlockhash = recentBlockhash
tx.sign(owner)

printSimulate([tx])
}
swapBaseOutInstruction()
9 changes: 5 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,10 @@
"@pnpm/network.ca-file" "^1.0.1"
config-chain "^1.1.11"

"@raydium-io/[email protected].73-alpha":
version "0.1.73-alpha"
resolved "https://registry.yarnpkg.com/@raydium-io/raydium-sdk-v2/-/raydium-sdk-v2-0.1.73-alpha.tgz#1501e5c216f8f6ae7afe19880cf7ac751e528939"
integrity sha512-qUhsEV/phGW6fwzHkdWcKa+qdomTouheo0xZTcoIZQNF0xAHQ4bNgnhi+Q28oD37+wuL+SzreKnbIRgE3r629Q==
"@raydium-io/[email protected].92-alpha":
version "0.1.92-alpha"
resolved "https://registry.yarnpkg.com/@raydium-io/raydium-sdk-v2/-/raydium-sdk-v2-0.1.92-alpha.tgz#06b782725b3a7c5188d6fb0f0292cec6f0af12ed"
integrity sha512-oCI2a+eN0JafnBa4zcEYBd9PUzqIVFjDnonXqUQF2WKcSiYRAdZq2zRx8QgVh7bZTK1Q4Jetjvw3wT2s4bZoig==
dependencies:
"@solana/buffer-layout" "^4.0.1"
"@solana/spl-token" "^0.4.8"
Expand All @@ -215,6 +215,7 @@
bn.js "^5.2.1"
dayjs "^1.11.5"
decimal.js-light "^2.5.1"
jsonfile "^6.1.0"
lodash "^4.17.21"
toformat "^2.0.0"
tsconfig-paths "^4.2.0"
Expand Down

0 comments on commit 23fe65c

Please sign in to comment.