Skip to content

Commit

Permalink
fix first stackTooDeep in
Browse files Browse the repository at this point in the history
  • Loading branch information
dextracker committed Dec 18, 2023
1 parent b60c21a commit ba02111
Show file tree
Hide file tree
Showing 39 changed files with 20,448 additions and 486 deletions.
9 changes: 9 additions & 0 deletions aloe-ii/core/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export RPC_URL_MAINNET=https://eth-mainnet.g.alchemy.com/v2/_Sv9JWIldgWGapD4grHrFVQdvKyy-N0H
export RPC_URL_GOERLI=https://eth-goerli.g.alchemy.com/v2/tX_qmYCeo3HNFhdm8KXvSaRgT_MLkNST
export RPC_URL_OPTIMISM=https://opt-mainnet.g.alchemy.com/v2/dY3taoK4h07jMTDBfkCQGRlXOKecD2IK
export RPC_URL_ARBITRUM=https://arb-mainnet.g.alchemy.com/v2/WES3TWN1eD-C4RZJLr-E1WcboStJC-jV
export RPC_URL_BASE=https://base-mainnet.g.alchemy.com/v2/GLUD5c1BQgqI5-VvmisvY7gqjYiMMmBv
export ETHERSCAN_API_KEY=E26IME9PQXTNM9I2QIAAB2FHXBSUJY78DP
export ETHERSCAN_API_KEY_OPTIMISM=13BS8ICIS7HJKTS8DWP2ISDMTJKF465MZT
export ETHERSCAN_API_KEY_ARBITRUM=X483HXP3UJHZZ31CW1TYGKPE57KB8EZE5Z
export ETHERSCAN_API_KEY_BASE=E26IME9PQXTNM9I2QIAAB2FHXBSUJY78DP
3 changes: 1 addition & 2 deletions aloe-ii/core/foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
src = 'src'
test = 'test'
libs = ['lib']

solc_version = "0.8.17"
out = 'build'
cache_path = 'cache'

