Skip to content

Commit

Permalink
Add sdk-v2 base demo (raydium-io#1)
Browse files Browse the repository at this point in the history
* Add sdk-v2 base demo
  • Loading branch information
cruzshia authored May 16, 2024
1 parent 0fb2bc0 commit 609d188
Show file tree
Hide file tree
Showing 43 changed files with 2,370 additions and 7,943 deletions.
28 changes: 0 additions & 28 deletions .eslintrc.js

This file was deleted.

8 changes: 5 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
*.log
.DS_Store
node_modules
dist
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
src/config.ts
5 changes: 5 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.next
yarn.lock
package-lock.json
public
10 changes: 10 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"semi": false,
"bracketSpacing": true,
"printWidth": 120,
"arrowParens": "always",
"eslintIntegration": true
}
21 changes: 0 additions & 21 deletions LICENSE

This file was deleted.

14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# RAYDIUM SDK V2 demo

## About the project

This project is for [RAYDIUM SDK V2](https://github.com/raydium-io/raydium-sdk-V2) demonstration

## Getting Started

### Installation
Expand All @@ -10,17 +14,11 @@ this will install the dependencies for running the demo script

### Prerequisites

Modify `src/common/connection.ts` to fit your configuration
Modify `config.ts.template` to fit your configuration, and rename it to `config.ts`

- `<YOUR_WALLET_SECRET_KEY>`: replace to your own one
- `<YOUR_RPC_URL>`: replace to your prefer one

### Usage

- `yarn test` run all demo functions
- `yarn test test/<SCRIPT_NAME>.test.ts` run the specific demo test script. e.g. yarn test test/cpmm/create-pool.test.ts
- `yarn test test/<FOLDER_NAME>` run the specific feature all demo test script. e.g. yarn test test/cpmm/\*

### Skip test

if you want to skip some test function, modify test function `it(` -> `it.skip(` in test/xxx.test.ts file.
- `yarn dev src/<FOLDER>/<SCRIPT_NAME>` run the specific demo script, e.g. yarn dev src/cpmm/deposit.ts. **Note: if you want to execute tx, remember to uncomment code in last line**
5 changes: 0 additions & 5 deletions jest.config.js

This file was deleted.

72 changes: 18 additions & 54 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,60 +1,24 @@
{
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"test": "tsdx test",
"lint": "tsdx lint"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
"name": "test-rrr-sdk",
"version": "0.0.1-alpha",
"description": "An SDK for building applications on top of Raydium.",
"license": "GPL-3.0",
"dependencies": {
"bs58": "^5.0.0",
"decimal.js": "^10.4.3",
"node-cron": "^3.0.3",
"@raydium-io/raydium-sdk-v2": "npm:[email protected]",
"ts-node": "^10.9.1",
"typescript": "^5.3.3"
},
"name": "sdk-demo-v2",
"author": "CruzShia",
"module": "dist/sdk-demo-v2.esm.js",
"size-limit": [
{
"path": "dist/sdk-demo-v2.cjs.production.min.js",
"limit": "10 KB"
},
{
"path": "dist/sdk-demo-v2.esm.js",
"limit": "10 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^11.1.2",
"husky": "^9.0.11",
"size-limit": "^11.1.2",
"tsdx": "^0.14.1",
"tslib": "^2.6.2",
"typescript": "^5.4.5"
},
"dependencies": {
"@project-serum/borsh": "^0.2.5",
"@solana/spl-token": "^0.4.6",
"@solana/web3.js": "^1.91.8",
"@types/bn.js": "^5.1.5",
"bn.js": "^5.2.1",
"bs58": "^5.0.0",
"buffer-layout": "^1.2.2",
"decimal.js": "^10.4.3"
"npm-check-updates": "^16.14.11"
},
"scripts": {
"start": "node",
"build": "tsc",
"clean": "tsc --build --clean",
"dev": "ts-node"
}
}
39 changes: 39 additions & 0 deletions src/amm/addLiquidity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ApiV3PoolInfoStandardItem, TokenAmount, toToken, Percent } from '@raydium-io/raydium-sdk-v2'
import { initSdk, txVersion } from '../config'
import Decimal from 'decimal.js'

export const addLiquidity = async () => {
const raydium = await initSdk()
// RAY-USDC pool
const data = await raydium.api.fetchPoolById({ ids: '6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg' })
const poolInfo = data[0] as ApiV3PoolInfoStandardItem

const inputAmount = '1'

const r = raydium.liquidity.computePairAmount({
poolInfo,
amount: inputAmount,
baseIn: true,
slippage: new Percent(1, 100), // 1%
})

const { execute } = await raydium.liquidity.addLiquidity({
poolInfo,
amountInA: new TokenAmount(
toToken(poolInfo.mintA),
new Decimal(inputAmount).mul(10 ** poolInfo.mintA.decimals).toFixed(0)
),
amountInB: new TokenAmount(
toToken(poolInfo.mintA),
new Decimal(r.maxAnotherAmount.toExact()).mul(10 ** poolInfo.mintA.decimals).toFixed(0)
),
fixedSide: 'a',
txVersion,
})

const { txId } = await execute()
console.log('liquidity added:', { txId })
}

/** uncomment code below to execute */
// addLiquidity()
49 changes: 49 additions & 0 deletions src/amm/swap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ApiV3PoolInfoStandardItem, fetchMultipleInfo } from '@raydium-io/raydium-sdk-v2'
import { initSdk, txVersion } from '../config'
import BN from 'bn.js'

