raydium-io / raydium-sdk-V2-demo

Open-source Typescript SDK demos
73 stars 36 forks source link

Slippage changes do not affect to amountOut #24

Closed dexweb3 closed 5 months ago

dexweb3 commented 5 months ago

https://github.com/raydium-io/raydium-sdk-V2-demo/blob/ca8615fce7d911eece0370d58f2d67b016482aa9/src/amm/swap.ts#L33

For some reason slippage change do not affect to requested amountOut when I make trx. I getting very often exception like "Program Error: "Instruction #4 Failed - exceeds desired slippage limit" with absolutelly different values for slippage 0.001 / 0.1 / 0.5 / 1 / 10 / 50 and etc.

I logging amountOut but for different slippage value this log the same console.log(out.amountOut.toString());

Am I missing something or is this not working correctly now? What kind of numbers should be for slippage?

cruzshia commented 5 months ago

Can you share your code and pool id?

cruzshia commented 5 months ago

slippage only affects out.minAmountOut which means amounts with slippage and out.amountOut is amount without slippage valid slippage range is 1~0, and 0.001 means 0.001 * 100 = 0.1% slippage

dexweb3 commented 5 months ago

PoolId: FCEnSxyJfRSKsz6tASUENCsfGwKgkH6YuRn1AMmyHhZn

Slippage (for our example): 0.99

The code is default, I'll provide you params for computeAmountOut and swap ops

raydium.liquidity.computeAmountOut: {"poolInfo":{"type":"Standard","programId":"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8","id":"FCEnSxyJfRSKsz6tASUENCsfGwKgkH6YuRn1AMmyHhZn","mintA":{"chainId":101,"address":"So11111111111111111111111111111111111111112","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","logoURI":"https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png","symbol":"WSOL","name":"Wrapped SOL","decimals":9,"tags":[],"extensions":{}},"mintB":{"chainId":101,"address":"B5WTLaRwaUQpKk7ir1wniNB6m5o8GgMrimhKMYan2R6B","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","logoURI":"https://img-v1.raydium.io/icon/B5WTLaRwaUQpKk7ir1wniNB6m5o8GgMrimhKMYan2R6B.png","symbol":"Pepe","name":"Pepe","decimals":6,"tags":[],"extensions":{}},"price":6213.891858260649,"mintAmountA":3426.502679115,"mintAmountB":21291917.100061,"feeRate":0.0025,"openTime":"0","tvl":1133394.41,"day":{"volume":5034196.481240237,"volumeQuote":160320528.78985372,"volumeFee":12584.935534767214,"apr":405.83343313595634,"feeApr":405.29,"priceMin":3455.751945979798,"priceMax":6868.527551773632,"rewardApr":[0.5434331359563114]},"week":{"volume":138548680.68355,"volumeQuote":6294738091.021758,"volumeFee":346371.701708875,"apr":917.3634331359564,"feeApr":916.82,"priceMin":1491.5509437557391,"priceMax":51948.540808022924,"rewardApr":[0.5434331359563114]},"month":{"volume":166762227.10420752,"volumeQuote":20097001055.144123,"volumeFee":416905.5677605184,"apr":441.95343313595635,"feeApr":441.41,"priceMin":1491.5509437557391,"priceMax":6764069.488411051,"rewardApr":[0.5434331359563114]},"pooltype":["OpenBookMarket"],"rewardDefaultPoolInfos":"Ecosystem","rewardDefaultInfos":[{"mint":{"chainId":101,"address":"EYpbFTJYv91qqYSRZoKgnxLvBQGurYq4w7djrpPyd4T8","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","logoURI":"https://img-v1.raydium.io/icon/EYpbFTJYv91qqYSRZoKgnxLvBQGurYq4w7djrpPyd4T8.png","symbol":"COJON","name":"COJON","decimals":8,"tags":[],"extensions":{}},"perSecond":"16534391","startTime":"1716939764","endTime":"1717544564"}],"farmUpcomingCount":0,"farmOngoingCount":1,"farmFinishedCount":0,"marketId":"DTz4Aq3JxgiujASckarAqiXN58MEdsnFddica5sNDuko","lpMint":{"chainId":101,"address":"CTkUPPRcLp5UqSwNfjafAnvm3zcM5mbsuXAUNhwxHpHo","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","logoURI":"","symbol":"","name":"","decimals":9,"tags":[],"extensions":{}},"lpPrice":273.5837362797745,"lpAmount":4142.769703171,"baseReserve":"02f6676121f8","quoteReserve":"1181711a3df2"},"amountIn":"05f5e100","mintIn":"So11111111111111111111111111111111111111112","mintOut":"B5WTLaRwaUQpKk7ir1wniNB6m5o8GgMrimhKMYan2R6B","slippage":**0.99**}

raydium.liquidity.swap:

