Verified contractPartialMIT
GoldEngine
Address0x30bed991eb10a60dc45223ff3daa58f84e9d6d98
- Balance
0 ETH
- Transactions
78
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,129,285
- Creation transaction
- 0x9d20148441…f548efc67c
7 files
- src/pad/engine/GoldEngine.solmain34.12 KB
- lib/solady/src/utils/SafeTransferLib.sol32.8 KB
- lib/v4-core/src/libraries/BitMath.sol2.61 KB
- lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/src/libraries/FullMath.sol5.46 KB
- lib/v4-core/src/libraries/TickMath.sol12.38 KB
- src/pad/engine/EngineExternal.sol3.07 KB
src/pad/engine/GoldEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {
IAavePool, IChainlinkFeed, IUniV3Pool, ReserveDataLegacy, EModeCollateralConfig
} from "./EngineExternal.sol";
/// @title EngineCourier
/// @notice The engine's hands. It receives swap outputs and inflows and moves them into Aave ON BEHALF OF the engine,
/// so the engine itself never has to send XAUT or USDT on the safety paths (delever, harvest). A Tether blocklist
/// of the engine address then cannot stop a delever or a harvest (Aave's aToken sends the XAUT, not the engine).
/// @dev Only the engine can call it; it can only (a) supply its XAUT to Aave for the engine, (b) repay the engine's
/// USDT debt with its USDT, (c) send its XAUT to the RatchetSink (the floor). Nothing else, no admin.
contract EngineCourier {
using SafeTransferLib for address;
address public immutable ENGINE;
address public immutable AAVE;
address public immutable XAUT;
address public immutable USDT;
address public immutable SINK;
error NotEngine();
constructor(address aave, address xaut, address usdt, address sink) {
ENGINE = msg.sender;
AAVE = aave;
XAUT = xaut;
USDT = usdt;
SINK = sink;
xaut.safeApproveWithRetry(aave, type(uint256).max);
usdt.safeApproveWithRetry(aave, type(uint256).max);
}
modifier onlyEngine() {
if (msg.sender != ENGINE) revert NotEngine();
_;
}
function supply() external onlyEngine returns (uint256 a) {
a = XAUT.balanceOf(address(this));
if (a != 0) IAavePool(AAVE).supply(XAUT, a, ENGINE, 0);
}
function repay() external onlyEngine returns (uint256 r) {
uint256 a = USDT.balanceOf(address(this));
if (a != 0) r = IAavePool(AAVE).repay(USDT, a, 2, ENGINE);
}
function toSink() external onlyEngine returns (uint256 a) {
a = XAUT.balanceOf(address(this));
if (a != 0) XAUT.safeTransfer(SINK, a);
}
}
/// @title GoldEngine
/// @notice KINEKO's second backing layer: gold levered ~1.5x beside the pool, with a RATCHET into the hard floor.
/// XAUT is supplied to Aave v3 (eMode "XAUt / USDC, USDT, GHO": LTV 70%, LT 75%), USDT is borrowed and swapped
/// into more XAUT on the USDT/XAUT 0.05% v3 pool. When the engine's equity measured IN GOLD rises above its
/// high-water mark (net of interest and every cost), the gain is withdrawn straight from Aave into the
/// RatchetSink, which feeds KINEKO's floor band. Losses only shrink the engine.
///
/// Rules (all mechanical, no discretion, no admin over funds):
/// - leverage band [MIN, MAX] around TARGET (1.35x / 1.65x / 1.5x); keeper-first lever-up, delever by anyone;
/// - the target scales down linearly to 1.0x as the engine's gold equity falls from 100% to DD_FLOOR of its HWM;
/// - no new leverage while USDT's averaged borrow rate > LEVER_RATE_MAX, full unwind while it is > RISK_OFF_RATE,
/// or if Aave freezes XAUT or lowers the eMode LTV/LT;
/// - harvest at most once per HARVEST_INTERVAL, only gains above the HWM, valued at min(Chainlink, 30-min TWAP),
/// only with both oracles agreeing, capped so leverage after the harvest stays <= HARVEST_MAX_LEV;
/// - the engine holds no reference to the PoolManager, the hook or the floor band: its only outbound token paths are
/// the v3 pool (swap payment), Aave (supply / repay) and the RatchetSink (-> feedFloor). It cannot reduce the floor.
contract GoldEngine {
using SafeTransferLib for address;
// ------------------------------------------------------------------ errors / events
error ZeroAddress();
error BadConfig();
error Reentrant();
error NotPool();
error NotKeeperAdmin();
error ZeroAmount();
error OracleDown();
error OracleUnhealthy();
error NothingToDo();
error NothingToHarvest();
error TooEarly();
error Cooldown();
error RateTooHigh();
error LenderBroken();
error KeeperOnly();
error Slippage();
error Unhealthy();
error NotRetirable();
error Retired();
event Funded(address indexed from, uint256 xaut, bool principal);
event Overflow(address indexed from, uint256 xaut);
event Levered(address indexed caller, uint256 usdtBorrowed, uint256 xautBought, uint256 leverageBps);
event Delevered(address indexed caller, uint256 usdtRepaid, uint256 xautSold, uint256 leverageBps, bool emergency);
event Harvested(address indexed caller, uint256 xaut, uint256 equityGold, uint256 hwmAfter, uint256 price18);
event RetiredToFloor(uint256 xaut);
event KeeperSet(address indexed keeper, bool on);
event KeeperAdminSet(address indexed admin);
// ------------------------------------------------------------------ config
struct Params {
uint16 targetBps; // 15000 = 1.5x
uint16 minBps; // 13500
uint16 maxBps; // 16500
uint16 emergBps; // 18000: delever with the wide slippage, no cooldown, no oracle-agreement requirement
uint16 ddFloorBps; // 6000: target -> 1.0x when equity <= 60% of HWM (0 = off)
uint16 harvestMaxLevBps; // 16000: leverage after a harvest
uint16 harvestShareBps; // 10000 = 100% of the gain above the HWM goes to the floor
uint16 maxHarvestBps; // 1000: one harvest <= 10% of equity
uint16 minGainBps; // 20: ignore gains below 0.2% of the HWM
uint16 slipBps; // 75
uint16 emergSlipBps; // 300
uint16 devBps; // 300: Chainlink vs TWAP agreement (markets open)
uint16 devClosedBps; // 500: when Chainlink is older than CL_CLOSED_AGE (weekend / holiday)
uint16 minLtvBps; // 7000: expected eMode LTV; lower -> risk-off
uint16 minLtBps; // 7500: expected eMode LT; lower -> risk-off
uint32 harvestInterval; // 1 days
uint32 clMaxAge; // 26 hours (24 h heartbeat)
uint32 clClosedAge; // 6 hours
uint32 twapWindow; // 1800 s
uint32 publicLeverDelay; // 1 days: anyone may lever up if no keeper acted for this long
uint32 leverCooldown; // 1 hours
uint32 deleverCooldown; // 60 s
uint32 retireAfter; // 180 days of continuous risk-off with zero debt -> everything to the floor
uint64 leverRateMax; // 0.10e18 (APR, 1e18 = 100%)
uint64 riskOffRate; // 0.15e18
uint64 hfMinPost; // 1.3e18: Aave HF after a lever or a harvest
uint64 hfEmerg; // 1.25e18: HF below this = emergency delever
uint128 maxStepUsdt; // 250_000e6 per rebalance call
uint128 capXaut; // 250e6: principal cap; inflows above it go straight to the floor
}
IAavePool public immutable AAVE;
address public immutable XAUT;
address public immutable USDT;
address public immutable A_XAUT;
address public immutable VDEBT_USDT;
IUniV3Pool public immutable POOL; // USDT/XAUT 0.05%: token0 = XAUT, token1 = USDT
IChainlinkFeed public immutable CL_XAU_USD;
address public immutable SINK;
EngineCourier public immutable COURIER;
uint8 public immutable EMODE;
uint256 internal immutable TARGET;
uint256 internal immutable MIN;
uint256 internal immutable MAX;
uint256 internal immutable EMERG;
uint256 internal immutable DD_FLOOR;
uint256 internal immutable HARVEST_MAX_LEV;
uint256 internal immutable HARVEST_SHARE;
uint256 internal immutable MAX_HARVEST;
uint256 internal immutable MIN_GAIN;
uint256 internal immutable SLIP;
uint256 internal immutable EMERG_SLIP;
uint256 internal immutable DEV;
uint256 internal immutable DEV_CLOSED;
uint256 internal immutable MIN_LTV;
uint256 internal immutable MIN_LT;
uint256 internal immutable HARVEST_INTERVAL;
uint256 internal immutable CL_MAX_AGE;
uint256 internal immutable CL_CLOSED_AGE;
uint32 internal immutable TWAP_WINDOW;
uint256 internal immutable PUBLIC_LEVER_DELAY;
uint256 internal immutable LEVER_COOLDOWN;
uint256 internal immutable DELEVER_COOLDOWN;
uint256 internal immutable RETIRE_AFTER;
uint256 internal immutable LEVER_RATE_MAX;
uint256 internal immutable RISK_OFF_RATE;
uint256 internal immutable HF_MIN_POST;
uint256 internal immutable HF_EMERG;
uint256 internal immutable MAX_STEP;
uint256 internal immutable CAP;
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
uint256 internal constant BPS = 10_000;
// ------------------------------------------------------------------ state
/// @notice high-water mark of the engine's equity, in raw XAUT. Never decreases.
uint256 public hwm;
uint256 public funded; // principal received (raised the HWM)
uint256 public served; // pass-through inflows (did not raise the HWM: they fill a loss first, then go to the floor)
uint256 public overflowed; // inflows sent straight to the floor (cap reached / supply blocked / retired)
uint256 public harvested; // XAUT moved into the floor by harvests
uint64 public lastHarvest;
uint64 public lastRebalance;
uint64 public lastLever;
uint64 public lastKeeperAction;
uint64 public riskOffSince; // first observation of the current continuous risk-off period (0 = not risk-off)
bool public retired;
struct RateSnap {
uint128 index;
uint64 time;
}
RateSnap public snapOld;
RateSnap public snapNew;
address public keeperAdmin;
mapping(address => bool) public isKeeper;
// transient slots
uint256 private constant LOCK_SLOT = 0x4f1e6c5f0b4e0b9f8c7a5d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f00;
uint256 private constant SWAP_MODE_SLOT = 0x4f1e6c5f0b4e0b9f8c7a5d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f01;
uint256 private constant SWAP_BOUND_SLOT = 0x4f1e6c5f0b4e0b9f8c7a5d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f02;
uint256 private constant MODE_BUY = 1;
uint256 private constant MODE_SELL = 2;
constructor(
IAavePool aave,
address xaut,
address usdt,
IUniV3Pool pool,
IChainlinkFeed clXauUsd,
address sink,
uint8 eModeId,
address keeperAdmin_,
address[] memory keepers,
Params memory p
) {
if (
address(aave) == address(0) || xaut == address(0) || usdt == address(0) || address(pool) == address(0)
|| address(clXauUsd) == address(0) || sink == address(0) || keeperAdmin_ == address(0)
) revert ZeroAddress();
// parameter sanity (the deployed engine is immutable)
if (
p.minBps < BPS || p.minBps > p.targetBps || p.targetBps > p.maxBps || p.maxBps > p.emergBps
|| p.emergBps > 25_000 || p.harvestMaxLevBps < p.targetBps || p.harvestMaxLevBps > p.maxBps
|| p.harvestShareBps == 0 || p.harvestShareBps > BPS || p.maxHarvestBps == 0 || p.maxHarvestBps > BPS
|| p.ddFloorBps >= BPS || p.slipBps == 0 || p.slipBps > p.emergSlipBps || p.emergSlipBps > 1000
|| p.devBps == 0 || p.devClosedBps < p.devBps || p.twapWindow < 600 || p.clMaxAge == 0
|| p.riskOffRate < p.leverRateMax || p.hfMinPost < 1.1e18 || p.hfEmerg < 1.05e18 || p.maxStepUsdt == 0
|| p.capXaut == 0
) revert BadConfig();
// the engine's own leverage limits must sit well inside Aave's eMode limits
EModeCollateralConfig memory em = aave.getEModeCategoryCollateralConfig(eModeId);
if (em.ltv < p.minLtvBps || em.liquidationThreshold < p.minLtBps) revert BadConfig();
// max LTV the engine ever targets: 1 - 1/emerg; must be < eMode LTV
if ((BPS - BPS * BPS / p.emergBps) >= em.ltv) revert BadConfig();
if (pool.token0() != xaut || pool.token1() != usdt) revert BadConfig();
if (clXauUsd.decimals() != 8) revert BadConfig();
AAVE = aave;
XAUT = xaut;
USDT = usdt;
POOL = pool;
CL_XAU_USD = clXauUsd;
SINK = sink;
EMODE = eModeId;
A_XAUT = aave.getReserveData(xaut).aTokenAddress;
VDEBT_USDT = aave.getReserveData(usdt).variableDebtTokenAddress;
if (A_XAUT == address(0) || VDEBT_USDT == address(0)) revert BadConfig();
TARGET = p.targetBps;
MIN = p.minBps;
MAX = p.maxBps;
EMERG = p.emergBps;
DD_FLOOR = p.ddFloorBps;
HARVEST_MAX_LEV = p.harvestMaxLevBps;
HARVEST_SHARE = p.harvestShareBps;
MAX_HARVEST = p.maxHarvestBps;
MIN_GAIN = p.minGainBps;
SLIP = p.slipBps;
EMERG_SLIP = p.emergSlipBps;
DEV = p.devBps;
DEV_CLOSED = p.devClosedBps;
MIN_LTV = p.minLtvBps;
MIN_LT = p.minLtBps;
HARVEST_INTERVAL = p.harvestInterval;
CL_MAX_AGE = p.clMaxAge;
CL_CLOSED_AGE = p.clClosedAge;
TWAP_WINDOW = p.twapWindow;
PUBLIC_LEVER_DELAY = p.publicLeverDelay;
LEVER_COOLDOWN = p.leverCooldown;
DELEVER_COOLDOWN = p.deleverCooldown;
RETIRE_AFTER = p.retireAfter;
LEVER_RATE_MAX = p.leverRateMax;
RISK_OFF_RATE = p.riskOffRate;
HF_MIN_POST = p.hfMinPost;
HF_EMERG = p.hfEmerg;
MAX_STEP = p.maxStepUsdt;
CAP = p.capXaut;
COURIER = new EngineCourier(address(aave), xaut, usdt, sink);
aave.setUserEMode(eModeId);
keeperAdmin = keeperAdmin_;
lastKeeperAction = uint64(block.timestamp); // the public lever-up fallback opens PUBLIC_LEVER_DELAY after deploy
for (uint256 i; i < keepers.length; ++i) {
isKeeper[keepers[i]] = true;
emit KeeperSet(keepers[i], true);
}
emit KeeperAdminSet(keeperAdmin_);
}
modifier nonReentrant() {
assembly ("memory-safe") {
if tload(LOCK_SLOT) {
mstore(0x00, 0xab143c06) // Reentrant()
revert(0x1c, 0x04)
}
tstore(LOCK_SLOT, 1)
}
_;
assembly ("memory-safe") {
tstore(LOCK_SLOT, 0)
}
}
// ------------------------------------------------------------------ keepers (no power over funds)
/// @notice The keeper admin can only add/remove keepers. Keepers can only call `rebalance()` earlier than the
/// public (lever-up without the public delay); every amount is computed by the contract.
function setKeeper(address k, bool on) external {
if (msg.sender != keeperAdmin) revert NotKeeperAdmin();
isKeeper[k] = on;
emit KeeperSet(k, on);
}
function setKeeperAdmin(address a) external {
if (msg.sender != keeperAdmin) revert NotKeeperAdmin();
keeperAdmin = a; // address(0) renounces
emit KeeperAdminSet(a);
}
// ------------------------------------------------------------------ inflows
/// @notice Add PRINCIPAL (raises the HWM 1:1). Above the cap, or if Aave cannot take the supply, or after
/// retirement, the XAUT goes straight to the floor instead. Permissionless (it can only add).
function fund(uint256 amount) external nonReentrant {
_inflow(amount, true);
}
/// @notice Add pass-through gold (does NOT raise the HWM): it first fills any loss below the HWM, and whatever is
/// above the HWM is harvested into the floor. This is how "fees pay the interest" works.
function serve(uint256 amount) external nonReentrant {
_inflow(amount, false);
}
function _inflow(uint256 amount, bool principal) internal {
if (amount == 0) revert ZeroAmount();
uint256 toEngine = amount;
if (retired) toEngine = 0;
else if (principal && hwm + amount > CAP) toEngine = hwm >= CAP ? 0 : CAP - hwm;
uint256 toFloor = amount - toEngine;
if (toEngine != 0) {
uint256 b0 = XAUT.balanceOf(address(COURIER));
XAUT.safeTransferFrom(msg.sender, address(COURIER), toEngine);
uint256 got = XAUT.balanceOf(address(COURIER)) - b0;
try COURIER.supply() {
if (principal) {
hwm += got;
funded += got;
} else {
served += got;
}
emit Funded(msg.sender, got, principal);
} catch {
// XAUT reserve frozen / paused / supply cap: the gold goes to the floor instead of waiting
COURIER.toSink();
overflowed += got;
emit Overflow(msg.sender, got);
}
}
if (toFloor != 0) {
uint256 s0 = XAUT.balanceOf(SINK);
XAUT.safeTransferFrom(msg.sender, SINK, toFloor);
uint256 got = XAUT.balanceOf(SINK) - s0;
overflowed += got;
emit Overflow(msg.sender, got);
}
try IRatchetSinkFlush(SINK).flush() {} catch {}
}
// ------------------------------------------------------------------ views
struct State {
uint256 collateral; // raw XAUT (aXAUT balance)
uint256 debt; // raw USDT (variable debt)
uint256 idle; // raw USDT waiting in the courier (counts against the debt)
uint256 price; // USDT per XAUT, 1e18 (both tokens have 6 decimals)
uint256 valueUsd; // collateral value, raw USDT
uint256 equityUsd; // raw USDT, 0 if underwater
uint256 equityGold; // raw XAUT, 0 if underwater (debt rounded UP)
uint256 levBps; // collateral / equity, type(uint256).max if underwater
}
function _state(uint256 p) internal view returns (State memory s) {
s.price = p;
s.collateral = A_XAUT.balanceOf(address(this));
s.debt = VDEBT_USDT.balanceOf(address(this));
s.idle = USDT.balanceOf(address(COURIER));
s.valueUsd = FullMath.mulDiv(s.collateral, p, 1e18);
uint256 net = s.debt > s.idle ? s.debt - s.idle : 0;
uint256 extra = s.idle > s.debt ? s.idle - s.debt : 0;
if (s.valueUsd + extra > net) {
s.equityUsd = s.valueUsd + extra - net;
uint256 debtGold = FullMath.mulDivRoundingUp(net, 1e18, p);
uint256 extraGold = FullMath.mulDiv(extra, 1e18, p);
s.equityGold = s.collateral + extraGold > debtGold ? s.collateral + extraGold - debtGold : 0;
s.levBps = s.equityUsd == 0 ? type(uint256).max : FullMath.mulDiv(s.valueUsd, BPS, s.equityUsd);
} else {
s.levBps = type(uint256).max;
}
}
/// @notice Conservative gold price (USDT per XAUT, 1e18) = min(Chainlink XAU/USD, 30-min XAUT/USDT TWAP), and
/// whether both are live and agree. Reverts only if neither is available.
function price() public view returns (uint256 p, bool healthy, bool marketClosed) {
(p, healthy, marketClosed,,) = _oracle();
}
function _oracle() internal view returns (uint256 p, bool healthy, bool marketClosed, uint256 cl, bool clOk) {
uint256 age;
(cl, age, clOk) = _chainlink();
(uint256 tw, bool twOk) = _twap();
if (!clOk && !twOk) revert OracleDown();
if (clOk && twOk) {
p = cl < tw ? cl : tw;
marketClosed = age > CL_CLOSED_AGE;
uint256 diff = cl > tw ? cl - tw : tw - cl;
healthy = diff * BPS <= cl * (marketClosed ? DEV_CLOSED : DEV);
} else {
p = clOk ? cl : tw;
}
}
function _chainlink() internal view returns (uint256 p, uint256 age, bool ok) {
try CL_XAU_USD.latestRoundData() returns (uint80, int256 a, uint256, uint256 upd, uint80) {
if (a > 0 && upd <= block.timestamp) {
age = block.timestamp - upd;
if (age <= CL_MAX_AGE) {
p = uint256(a) * 1e10; // 8 dec USD per oz -> 1e18; USDT taken at $1 (min() with the TWAP covers a depeg)
ok = true;
}
}
} catch {}
}
function _twap() internal view returns (uint256 p, bool ok) {
uint32[] memory ago = new uint32[](2);
ago[0] = TWAP_WINDOW;
try POOL.observe(ago) returns (int56[] memory tc, uint160[] memory) {
int56 delta = tc[1] - tc[0];
int24 mean = int24(delta / int56(uint56(TWAP_WINDOW)));
if (delta < 0 && (delta % int56(uint56(TWAP_WINDOW)) != 0)) mean--;
uint160 sq = TickMath.getSqrtPriceAtTick(mean);
// price = sqrt^2 / 2^192 (token1 raw per token0 raw = USDT per XAUT, both 6 dec), scaled 1e18
p = FullMath.mulDiv(FullMath.mulDiv(uint256(sq), uint256(sq), 1 << 96), 1e18, 1 << 96);
ok = p != 0;
} catch {}
}
/// @notice USDT borrow rate (APR, 1e18), averaged over 1-2 days from Aave's own debt index when possible.
function borrowRate() public view returns (uint256 rate, bool averaged) {
RateSnap memory r = snapOld;
if (r.time == 0 || block.timestamp - r.time < 1 days) r = snapNew;
if (r.time != 0 && block.timestamp - r.time >= 12 hours && r.index != 0) {
uint256 idx = AAVE.getReserveNormalizedVariableDebt(USDT);
uint256 g = idx > r.index ? FullMath.mulDiv(idx, 1e18, r.index) - 1e18 : 0;
rate = g * 365 days / (block.timestamp - r.time);
averaged = true;
} else {
rate = uint256(AAVE.getReserveData(USDT).currentVariableBorrowRate) / 1e9; // ray -> 1e18
}
}
/// @notice Aave changed something the engine's safety depends on (XAUT frozen/paused/inactive, eMode LTV/LT cut).
function lenderBroken() public view returns (bool) {
if (AAVE.getUserEMode(address(this)) != EMODE) return true;
EModeCollateralConfig memory em = AAVE.getEModeCategoryCollateralConfig(EMODE);
if (em.ltv < MIN_LTV || em.liquidationThreshold < MIN_LT) return true;
uint256 cfg = AAVE.getReserveData(XAUT).configuration;
bool active = (cfg >> 56) & 1 == 1;
bool frozen = (cfg >> 57) & 1 == 1;
bool paused = (cfg >> 60) & 1 == 1;
return !active || frozen || paused;
}
function riskOff() public view returns (bool) {
(uint256 r, bool avg) = borrowRate();
return (avg && r > RISK_OFF_RATE) || lenderBroken();
}
/// @notice the current leverage target in bps (scaled down by the drawdown rule, 1.0x when risk-off)
function targetBps(uint256 equityGold) public view returns (uint256 t) {
if (riskOff()) return BPS;
t = TARGET;
if (DD_FLOOR != 0 && hwm != 0) {
uint256 e = FullMath.mulDiv(equityGold, BPS, hwm);
if (e < BPS) {
if (e <= DD_FLOOR) return BPS;
t = BPS + (TARGET - BPS) * (e - DD_FLOOR) / (BPS - DD_FLOOR);
}
}
}
function healthFactor() public view returns (uint256 hf) {
(,,,,, hf) = AAVE.getUserAccountData(address(this));
}
/// @notice one call for the UI
function state()
external
view
returns (State memory s, uint256 target, bool healthy, bool closed, bool off, uint256 hf)
{
uint256 p;
(p, healthy, closed) = price();
s = _state(p);
target = targetBps(s.equityGold);
off = riskOff();
hf = healthFactor();
}
// ------------------------------------------------------------------ rebalance
/// @notice Move leverage back into its band. Delever: anyone, any time the rules say so. Lever-up: a keeper, or
/// anyone once no keeper has acted for PUBLIC_LEVER_DELAY. One bounded step per call.
function rebalance() external nonReentrant returns (uint256 usdtMoved, bool levered) {
if (retired) revert Retired();
_rollRate();
bool off = _observeRiskOff();
(uint256 p, bool healthy,, uint256 cl, bool clOk) = _oracle();
State memory s = _state(p);
if (s.collateral == 0) revert NothingToDo();
if (s.equityUsd == 0) revert NothingToDo(); // underwater: Aave's liquidators own it now
// the EMERGENCY zone is judged at Chainlink (what Aave liquidates on), never at the TWAP: an attacker who holds
// the pool down cannot push the engine into a wide-slippage fire sale
uint256 levCl = clOk ? _state(cl).levBps : s.levBps;
uint256 t = off ? BPS : targetBps(s.equityGold);
uint256 hf = healthFactor();
uint256 netDebt = s.debt > s.idle ? s.debt - s.idle : 0;
bool emergency = netDebt != 0 && (levCl >= EMERG || hf < HF_EMERG);
uint256 hiBand = t + (MAX - TARGET);
uint256 loBand = t > (TARGET - MIN) + BPS ? t - (TARGET - MIN) : BPS;
if (netDebt != 0 && (s.levBps > hiBand || emergency || (off && s.levBps > BPS))) {
if (!emergency) {
if (!healthy) revert OracleUnhealthy();
if (block.timestamp < lastRebalance + DELEVER_COOLDOWN) revert Cooldown();
}
// repay so that value' = t * equity (value - x = t * equity => x = value - t * equity)
uint256 want = t <= BPS ? netDebt : _sub(s.valueUsd, FullMath.mulDiv(t, s.equityUsd, BPS));
if (want > netDebt) want = netDebt;
if (want > MAX_STEP) want = MAX_STEP;
if (want == 0) revert NothingToDo();
// emergency fills are bounded against Chainlink too: never below CL x (1 - DEV_CLOSED) - EMERG_SLIP
uint256 ref = p;
// normal delevers are bounded against the HIGHER of TWAP and Chainlink: a TWAP held down cannot widen the sell bound
if (!emergency && clOk && ref < cl) ref = cl;
if (emergency && clOk) {
uint256 lo = FullMath.mulDiv(cl, BPS - DEV_CLOSED, BPS);
if (ref < lo) ref = lo;
}
uint256 sold = _sell(want, ref, emergency ? EMERG_SLIP : SLIP);
usdtMoved = want;
emit Delevered(msg.sender, want, sold, _state(p).levBps, emergency);
} else if (s.levBps < loBand && t > s.levBps && !off) {
if (!healthy) revert OracleUnhealthy();
(uint256 rate,) = borrowRate();
if (rate > LEVER_RATE_MAX) revert RateTooHigh();
if (!isKeeper[msg.sender] && block.timestamp < lastKeeperAction + PUBLIC_LEVER_DELAY) revert KeeperOnly();
if (block.timestamp < lastLever + LEVER_COOLDOWN) revert Cooldown();
uint256 b = _sub(FullMath.mulDiv(t, s.equityUsd, BPS), s.valueUsd);
if (b > MAX_STEP) b = MAX_STEP;
if (b == 0) revert NothingToDo();
uint256 bought = _buy(b, p, SLIP);
if (healthFactor() < HF_MIN_POST) revert Unhealthy();
lastLever = uint64(block.timestamp);
usdtMoved = b;
levered = true;
emit Levered(msg.sender, b, bought, _state(p).levBps);
} else {
revert NothingToDo();
}
lastRebalance = uint64(block.timestamp);
if (isKeeper[msg.sender]) lastKeeperAction = uint64(block.timestamp);
}
/// @notice keep the rate average and the risk-off clock fresh (anyone; the keeper calls it daily)
function poke() external nonReentrant {
_rollRate();
_observeRiskOff();
}
function _rollRate() internal {
RateSnap memory n = snapNew;
if (n.time != 0 && block.timestamp < n.time + 1 days) return;
uint256 idx = AAVE.getReserveNormalizedVariableDebt(USDT);
if (n.time != 0) snapOld = n;
snapNew = RateSnap(uint128(idx), uint64(block.timestamp));
}
function _observeRiskOff() internal returns (bool off) {
off = riskOff();
if (off) {
if (riskOffSince == 0) riskOffSince = uint64(block.timestamp);
} else if (riskOffSince != 0) {
riskOffSince = 0;
}
}
// ------------------------------------------------------------------ harvest (the ratchet)
/// @notice Move REAL gains into KINEKO's hard floor. Permissionless, at most once per HARVEST_INTERVAL.
/// gain = equity in gold (collateral - debt / price, debt incl. accrued interest, price = min(CL, TWAP))
/// minus the HWM. The XAUT is withdrawn from Aave straight to the RatchetSink.
function harvest() external nonReentrant returns (uint256 h) {
if (retired) revert Retired();
if (block.timestamp < lastHarvest + HARVEST_INTERVAL) revert TooEarly();
(uint256 p, bool healthy,) = price();
if (!healthy) revert OracleUnhealthy();
State memory s = _state(p);
uint256 e = s.equityGold;
uint256 mark = hwm;
if (e <= mark) revert NothingToHarvest();
uint256 gain = e - mark;
if (gain * BPS < MIN_GAIN * mark) revert NothingToHarvest();
h = gain * HARVEST_SHARE / BPS;
uint256 cap = e * MAX_HARVEST / BPS;
if (h > cap) h = cap;
uint256 netDebt = s.debt > s.idle ? s.debt - s.idle : 0;
if (netDebt != 0) {
// leverage after the harvest <= HARVEST_MAX_LEV: (value - hP) <= K (equity - hP) => hP <= (K*eq - value)/(K-1)
uint256 kv = FullMath.mulDiv(HARVEST_MAX_LEV, s.equityUsd, BPS);
uint256 hUsd = kv > s.valueUsd ? FullMath.mulDiv(kv - s.valueUsd, BPS, HARVEST_MAX_LEV - BPS) : 0;
uint256 hMax = FullMath.mulDiv(hUsd, 1e18, p);
if (h > hMax) h = hMax;
}
if (h > s.collateral) h = s.collateral;
if (h == 0) revert NothingToHarvest();
// HWM: the processed part of the gain is booked; what was not paid out (share < 100%) stays in the engine
uint256 processed = h * BPS / HARVEST_SHARE;
if (processed > gain) processed = gain;
hwm = mark + processed - h;
lastHarvest = uint64(block.timestamp);
harvested += h;
uint256 got = AAVE.withdraw(XAUT, h, SINK);
if (got != h) revert Slippage();
if (netDebt != 0 && healthFactor() < HF_MIN_POST) revert Unhealthy();
try IRatchetSinkFlush(SINK).flush() {} catch {}
emit Harvested(msg.sender, h, e, hwm, p);
}
/// @notice If the engine has been risk-off (lender broken or rates too high) with zero debt for RETIRE_AFTER,
/// anyone can retire it: every remaining XAUT goes into the floor and future inflows go there directly.
function retire() external nonReentrant {
if (retired) revert Retired();
_rollRate();
bool off = _observeRiskOff();
if (!off || riskOffSince == 0 || block.timestamp < riskOffSince + RETIRE_AFTER) revert NotRetirable();
if (VDEBT_USDT.balanceOf(address(this)) != 0) revert NotRetirable();
retired = true;
uint256 c = A_XAUT.balanceOf(address(this));
uint256 got = c == 0 ? 0 : AAVE.withdraw(XAUT, type(uint256).max, SINK);
harvested += got;
hwm = 0;
try IRatchetSinkFlush(SINK).flush() {} catch {}
emit RetiredToFloor(got);
}
// ------------------------------------------------------------------ swaps (v3 pool, direct, callback-settled)
/// sell XAUT for exactly `usdtOut` (exact output). The USDT goes to the courier and repays the debt FIRST, then
/// Aave pays the pool in XAUT directly (withdraw to the pool): HF only improves inside the callback.
function _sell(uint256 usdtOut, uint256 p, uint256 slip) internal returns (uint256 xautIn) {
uint256 maxIn = FullMath.mulDivRoundingUp(usdtOut, 1e18 * (BPS + slip), p * BPS);
_setSwap(MODE_SELL, maxIn);
(int256 a0,) = POOL.swap(address(COURIER), true, -int256(usdtOut), MIN_SQRT_PRICE + 1, "");
_setSwap(0, 0);
xautIn = uint256(a0);
}
/// buy XAUT with exactly `usdtIn` (exact input). XAUT goes to the courier and is supplied for the engine, then the
/// engine borrows exactly what the pool is owed.
function _buy(uint256 usdtIn, uint256 p, uint256 slip) internal returns (uint256 xautOut) {
uint256 minOut = FullMath.mulDiv(usdtIn, 1e18 * (BPS - slip), p * BPS);
_setSwap(MODE_BUY, minOut);
(int256 a0,) = POOL.swap(address(COURIER), false, int256(usdtIn), MAX_SQRT_PRICE - 1, "");
_setSwap(0, 0);
xautOut = uint256(-a0);
}
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
if (msg.sender != address(POOL)) revert NotPool();
uint256 mode;
uint256 bound;
assembly ("memory-safe") {
mode := tload(SWAP_MODE_SLOT)
bound := tload(SWAP_BOUND_SLOT)
}
if (mode == MODE_SELL) {
// we owe XAUT (amount0 > 0); the USDT (amount1 < 0) is already at the courier
if (amount0Delta <= 0 || uint256(amount0Delta) > bound) revert Slippage();
COURIER.repay();
AAVE.withdraw(XAUT, uint256(amount0Delta), address(POOL));
} else if (mode == MODE_BUY) {
// we owe USDT (amount1 > 0); the XAUT (amount0 < 0) is already at the courier
if (amount0Delta >= 0 || uint256(-amount0Delta) < bound || amount1Delta <= 0) revert Slippage();
COURIER.supply();
AAVE.borrow(USDT, uint256(amount1Delta), 2, 0, address(this));
USDT.safeTransfer(address(POOL), uint256(amount1Delta));
} else {
revert NotPool();
}
_setSwap(0, 0); // one callback per swap
}
function _setSwap(uint256 mode, uint256 bound) private {
assembly ("memory-safe") {
tstore(SWAP_MODE_SLOT, mode)
tstore(SWAP_BOUND_SLOT, bound)
}
}
function _sub(uint256 a, uint256 b) private pure returns (uint256) {
return a > b ? a - b : 0;
}
}
interface IRatchetSinkFlush {
function flush() external returns (uint256);
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) {
revert(codesize(), codesize())
} // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount := mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` implements `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented := and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
lib/v4-core/src/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-core/src/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}
lib/v4-core/src/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
src/pad/engine/EngineExternal.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// Minimal external interfaces used by the Gold Engine. Mainnet addresses are in test/fork/EngineForkBase.sol.
/// Aave v3 ReserveDataLegacy (what Pool.getReserveData returns on Ethereum Core, v3.3)
struct ReserveDataLegacy {
uint256 configuration;
uint128 liquidityIndex;
uint128 currentLiquidityRate;
uint128 variableBorrowIndex;
uint128 currentVariableBorrowRate;
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
uint16 id;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
uint128 accruedToTreasury;
uint128 unbacked;
uint128 isolationModeTotalDebt;
}
struct EModeCollateralConfig {
uint16 ltv;
uint16 liquidationThreshold;
uint16 liquidationBonus;
}
interface IAavePool {
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)
external;
function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256);
function setUserEMode(uint8 categoryId) external;
function getUserEMode(address user) external view returns (uint256);
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 availableBorrowsBase,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function getReserveData(address asset) external view returns (ReserveDataLegacy memory);
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
function getEModeCategoryCollateralConfig(uint8 id) external view returns (EModeCollateralConfig memory);
}
interface IChainlinkFeed {
function decimals() external view returns (uint8);
function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
}
interface IUniV3Pool {
function token0() external view returns (address);
function token1() external view returns (address);
function swap(address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data)
external
returns (int256 amount0, int256 amount1);
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
}
/// the production floor-feed path: FeeConverter.feedFloor(KINEKO, amount) (house coins only, pulls XAUT, credits the
/// hook's pendingFloor, placed by the next collect())
interface IFloorFeeder {
function feedFloor(address coin, uint256 amount) external;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/src/",
"metamorpho/=lib/metamorpho-v1.1/src/",
"solady/=lib/solady/src/",
"v4-core/=lib/v4-core/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
"lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
"lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"metamorpho-v1.1/=lib/metamorpho-v1.1/",
"morpho-blue-irm/=lib/metamorpho-v1.1/lib/morpho-blue-irm/src/",
"openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
"solmate/=lib/v4-core/lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.