Expand All @@ -16,7 +16,6 @@ auto_detect_remappings = false
remappings = [
'ds-test/=lib/forge-std/lib/ds-test/src/',
'forge-std/=lib/forge-std/src/',

'clones-with-immutable-args/=lib/clones-with-immutable-args/src/',
'openzeppelin-contracts/=lib/openzeppelin-contracts/',
'solady/=lib/solady/src/',
Expand Down
29 changes: 14 additions & 15 deletions aloe-ii/core/src/Borrower.sol
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ contract Borrower is IUniswapV3MintCallback {
}

uint256 private constant SLOT0_MASK_POSITIONS = 0x000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 private constant SLOT0_MASK_UNLEASH = 0x00ffffffffff0000000000000000000000000000000000000000000000000000; // prettier-ignore
uint256 private constant SLOT0_MASK_STATE = 0x7f00000000000000000000000000000000000000000000000000000000000000; // prettier-ignore
uint256 private constant SLOT0_DIRT = 0x8000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore
uint256 private constant SLOT0_MASK_UNLEASH = 0x00ffffffffff0000000000000000000000000000000000000000000000000000; // prettier-ignore
uint256 private constant SLOT0_MASK_STATE = 0x7f00000000000000000000000000000000000000000000000000000000000000; // prettier-ignore
uint256 private constant SLOT0_DIRT = 0x8000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore

/// @notice The factory that created this contract
Factory public immutable FACTORY;
Expand Down Expand Up @@ -159,7 +159,7 @@ contract Borrower is IUniswapV3MintCallback {

{
// Fetch prices from oracle
(Prices memory prices, ) = getPrices(oracleSeed);
(Prices memory prices,) = getPrices(oracleSeed);
// Tally assets without actually withdrawing Uniswap positions
Assets memory assets = _getAssets(slot0_, prices, false);
// Fetch liabilities from lenders
Expand Down Expand Up @@ -203,7 +203,7 @@ contract Borrower is IUniswapV3MintCallback {
uint256 incentive1;
{
// Fetch prices from oracle
(Prices memory prices, ) = getPrices(oracleSeed);
(Prices memory prices,) = getPrices(oracleSeed);
priceX128 = square(prices.c);
// Withdraw Uniswap positions while tallying assets
Assets memory assets = _getAssets(slot0_, prices, true);
Expand Down Expand Up @@ -382,7 +382,11 @@ contract Borrower is IUniswapV3MintCallback {
int24 upper,
uint128 liquidity,
address recipient
) external onlyInModifyCallback returns (uint256 burned0, uint256 burned1, uint256 collected0, uint256 collected1) {
)
external
onlyInModifyCallback
returns (uint256 burned0, uint256 burned1, uint256 collected0, uint256 collected1)
{
(burned0, burned1, collected0, collected1) = _uniswapWithdraw(lower, upper, liquidity, recipient);
}

Expand Down Expand Up @@ -464,7 +468,7 @@ contract Borrower is IUniswapV3MintCallback {
* @return seemsLegit Whether the Uniswap TWAP seems to have been manipulated or not
*/
function getPrices(uint40 oracleSeed) public view returns (Prices memory prices, bool seemsLegit) {
(, uint8 nSigma, uint8 manipulationThresholdDivisor, ) = FACTORY.getParameters(UNISWAP_POOL);
(, uint8 nSigma, uint8 manipulationThresholdDivisor,) = FACTORY.getParameters(UNISWAP_POOL);
(prices, seemsLegit) = _getPrices(oracleSeed, nSigma, manipulationThresholdDivisor);
}

Expand All @@ -478,13 +482,8 @@ contract Borrower is IUniswapV3MintCallback {
// compute current price and volatility
(metric, prices.c, iv) = ORACLE.consult(UNISWAP_POOL, oracleSeed);
// compute prices at which solvency will be checked
(prices.a, prices.b, seemsLegit) = BalanceSheet.computeProbePrices(
metric,
prices.c,
iv,
nSigma,
manipulationThresholdDivisor
);
(prices.a, prices.b, seemsLegit) =
BalanceSheet.computeProbePrices(metric, prices.c, iv, nSigma, manipulationThresholdDivisor);
}

function _getAssets(uint256 slot0_, Prices memory prices, bool withdraw) private returns (Assets memory assets) {
Expand All @@ -499,7 +498,7 @@ contract Borrower is IUniswapV3MintCallback {
int24 l = positions[i];
int24 u = positions[i + 1];
// Fetch amount of `liquidity` in the position
(uint128 liquidity, , , , ) = UNISWAP_POOL.positions(keccak256(abi.encodePacked(address(this), l, u)));
(uint128 liquidity,,,,) = UNISWAP_POOL.positions(keccak256(abi.encodePacked(address(this), l, u)));

if (liquidity == 0) continue;

Expand Down
30 changes: 18 additions & 12 deletions aloe-ii/core/src/Factory.sol
Original file line number Diff line number Diff line change
Expand Up @@ -284,18 +284,24 @@ contract Factory {

require(
// ante: max
(config.ante <= CONSTRAINT_ANTE_MAX) &&
// nSigma: min, max
(CONSTRAINT_N_SIGMA_MIN <= config.nSigma && config.nSigma <= CONSTRAINT_N_SIGMA_MAX) &&
// manipulationThresholdDivisor: min, max
(CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MIN <= config.manipulationThresholdDivisor &&
config.manipulationThresholdDivisor <= CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MAX) &&
// reserveFactor0: min, max
(CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor0 &&
config.reserveFactor0 <= CONSTRAINT_RESERVE_FACTOR_MAX) &&
// reserveFactor1: min, max
(CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor1 &&
config.reserveFactor1 <= CONSTRAINT_RESERVE_FACTOR_MAX),
(config.ante <= CONSTRAINT_ANTE_MAX)
// nSigma: min, max
&& (CONSTRAINT_N_SIGMA_MIN <= config.nSigma && config.nSigma <= CONSTRAINT_N_SIGMA_MAX)
// manipulationThresholdDivisor: min, max
&& (
CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MIN <= config.manipulationThresholdDivisor
&& config.manipulationThresholdDivisor <= CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MAX
)
// reserveFactor0: min, max
&& (
CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor0
&& config.reserveFactor0 <= CONSTRAINT_RESERVE_FACTOR_MAX
)
// reserveFactor1: min, max
&& (
CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor1
&& config.reserveFactor1 <= CONSTRAINT_RESERVE_FACTOR_MAX
),
"Aloe: constraints"
);

Expand Down
34 changes: 14 additions & 20 deletions aloe-ii/core/src/Ledger.sol
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,8 @@ contract Ledger {

/// @notice Returns true if this contract implements the interface defined by `interfaceId`
function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC2612).interfaceId ||
interfaceId == type(IERC4626).interfaceId;
return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC2612).interfaceId
|| interfaceId == type(IERC4626).interfaceId;
}

/// @notice The name of the banknote.
Expand Down Expand Up @@ -126,15 +124,14 @@ contract Ledger {

/// @notice The domain separator for EIP-2612
function DOMAIN_SEPARATOR() public view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string version,uint256 chainId,address verifyingContract)"),
keccak256("1"),
block.chainid,
address(this)
)
);
return keccak256(
abi.encode(
keccak256("EIP712Domain(string version,uint256 chainId,address verifyingContract)"),
keccak256("1"),
block.chainid,
address(this)
)
);
}

/**
Expand Down Expand Up @@ -216,7 +213,7 @@ contract Ledger {
function borrowBalance(address account) external view returns (uint256) {
uint256 b = borrows[account];

(Cache memory cache, , ) = _previewInterest(_getCache());
(Cache memory cache,,) = _previewInterest(_getCache());
unchecked {
return b > 1 ? ((b - 1) * cache.borrowIndex).unsafeDivUp(BORROWS_SCALER) : 0;
}
Expand All @@ -241,7 +238,7 @@ contract Ledger {
* the up-to-date supply, use `stats()`
*/
function totalAssets() external view returns (uint256) {
(, uint256 inventory, ) = _previewInterest(_getCache());
(, uint256 inventory,) = _previewInterest(_getCache());
return inventory;
}

Expand Down Expand Up @@ -357,11 +354,8 @@ contract Ledger {
cache.lastAccrualTime = 0; // 0 in storage means locked to reentrancy; 0 in `cache` means `borrowIndex` was updated

uint256 newInventory = cache.lastBalance + (cache.borrowBase * cache.borrowIndex) / BORROWS_SCALER;
uint256 newTotalSupply = Math.mulDiv(
cache.totalSupply,
newInventory,
newInventory - (newInventory - oldInventory) / rf
);
uint256 newTotalSupply =
Math.mulDiv(cache.totalSupply, newInventory, newInventory - (newInventory - oldInventory) / rf);
return (cache, newInventory, newTotalSupply);
}
}
Expand Down
26 changes: 11 additions & 15 deletions aloe-ii/core/src/Lender.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,7 @@ contract Lender is Ledger {
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);

event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares
);

event Borrow(address indexed caller, address indexed recipient, uint256 amount, uint256 units);
Expand Down Expand Up @@ -118,13 +114,13 @@ contract Lender is Ledger {

require(
// Callers are free to set their own courier, but they need permission to mess with others'
(msg.sender == beneficiary || allowance[beneficiary][msg.sender] != 0) &&
// Prevent `RESERVE` from having a courier, since its principle wouldn't be tracked properly
(beneficiary != RESERVE) &&
// Payout logic can't handle self-reference, so don't let accounts credit themselves
(beneficiary != courier) &&
// Make sure `cut` has been set
(cut != 0),
(msg.sender == beneficiary || allowance[beneficiary][msg.sender] != 0)
// Prevent `RESERVE` from having a courier, since its principle wouldn't be tracked properly
&& (beneficiary != RESERVE)
// Payout logic can't handle self-reference, so don't let accounts credit themselves
&& (beneficiary != courier)
// Make sure `cut` has been set
&& (cut != 0),
"Aloe: courier"
);
}
Expand Down Expand Up @@ -218,7 +214,7 @@ contract Lender is Ledger {
require(b != 0, "Aloe: not a borrower");

// Accrue interest and update reserves
(Cache memory cache, ) = _load();
(Cache memory cache,) = _load();

unchecked {
// Convert `amount` to `units`
Expand Down Expand Up @@ -258,7 +254,7 @@ contract Lender is Ledger {
uint256 b = borrows[beneficiary];

// Accrue interest and update reserves
(Cache memory cache, ) = _load();
(Cache memory cache,) = _load();

unchecked {
// Convert `amount` to `units`
Expand Down Expand Up @@ -309,7 +305,7 @@ contract Lender is Ledger {
}

function accrueInterest() external returns (uint72) {
(Cache memory cache, ) = _load();
(Cache memory cache,) = _load();
_save(cache, /* didChangeBorrowBase: */ false);
return uint72(cache.borrowIndex);
}
Expand Down
11 changes: 4 additions & 7 deletions aloe-ii/core/src/VolatilityOracle.sol
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ contract VolatilityOracle {
}

function _getPoolMetadata(IUniswapV3Pool pool) private view returns (Volatility.PoolMetadata memory metadata) {
(, , uint16 observationIndex, uint16 observationCardinality, , uint8 feeProtocol, ) = pool.slot0();
(,, uint16 observationIndex, uint16 observationCardinality,, uint8 feeProtocol,) = pool.slot0();
// We want observations from `UNISWAP_AVG_WINDOW` and `UNISWAP_AVG_WINDOW * 2` seconds ago. Since observation
// frequency varies with `pool` usage, we apply an extra 3x safety factor. If `pool` usage increases,
// oracle cardinality may need to be increased as well. This should be monitored off-chain.
Expand All @@ -120,12 +120,9 @@ contract VolatilityOracle {
}

function _getFeeGrowthGlobalsNow(IUniswapV3Pool pool) private view returns (Volatility.FeeGrowthGlobals memory) {
return
Volatility.FeeGrowthGlobals(
pool.feeGrowthGlobal0X128(),
pool.feeGrowthGlobal1X128(),
uint32(block.timestamp)
);
return Volatility.FeeGrowthGlobals(
pool.feeGrowthGlobal0X128(), pool.feeGrowthGlobal1X128(), uint32(block.timestamp)
);
}

function _getFeeGrowthGlobalsOld(
Expand Down
16 changes: 6 additions & 10 deletions aloe-ii/core/src/libraries/BalanceSheet.sol
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,10 @@ library BalanceSheet {
) internal pure returns (bool) {
unchecked {
// The optimizer eliminates the conditional in `divUp`; don't worry about gas golfing that
liabilities0 +=
liabilities0.divUp(MAX_LEVERAGE) +
liabilities0.zeroFloorSub(mem.fixed0 + mem.fluid0C).divUp(LIQUIDATION_INCENTIVE);
liabilities1 +=
liabilities1.divUp(MAX_LEVERAGE) +
liabilities1.zeroFloorSub(mem.fixed1 + mem.fluid1C).divUp(LIQUIDATION_INCENTIVE);
liabilities0 += liabilities0.divUp(MAX_LEVERAGE)
+ liabilities0.zeroFloorSub(mem.fixed0 + mem.fluid0C).divUp(LIQUIDATION_INCENTIVE);
liabilities1 += liabilities1.divUp(MAX_LEVERAGE)
+ liabilities1.zeroFloorSub(mem.fixed1 + mem.fluid1C).divUp(LIQUIDATION_INCENTIVE);
}

// combine
Expand Down Expand Up @@ -100,10 +98,8 @@ library BalanceSheet {
) internal pure returns (uint160 a, uint160 b, bool seemsLegit) {
unchecked {
// Essentially sqrt(e^{nSigma*iv}). Note the `Factory` defines `nSigma` with an extra factor of 10
uint256 sqrtScaler = uint256(exp1e12(int256((nSigma * iv) / 20))).clamp(
PROBE_SQRT_SCALER_MIN,
PROBE_SQRT_SCALER_MAX
);
uint256 sqrtScaler =
uint256(exp1e12(int256((nSigma * iv) / 20))).clamp(PROBE_SQRT_SCALER_MIN, PROBE_SQRT_SCALER_MAX);

seemsLegit = metric < _manipulationThreshold(_ltv(sqrtScaler), manipulationThresholdDivisor);

Expand Down
7 changes: 2 additions & 5 deletions aloe-ii/core/src/libraries/LiquidityAmounts.sol
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,8 @@ library LiquidityAmounts {
unchecked {
if (sqrtRatioX96 <= sqrtRatioAX96) {
uint256 priceX128 = square(sqrtRatioX96);
uint256 amount0XSqrtRatioAX64 = Math.mulDiv(
uint256(liquidity) << 64,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
);
uint256 amount0XSqrtRatioAX64 =
Math.mulDiv(uint256(liquidity) << 64, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96);

value0 = Math.mulDiv(amount0XSqrtRatioAX64, priceX128, uint256(sqrtRatioAX96) << 96);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
Expand Down
19 changes: 8 additions & 11 deletions aloe-ii/core/src/libraries/Log2.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ function msb(uint256 x) pure returns (uint256 y) {
x := or(x, shr(8, x))
x := or(x, shr(16, x))

y := or(
y,
byte(
shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
y :=
or(
y,
byte(
shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
)
)
)
}
}

Expand Down Expand Up @@ -201,11 +202,7 @@ function log2(uint256 x, uint8 iters) pure returns (int256 result) {
result = (int256(n) - 128) << 64;

assembly ("memory-safe") {
for {
let i := 1
} lt(i, add(iters, 1)) {
i := add(i, 1)
} {
for { let i := 1 } lt(i, add(iters, 1)) { i := add(i, 1) } {
y := shr(127, mul(y, y))
let isGe2 := shr(128, y)
result := or(result, shl(sub(64, i), isGe2))
Expand Down
Loading

0 comments on commit ba02111

Please sign in to comment.