Skip to content

Commit

Permalink
rebase off main and start working on multi collateral and other recen…
Browse files Browse the repository at this point in the history
…t changes
  • Loading branch information
fredsnax committed Aug 16, 2024
1 parent b56b7a7 commit db82548
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 55 deletions.
48 changes: 16 additions & 32 deletions markets/perps-market/contracts/modules/LimitOrderModule.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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()) {
Expand All @@ -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(),
Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down
5 changes: 1 addition & 4 deletions markets/perps-market/contracts/storage/LimitOrder.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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})`,
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down

0 comments on commit db82548

Please sign in to comment.