Verified contractExactMIT
zSolverFill
Address0xa9ff2fff37576304ecb108e313e9364bc92412a1
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 9,999,999 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,870,161
- Creation transaction
- 0x92e07822e4…a51505ab0f
2 files
- src/utils/zSolverFill.solmain20.02 KB
- lib/solady/src/utils/SafeTransferLib.sol32.86 KB
src/utils/zSolverFill.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.36;
import {SafeTransferLib} from "../../lib/solady/src/utils/SafeTransferLib.sol";
/// @title zSolverExec
/// @notice The hand that touches the untrusted route. Owns nothing, is
/// approved by nobody, and answers only to the zSolverFill that
/// created it.
///
/// WHY THIS IS A SEPARATE CONTRACT
/// An earlier version of this design executed the solver's route from the
/// same contract users approve. That was wrong, and the way it was wrong is
/// worth writing down, because the mistake looks safe: the caller supplies
/// `target` and `data`, so the contract guarded them - `target` may not be
/// `tokenIn`, `tokenOut` or itself. But THE CALLER ALSO SUPPLIES `tokenIn`
/// AND `tokenOut`. A guard that compares the target against this call's
/// assets excludes nothing when the attacker picks this call's assets: pass
/// `tokenIn = ETH`, `amountIn = 0`, `minOut = 0` and a `tokenOut` whose
/// balance never moves, and every check passes, the measurement compares
/// zero against zero, and the contract makes an arbitrary call for anyone
/// who asks. Whatever standing allowance a user had granted it - and the
/// universal front-end habit is an infinite one - is then spendable by that
/// arbitrary call, because the spender is the contract itself.
///
/// No blacklist fixes that; the parameters it would have to constrain are
/// the attacker's to choose. What fixes it is SEPARATING THE ALLOWANCE FROM
/// THE ARBITRARY CALL. Users approve zSolverFill, which never calls anything
/// but this contract. This contract makes the untrusted call, and holds no
/// allowance from anyone, ever - so reaching it and steering it, which
/// remains possible, reaches nothing worth stealing.
///
/// WHAT AN ATTACKER STILL GETS, AND WHY IT IS SURVIVABLE
/// A funded `fill` can still steer this contract's `call` at an address of
/// the attacker's choosing, so `msg.sender == address(this)` is a signature
/// anyone can produce. Nothing should ever grant this address anything on
/// that basis.
///
/// BE PRECISE ABOUT WHAT IS AND IS NOT SWEPT, because an earlier version of
/// this comment overclaimed and the overclaim hid a bug. What `run` returns
/// to FILL is the DELTA it produced in `tokenOut`, the input it did not
/// spend, and ETH. What it does not touch is anything else: a third token
/// the arbitrary call acquired, or a token somebody transferred here, stays
/// put, and an allowance the arbitrary call granted on some unrelated token
/// stays granted. So this contract can hold balances and allowances between
/// calls. What matters is that NONE OF IT IS CREDITED TO A FILL - the delta
/// measurement above is what makes a fill's output attributable to its own
/// route - and that nothing here is ever a user's: no user approves this
/// address, and it is never a `to`.
///
/// `fill` also refuses a zero `amountIn` and a zero `minOut`. That raises
/// the price of producing the signature above zero; it does not make it
/// expensive, and it never did. Do not rely on it.
contract zSolverExec {
using SafeTransferLib for address;
/// @notice The only address that may call `run`.
/// @dev Set to the deployer, which is zSolverFill's constructor. There is
/// no setter and no second constructor argument: an executor whose
/// caller could be re-pointed would be an executor an attacker could
/// adopt.
address public immutable FILL;
error NotFill();
constructor() {
FILL = msg.sender;
}
/// @notice Approve, execute the route, and sweep everything back to FILL.
/// @dev Everything this touches is untrusted except `msg.sender`. It ends
/// holding nothing, which is the invariant the whole split exists to
/// preserve - a balance left here is a balance the next arbitrary
/// call could hand to whoever asked for it.
/// @return got The `tokenOut` this route actually produced, measured here
/// and RETURNED rather than left for the caller to infer from a
/// balance. That distinction is the whole fix for the hole below.
function run(
address target,
address spender,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes calldata data
) public payable returns (uint256 got) {
if (msg.sender != FILL) revert NotFill();
// SNAPSHOT BEFORE THE ROUTE RUNS, AND SWEEP ONLY THE DIFFERENCE. An
// earlier version swept this contract's whole `tokenOut` balance, which
// credited the fill with anything that happened to be sitting here -
// and anyone can put something here with a plain transfer. One wei
// planted in an earlier transaction then read as a complete fill, so a
// route that did nothing at all (or a `target` with no code) could
// clear a bound of one wei and commit whatever the arbitrary call had
// done. Measuring the delta is what makes the output attributable to
// THIS route rather than to the balance of a contract nobody guards.
uint256 outBefore = tokenOut == address(0) ? address(this).balance - msg.value : tokenOut.balanceOf(address(this));
// Exact, not infinite: an allowance larger than the route needs is an
// allowance the route can keep.
if (tokenIn != address(0)) tokenIn.safeApproveWithRetry(spender, amountIn);
bool ok;
assembly ("memory-safe") {
let p := mload(0x40)
calldatacopy(p, data.offset, data.length)
ok := call(gas(), target, callvalue(), p, data.length, codesize(), 0x00)
if iszero(ok) {
// Bubble the router's own revert so an aggregator's error
// survives the hop - but CAPPED. Copying unbounded returndata
// is a gas bomb a hostile target can hand any integrator that
// forwards a bounded gas budget.
let n := returndatasize()
if gt(n, 0x100) { n := 0x100 }
returndatacopy(p, 0x00, n)
revert(p, n)
}
}
// Zero the approval whether or not the route spent it, then leave with
// empty hands. `to` is FILL, not the user: FILL is the only party that
// can tell fill output from anything else, because it is the only one
// holding the before-measurement.
if (tokenIn != address(0)) {
tokenIn.safeApproveWithRetry(spender, 0);
// Capped at what we were handed. Returning more than that would be
// handing this fill a balance that belongs to no fill at all.
uint256 dust = tokenIn.balanceOf(address(this));
if (dust > amountIn) dust = amountIn;
if (dust != 0) tokenIn.safeTransfer(FILL, dust);
}
if (tokenOut != address(0)) {
got = tokenOut.balanceOf(address(this)) - outBefore;
if (got != 0) tokenOut.safeTransfer(FILL, got);
// Unspent ETH on a token-out route is change, and all of it goes
// back: the caller sent it, and FILL returns it from there.
uint256 eth = address(this).balance;
if (eth != 0) FILL.safeTransferETH(eth);
} else {
got = address(this).balance - outBefore;
if (got != 0) FILL.safeTransferETH(got);
}
}
/// @dev Routers refund ETH here mid-route. Anything that arrives outside a
/// route is swept to FILL by the next one and credited to whoever is
/// filling then - this contract is not custody and never was.
receive() external payable {}
}
/// @title zSolverFill
/// @notice Executes an off-chain solver's proposed route through zSolverExec
/// and pays out only what the recipient actually received, reverting
/// below the user's bound.
///
/// WHAT A SOLVER RETURNS, AND WHY IT CANNOT BE TRUSTED
/// An aggregator's quote endpoint hands back an address to call and a blob
/// of calldata to call it with. Neither is a promise. The endpoint may be
/// stale, degraded, rate-limited into nonsense, misconfigured, or hostile;
/// the page cannot tell which, and neither can this contract. So nothing
/// here reads the solver's claim about the outcome. The claim is discarded
/// and the outcome is MEASURED.
///
/// WHAT THIS CONTRACT GUARANTEES, STATED HONESTLY
/// `to` ends the call holding at least `minOut` more of `tokenOut` than it
/// started with, or the whole transaction reverts and the user keeps their
/// input. That is the entire promise, and it is deliberately narrower than
/// the one an earlier draft of this file made:
///
/// IT DOES NOT PROMISE THE PRICE WAS GOOD. `minOut` is supplied by the
/// caller, and on the page it is derived from the winning solver's OWN
/// quoted amount less the user's slippage. A solver that quotes high to win
/// the race and then settles at exactly the floor it induced extracts the
/// difference on every fill, and does so without ever tripping the check
/// below, because every one of those fills is a valid fill. Nothing in this
/// contract can see that, and nothing in it should pretend to. It is the
/// roster's problem: the handicap a lane must beat the on-chain best by has
/// to exceed the user's slippage, or the gap is a standing subsidy - and the
/// realized shortfall between what a lane quoted and what `Filled` records
/// is the evidence a curator should act on.
///
/// So: this contract bounds what a route may do once chosen. Choosing well
/// is somebody else's job, and saying otherwise here would be the kind of
/// overclaim that stops people from doing that job.
///
/// THE ARBITRARY CALL LIVES NEXT DOOR
/// `target`, `spender` and `data` come from the solver, and this contract
/// never passes them to anything but `EXEC` - a contract with no allowances,
/// no balances between calls and nothing to steal. See zSolverExec above for
/// why that separation is the fix and a target blacklist is not.
///
/// THE OUTPUT MUST BE ROUTED TO `EXEC`, NOT TO THE USER
/// Aggregator routers take a recipient. The page must set it to `EXEC()`.
/// A route that pays the user directly measures nothing here and reverts -
/// a safe failure, and a loud one, which is the intent.
///
/// APPROVE EXACTLY WHAT YOU ARE SELLING, FOR EXACTLY ONE TRANSACTION.
/// Never grant this contract an infinite allowance. The split above is what
/// makes a standing approval survivable rather than fatal; it is not a
/// reason to leave one lying around.
///
/// GOVERNANCE
/// There is none. No owner, no admin, no pause, no upgrade: this is the
/// fixed thing the mutable rosters are measured by, and a governable bound
/// check would put the bound under the same key that curates the endpoints
/// proposing routes through it. Changing behaviour means deploying a new
/// adapter and re-pointing a lane at it - a public, per-lane, reviewable act.
///
/// THE ROSTER NAMES THIS ADDRESS, WHICH IS WEAKER THAN IT SOUNDS. The page
/// learns which adapter to use by reading zSolverList through an RPC it also
/// learned from chain. A reader who controls that node controls both answers
/// and can name an adapter that is not this contract at all, in which case
/// none of the above applies because none of it ran. The page must therefore
/// pin the adapters it will accept - by address or by codehash - rather than
/// trusting the roster's answer. This contract cannot enforce that; it can
/// only refuse to imply the guarantee holds when it is bypassed.
contract zSolverFill {
using SafeTransferLib for address;
/// @dev ETH is `address(0)` throughout, as in zRouter.
address internal constant ETH = address(0);
/// @notice The stateless executor this contract routes every untrusted
/// call through. Created here, so its `FILL` is this address and
/// no third party could have adopted it first.
address public immutable EXEC;
/// @dev Transient reentrancy lock, `keccak256("zSolverFill.lock")`.
bytes32 internal constant LOCK = 0x59895352ebcc107737439479a84629478b2b9e50df57410ef238a409a55ba965;
/// @notice `to` did not end up with `minOut`. Carries both numbers, so a
/// failed fill says how far short it fell, not merely that it did.
error Insufficient(uint256 got, uint256 minOut);
/// @notice `target` or `spender` was one of the assets, the executor, or
/// this contract.
error BadTarget();
/// @notice `tokenIn == tokenOut`: no delta could distinguish fill from
/// refund, so there is no measurement to enforce a bound with.
error SameToken();
/// @notice `msg.value` did not match the input side: exactly `amountIn`
/// for an ETH input, exactly zero otherwise.
error BadValue();
/// @notice `amountIn` or `minOut` was zero. Neither is a swap, and a fill
/// that measures nothing against nothing is the free arbitrary
/// call this design exists to price.
error NothingToDo();
/// @notice Reentered mid-route.
error Reentrancy();
/// @notice A fill that cleared its bound, recorded with the MEASURED
/// output rather than the quoted one. The two are equal only when
/// nothing went wrong, and the gap between them - over many fills,
/// per lane - is the only honest evidence about whether a solver's
/// quotes mean anything. Curate on it.
event Filled(
address indexed target,
address indexed tokenIn,
address indexed tokenOut,
address to,
uint256 amountIn,
uint256 amountOut
);
constructor() {
EXEC = address(new zSolverExec());
}
/// @notice Execute a solver's route and pay out the measured output.
/// @param target The router the solver named. Untrusted.
/// @param spender Who pulls `tokenIn` - usually `target`, sometimes a
/// separate allowance holder. Ignored for an ETH input.
/// @param tokenIn What the user is selling; `address(0)` for ETH.
/// @param amountIn How much. Pulled from `msg.sender`, who must have
/// approved exactly this much, for exactly this call.
/// @param tokenOut What the user is buying; `address(0)` for ETH.
/// @param minOut The user's bound, checked against what `to` RECEIVES.
/// @param to Who receives the output.
/// @param data The solver's calldata, passed through unread. It must
/// route the output to `EXEC()`.
/// @return out What `to` actually received.
function fill(
address target,
address spender,
address tokenIn,
uint256 amountIn,
address tokenOut,
uint256 minOut,
address to,
bytes calldata data
) public payable returns (uint256 out) {
assembly ("memory-safe") {
if tload(LOCK) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
tstore(LOCK, 1)
}
if (tokenIn == tokenOut) revert SameToken();
if (amountIn == 0 || minOut == 0) revert NothingToDo();
address exec = EXEC;
// Paying the measurement's own endpoints turns the bound into a
// tautology: `to == exec` leaves the output where the next filler
// sweeps it while reporting success, and `to == address(this)` measures
// a self-transfer.
if (to == exec || to == address(this) || to == address(0)) revert BadTarget();
if (
target == tokenIn || target == tokenOut || target == address(this) || target == exec
|| spender == tokenIn || spender == tokenOut || spender == address(this) || spender == exec
) revert BadTarget();
bool ethIn = tokenIn == ETH;
if (msg.value != (ethIn ? amountIn : 0)) revert BadValue();
// MEASURE WHERE THE ROUTE CANNOT REACH. An earlier version took this
// contract's own `tokenOut` balance before and after, which looked
// equivalent and was not: `target` runs between those two reads and can
// simply transfer `tokenOut` straight here, so a route that swapped
// nothing could plant a wei, have it read as output, clear a bound of a
// wei, and commit whatever else the arbitrary call did. The executor's
// delta is the only number the route cannot forge - it is measured
// around the call, inside the contract the call runs as - so `held` is
// what `run` REPORTS, not what this balance says.
if (!ethIn) tokenIn.safeTransferFrom(msg.sender, exec, amountIn);
uint256 held =
zSolverExec(payable(exec)).run{value: msg.value}(target, spender, tokenIn, amountIn, tokenOut, data);
// REFUND THE INPUT BEFORE MEASURING THE OUTPUT. Ordering, not
// decoration: if `tokenIn` and `tokenOut` are two addresses over one
// ledger - a proxy pair, an aliased entry point - then unspent input
// sitting here would read as output and a no-op route would "clear"
// any bound up to `amountIn`. Returning it first means such a route
// measures nothing and reverts, which is the honest answer.
if (!ethIn) {
uint256 dust = tokenIn.balanceOf(address(this));
if (dust != 0) tokenIn.safeTransfer(msg.sender, dust);
} else {
// Only on the ETH-input path: when the OUTPUT is ETH this balance
// is the fill, not change. `force` because a refund must never be
// able to brick the contract - an integrator without a payable
// receive would otherwise be one stray wei away from every fill
// reverting, permanently, at an attacker's cost of one wei.
uint256 back = address(this).balance;
if (back != 0) msg.sender.forceSafeTransferETH(back);
}
if (held == 0) revert Insufficient(0, minOut);
// THE BOUND IS CHECKED WHERE THE USER IS. Measuring only what arrived
// HERE would promise "the adapter received minOut", which for a
// fee-on-transfer or rebasing output is not the same sentence as "the
// user received minOut" - and it is the second one people are relying
// on.
uint256 had = _balance(tokenOut, to);
_pay(tokenOut, to, held);
// CHECKED, DELIBERATELY. `unchecked` here saved about twenty gas and
// disabled the only guarantee this contract makes: a `tokenOut` that
// REDUCES the recipient's balance during transfer - reflection,
// anti-whale, a forwarding hook - made this wrap to ~2**256 and sail
// past `minOut` while the recipient ended the call poorer. The revert
// on underflow is the correct answer to a token that does that.
out = _balance(tokenOut, to) - had;
if (out < minOut) revert Insufficient(out, minOut);
emit Filled(target, tokenIn, tokenOut, to, amountIn, out);
assembly ("memory-safe") {
tstore(LOCK, 0)
}
}
/// @dev ETH from `EXEC`'s sweep lands here mid-fill. Nothing is meant to
/// rest here between calls.
receive() external payable {}
function _balance(address token) internal view returns (uint256) {
return _balance(token, address(this));
}
function _balance(address token, address who) internal view returns (uint256) {
return token == ETH ? who.balance : token.balanceOf(who);
}
function _pay(address token, address to, uint256 amount) internal {
if (token == ETH) to.safeTransferETH(amount);
else token.safeTransfer(to, amount);
}
}
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` does not implement `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), 0xa0, 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)
}
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 9999999,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.