From 0e1ba0c42b70d1ba6665c2d32cca51ee558529d0 Mon Sep 17 00:00:00 2001 From: Fred Snax Date: Fri, 16 Aug 2024 11:48:49 -0700 Subject: [PATCH] rebase off main and start working on multi collateral and other recent changes --- .../contracts/modules/LimitOrderModule.sol | 48 +++++++------------ .../contracts/storage/LimitOrder.sol | 5 +- ...ffchainLimitOrder.settleLimitOrder.test.ts | 38 +++++++-------- 3 files changed, 36 insertions(+), 55 deletions(-) diff --git a/markets/perps-market/contracts/modules/LimitOrderModule.sol b/markets/perps-market/contracts/modules/LimitOrderModule.sol index 33557edcb0..6db46d6af8 100644 --- a/markets/perps-market/contracts/modules/LimitOrderModule.sol +++ b/markets/perps-market/contracts/modules/LimitOrderModule.sol @@ -22,7 +22,7 @@ import {PerpsAccount, SNX_USD_MARKET_ID} from "../storage/PerpsAccount.sol"; import {PerpsMarketConfiguration} from "../storage/PerpsMarketConfiguration.sol"; import {MathUtil} from "../utils/MathUtil.sol"; import {Flags} from "../utils/Flags.sol"; -import "hardhat/console.sol"; +// import "hardhat/console.sol"; /** * @title Module for settling signed P2P limit orders @@ -119,8 +119,8 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { PerpsMarketConfiguration.Data storage marketConfig = PerpsMarketConfiguration.load( shortOrder.marketId ); - console.log("maxMarketSize", marketConfig.maxMarketSize); - console.log("maxMarketValue", marketConfig.maxMarketValue); + // console.log("maxMarketSize", marketConfig.maxMarketSize); + // console.log("maxMarketValue", marketConfig.maxMarketValue); perpsMarketData.validateLimitOrderSize( marketConfig.maxMarketSize, marketConfig.maxMarketValue, @@ -158,7 +158,7 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { LimitOrder.SignedOrderRequest calldata order, LimitOrder.Signature calldata sig ) internal { - // Account.exists(order.accountId); + Account.exists(order.accountId); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", @@ -189,6 +189,7 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { } function validateLimitOrder(LimitOrder.SignedOrderRequest calldata order) internal view { + // TODO still need this? AsyncOrder.checkPendingOrder(order.accountId); PerpsAccount.validateMaxPositions(order.accountId, order.marketId); LimitOrder.load().isLimitOrderNonceUsed(order.accountId, order.nonce); @@ -273,7 +274,7 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { // only account for negative pnl runtime.currentAvailableMargin += MathUtil.min( - AsyncOrder.calculateStartingPnl(runtime.price, lastPriceCheck, runtime.newPositionSize), + AsyncOrder.calculateFillPricePnl(runtime.price, lastPriceCheck, runtime.amount), 0 ); if (runtime.currentAvailableMargin < runtime.limitOrderFees.toInt()) { @@ -295,6 +296,13 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { if (runtime.currentAvailableMargin < runtime.totalRequiredMargin.toInt()) { revert InsufficientMargin(runtime.currentAvailableMargin, runtime.totalRequiredMargin); } + // TODO add check if this logic below is needed or should be changed + // int256 lockedCreditDelta = perpsMarketData.requiredCreditForSize( + // MathUtil.abs(runtime.newPositionSize).toInt() - MathUtil.abs(oldPosition.size).toInt(), + // PerpsPrice.Tolerance.DEFAULT + // ); + // GlobalPerpsMarket.load().validateMarketCapacity(lockedCreditDelta); + runtime.newPosition = Position.Data({ marketId: runtime.marketId, latestInteractionPrice: order.price.to128(), @@ -323,13 +331,10 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { (runtime.pnl, , runtime.chargedInterest, runtime.accruedFunding, , ) = oldPosition.getPnl( order.price ); - runtime.pnlUint = MathUtil.abs(runtime.pnl); - if (runtime.pnl > 0) { - perpsAccount.updateCollateralAmount(SNX_USD_MARKET_ID, runtime.pnl); - } else if (runtime.pnl < 0) { - runtime.limitOrderFees += runtime.pnlUint; - } + runtime.chargedAmount = runtime.pnl - runtime.limitOrderFees.toInt(); + perpsAccount.charge(runtime.chargedAmount); + emit AccountCharged(runtime.accountId, runtime.chargedAmount, perpsAccount.debt); // after pnl is realized, update position runtime.updateData = PerpsMarket.loadValid(runtime.marketId).updatePositionData( @@ -349,27 +354,6 @@ contract LimitOrderModule is ILimitOrderModule, IMarketEvents, IAccountEvents { runtime.updateData.interestRate ); - // since margin is deposited when trader deposits, as long as the owed collateral is deducted - // from internal accounting, fees are automatically realized by the stakers - if (runtime.limitOrderFees > 0) { - (runtime.deductedSynthIds, runtime.deductedAmount) = perpsAccount.deductFromAccount( - runtime.limitOrderFees - ); - for ( - runtime.synthDeductionIterator = 0; - runtime.synthDeductionIterator < runtime.deductedSynthIds.length; - runtime.synthDeductionIterator++ - ) { - if (runtime.deductedAmount[runtime.synthDeductionIterator] > 0) { - emit CollateralDeducted( - runtime.accountId, - runtime.deductedSynthIds[runtime.synthDeductionIterator], - runtime.deductedAmount[runtime.synthDeductionIterator] - ); - } - } - } - PerpsMarketFactory.Data storage factory = PerpsMarketFactory.load(); (runtime.relayerFees, runtime.feeCollectorFees) = GlobalPerpsMarketConfiguration .load() diff --git a/markets/perps-market/contracts/storage/LimitOrder.sol b/markets/perps-market/contracts/storage/LimitOrder.sol index 2f74374d73..6911641378 100644 --- a/markets/perps-market/contracts/storage/LimitOrder.sol +++ b/markets/perps-market/contracts/storage/LimitOrder.sol @@ -96,19 +96,16 @@ library LimitOrder { uint128 accountId; int128 amount; int256 pnl; - uint256 pnlUint; MarketUpdate.Data updateData; uint256 chargedInterest; Position.Data newPosition; Position.Data oldPosition; - uint256 synthDeductionIterator; - uint128[] deductedSynthIds; - uint256[] deductedAmount; uint256 relayerFees; uint256 feeCollectorFees; int256 accruedFunding; uint256 limitOrderFees; uint256 price; + int256 chargedAmount; } function load() internal pure returns (Data storage limitOrderNonces) { diff --git a/markets/perps-market/test/integration/LimitOrders/OffchainLimitOrder.settleLimitOrder.test.ts b/markets/perps-market/test/integration/LimitOrders/OffchainLimitOrder.settleLimitOrder.test.ts index f350bed584..14fb465161 100644 --- a/markets/perps-market/test/integration/LimitOrders/OffchainLimitOrder.settleLimitOrder.test.ts +++ b/markets/perps-market/test/integration/LimitOrders/OffchainLimitOrder.settleLimitOrder.test.ts @@ -17,7 +17,7 @@ import assertRevert from '@synthetixio/core-utils/utils/assertions/assert-revert // import assert from 'assert'; // import { getTxTime } from '@synthetixio/core-utils/src/utils/hardhat/rpc'; -describe.only('Settle Offchain Limit Order tests', () => { +describe('Settle Offchain Limit Order tests', () => { const { systems, perpsMarkets, synthMarkets, provider, trader1, trader2, signers, owner } = bootstrapMarkets({ synthMarkets: [ @@ -142,7 +142,7 @@ describe.only('Settle Offchain Limit Order tests', () => { const restoreToSnapshot = snapshotCheckpoint(provider); - it.only('settles the orders and emits the proper events', async () => { + it('settles the orders and emits the proper events', async () => { const signedShortOrder = await signOrder( shortOrder, trader1() as ethers.Wallet, @@ -233,10 +233,10 @@ describe.only('Settle Offchain Limit Order tests', () => { 0, ].join(', '), }; - const collateralDeductedEventsArgs = { - trader1: [`${shortOrder.accountId}`, `${0}`, `${limitOrderFeesShort}`].join(', '), - trader2: [`${longOrder.accountId}`, `${0}`, `${limitOrderFeesLong}`].join(', '), - }; + // const collateralDeductedEventsArgs = { + // trader1: [`${shortOrder.accountId}`, `${0}`, `${limitOrderFeesShort}`].join(', '), + // trader2: [`${longOrder.accountId}`, `${0}`, `${limitOrderFeesLong}`].join(', '), + // }; await assertEvent( tx, `LimitOrderSettled(${orderSettledEventsArgs.trader1})`, @@ -257,19 +257,19 @@ describe.only('Settle Offchain Limit Order tests', () => { `MarketUpdated(${marketUpdateEventsArgs.trader2})`, systems().PerpsMarket ); - await assertEvent( - tx, - `CollateralDeducted(${collateralDeductedEventsArgs.trader1})`, - systems().PerpsMarket - ); - await assertEvent( - tx, - `CollateralDeducted(${collateralDeductedEventsArgs.trader2})`, - systems().PerpsMarket - ); + // await assertEvent( + // tx, + // `CollateralDeducted(${collateralDeductedEventsArgs.trader1})`, + // systems().PerpsMarket + // ); + // await assertEvent( + // tx, + // `CollateralDeducted(${collateralDeductedEventsArgs.trader2})`, + // systems().PerpsMarket + // ); }); - it.only('fails to cancel an already completed limit order', async () => { + it('fails to cancel an already completed limit order', async () => { const signedShortOrder = await signOrder( shortOrder, trader1() as ethers.Wallet, @@ -281,7 +281,7 @@ describe.only('Settle Offchain Limit Order tests', () => { ); }); - it.only('successfully cancels a new limit order', async () => { + it('successfully cancels a new limit order', async () => { const newNonceShortOrder = { ...shortOrder, nonce: 197889234 }; const signedNewNonceShortOrder = await signOrder( newNonceShortOrder, @@ -299,7 +299,7 @@ describe.only('Settle Offchain Limit Order tests', () => { ); }); - it.only('fails to cancel a new limit order that is already settled', async () => { + it('fails to cancel a new limit order that is already settled', async () => { const newNonceShortOrder = { ...shortOrder, nonce: 197889234 }; const signedNewNonceShortOrder = await signOrder( newNonceShortOrder,