Skip to content

Instantly share code, notes, and snippets.

@bzpassersby
Created May 10, 2023 02:44
Show Gist options
  • Save bzpassersby/b6c573d0ad3b34e2d33f4b567896f087 to your computer and use it in GitHub Desktop.
Save bzpassersby/b6c573d0ad3b34e2d33f4b567896f087 to your computer and use it in GitHub Desktop.
trader may experience drastic loss at the point of order execution due to slippage
////note: trader may experience drastic loss at the point of order execution due to slippage
////note: This test is in the context of JoJo unit test file- liquidation-test.ts-"check position"
it("trader loss due to slippage and at brink of liquidation", async () => {
//note: test preparation so that trader1 starts a trade with sufficient deposits
//note: trader1 withdraw 5000-1885=3115 (1885 is calculated in trade-test.ts with transaction execution price of 29000)
await context.dealer
.connect(trader1)
.requestWithdraw(utils.parseEther("3115"), utils.parseEther("5000"));
await timeJump(100);
await context.dealer
.connect(trader1)
.executeWithdraw(trader1.address, false);
await checkCredit(context, trader1.address, "1885", "0");
//note: price changed against trader1's favor at the time of on-chain approval
await context.priceSourceList[0].setMarkPrice(utils.parseEther("29000"));
const risk0 = await context.dealer.getTraderRisk(trader1.address);
console.log(risk0.netValue.toString());
await openPosition(
trader1,
trader2,
"1",
"30000",
context.perpList[0],
orderEnv
);
expect(await context.dealer.isSafe(trader2.address)).to.be.true;
expect(await context.dealer.isSafe(trader1.address)).to.be.true;
await checkBalance(context.perpList[0], trader1.address, "1", "-30015");
await checkCredit(context, trader1.address, "1885", "0");
const risk = await context.dealer.getTraderRisk(trader1.address);
////note: trader1 net value loss after trade
const netValueDelta =
risk.netValue.toString() - risk0.netValue.toString();
console.log(netValueDelta);
//log: -1.015e+21 (-1015 USD) trader lost 1015 USD at transaction executed after slippage even though trader is still safe
expect(risk.netValue).to.equal(risk.maintenanceMargin); //// but trader1's margin of liquidation is already 0!
await context.priceSourceList[0].setMarkPrice(utils.parseEther("28999")); ////:Tiny price change will trigger liquidation
expect(await context.dealer.isSafe(trader1.address)).to.be.false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment