Verified contractExactMIT
CurveStableNgPoolAdapter
Address0x215792ab846705548a1c8eef7ceaf86bd2e4ce2a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.19
- Same code
Only this contract
Details
- Compiler
- solc 0.8.19+commit.7dd6d404
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,152,173
- Creation transaction
- 0x7a59113d70…228bf84896
10 files
- contracts/dex/adapters/CurveStableNgPoolAdapter.solmain8.4 KB
- contracts/dex/DexAdapterBase.sol8.96 KB
- contracts/dex/IDexAdapter.sol1.74 KB
- contracts/dex/ISwapRouter.sol2.06 KB
- contracts/dex/SwapTypes.sol1.88 KB
- contracts/interfaces/IRouterAllowlist.sol3.18 KB
- contracts/interfaces/external/curve/ICurveStableNgSwap.sol1.14 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/solmate/src/tokens/ERC20.sol6.81 KB
- lib/solmate/src/utils/SafeTransferLib.sol6.26 KB
contracts/dex/adapters/CurveStableNgPoolAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { DexAdapterBase } from "contracts/dex/DexAdapterBase.sol";
import { DexType, SwapStep } from "contracts/dex/SwapTypes.sol";
import {
ICurveStableNgSwapFactory,
ICurveStableNgSwapPool
} from "contracts/interfaces/external/curve/ICurveStableNgSwap.sol";
/// @notice Direct ordinary ERC20 swaps in the authenticated DCc NG profile,
/// N=2..8, including precise active/fractional/up/down/stopped A ramps.
/// @dev step.router is FACTORY, authorized by the existing SwapRouter gate.
/// dexData is abi.encode(address pool, int128 i, int128 j), in coin order.
/// No optimistic transfer, underlying swap, metapool or rate-moving profile.
/// SwapRouter keeps custody and enforces its final post-fee output minimum.
contract CurveStableNgPoolAdapter is DexAdapterBase {
error InvalidDexType();
error InvalidDexData();
error InvalidPool();
error InvalidTokens();
error InvalidAmountIn();
error UnsupportedAmplification();
error FeeOnTransferNotSupported();
error UnsupportedImplementation();
/// @dev Source/compiler provenance and immutable offsets are shared with
/// merged DB input revision 1. These hashes identify source, not
/// deployments. The same factory/blueprint can be configured at any address
/// on any chain.
bytes32 public constant PROFILE = keccak256("stableswap-ng-dcc-v1");
uint256 public constant INPUT_REVISION = 1;
bytes32 public constant FACTORY_CODE_HASH =
0xb78c1b32cd364260f3fa497ccc7e98c73cdc26bdae2d3635e763ee8b59a1d6fd;
bytes32 public constant BLUEPRINT_CODE_HASH =
0xe2a3dd8d583b86eb7f562b4307aab6e5a373ddb5c6b348e4cf63d41914f35a9f;
bytes32 public constant POOL_EXECUTABLE_HASH =
0x04b4bd650d72be4619d76c7b5a052de46d95b5194945fe44bba7e49b729d3d60;
uint256 internal constant EXECUTABLE_BYTES = 21_491;
uint256 internal constant IMMUTABLE_BYTES = 2144;
ICurveStableNgSwapFactory public immutable FACTORY;
address public immutable IMPLEMENTATION;
constructor(
address admin_,
address swapRouter_,
address allowlist_,
address factory_,
address implementation_
) DexAdapterBase(admin_, swapRouter_, allowlist_) {
if (factory_.code.length == 0 || implementation_.code.length == 0) {
revert InvalidAddress();
}
if (
factory_.codehash != FACTORY_CODE_HASH
|| implementation_.codehash != BLUEPRINT_CODE_HASH
) revert UnsupportedImplementation();
FACTORY = ICurveStableNgSwapFactory(factory_);
IMPLEMENTATION = implementation_;
}
function version() external pure override returns (uint16) {
return 2;
}
function _swap(
SwapStep calldata step,
uint256 amountIn
) internal override returns (uint256) {
if (step.dexType != uint8(DexType.CurveStableNgPool)) {
revert InvalidDexType();
}
if (step.router != address(FACTORY)) revert InvalidPool();
if (step.dexData.length != 96) revert InvalidDexData();
(address pool, int128 i, int128 j) =
abi.decode(step.dexData, (address, int128, int128));
if (i < 0 || j < 0 || i > 7 || j > 7 || i == j) {
revert InvalidDexData();
}
if (amountIn == 0) revert InvalidAmountIn();
_validatePool(step, pool, uint256(uint128(i)), uint256(uint128(j)));
IERC20 tokenIn = IERC20(step.tokenIn);
IERC20 tokenOut = IERC20(step.tokenOut);
uint256 inputBefore = tokenIn.balanceOf(pool);
uint256 outputBefore = tokenOut.balanceOf(address(swapRouter));
_adapterApprove(step.tokenIn, pool, amountIn);
bytes memory result = _adapterCall(
pool,
0,
abi.encodeCall(
ICurveStableNgSwapPool.exchange,
(i, j, amountIn, 0, address(swapRouter))
)
);
_adapterApprove(step.tokenIn, pool, 0);
// Asset type 0 is permissionless metadata, not evidence of ordinary
// transfer behavior. Refuse taxation on either side of the pool.
uint256 inputAfter = tokenIn.balanceOf(pool);
uint256 outputAfter = tokenOut.balanceOf(address(swapRouter));
uint256 amountOut = abi.decode(result, (uint256));
if (
inputAfter < inputBefore || inputAfter - inputBefore != amountIn
|| outputAfter < outputBefore
|| outputAfter - outputBefore != amountOut
) revert FeeOnTransferNotSupported();
return amountOut;
}
function _validatePool(
SwapStep calldata step,
address pool,
uint256 i,
uint256 j
) internal view {
allowlist.requireAllowedFactory(address(FACTORY));
if (
address(FACTORY).codehash != FACTORY_CODE_HASH
|| IMPLEMENTATION.codehash != BLUEPRINT_CODE_HASH
) revert UnsupportedImplementation();
uint256 n = FACTORY.get_n_coins(pool);
if (
FACTORY.get_implementation_address(pool) != IMPLEMENTATION || n < 2
|| n > 8 || FACTORY.is_meta(pool)
) revert InvalidPool();
if (i >= n || j >= n) revert InvalidDexData();
address[] memory coins = FACTORY.get_coins(pool);
uint8[] memory assetTypes = FACTORY.get_pool_asset_types(pool);
uint256[] memory decimals = FACTORY.get_decimals(pool);
if (coins.length != n || assetTypes.length != n || decimals.length != n)
{
revert InvalidPool();
}
_validateRuntime(pool, n, coins, assetTypes, decimals);
// The immutable source evaluates exact A at execution time. Fractional
// A and ongoing ramps are valid; the merged math domain starts at 100.
if (ICurveStableNgSwapPool(pool).A_precise() < 100) {
revert UnsupportedAmplification();
}
if (coins[i] != step.tokenIn || coins[j] != step.tokenOut) {
revert InvalidTokens();
}
}
function _validateRuntime(
address pool,
uint256 n,
address[] memory coins,
uint8[] memory assetTypes,
uint256[] memory decimals
) internal view {
bytes memory code = pool.code;
if (code.length != EXECUTABLE_BYTES + IMMUTABLE_BYTES) {
revert InvalidPool();
}
bytes32 executableHash;
assembly {
executableHash := keccak256(add(code, 32), EXECUTABLE_BYTES)
}
if (
executableHash != POOL_EXECUTABLE_HASH || _word(code, 0) != n
|| _word(code, 32) != n
|| _word(code, 64) != uint256(uint160(address(FACTORY)))
|| _word(code, 2048) != block.chainid || _word(code, 672) != 0
) revert InvalidPool();
if (
_word(code, 96) != n || _word(code, 384) != n
|| _word(code, 704) != n || _word(code, 992) != n
|| _word(code, 1280) != n || _word(code, 1568) != n
) revert InvalidPool();
for (uint256 k; k < n; k++) {
if (
coins[k].code.length == 0 || assetTypes[k] != 0
|| decimals[k] > 18
|| _word(code, 128 + k * 32) != uint256(uint160(coins[k]))
|| _word(code, 416 + k * 32) != 0
|| _word(code, 736 + k * 32) != 10 ** (36 - decimals[k])
|| _word(code, 1312 + k * 32) != 0
|| _word(code, 1600 + k * 32) != 0
) revert InvalidPool();
for (uint256 prior; prior < k; prior++) {
if (coins[prior] == coins[k]) revert InvalidPool();
}
}
// Type-zero metadata alone cannot certify ordinary ERC20 behaviour.
// The quote reader separately requires source-qualified ordinary
// tokens. Factory admission is not a token-behaviour certification.
// Exact deltas above still reject taxed transfers during this swap.
}
function _word(
bytes memory code,
uint256 offset
) internal pure returns (uint256 value) {
assembly {
value := mload(add(add(code, add(EXECUTABLE_BYTES, 32)), offset))
}
}
}
contracts/dex/DexAdapterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { IRouterAllowlist } from "contracts/interfaces/IRouterAllowlist.sol";
import { IDexAdapter } from "contracts/dex/IDexAdapter.sol";
import { ISwapRouter } from "contracts/dex/ISwapRouter.sol";
import { SwapStep } from "contracts/dex/SwapTypes.sol";
/// @title DexAdapterBase
/// @notice Shared base for DEX adapters. Adapters in this codebase are
/// pure orchestrators — they decode `step.dexData`, build the target
/// router's calldata, and tell `SwapRouter` what to approve, transfer,
/// or call. They never hold tokens or ETH between (or during) swap
/// steps. `SwapRouter` itself remains `msg.sender` for every external
/// call, which means pool callbacks land on the existing callbacks on
/// `SwapRouter`, FOT accounting stays consistent, and there is no
/// per-step custody surface that a buggy adapter could leak.
/// @dev Mirrors `contracts/bridges/adapters/BridgeAdapterBase.sol` in
/// spirit (admin + rescue helpers); guardian role is intentionally
/// omitted to match `SwapRouter`'s admin-only governance model.
abstract contract DexAdapterBase is IDexAdapter {
error NotAdmin();
error NotSwapRouter();
error InvalidAddress();
event AdminUpdated(address oldAdmin, address newAdmin);
event SwapRouterUpdated(address oldSwapRouter, address newSwapRouter);
/// @notice Router that dispatches swap steps to this adapter and
/// holds all custody for the swap.
///
/// Deliberately NOT immutable. As an immutable it made every adapter a
/// dependent of `SwapRouter`'s address, so any change to SwapRouter forced
/// a redeploy of every adapter on every chain and a re-registration of the
/// new addresses. One fee-rounding fix cost 621 contract deploys across 35
/// chains that way. As storage it is a single batched `setSwapRouter` call
/// per chain through SickleMultisig, and adapter addresses never move, so
/// nothing downstream needs re-registering.
///
/// This is safe because the guard that protects funds lives in the ROUTER,
/// not here: `SwapRouter` gates `adapterApprove` / `adapterCall` /
/// `adapterPull` on its `_activeAdapter` slot, set immediately before
/// dispatch and cleared immediately after, and it never transfers custody
/// to the adapter -- it measures its own balance delta as the authoritative
/// output. Pointing this at a hostile contract therefore breaks the adapter
/// (its callbacks go somewhere with no authority over the real router)
/// rather than draining it. `setDexAdapter` never validated this
/// back-pointer either, so immutability was not enforcing a router-side
/// invariant.
ISwapRouter public swapRouter;
/// @notice Router allowlist shared with `SwapRouter`. Pool/factory-
/// style adapters read this directly to authorise their factory or
/// custom deployer checks.
IRouterAllowlist public immutable allowlist;
/// @notice Admin authorised to rotate this adapter's admin and
/// rescue any stuck balances. Adapter swap dispatch itself is
/// gated by `SwapRouter`'s active-adapter slot, not by this admin.
address public admin;
constructor(address admin_, address swapRouter_, address allowlist_) {
if (admin_ == address(0)) revert InvalidAddress();
if (swapRouter_ == address(0)) revert InvalidAddress();
if (allowlist_ == address(0)) revert InvalidAddress();
admin = admin_;
swapRouter = ISwapRouter(swapRouter_);
allowlist = IRouterAllowlist(allowlist_);
}
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdmin();
_;
}
/// @notice Repoint this adapter at a redeployed `SwapRouter`.
/// @dev The trade-off this exists for is described on `swapRouter`. Emits
/// so the binding stays auditable: as an immutable it was readable from
/// constructor args and could never change, and anyone verifying "this
/// adapter points at the real router" must now read state instead.
/// @custom:access Restricted to the adapter admin.
function setSwapRouter(
address newSwapRouter
) external onlyAdmin {
if (newSwapRouter == address(0)) revert InvalidAddress();
emit SwapRouterUpdated(address(swapRouter), newSwapRouter);
swapRouter = ISwapRouter(newSwapRouter);
}
/// @notice Defensive — adapters are not supposed to hold ETH, but
/// stay payable so an over-refund from a router (e.g. universal
/// router excess ETH on a partial swap) doesn't get rejected and
/// can be swept by admin afterwards.
receive() external payable { }
/// @notice External `swap` entry point implementing `IDexAdapter`.
/// Centralised here so every concrete adapter inherits the
/// `msg.sender == swapRouter` guard structurally — impossible to
/// forget per-impl. Without this guard, a reentrant callee invoked
/// from inside the adapter's own helpers (token transferFrom, V4
/// hook, malicious router) could call `swap` directly with an
/// attacker-chosen `SwapStep`, satisfy `_activeAdapter` since this
/// contract is still the active adapter, and instruct `SwapRouter`
/// to approve / call / pull against attacker-controlled targets.
/// Concrete adapters override `_swap` instead.
function swap(
SwapStep calldata step,
uint256 amountIn
) external payable override returns (uint256) {
if (msg.sender != address(swapRouter)) revert NotSwapRouter();
return _swap(step, amountIn);
}
/// @dev Concrete per-DEX implementation. Always invoked via the
/// guarded `swap` entry point above.
function _swap(
SwapStep calldata step,
uint256 amountIn
) internal virtual returns (uint256);
function setAdmin(
address newAdmin
) external onlyAdmin {
if (newAdmin == address(0)) revert InvalidAddress();
emit AdminUpdated(admin, newAdmin);
admin = newAdmin;
}
function rescueTokens(
address token,
address to,
uint256 amount
) external virtual onlyAdmin {
SafeTransferLib.safeTransfer(token, to, amount);
}
function rescueETH(
address to
) external virtual onlyAdmin {
SafeTransferLib.safeTransferETH(to, address(this).balance);
}
// ── Internal helpers shared by adapter implementations ────────────────
/// @dev Pull `amount` of `token` from `SwapRouter` directly into
/// `recipient` (used for pre-deposit-style routers such as
/// Velodrome's UniversalRouter with `payerIsUser = false`).
function _adapterPullTo(
address token,
uint256 amount,
address recipient
) internal {
swapRouter.adapterPull(token, amount, recipient);
}
/// @dev Set an ERC20 approval from `SwapRouter` to `spender`. Use
/// `amount = 0` to revoke. Wraps `swapRouter.adapterApprove`.
function _adapterApprove(
address token,
address spender,
uint256 amount
) internal {
swapRouter.adapterApprove(token, spender, amount);
}
/// @dev Execute an external call from `SwapRouter`'s address.
function _adapterCall(
address target,
uint256 value,
bytes memory data
) internal returns (bytes memory) {
return swapRouter.adapterCall(target, value, data);
}
/// @dev Arm the V3 / Algebra pool callback before invoking a direct
/// pool swap via `_adapterCall`.
function _armPoolCallback(
address pool,
address tokenToPay,
uint256 maxAmountToPay
) internal {
swapRouter.adapterArmPoolCallback(pool, tokenToPay, maxAmountToPay);
}
/// @dev Resolve the target pool for a direct pool-swap step: the
/// `(address pool)` (optionally followed by a custom deployer) encoded
/// in `step.dexData`, falling back to `step.router` when no pool is
/// encoded. Shared by the V3 and Algebra pool adapters.
function _decodePoolAddress(
SwapStep calldata step
) internal pure returns (address pool) {
if (step.dexData.length >= 32) {
pool = abi.decode(step.dexData, (address));
} else {
pool = step.router;
}
}
/// @dev Common router-style swap: `SwapRouter` approves the router,
/// calls it (with `msg.sender == SwapRouter`), revokes the approval.
/// Output recipient must be baked into `data` as `address(swapRouter)`.
function _swapViaRouter(
address token,
uint256 amount,
address router,
bytes memory data
) internal {
_adapterApprove(token, router, amount);
_adapterCall(router, 0, data);
_adapterApprove(token, router, 0);
}
}
contracts/dex/IDexAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";
/// @title IDexAdapter
/// @notice Interface implemented by per-DEX adapter contracts that
/// `SwapRouter` dispatches to when its `dexAdapter[dexType]` slot is set.
/// @dev Under the Option C custody model, the adapter starts with no
/// tokens and pulls them from `SwapRouter` via `adapterPull` while
/// `SwapRouter` holds it as the in-flight active adapter. Output tokens
/// land back in `SwapRouter`, which measures the balance delta to compute
/// the hop's effective output. The function is `payable` so `SwapRouter`
/// can forward native ETH custody alongside the swap when
/// `step.tokenIn == address(0)`. The interface intentionally does not
/// import the concrete `SwapRouter` contract — adapters depend on the
/// shared `SwapTypes` only.
interface IDexAdapter {
/// @notice Adapter implementation version. Off-chain tooling
/// (vfat-api, deploy scripts) reads this to detect which adapter
/// build is currently wired into `SwapRouter`.
function version() external view returns (uint16);
/// @notice Execute a single swap step on behalf of `SwapRouter`.
/// @param step Swap step parameters (dex type, router, tokens, dex-
/// specific data) as defined by `SwapRouter`'s public ABI.
/// @param amountIn Amount of `step.tokenIn` available for this step.
/// @return amountOut Amount of `step.tokenOut` the adapter believes
/// it delivered to `SwapRouter`. Informational only — `SwapRouter`
/// cross-checks via a balance delta.
function swap(
SwapStep calldata step,
uint256 amountIn
) external payable returns (uint256 amountOut);
}
contracts/dex/ISwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IRouterAllowlist } from "contracts/interfaces/IRouterAllowlist.sol";
/// @title ISwapRouter
/// @notice Minimal subset of `SwapRouter` consumed by per-DEX adapters.
/// @dev Lives in its own file (rather than importing `SwapRouter` directly)
/// so the dependency between `DexAdapterBase` and the router stays a thin
/// interface and Solidity doesn't have to resolve the import cycle that
/// `IDexAdapter` already establishes.
interface ISwapRouter {
/// @notice Move ERC20 custody from the router to `to`. Only callable
/// by the in-flight active adapter; reverts otherwise.
function adapterPull(address token, uint256 amount, address to) external;
/// @notice Set an ERC20 approval from the router itself to
/// `spender`. Used by router-style adapters so the eventual
/// `transferFrom` lifts tokens directly from `SwapRouter` rather
/// than via the adapter (single-FOT-hit accounting).
function adapterApprove(
address token,
address spender,
uint256 amount
) external;
/// @notice Execute an external call from `SwapRouter` on behalf of
/// the active adapter. Used so `msg.sender` seen by the target
/// equals `SwapRouter`.
function adapterCall(
address target,
uint256 value,
bytes calldata data
) external returns (bytes memory);
/// @notice Arm the V3 / Algebra pool callback for the next direct
/// pool call in the current adapter dispatch. The callback rejects
/// any payment whose pool, token, or amount does not match the
/// armed expectations.
function adapterArmPoolCallback(
address pool,
address tokenToPay,
uint256 maxAmountToPay
) external;
function allowlist() external view returns (IRouterAllowlist);
function wrappedNative() external view returns (address);
function PERMIT2() external view returns (address);
function PANCAKE_INFINITY_PERMIT2() external view returns (address);
}
contracts/dex/SwapTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @notice DEX types `SwapRouter` knows how to dispatch. This enum is a
/// set of named constants only — `SwapStep.dexType` is a raw `uint8` (not
/// this enum), so the dispatch table `dexAdapter[uint8]` carries the byte
/// directly with no enum range-check at the ABI boundary. A new *standard*
/// type (allow-listed router + ERC20 `tokenIn`) can therefore be appended
/// and dispatched on an already-deployed `SwapRouter` via `setDexAdapter`
/// alone — no redeploy. NOTE this does NOT cover a type that needs a new
/// `SwapRouter._executeStep` exemption (router-allowlist bypass or
/// native-ETH `tokenIn`); those exemption lists are hardcoded and still
/// require a `SwapRouter` redeploy. Append new entries rather than
/// reordering existing ones.
enum DexType {
UniswapV2,
UniswapV3Router02,
Solidly,
Algebra,
UniswapV4,
VelodromeUniversalRouter,
UniswapV3Router,
AerodromeRouter,
AlgebraPool,
SlipstreamRouter,
BlackholeV2Router,
UniswapV3Pool,
WrapWETH,
UnwrapWETH,
CamelotV2Router,
PancakeInfinity,
AaveSupply,
AaveWithdraw,
BaselineRelay,
FlowStateMarket,
SolidlyPool,
AeroMetarouter,
UniswapV2Fot,
BushAggregatorRouter,
LiquidityBook,
CurveStableNgPool
}
/// @notice One hop of a multi-step swap. Stable, ABI-stable struct used
/// by `SwapRouter`, every `IDexAdapter`, every bridge swap receiver, and
/// every off-chain encoder (vfat-api, deploy scripts).
struct SwapStep {
/// @dev Raw `uint8` (not the `DexType` enum) so dispatch is purely
/// `dexAdapter[dexType]` — adding a new DEX type never requires
/// redeploying `SwapRouter`. Compare against `uint8(DexType.X)`.
uint8 dexType;
address router;
address tokenIn;
address tokenOut;
bytes dexData;
}
contracts/interfaces/IRouterAllowlist.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IRouterAllowlist {
/// @notice Check if a router is allowed
/// @param router The router address to check
/// @return True if the router is allowed
function isAllowed(address router) external view returns (bool);
/// @notice Revert if the router is not allowed
/// @param router The router address to check
function requireAllowed(address router) external view;
/// @notice Check if a factory is allowed
/// @param factory The factory address to check
/// @return True if the factory is allowed
function isAllowedFactory(address factory) external view returns (bool);
/// @notice Revert if the factory is not allowed
/// @param factory The factory address to check
function requireAllowedFactory(address factory) external view;
/// @notice Check if a custom pool deployer is allowed for a factory
/// @param factory The factory address to check
/// @param deployer The custom pool deployer address to check
/// @return True if the custom deployer is allowed for the factory
function isAllowedCustomDeployer(address factory, address deployer) external view returns (bool);
/// @notice Revert if the custom pool deployer is not allowed for a factory
/// @param factory The factory address to check
/// @param deployer The custom pool deployer address to check
function requireAllowedCustomDeployer(address factory, address deployer) external view;
/// @notice Check if a v4 hook is allowed
/// @param hook The hook address to check
/// @return True if the hook is allowed
function isAllowedHook(address hook) external view returns (bool);
/// @notice Revert if the v4 hook is not allowed
/// @param hook The hook address to check
function requireAllowedHook(address hook) external view;
/// @notice Check if a bridge contract is allowed
/// @param bridge The bridge contract address
/// @return True if the bridge is allowed
function isAllowedBridge(address bridge) external view returns (bool);
/// @notice Revert if the bridge contract is not allowed
/// @param bridge The bridge contract address
function requireAllowedBridge(address bridge) external view;
/// @notice Check if a function selector is allowed for a bridge contract
/// @param bridge The bridge contract address
/// @param selector The function selector
/// @return True if the selector is allowed
function isAllowedSelector(address bridge, bytes4 selector) external view returns (bool);
/// @notice Revert if the function selector is not allowed for a bridge contract
/// @param bridge The bridge contract address
/// @param selector The function selector
function requireAllowedSelector(address bridge, bytes4 selector) external view;
/// @notice Enumerate the currently-allowed function selectors for a bridge
/// @param bridge The bridge contract address
/// @return selectors The set of selectors currently marked allowed for the bridge
function bridgeSelectors(address bridge) external view returns (bytes4[] memory selectors);
}
contracts/interfaces/external/curve/ICurveStableNgSwap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/// @notice The authenticated plain StableSwap-NG factory registry.
interface ICurveStableNgSwapFactory {
function get_implementation_address(
address pool
) external view returns (address);
function get_n_coins(
address pool
) external view returns (uint256);
function get_coins(
address pool
) external view returns (address[] memory);
function get_pool_asset_types(
address pool
) external view returns (uint8[] memory);
function get_decimals(
address pool
) external view returns (uint256[] memory);
function is_meta(
address pool
) external view returns (bool);
}
interface ICurveStableNgSwapPool {
function A_precise() external view returns (uint256);
function future_A_time() external view returns (uint256);
function coins(
uint256 index
) external view returns (address);
function exchange(
int128 i,
int128 j,
uint256 amountIn,
uint256 minAmountOut,
address receiver
) external returns (uint256);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error ETHTransferFailed();
error TransferFromFailed();
error TransferFailed();
error ApproveFailed();
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
if (!success) revert ETHTransferFailed();
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
address token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
if (!success) revert TransferFromFailed();
}
function safeTransfer(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert TransferFailed();
}
function safeApprove(
address token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
if (!success) revert ApproveFailed();
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"solmate/=lib/solmate/src/",
"@openzeppelin/=lib/openzeppelin-contracts/",
"@morpho-blue/=lib/morpho-blue/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.