minswap / sdk

Query Minswap data and build transactions
MIT License
51 stars 20 forks source link

calculateSwapExactIn return wrong value #25

Open kieutuan218 opened 11 months ago

kieutuan218 commented 11 months ago

I use calculateSwapExactIn function to calculate amount out but it is returning different data than the interface. Tried with the ADA/tMELD pair and it is displaying amount out correctly with the interface. But it doesn't need divide by 10^6

Where is it going wrong?

async function getPool(
  assetA: string,
  assetB: string
): Promise<PoolState | undefined> {
  for (let i = 1; ; i++) {
    const pools = await blockfrostAdapter.getPools({
      page: i,
    });
    if (pools.length === 0) {
      // last page
      break;
    }
    const pool = pools.find((p) => p.assetA === assetA && p.assetB === assetB);
    if (pool) {
      return pool;
    }
  }
  return;
}

async function main(): Promise<void> {
  {
    // tMELD/tMIN
    const pool = await getPool(
      "88dc7cd1c28d3a0c7ef4df99036c7c9688d309d91a1bb6fe4b08fee9744d454c44",
      "f6f49b186751e61f1fb8c64e7504e771f968cea9f4d11f5222b169e3744d494e"
    );
    if (pool) {
      const amountIn = 10_000_000n;
      const data = calculateSwapExactIn({
        amountIn,
        reserveIn: pool.reserveA,
        reserveOut: pool.reserveB,
      });
      const amountOut = new Big(data.amountOut.toString()).div(
        new Big(10).pow(6)
      );
      console.log("amountOutFull", data.amountOut.toString());
      console.log("amountOut", amountOut.toString());
      console.log("priceImpact", data.priceImpact.toString());
    }
  }
}

Output:

amountOutFull 907854
amountOut 0.907854
priceImpact 90.60331783793637772309

UI: image

h2physics commented 11 months ago

@kieutuan218 The Testnet Enviroment is quite different with the Mainnet. There's no Token Metadata, it means that all Token on the Testnet will have decimal zero as well (except ADA, we assume that ADA always has 6 decimals)

In that case, you are exchanging 10 tMELD to get around 9 tMIN, not 10_000_000 tMELD

h2physics commented 11 months ago

1 Tip for it is we always show Invisible Token on the Swap page for zero decimals Tokens like the picture you provided above.

kieutuan218 commented 11 months ago

Thank you. @h2physics I have 1 more question. If I reverse swap tMIN -> tMELD, the parameters reserveIn, reserveOut, assetIn, assetOut will be reversed, right?

const data = calculateSwapExactIn({
    amountIn,
    reserveIn: pool.assetA === tMinAddress ? pool.reserveA : pool.reserveB,
    reserveOut: pool.assetB === tMeldAddress ? pool.reserveB : pool.reserveA,
});
kieutuan218 commented 11 months ago

@h2physics Decimal = 0 then amount out is the same as UI but priceImpact is always different from UI

amountOut 9. amountOut 9
priceImpact 0.00099300609363561084