Skip to content

Commit

Permalink
Testnet Competition Code Changes (#1817)
Browse files Browse the repository at this point in the history
* switch to have payable functions with autofix

* stuff builds, but lint is probably failing

* fix linting issues

* fix solhint plugin payable's resolution

* last lint fix pass

* fix failure in core-contracts

* fix election module build failure

* fix tests

* ERC functions should not be affected by our decisions

* enable basic features on perps market

createAccount is protected by feature flag

* fix compile errors

* add multicall module to spot market cannonfile

* revert ownable module to avoid proxy redeployment

* add amount to collateral price

* change name to size

* preset

* remove price deviation

* change update fee

* Trusted Multicall Forwarder (#1827)

* add trusted forwarder

* update context and change linter

* remove payables

* add new solhint

* successful build

* test fixes

* missing imports

* test fix

* test fix

* lint fix

* spot and perps markets do not need to include

trusted forwarder provision

* remove amount from external func

* use amount instead of 1

* Change getPositionCollateral to only return amount.
- The lets users get a position's collateral amount without having to do a price update due to ERC7412

* comments

* remove payable from multicall in multicallmodule

---------

Co-authored-by: Daniel Beal <[email protected]>
Co-authored-by: Sunny Vempati <[email protected]>
Co-authored-by: joey <[email protected]>
  • Loading branch information
4 people authored Sep 28, 2023
1 parent b51ef06 commit 2651949
Show file tree
Hide file tree
Showing 124 changed files with 670 additions and 721 deletions.
4 changes: 3 additions & 1 deletion .solhint.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": ["solhint:recommended"],
"plugins": ["numcast"],
"plugins": ["numcast", "meta-transactions"],
"rules": {
"not-rely-on-time": "off",
"avoid-low-level-calls": "off",
Expand All @@ -21,6 +21,8 @@
"maxLength": 32
}
],
"meta-transactions/no-msg-sender": "error",
"meta-transactions/no-msg-data": "error",
"numcast/safe-cast": "error"
}
}
13 changes: 10 additions & 3 deletions .solhintignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
*.dump.sol
\*.dump.sol
artifacts/
node_modules/
**/contracts/generated
**/contracts/routers
**/typechain-types
utils/core-contracts/contracts/utils/SafeCast
\*\*/typechain-types
utils/core-contracts/contracts/utils/SafeCast

# files that we cannot change due to immutable proxies

\*\*/contracts/Proxy.sol
utils/core-modules/contracts/modules/UpgradeModule.sol
utils/core-contracts/contracts/ownership/Ownable.sol
utils/core-contracts/contracts/ownership/OwnableStorage.sol
Binary file not shown.
3 changes: 3 additions & 0 deletions markets/legacy-market/cannonfile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,6 @@ func = "setPreferredPool"
args = ["<%= settings.sc_pool_id %>"]
fromCall.func = "owner"
depends = ["invoke.createPool"]

[provision.trusted_multicall_forwarder]
source = "trusted-multicall-forwarder"
15 changes: 8 additions & 7 deletions markets/legacy-market/contracts/LegacyMarket.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import "./interfaces/ILegacyMarket.sol";
import "./interfaces/external/ISynthetix.sol";
import "./interfaces/external/IRewardEscrowV2.sol";

import "@synthetixio/core-contracts/contracts/utils/ERC2771Context.sol";
import "@synthetixio/core-contracts/contracts/ownership/Ownable.sol";
import "@synthetixio/core-contracts/contracts/interfaces/IERC20.sol";
import "@synthetixio/core-contracts/contracts/interfaces/IERC721.sol";
Expand Down Expand Up @@ -46,7 +47,7 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
error Paused();

// solhint-disable-next-line no-empty-blocks
constructor() Ownable(msg.sender) {}
constructor() Ownable(ERC2771Context._msgSender()) {}

