raydium-io / raydium-sdk-V2-demo

Open-source Typescript SDK demos
48 stars 31 forks source link

Reduce transaction size with a swap #59

Closed lleewwiiss closed 3 months ago

lleewwiiss commented 3 months ago

I am using the SDK to create a swap instruction which works well, but as soon as I try add some other instructions (bribes, fee transfer etc) I go over the size limit of a transaction, is there anyway I can reduce the size?

Here is my full working code:

async function createRaydiumInstructions(
  inputAmount: BN,
  action: "buy" | "sell",
  slippagePercentage: number,
  metadata: any,
  userKeypair: Keypair,
  connection: web3.Connection
) {
  const raydium = await Raydium.load({
    connection,
    owner: userKeypair,
    disableLoadToken: true,
  });

  const [poolInfo, poolKeys] = await Promise.all([
    raydium.api.fetchPoolById({ ids: metadata.raydium_pool }),
    raydium.liquidity.getAmmPoolKeys(metadata.raydium_pool),
  ]);

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

  await raydium.liquidity.initLayout();
  const out = raydium.liquidity.computeAmountOut({
    poolInfo: {
      ...(poolInfo[0] as ApiV3PoolInfoStandardItem),
      baseReserve: res.baseReserve,
      quoteReserve: res.quoteReserve,
    },
    amountIn: new BN(inputAmount),
    mintIn:
      action === "buy" ? poolInfo[0].mintA.address : poolInfo[0].mintB.address,
    mintOut:
      action === "buy" ? poolInfo[0].mintB.address : poolInfo[0].mintA.address,
    slippage: slippagePercentage,
  });

  const { builder } = await raydium.liquidity.swap({
    poolInfo: poolInfo[0] as ApiV3PoolInfoStandardItem,
    amountIn: new BN(inputAmount),
    amountOut: out.minAmountOut,
    fixedSide: "in",
    inputMint:
      action === "buy" ? poolInfo[0].mintA.address : poolInfo[0].mintB.address,
    associatedOnly: false,
    txVersion: TxVersion.V0,
  });

  return {
    instructions: builder.allInstructions,
  };
}
cruzshia commented 3 months ago

we already downsize tx size as possible as we can and there's no way to reduce more, if you want to add more instructions, you have to check it's over tx size limit or not and separate them into 2 tx