Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/GoBridgeManager_V1.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/**
* @title GoBridgeManager_V1
* @notice Source/Destination bridge manager:
* - Pulls user funds via Uniswap Permit2 (SignatureTransfer)
* - Swaps to/from goUSD via Uniswap V3 router
* - Burns on source, mints on destination, charges protocol & ops fees
* - Guards: pausability, allowlisted tokens, min/max USD value per bridge
* - Oracle: IGOracle for price feeds (USD value, use WETH address for native)
* @dev EIP-712 used for ops fee quote; price checks via IGOracle; WETH wrapping.
*/
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { BridgeTypes } from "./libs/BridgeTypes.sol";
import { IGoUSD } from "./interfaces/IGoUSD.sol";
import { IGOracle } from "./interfaces/IGOracle.sol";
import { IGoTreasury } from "./interfaces/IGoTreasury.sol";
import { ISwapRouter } from "./interfaces/external/ISwapRouter.sol";
import { IPermit2 } from "./interfaces/external/IPermit2.sol";
import { IWrapped } from "./interfaces/external/IWrapped.sol";
import { AbstractCallback } from "@reactive/src/abstract-base/AbstractCallback.sol";
contract GoBridgeManager_V1 is AccessControl, ReentrancyGuard, Pausable, AbstractCallback, EIP712 {
using SafeERC20 for IERC20;
// ─────────────────────────────────────────────────────────────────────────────
// Roles / Events / Errors
// ─────────────────────────────────────────────────────────────────────────────
/// @notice Ops/admin config (limits, tokens, fees).
bytes32 public constant OPS_ADMIN_ROLE = keccak256("OPS_ADMIN_ROLE");
/// @notice Emergency pause/unpause.
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Emitted when a bridge request is accepted on source chain.
event BridgeInitialized(
bytes32 indexed requestId,
uint64 indexed srcChainId,
uint64 indexed destChainId,
bytes destSwapPath,
address srcBridge,
uint128 srcNonce,
address srcInitiator,
address destTo,
address srcToken,
address destToken,
uint256 srcAmountIn,
uint256 goUSDBurned,
uint256 minAmountOut,
uint256 rnkFee,
uint256 destFee
);
/// @notice Emitted when a bridge request is fulfilled on destination chain.
event BridgeFinalized(bytes32 indexed requestId, address to, address destToken, uint256 amountOut);
event SetRouter(address router);
event SetOracle(address oracle);
event SetSrcSlippageBps(uint16 bps);
event SetProtocolFeeBps(uint16 bps);
event SetAllowedToken(address token, bool allowed);
event SetMinValuePerBridge(uint256 minUsd);
event SetMaxValuePerBridge(uint256 maxUsd);
// Short, explicit reverts for auditability
error InvalidParams();
error InvalidSwapData();
error Permit2Error();
error ErrDestEqSrc();
error ErrFinalized();
error OracleError();
error ErrFeesTooHigh();
error ErrQuoteExpired();
error ErrBadSignature();
error ErrPercentTooHigh();
error BelowMinValuePerBridge();
error ExceedsMaxValuePerBridge();
// ─────────────────────────────────────────────────────────────────────────────
// Immutable / Config
// ─────────────────────────────────────────────────────────────────────────────
IGoUSD public immutable goUSD;
IGOracle public gOracle;
IGoTreasury public immutable goTreasury;
IWrapped public immutable WETH;
ISwapRouter public router;
IPermit2 public immutable PERMIT2;
uint16 public srcSlippageBps; // max src slippage (bps) for oracle-anchored minOut
uint16 public protocolFeeBps; // protocol fee on destination mint (bps)
uint128 private _nonce; // source-chain nonce for requestId
uint256 public minValuePerBridge = 1e18; // min USD value (18d)
uint256 public maxValuePerBridge = 15e18; // max USD value (18d)
mapping(address => bool) public allowedToken; // allowlist for src/dest tokens (address(0) = native)
mapping(bytes32 => bool) public finalized; // requestId -> finalized?
bytes32 constant RID_TYPEHASH = keccak256("GoBridge::BridgeRequest_V1");
struct GasShape {
bool isNative; // srcToken == address(0) ? WETH.deposit : ERC-20
bool usesPermit2; // if ERC-20 true (pull via Permit2)
bool needsSwap; // inputToken -> goUSD swap (srcToken != goUSD)
uint8 hopCount; // Uniswap V3 path hop count (0 = direct)
bool needsAllowanceWrite; // if router allowance < amountIn
bool willBurn; // goUSD burn
address inputToken; // if native WETH or srcToken
uint256 minGoUSDEstimate; // oracle based min goUSD out (srcToken -> goUSD)
uint256 expectedMsgValue; // expected msg.value (native srcToken)
}
// ─────────────────────────────────────────────────────────────────────────────
// Init / Admin
// ─────────────────────────────────────────────────────────────────────────────
/**
* @dev Wires core dependencies and seeds roles.
* Note: DEFAULT_ADMIN can grant/revoke OPS_ADMIN/GUARDIAN later.
*/
constructor(
address admin,
address _goUSD,
address _gOracle,
address _goTreasury,
address _router,
address _permit2,
address _WETH,
address _reactiveEngine,
uint16 _protocolFeeBps,
uint16 _srcSlippageBps
) AbstractCallback(_reactiveEngine) EIP712("GoBridge", "1") {
if (_goUSD == address(0) || _gOracle == address(0) || _goTreasury == address(0) || _router == address(0) || _permit2 == address(0) || _WETH == address(0)) {
revert InvalidParams();
}
_grantRole(GUARDIAN_ROLE, admin);
_grantRole(OPS_ADMIN_ROLE, admin);
_grantRole(DEFAULT_ADMIN_ROLE, admin);
if (msg.sender != admin) _revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
goUSD = IGoUSD(_goUSD);
gOracle = IGOracle(_gOracle);
goTreasury = IGoTreasury(_goTreasury);
router = ISwapRouter(_router);
PERMIT2 = IPermit2(_permit2);
WETH = IWrapped(_WETH);
protocolFeeBps = _protocolFeeBps;
srcSlippageBps = _srcSlippageBps;
// Default allowlist: goUSD, WETH, native
allowedToken[address(goUSD)] = true;
allowedToken[address(WETH)] = true;
allowedToken[address(0)] = true;
emit SetAllowedToken(address(goUSD), true);
emit SetAllowedToken(address(WETH), true);
emit SetAllowedToken(address(0), true);
}
/// @notice Manage roles & core params.
function setOPSAdmin(address setter, bool allow) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (allow) _grantRole(OPS_ADMIN_ROLE, setter);
else _revokeRole(OPS_ADMIN_ROLE, setter);
}
function setGuardian(address guardian, bool allow) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (allow) _grantRole(GUARDIAN_ROLE, guardian);
else _revokeRole(GUARDIAN_ROLE, guardian);
}
function setRouter(address _router) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_router == address(0)) revert InvalidParams();
router = ISwapRouter(_router);
emit SetRouter(_router);
}
function setGOracle(address _gOracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_gOracle == address(0)) revert InvalidParams();
gOracle = IGOracle(_gOracle);
emit SetOracle(_gOracle);
}
function setSrcSlippageBps(uint16 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (bps > 10_000) revert ErrPercentTooHigh();
srcSlippageBps = bps;
emit SetSrcSlippageBps(bps);
}
/// @notice Token allowlist management (src & dest).
function setAllowedToken(address token, bool allowed) external onlyRole(OPS_ADMIN_ROLE) {
allowedToken[token] = allowed;
emit SetAllowedToken(token, allowed);
}
function setAllowedTokens(address[] calldata tokens, bool allowed) external onlyRole(OPS_ADMIN_ROLE) {
for (uint256 i; i < tokens.length; ++i) {
allowedToken[tokens[i]] = allowed;
emit SetAllowedToken(tokens[i], allowed);
}
}
/// @notice USD value limits (18 decimals).
function setMinValuePerBridge(uint256 v) external onlyRole(OPS_ADMIN_ROLE) {
minValuePerBridge = v;
emit SetMinValuePerBridge(v);
}
function setMaxValuePerBridge(uint256 v) external onlyRole(OPS_ADMIN_ROLE) {
maxValuePerBridge = v;
emit SetMaxValuePerBridge(v);
}
/// @notice Protocol fee on destination (bps).
function setProtocolFeeBps(uint16 bps) external onlyRole(OPS_ADMIN_ROLE) {
if (bps > 10_000) revert ErrPercentTooHigh();
protocolFeeBps = bps;
emit SetProtocolFeeBps(bps);
}
/// @notice Admin sweep for emergency/failure (any token, incl. native).
function sweep(address token, address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (to == address(0)) revert InvalidParams();
if (token == address(0)) {
(bool ok,) = payable(to).call{value: amount}(""); require(ok, "ETH_SEND_FAIL");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
/// @notice Pause controls.
function pause() external onlyRole(GUARDIAN_ROLE) { _pause(); }
function unpause() external onlyRole(GUARDIAN_ROLE) { _unpause(); }
// ─────────────────────────────────────────────────────────────────────────────
// Core (source & destination legs)
// ─────────────────────────────────────────────────────────────────────────────
/**
* @notice Source leg: pull funds (Permit2 for ERC20 / wrap native), swap to goUSD, burn, emit request.
* @dev Enforces token allowlist and USD value bounds via oracle.
*/
function initiateBridge(
BridgeTypes.BridgeRequest calldata request,
BridgeTypes.Permit2Data calldata permit,
bytes calldata srcSwapPath,
bytes calldata destSwapPath,
BridgeTypes.FeeQuote calldata feeQuote
) external payable nonReentrant whenNotPaused returns (bytes32) {
if (request.destChainId == uint64(block.chainid)) revert ErrDestEqSrc();
if (request.amountIn == 0 || request.minAmountOut == 0) revert InvalidParams();
if (request.destTo == address(0)) revert InvalidParams();
if (request.srcInitiator == address(0)) revert InvalidParams();
if (request.srcToken == address(0) && (msg.value == 0 || request.amountIn != msg.value)) revert InvalidParams();
_requireAllowedToken(request.srcToken);
// USD value guard (18d)
address tokenForUsd = request.srcToken == address(0) ? address(WETH) : request.srcToken;
uint256 usdVal = _oracleUsdValue18(tokenForUsd, request.amountIn);
if (usdVal > maxValuePerBridge) revert ExceedsMaxValuePerBridge();
if (usdVal < minValuePerBridge) revert BelowMinValuePerBridge();
// Ops quote signer check (EIP-712)
_verifyFeeQuote(feeQuote, uint64(block.chainid), request.destChainId);
// Pull funds (native→wrap or Permit2)
address inputToken;
if (request.srcToken == address(0)) {
WETH.deposit{value: request.amountIn}();
inputToken = address(WETH);
} else {
_pullWithPermit(request, permit);
inputToken = request.srcToken;
}
// Swap to goUSD if needed
uint256 goUSDAmount;
if (inputToken == address(goUSD)) {
goUSDAmount = request.amountIn;
} else {
if (srcSwapPath.length == 0) revert InvalidSwapData();
if (_v3LastToken(srcSwapPath) != address(goUSD)) revert InvalidSwapData();
if (_v3FirstToken(srcSwapPath) != inputToken) revert InvalidSwapData();
if (IERC20(inputToken).allowance(address(this), address(router)) < request.amountIn) {
uint256 cur = IERC20(inputToken).allowance(address(this), address(router));
if (cur != 0) IERC20(inputToken).safeDecreaseAllowance(address(router), cur);
IERC20(inputToken).safeIncreaseAllowance(address(router), type(uint256).max);
}
uint256 minOut = _oracleMinGoUSDOut(inputToken, request.amountIn);
uint256 routerOut = router.exactInput(
ISwapRouter.ExactInputParams({
path: srcSwapPath,
recipient: address(this),
amountIn: request.amountIn,
amountOutMinimum: minOut
})
);
goUSDAmount = routerOut;
}
// Burn & emit
if (IERC20(address(goUSD)).balanceOf(address(this)) < goUSDAmount) revert InvalidParams();
goUSD.burn(goUSDAmount);
uint128 n; unchecked { n = ++_nonce; }
uint64 srcCid = uint64(block.chainid);
address srcBridge = address(this);
bytes32 rid = _rid(request, msg.sender, goUSDAmount, n, srcCid, srcBridge);
emit BridgeInitialized(
rid, srcCid, request.destChainId, destSwapPath, srcBridge, n, msg.sender, request.destTo,
request.srcToken, request.destToken, request.amountIn, goUSDAmount, request.minAmountOut,
feeQuote.rnk, feeQuote.dest
);
return rid;
}
/**
* @notice Destination leg: mint goUSD, take fees, optional swap to target token/ETH, deliver.
* @dev Protects against double-finalize; validates requestId consistency.
*/
function finalizeBridge(
address rvmId,
BridgeTypes.BridgePacket calldata pkt,
bytes calldata destSwapPath,
uint256 rnkFee,
uint256 destFee
) external nonReentrant authorizedSenderOnly rvmIdOnly(rvmId) whenNotPaused {
if (finalized[pkt.requestId]) revert ErrFinalized();
if (pkt.req.destChainId != block.chainid) revert InvalidParams();
finalized[pkt.requestId] = true;
_requireAllowedToken(pkt.req.destToken);
// Rebuild and check requestId
bytes32 rid = _rid(pkt.req, pkt.req.srcInitiator, pkt.goUSDBurned, pkt.srcNonce, pkt.srcChainId, pkt.srcBridge);
if (rid != pkt.requestId) revert InvalidParams();
// Mint & fee accounting
goUSD.mint(address(this), pkt.goUSDBurned);
uint256 minted = pkt.goUSDBurned;
uint256 protocolFee = protocolFeeBps == 0 ? 0 : (minted * protocolFeeBps) / 10_000;
if (protocolFee + rnkFee + destFee >= minted) revert ErrFeesTooHigh();
// Convert destFee goUSD -> WETH -> hold as ETH (for gas & ops)
if (destFee != 0) {
if (IERC20(address(goUSD)).allowance(address(this), address(router)) < destFee) {
uint256 cur = IERC20(address(goUSD)).allowance(address(this), address(router));
if (cur != 0) IERC20(address(goUSD)).safeDecreaseAllowance(address(router), cur);
IERC20(address(goUSD)).safeIncreaseAllowance(address(router), type(uint256).max);
}
uint256 minWethOut = _oracleMinWETHOut(destFee);
uint256 gotWeth = router.exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: address(goUSD),
tokenOut: address(WETH),
fee: 500,
recipient: address(this),
amountIn: destFee,
amountOutMinimum: minWethOut,
sqrtPriceLimitX96: 0
})
);
WETH.withdraw(gotWeth);
}
// Send RNK fee to treasury
if (rnkFee != 0) {
if (IERC20(address(goUSD)).allowance(address(this), address(goTreasury)) < rnkFee) {
uint256 cur = IERC20(address(goUSD)).allowance(address(this), address(goTreasury));
if (cur != 0) IERC20(address(goUSD)).safeDecreaseAllowance(address(goTreasury), cur);
IERC20(address(goUSD)).safeIncreaseAllowance(address(goTreasury), type(uint256).max);
}
goTreasury.depositTagged(rnkFee, bytes32("BRIDGE_RNK_FEE"));
}
// Send protocol fee to treasury
if (protocolFee != 0) {
if (IERC20(address(goUSD)).allowance(address(this), address(goTreasury)) < protocolFee) {
uint256 cur = IERC20(address(goUSD)).allowance(address(this), address(goTreasury));
if (cur != 0) IERC20(address(goUSD)).safeDecreaseAllowance(address(goTreasury), cur);
IERC20(address(goUSD)).safeIncreaseAllowance(address(goTreasury), type(uint256).max);
}
goTreasury.depositTagged(protocolFee, bytes32("BRIDGE_PROTOCOL_FEE"));
}
// Deliver remainder to user (direct goUSD or swap)
uint256 net = minted - protocolFee - rnkFee - destFee;
address destToken = pkt.req.destToken;
uint256 outAmt;
if (destToken == address(goUSD)) {
IERC20(address(goUSD)).safeTransfer(pkt.req.destTo, net);
outAmt = net;
} else {
if (destSwapPath.length == 0) revert InvalidSwapData();
if (_v3FirstToken(destSwapPath) != address(goUSD)) revert InvalidSwapData();
address outputToken = _v3LastToken(destSwapPath);
bool wantETH = (destToken == address(0));
if (wantETH) {
if (outputToken != address(WETH)) revert InvalidSwapData();
} else {
if (outputToken != destToken) revert InvalidSwapData();
}
if (IERC20(address(goUSD)).allowance(address(this), address(router)) < net) {
uint256 cur = IERC20(address(goUSD)).allowance(address(this), address(router));
if (cur != 0) IERC20(address(goUSD)).safeDecreaseAllowance(address(router), cur);
IERC20(address(goUSD)).safeIncreaseAllowance(address(router), type(uint256).max);
}
address recipient = wantETH ? address(this) : pkt.req.destTo;
uint256 got = router.exactInput(
ISwapRouter.ExactInputParams({
path: destSwapPath,
recipient: recipient,
amountIn: net,
amountOutMinimum: pkt.req.minAmountOut
})
);
if (wantETH) {
WETH.withdraw(got);
(bool ok,) = payable(pkt.req.destTo).call{value: got}("");
require(ok, "ETH_SEND_FAIL");
}
outAmt = got;
}
emit BridgeFinalized(pkt.requestId, pkt.req.destTo, destToken, outAmt);
}
function quoteInitiateBridgeGasShape(
BridgeTypes.BridgeRequest calldata request,
bytes calldata srcSwapPath,
BridgeTypes.FeeQuote calldata feeQuote
) external view returns (GasShape memory s) {
if (request.destChainId == uint64(block.chainid)) revert ErrDestEqSrc();
if (request.amountIn == 0 || request.minAmountOut == 0) revert InvalidParams();
if (request.destTo == address(0)) revert InvalidParams();
if (request.srcInitiator == address(0)) revert InvalidParams();
_requireAllowedToken(request.srcToken);
address tokenForUsd = request.srcToken == address(0) ? address(WETH) : request.srcToken;
uint256 usdVal = _oracleUsdValue18(tokenForUsd, request.amountIn);
if (usdVal > maxValuePerBridge) revert ExceedsMaxValuePerBridge();
if (usdVal < minValuePerBridge) revert BelowMinValuePerBridge();
_verifyFeeQuote(feeQuote, uint64(block.chainid), request.destChainId);
// === Shape ===
s.isNative = (request.srcToken == address(0));
s.usesPermit2 = !s.isNative;
s.willBurn = true;
s.inputToken = s.isNative ? address(WETH) : request.srcToken;
s.expectedMsgValue = s.isNative ? request.amountIn : 0;
if (s.inputToken == address(goUSD)) {
s.needsSwap = false;
s.hopCount = 0;
s.minGoUSDEstimate = request.amountIn;
} else {
if (srcSwapPath.length == 0) revert InvalidSwapData();
if (_v3LastToken(srcSwapPath) != address(goUSD)) revert InvalidSwapData();
if (_v3FirstToken(srcSwapPath) != s.inputToken) revert InvalidSwapData();
s.needsSwap = true;
s.hopCount = _v3HopCount(srcSwapPath);
s.minGoUSDEstimate = _oracleMinGoUSDOut(s.inputToken, request.amountIn);
}
if (s.needsSwap) {
uint256 cur = IERC20(s.inputToken).allowance(address(this), address(router));
s.needsAllowanceWrite = (cur < request.amountIn);
} else {
s.needsAllowanceWrite = false;
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Signatures / Oracle / Helpers
// ─────────────────────────────────────────────────────────────────────────────
/// @dev EIP-712 ops fee quote verification (signer must have OPS_ADMIN_ROLE).
function _verifyFeeQuote(BridgeTypes.FeeQuote calldata q, uint64 srcChainId, uint64 destChainId) internal view {
if (q.expiresAt != 0 && block.timestamp > q.expiresAt) revert ErrQuoteExpired();
bytes32 structHash = keccak256(
abi.encode(
BridgeTypes.FEEQUOTE_TYPEHASH,
address(this),
srcChainId,
destChainId,
q.rnk,
q.dest,
q.expiresAt
)
);
bytes32 digest = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(digest, q.signature);
if (!hasRole(OPS_ADMIN_ROLE, signer)) revert ErrBadSignature();
}
/// @dev Deterministic requestId used for dedupe and finalize validation.
function _rid(
BridgeTypes.BridgeRequest calldata r,
address srcInitiator,
uint256 burned,
uint128 n,
uint64 srcChainId,
address srcBridge
) internal pure returns (bytes32) {
return keccak256(
abi.encode(
RID_TYPEHASH,
srcInitiator,
r.destTo,
r.srcToken,
r.destToken,
r.amountIn,
burned,
r.minAmountOut,
r.destChainId,
n,
srcChainId,
srcBridge
)
);
}
/// @dev Pull ERC20 via Permit2 with witness binding to bridge params.
function _pullWithPermit(BridgeTypes.BridgeRequest calldata r, BridgeTypes.Permit2Data calldata p) internal {
if (p.owner != msg.sender) revert Permit2Error();
IPermit2.PermitTransferFrom memory permit = IPermit2.PermitTransferFrom({
permitted: IPermit2.TokenPermissions({ token: r.srcToken, amount: r.amountIn }),
nonce: p.nonce,
deadline: p.deadline
});
IPermit2.SignatureTransferDetails memory details = IPermit2.SignatureTransferDetails({
to: address(this),
requestedAmount: r.amountIn
});
bytes32 witness = keccak256(
abi.encode(
BridgeTypes.WITNESS_TYPE,
r.destTo,
r.destToken,
r.minAmountOut,
r.destChainId,
p.deadline,
p.nonce
)
);
PERMIT2.permitWitnessTransferFrom(permit, details, p.owner, witness, BridgeTypes.WITNESS_TYPE_STR, p.signature);
}
/// @dev USD valuation (18d) via oracle (native handled as address(WETH)).
function _oracleUsdValue18(address token, uint256 amount) internal view returns (uint256 usd18) {
if (token == address(goUSD)) return amount;
uint8 tdec = (token == address(WETH)) ? 18 : IERC20Metadata(token).decimals();
(uint256 px, uint8 pdec, , bool liveHealthy) = gOracle.peekAssetPrice(token);
if (!liveHealthy || px == 0) revert OracleError();
if (pdec <= 18) {
uint256 up = 10 ** uint256(18 - pdec);
usd18 = Math.mulDiv(amount, px, 10 ** uint256(tdec));
usd18 = usd18 * up;
} else {
uint256 down = 10 ** uint256(pdec - 18);
usd18 = Math.mulDiv(amount, px, 10 ** uint256(tdec));
usd18 = usd18 / down;
}
}
/// @dev Oracle-anchored min goUSD out for source swap.
function _oracleMinGoUSDOut(address srcToken, uint256 amountIn) internal view returns (uint256 minOut) {
if (srcToken == address(goUSD)) return amountIn;
uint8 tdec = (srcToken == address(WETH)) ? 18 : IERC20Metadata(srcToken).decimals();
(uint256 px, uint8 pdec, , bool liveHealthy) = gOracle.peekAssetPrice(srcToken);
if (!liveHealthy || px == 0) revert OracleError();
uint256 usd18;
if (pdec <= 18) {
uint256 up = 10 ** uint256(18 - pdec);
usd18 = Math.mulDiv(amountIn, px, 10 ** uint256(tdec));
usd18 = usd18 * up;
} else {
uint256 down = 10 ** uint256(pdec - 18);
usd18 = Math.mulDiv(amountIn, px, (10 ** uint256(tdec)));
usd18 = usd18 / down;
}
uint256 bps = 10_000 - srcSlippageBps;
minOut = (usd18 * bps) / 10_000;
}
/// @dev Oracle-anchored min WETH out when converting dest fees (goUSD→WETH).
function _oracleMinWETHOut(uint256 usd18) internal view returns (uint256 minOut) {
(uint256 px, uint8 pdec, , bool ok) = gOracle.peekAssetPrice(address(WETH)); // native/WETH per oracle
if (!ok || px == 0) revert OracleError();
// WETH = USD / price (all normalized to 18d)
uint256 weth18 = Math.mulDiv(usd18, 10 ** uint256(pdec), px);
uint256 bps = 10_000 - srcSlippageBps;
minOut = (weth18 * bps) / 10_000;
}
/// @dev Uniswap V3 path helpers (first/last token).
function _v3FirstToken(bytes memory path) internal pure returns (address a) {
if (path.length < 43) revert InvalidSwapData();
assembly { a := shr(96, mload(add(path, 32))) }
}
function _v3LastToken(bytes memory path) internal pure returns (address out) {
if (path.length < 20) revert InvalidSwapData();
uint256 off;
unchecked { off = path.length - 20; }
assembly { out := shr(96, mload(add(path, add(32, off)))) }
}
function _v3HopCount(bytes memory path) internal pure returns (uint8) {
if (path.length < 20) revert InvalidSwapData();
uint256 rem = path.length - 20;
if (rem % 23 != 0) revert InvalidSwapData();
uint256 hops = rem / 23;
require(hops <= type(uint8).max, "HopOverflow");
return uint8(hops);
}
/// @dev Reusable allowlist require.
function _requireAllowedToken(address token) internal view {
if (!allowedToken[token]) revert InvalidParams();
}
}"
},
"lib/openzeppelin-contracts/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/Pausable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos s
Submitted on: 2025-10-03 11:44:30
Comments
Log in to comment.
No comments yet.