/**
* @inheritdoc ILegacyMarket
Expand Down Expand Up @@ -137,7 +138,7 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
IIssuer iss = IIssuer(v2xResolver.getAddress("Issuer"));

// retrieve the sUSD from the user so we can burn it
oldUSD.transferFrom(msg.sender, address(this), amount);
oldUSD.transferFrom(ERC2771Context._msgSender(), address(this), amount);

// now burn it
uint beforeDebt = iss.debtBalanceOf(address(this), "sUSD");
Expand All @@ -147,9 +148,9 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
}

// now mint same amount of snxUSD (called a "withdraw" in v3 land)
v3System.withdrawMarketUsd(marketId, msg.sender, amount);
v3System.withdrawMarketUsd(marketId, ERC2771Context._msgSender(), amount);

emit ConvertedUSD(msg.sender, amount);
emit ConvertedUSD(ERC2771Context._msgSender(), amount);
}

/**
Expand All @@ -160,7 +161,7 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
revert Paused();
}

_migrate(msg.sender, accountId);
_migrate(ERC2771Context._msgSender(), accountId);
}

/**
Expand Down Expand Up @@ -289,7 +290,7 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
function setPauseStablecoinConversion(bool paused) external onlyOwner {
pauseStablecoinConversion = paused;

emit PauseStablecoinConversionSet(msg.sender, paused);
emit PauseStablecoinConversionSet(ERC2771Context._msgSender(), paused);
}

/**
Expand All @@ -298,7 +299,7 @@ contract LegacyMarket is ILegacyMarket, Ownable, UUPSImplementation, IMarket {
function setPauseMigration(bool paused) external onlyOwner {
pauseMigration = paused;

emit PauseMigrationSet(msg.sender, paused);
emit PauseMigrationSet(ERC2771Context._msgSender(), paused);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ interface ILegacyMarket {
* 1. collect all their SNX collateral and debt from v2x
* 2. create a new staking account on v3 with the supplied {accountId}
* 3. put the collateral and debt into this newly created staking account
* 4. send the created staking account to the msg.sender.
* 4. send the created staking account to the ERC2771Context._msgSender().
* @param accountId the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
*/
function migrate(uint128 accountId) external;
Expand Down
14 changes: 6 additions & 8 deletions markets/legacy-market/test/integration/LegacyMarket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,13 @@ describe('LegacyMarket', () => {

// sanity
console.log(
'coll',
'coll', // TODO, what does 'coll' mean here, I'm now changing getPositionCollateral to not return value but only the amount
wei(
(
await v3System.getPositionCollateral(
migratedAccountId,
await v3System.getPreferredPool(),
snxToken.address
)
).value
await v3System.getPositionCollateral(
migratedAccountId,
await v3System.getPreferredPool(),
snxToken.address
)
).toString()
);
assertBn.gte(
Expand Down
16 changes: 16 additions & 0 deletions markets/perps-market/cannonfile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ defaultValue = "synthetix:<%= package.version %>"
[setting.synthetixPreset]
defaultValue = "main"

[setting.spotMarketPreset]
defaultValue = "main"

[setting.spotMarketPackage]
defaultValue = "synthetix-spot-market:<%= package.version %>"

Expand All @@ -28,6 +31,7 @@ preset = "<%= settings.synthetixPreset %>"

[import.spotMarket]
source = "<%= settings.spotMarketPackage %>"
preset = "<%= settings.spotMarketPreset %>"

[contract.PerpsMarketFactoryModule]
artifact = "PerpsMarketFactoryModule"
Expand Down Expand Up @@ -134,3 +138,15 @@ args = [
from = "<%= settings.owner %>"
extra.superMarketId.event = "FactoryInitialized"
extra.superMarketId.arg = 0

[invoke.enableBasicFeatures]
target = ["PerpsMarketProxy"]
fromCall.func = "owner"
func = "multicall"
args = [
[
# for all the below functions, "0x7d632bd2" is the selector for "setFeatureFlagAllowAll(bytes32,bool)"
"0x7d632bd2<%= defaultAbiCoder.encode(['bytes32', 'bool'], [formatBytes32String('createAccount'), true]).slice(2) %>",
]
]
depends = ["invoke.upgrade_proxy"]
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ interface IAsyncOrderModule {
* @param accountId id of the account.
* @return order async order claim details (see AsyncOrder.Data struct).
*/
function getOrder(uint128 accountId) external returns (AsyncOrder.Data memory order);
function getOrder(uint128 accountId) external view returns (AsyncOrder.Data memory order);

/**
* @notice Simulates what the order fee would be for the given market with the specified size.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,11 @@ interface IGlobalPerpsMarketModule {
* @param referrer The address of the referrer
* @return shareRatioD18 The configured share percentage for the referrer
*/
function getReferrerShare(address referrer) external returns (uint256 shareRatioD18);
function getReferrerShare(address referrer) external view returns (uint256 shareRatioD18);

/**
* @notice get all existing market ids
* @return marketIds an array of existing market ids
*/
function getMarkets() external returns (uint256[] memory marketIds);
function getMarkets() external view returns (uint256[] memory marketIds);
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,9 @@ interface ILiquidationModule {
)
external
view
returns (uint capacity, uint256 maxLiquidationInWindow, uint256 latestLiquidationTimestamp);
returns (
uint256 capacity,
uint256 maxLiquidationInWindow,
uint256 latestLiquidationTimestamp
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ interface IPerpsMarketModule {
* @param price Index price.
* @return price Fill price.
*/
function fillPrice(uint128 marketId, int128 orderSize, uint price) external returns (uint);
function fillPrice(uint128 marketId, int128 orderSize, uint price) external view returns (uint);

/**
* @notice Given a marketId return a market's summary details in one call.
Expand Down
1 change: 0 additions & 1 deletion markets/perps-market/contracts/mocks/FeeCollectorMock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ contract FeeCollectorMock is IFeeCollector {
feeRatioD18 = _feeRatio;
}

// solc-ignore-next-line func-mutability
function quoteFees(
uint128 marketId,
uint256 feeAmount,
Expand Down
5 changes: 3 additions & 2 deletions markets/perps-market/contracts/modules/AsyncOrderModule.sol
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.11 <0.9.0;

import "@synthetixio/core-contracts/contracts/utils/ERC2771Context.sol";
import {SafeCastU256, SafeCastI256} from "@synthetixio/core-contracts/contracts/utils/SafeCast.sol";
import {DecimalMath} from "@synthetixio/core-contracts/contracts/utils/DecimalMath.sol";
import {Account} from "@synthetixio/main/contracts/storage/Account.sol";
Expand Down Expand Up @@ -44,7 +45,7 @@ contract AsyncOrderModule is IAsyncOrderModule {
// Check if commitment.accountId is valid
Account.exists(commitment.accountId);

// Check msg.sender can commit order for commitment.accountId
// Check ERC2771Context._msgSender() can commit order for commitment.accountId
Account.loadAccountAndValidatePermission(
commitment.accountId,
AccountRBAC._PERPS_COMMIT_ASYNC_ORDER_PERMISSION
Expand Down Expand Up @@ -86,7 +87,7 @@ contract AsyncOrderModule is IAsyncOrderModule {
order.settlementTime,
order.settlementTime + strategy.settlementWindowDuration,
commitment.trackingCode,
msg.sender
ERC2771Context._msgSender()
);

return (order, feesAccrued);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.11 <0.9.0;

import "@synthetixio/core-contracts/contracts/utils/ERC2771Context.sol";
import {IAsyncOrderSettlementModule} from "../interfaces/IAsyncOrderSettlementModule.sol";
import {SafeCastU256, SafeCastI256} from "@synthetixio/core-contracts/contracts/utils/SafeCast.sol";
import {DecimalMath} from "@synthetixio/core-contracts/contracts/utils/DecimalMath.sol";
Expand Down Expand Up @@ -68,9 +69,12 @@ contract AsyncOrderSettlementModule is IAsyncOrderSettlementModule, IMarketEvent
bytes[] memory updateData = new bytes[](1);
updateData[0] = result;

IPythVerifier verifier = IPythVerifier(settlementStrategy.priceVerificationContract);
uint256 msgValue = verifier.getUpdateFee(1);

IPythVerifier.PriceFeed[] memory priceFeeds = IPythVerifier(
settlementStrategy.priceVerificationContract
).parsePriceFeedUpdates{value: msg.value}(
).parsePriceFeedUpdates{value: msgValue}(
updateData,
priceIds,
order.settlementTime.to64(),
Expand All @@ -80,11 +84,6 @@ contract AsyncOrderSettlementModule is IAsyncOrderSettlementModule, IMarketEvent
IPythVerifier.PriceFeed memory pythData = priceFeeds[0];
uint offchainPrice = _getScaledPrice(pythData.price.price, pythData.price.expo).toUint();

settlementStrategy.checkPriceDeviation(
offchainPrice,
PerpsPrice.getCurrentPrice(order.request.marketId)
);

_settleOrder(offchainPrice, order, settlementStrategy);
}

Expand Down Expand Up @@ -177,7 +176,7 @@ contract AsyncOrderSettlementModule is IAsyncOrderSettlementModule, IMarketEvent

if (runtime.settlementReward > 0) {
// pay keeper
factory.withdrawMarketUsd(msg.sender, runtime.settlementReward);
factory.withdrawMarketUsd(ERC2771Context._msgSender(), runtime.settlementReward);
}

(runtime.referralFees, runtime.feeCollectorFees) = GlobalPerpsMarketConfiguration
Expand Down Expand Up @@ -205,7 +204,7 @@ contract AsyncOrderSettlementModule is IAsyncOrderSettlementModule, IMarketEvent
runtime.feeCollectorFees,
runtime.settlementReward,
asyncOrder.request.trackingCode,
msg.sender
ERC2771Context._msgSender()
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {GlobalPerpsMarketConfiguration} from "../storage/GlobalPerpsMarketConfig
import {GlobalPerpsMarket} from "../storage/GlobalPerpsMarket.sol";
import {IGlobalPerpsMarketModule} from "../interfaces/IGlobalPerpsMarketModule.sol";
import {OwnableStorage} from "@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol";
import "@synthetixio/core-contracts/contracts/errors/AddressError.sol";
import "@synthetixio/core-contracts/contracts/errors/ParameterError.sol";
import {AddressError} from "@synthetixio/core-contracts/contracts/errors/AddressError.sol";
import {ParameterError} from "@synthetixio/core-contracts/contracts/errors/ParameterError.sol";

/**
* @title Module for global Perps Market settings.
Expand All @@ -26,7 +26,7 @@ contract GlobalPerpsMarketModule is IGlobalPerpsMarketModule {
*/
function setMaxCollateralAmount(
uint128 synthMarketId,
uint collateralAmount
uint256 collateralAmount
) external override {
OwnableStorage.onlyOwner();
GlobalPerpsMarketConfiguration.Data storage store = GlobalPerpsMarketConfiguration.load();
Expand All @@ -38,7 +38,9 @@ contract GlobalPerpsMarketModule is IGlobalPerpsMarketModule {
/**
* @inheritdoc IGlobalPerpsMarketModule
*/
function getMaxCollateralAmount(uint128 synthMarketId) external view override returns (uint) {
function getMaxCollateralAmount(
uint128 synthMarketId
) external view override returns (uint256) {
return GlobalPerpsMarketConfiguration.load().maxCollateralAmounts[synthMarketId];
}

Expand Down
8 changes: 6 additions & 2 deletions markets/perps-market/contracts/modules/LiquidationModule.sol
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.11 <0.9.0;

import "@synthetixio/core-contracts/contracts/utils/ERC2771Context.sol";
import {DecimalMath} from "@synthetixio/core-contracts/contracts/utils/DecimalMath.sol";
import {MathUtil} from "../utils/MathUtil.sol";
import {SafeCastU256} from "@synthetixio/core-contracts/contracts/utils/SafeCast.sol";
Expand Down Expand Up @@ -170,7 +171,10 @@ contract LiquidationModule is ILiquidationModule, IMarketEvents {
.calculateLiquidationReward(amountLiquidated.mulDecimal(price));

// endorsed liquidators do not get liquidation rewards
if (msg.sender != PerpsMarketConfiguration.load(positionMarketId).endorsedLiquidator) {
if (
ERC2771Context._msgSender() !=
PerpsMarketConfiguration.load(positionMarketId).endorsedLiquidator
) {
accumulatedLiquidationRewards += liquidationReward;
}
}
Expand All @@ -195,7 +199,7 @@ contract LiquidationModule is ILiquidationModule, IMarketEvents {
// pay out liquidation rewards
reward = GlobalPerpsMarketConfiguration.load().liquidationReward(totalRewards);
if (reward > 0) {
PerpsMarketFactory.load().withdrawMarketUsd(msg.sender, reward);
PerpsMarketFactory.load().withdrawMarketUsd(ERC2771Context._msgSender(), reward);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {OwnableStorage} from "@synthetixio/core-contracts/contracts/ownership/Ow
import {IMarketConfigurationModule} from "../interfaces/IMarketConfigurationModule.sol";
import {SettlementStrategy} from "../storage/SettlementStrategy.sol";
import {PerpsMarketConfiguration} from "../storage/PerpsMarketConfiguration.sol";
import {PerpsMarket} from "../storage/PerpsMarket.sol";
import {PerpsPrice} from "../storage/PerpsPrice.sol";

/**
Expand Down
Loading

0 comments on commit 2651949

Please sign in to comment.