{
  poolInfo: {
    type: 'Standard',
    programId: '675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8',
    id: 'FCEnSxyJfRSKsz6tASUENCsfGwKgkH6YuRn1AMmyHhZn',
    mintA: {
      chainId: 101,
      address: 'So11111111111111111111111111111111111111112',
      programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
      logoURI: 'https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png',
      symbol: 'WSOL',
      name: 'Wrapped SOL',
      decimals: 9,
      tags: [],
      extensions: {}
    },
    mintB: {
      chainId: 101,
      address: 'B5WTLaRwaUQpKk7ir1wniNB6m5o8GgMrimhKMYan2R6B',
      programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
      logoURI: 'https://img-v1.raydium.io/icon/B5WTLaRwaUQpKk7ir1wniNB6m5o8GgMrimhKMYan2R6B.png',
      symbol: 'Pepe',
      name: 'Pepe',
      decimals: 6,
      tags: [],
      extensions: {}
    },
    price: 6213.891858260649,
    mintAmountA: 3426.502679115,
    mintAmountB: 21291917.100061,
    feeRate: 0.0025,
    openTime: '0',
    tvl: 1133394.41,
    day: {
      volume: 5034196.481240237,
      volumeQuote: 160320528.78985372,
      volumeFee: 12584.935534767214,
      apr: 405.83343313595634,
      feeApr: 405.29,
      priceMin: 3455.751945979798,
      priceMax: 6868.527551773632,
      rewardApr: [Array]
    },
    week: {
      volume: 138548680.68355,
      volumeQuote: 6294738091.021758,
      volumeFee: 346371.701708875,
      apr: 917.3634331359564,
      feeApr: 916.82,
      priceMin: 1491.5509437557391,
      priceMax: 51948.540808022924,
      rewardApr: [Array]
    },
    month: {
      volume: 166762227.10420752,
      volumeQuote: 20097001055.144123,
      volumeFee: 416905.5677605184,
      apr: 441.95343313595635,
      feeApr: 441.41,
      priceMin: 1491.5509437557391,
      priceMax: 6764069.488411051,
      rewardApr: [Array]
    },
    pooltype: [ 'OpenBookMarket' ],
    rewardDefaultPoolInfos: 'Ecosystem',
    rewardDefaultInfos: [ [Object] ],
    farmUpcomingCount: 0,
    farmOngoingCount: 1,
    farmFinishedCount: 0,
    marketId: 'DTz4Aq3JxgiujASckarAqiXN58MEdsnFddica5sNDuko',
    lpMint: {
      chainId: 101,
      address: 'CTkUPPRcLp5UqSwNfjafAnvm3zcM5mbsuXAUNhwxHpHo',
      programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
      logoURI: '',
      symbol: '',
      name: '',
      decimals: 9,
      tags: [],
      extensions: {}
    },
    lpPrice: 273.5837362797745,
    lpAmount: 4142.769703171
  },
  amountIn: <BN: 5f5e100>,
  amountOut: <BN: 2321ab5f>,
  fixedSide: 'in',
  inputMint: 'So11111111111111111111111111111111111111112',
  associatedOnly: false,
  txVersion: 0,
  computeBudgetConfig: { microLamports: 1000000 }
}

__

console.log(out.amountOut.toString()); 589409119

It's looks like a value without slippage at all, because when I did the same with 0.001 slippage in 10 min I got 594194403 (the same +-)

cruzshia commented 5 months ago

I run this code and tx go through successfully 2 times. notice that out.minAmountOut is amount with slippage not out.amountOut

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 = 100
  const poolId = 'FCEnSxyJfRSKsz6tASUENCsfGwKgkH6YuRn1AMmyHhZn'

  // RAY-USDC pool
  // note: api doesn't support get devnet pool info
  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, // swap mintB -> mintA, use: poolInfo.mintB.address
    mintOut: poolInfo.mintB.address, // swap mintB -> mintA, use: poolInfo.mintA.address
    slippage: 0.01,
  })

  const { execute } = await raydium.liquidity.swap({
    poolInfo,
    amountIn: new BN(amountIn),
    amountOut: out.amountOut,
    fixedSide: 'in',
    inputMint: poolInfo.mintA.address, // swap mintB -> mintA, use: poolInfo.mintB.address
    associatedOnly: false,
    txVersion,
    // optional: set up priority fee here
    // computeBudgetConfig: {
    //   units: 600000,
    //   microLamports: 100000000,
    // },
  })
  const { txId } = await execute()
  console.log(`swap successfully in amm pool:`, { txId })
}

/** uncomment code below to execute */
swap()
dexweb3 commented 5 months ago

I am not sure why, but sometimes I get "Instruction #4 Failed - exceeds desired slippage limit" when I have 0.99 slippage. How it can be possible?

Trx for example: https://solscan.io/tx/42BfyZcFMM15S7bgVq2H4QDnNwoATtTERqBiBosA1bzRtT4GVWZN41kexdv2GJ3EM7jTsDWN8AeFikxSTtnQabHg

cruzshia commented 5 months ago

even you set a high slippage, you still have chance exceeds slippage limit due to lower priority fees or high frequency pool trading..etc. it's not a guarantee a tx will success even when you set 100% slippage.

dexweb3 commented 5 months ago

So you mean that the error with the text "Failed - exceeds desired slippage limit" may not relate to slippage at all?

It's a bit strange. For example case with "lower priority fees" - should be resolved with other exception, like "block height is exceeded". Not sure about high frequency pool trading, but as I see that pool is not high frequency now.

cruzshia commented 5 months ago

according to your tx

looks like you are not using out.minAmountOut for swap amountOut params which I said in previous reply.

const { execute } = await raydium.liquidity.swap({ poolInfo, amountIn: new BN(amountIn), amountOut: out.amountOut => out.minAmountOut, fixedSide: 'in', inputMint: poolInfo.mintA.address, associatedOnly: false, txVersion, })

correct slippage amount should be minAmountOut

image

but amount in your tx is out.amountOut

image