export const swap = async () => {
const raydium = await initSdk()
const amountIn = 10000
const poolId = '6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg'

// RAY-USDC pool
const data = (await raydium.api.fetchPoolById({ ids: poolId })) as any
const poolInfo = data[0] as ApiV3PoolInfoStandardItem
const poolKeys = await raydium.liquidity.getAmmPoolKeys(poolId)

const res = await fetchMultipleInfo({
connection: raydium.connection,
poolKeysList: [poolKeys],
config: undefined,
})
const pool = res[0]

await raydium.liquidity.initLayout()
const out = raydium.liquidity.computeAmountOut({
poolInfo: {
...poolInfo,
baseReserve: pool.baseReserve,
quoteReserve: pool.quoteReserve,
},
amountIn: new BN(amountIn),
mintIn: poolInfo.mintA.address,
mintOut: poolInfo.mintB.address,
slippage: 0.001,
})

const { execute } = await raydium.liquidity.swap({
poolInfo,
amountIn: new BN(amountIn),
amountOut: out.amountOut,
fixedSide: 'in',
inputMint: poolInfo.mintA.address,
associatedOnly: false,
txVersion,
})
const { txId } = await execute()
console.log(`swap ${poolInfo.mintA.symbol} -> ${poolInfo.mintB.symbol} in amm pool:`, { txId })
}

/** uncomment code below to execute */
// swap()
22 changes: 22 additions & 0 deletions src/amm/withdrawLiquidity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ApiV3PoolInfoStandardItem } from '@raydium-io/raydium-sdk-v2'
import { initSdk, txVersion } from '../config'
import BN from 'bn.js'

export const withdrawLiquidity = async () => {
const raydium = await initSdk()
// RAY-USDC pool
const data = await raydium.api.fetchPoolById({ ids: '6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg' })
const poolInfo = data[0] as ApiV3PoolInfoStandardItem

const { execute } = await raydium.liquidity.removeLiquidity({
poolInfo,
amountIn: new BN(1),
txVersion,
})

const { txId } = await execute()
console.log('liquidity withdraw:', { txId })
}

/** uncomment code below to execute */
// withdrawLiquidity()
57 changes: 57 additions & 0 deletions src/clmm/addLp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ApiV3PoolInfoConcentratedItem, TickUtils, PoolUtils } from '@raydium-io/raydium-sdk-v2'
import BN from 'bn.js'
import { initSdk, txVersion } from '../config'
import Decimal from 'decimal.js'

export const addLp = async () => {
const raydium = await initSdk()
// RAY-USDC pool
const data = await raydium.api.fetchPoolById({ ids: '61R1ndXxvsWXXkWSyNkCxnzwd3zUNB8Q2ibmkiLPC8ht' })
const poolInfo = (data as any)[0] as ApiV3PoolInfoConcentratedItem

const inputAmount = 1 // RAY amount
const [startPrice, endPrice] = [0.1, 100]

const { tick: lowerTick } = TickUtils.getPriceAndTick({
poolInfo,
price: new Decimal(startPrice),
baseIn: true,
})

const { tick: upperTick } = TickUtils.getPriceAndTick({
poolInfo,
price: new Decimal(endPrice),
baseIn: true,
})

const epochInfo = await raydium.fetchEpochInfo()

const res = await PoolUtils.getLiquidityAmountOutFromAmountIn({
poolInfo,
slippage: 0,
inputA: true,
tickUpper: Math.max(lowerTick, upperTick),
tickLower: Math.min(lowerTick, upperTick),
amount: new BN(new Decimal(inputAmount || '0').mul(10 ** poolInfo.mintA.decimals).toFixed(0)),
add: true,
amountHasFee: true,
epochInfo: epochInfo,
})

const { execute } = await raydium.clmm.openPositionFromBase({
poolInfo,
tickUpper: Math.max(lowerTick, upperTick),
tickLower: Math.min(lowerTick, upperTick),
base: 'MintA',
ownerInfo: {},
baseAmount: new BN(new Decimal(inputAmount || '0').mul(10 ** poolInfo.mintA.decimals).toFixed(0)),
otherAmountMax: res.amountSlippageB.amount,
txVersion,
})

const { txId } = await execute()
console.log('clmm position opened:', { txId })
}

/** uncomment code below to execute */
// addLp()
28 changes: 28 additions & 0 deletions src/clmm/createPool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { CLMM_PROGRAM_ID } from '@raydium-io/raydium-sdk-v2'
import { PublicKey } from '@solana/web3.js'
import { initSdk, txVersion } from '../config'
import Decimal from 'decimal.js'
import BN from 'bn.js'

export const createPool = async () => {
const raydium = await initSdk({ loadToken: true })

const mint1 = await raydium.token.getTokenInfo('4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R')
const mint2 = await raydium.token.getTokenInfo('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')
const clmmConfigs = await raydium.api.getClmmConfigs()

const { execute } = await raydium.clmm.createPool({
programId: CLMM_PROGRAM_ID,
mint1,
mint2,
ammConfig: { ...clmmConfigs[0], id: new PublicKey(clmmConfigs[0].id), fundOwner: '' },
initialPrice: new Decimal(1),
startTime: new BN(0),
txVersion,
})
const { txId } = await execute()
console.log('clmm pool created:', { txId })
}

/** uncomment code below to execute */
// createPool()
Loading

0 comments on commit 609d188

Please sign in to comment.