Verified contractPartialGPL-3.0-or-later
SpotOrderGateway
Address0xe355028ab20ee73938dcf8a91ddd3ce421b71a76
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- License
- GPL-3.0-or-later
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 21,835,788
- Creation transaction
- 0x9f7519ea5a…d10685c846
26 files
- src/spotOrderGateway/SpotOrderGateway.solmain40.08 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- @openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/math/SafeCast.sol34.69 KB
- across-protocol/contracts/contracts/interfaces/V3SpokePoolInterface.sol13.84 KB
- across-protocol/contracts/contracts/libraries/AddressConverters.sol883 B
- multicaller/LibMulticaller.sol2.4 KB
- permit2/src/interfaces/IAllowanceTransfer.sol7.7 KB
- permit2/src/interfaces/IEIP712.sol144 B
- permit2/src/interfaces/IERC1271.sol464 B
- permit2/src/interfaces/ISignatureTransfer.sol6.88 KB
- permit2/src/libraries/PermitHash.sol5.77 KB
- permit2/src/libraries/SignatureVerification.sol1.81 KB
- src/common/ContextBase.sol281 B
- src/common/LibConstant.sol364 B
- src/common/LibError.sol7.03 KB
- src/external/uniswap-v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol1.36 KB
- src/external/uniswap-v3-periphery/contracts/interfaces/ISwapRouter.sol2.77 KB
- src/spotOrderGateway/ERC7683Across.sol4.33 KB
- src/spotOrderGateway/IV3SpokePool.sol536 B
- src/spotOrderGateway/LegacyERC7683.sol4.23 KB
src/spotOrderGateway/SpotOrderGateway.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.24;
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// solhint-disable-next-line max-line-length
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { PermitHash } from "permit2/src/libraries/PermitHash.sol";
import { ISignatureTransfer } from "permit2/src/interfaces/ISignatureTransfer.sol";
import { SignatureVerification } from "permit2/src/libraries/SignatureVerification.sol";
import { AddressToBytes32, Bytes32ToAddress } from "across-protocol/contracts/contracts/libraries/AddressConverters.sol";
import { SwapType, AcrossOrderData, AcrossFillerData, ERC7683Permit2Lib } from "./ERC7683Across.sol";
import { ISettlementContract, CrossChainOrder, ResolvedCrossChainOrder, Input, Output } from "./LegacyERC7683.sol";
import { LibError } from "../common/LibError.sol";
import { ONE_PERCENT } from "../common/LibConstant.sol";
import { ContextBase } from "../common/ContextBase.sol";
import { IV3SpokePool } from "./IV3SpokePool.sol";
import { ISwapRouter } from "../external/uniswap-v3-periphery/contracts/interfaces/ISwapRouter.sol";
contract SpotOrderGateway is ISettlementContract, ContextBase, ReentrancyGuardUpgradeable {
using SafeCast for uint256;
using SafeCast for int256;
using SafeERC20 for IERC20Metadata;
using AddressToBytes32 for address;
using Bytes32ToAddress for bytes32;
address constant OneInchAggregationRouterV6 = address(0x111111125421cA6dc452d289314280a0f8842A65);
address constant KyberMetaAggregationRouterV2 = address(0x6131B5fae19EA4f9D964eAc0408E4408b66337b5);
// NOTE: handle "1-2 wei corner case" of rebase tokens, ex: stETH, USDM
// https://docs.lido.fi/guides/lido-tokens-integration-guide/#1-2-wei-corner-case
uint256 constant RebaseTokenToleranceWei = 2;
//
// EVENT
//
event SameChainOrderFilled(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
address indexed depositor,
address recipient,
bytes32 permitHash
);
event Deposited(
address inputToken,
address outputToken,
address bridgeToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 bridgeAmount,
uint256 indexed destinationChainId,
uint32 indexed depositId,
address indexed depositor,
address recipient,
address exclusiveRelayer,
bytes32 permitHash
);
event TokenSwapped(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
address recipient,
uint256 bonusInputAmountForRelayer,
uint256 bonusOutputAmountForRelayer
);
event SurplusDispersed(address indexed recipient, address indexed token, uint256 surplusAmount);
//
// STRUCT
//
/// @custom:storage-location erc7201:perp.storage.orderGateway
struct SpotOrderGatewayStorage {
ISignatureTransfer permit2;
IV3SpokePool spokePool;
mapping(bytes32 => bool) isOrderDeposited;
// swap-related
ISwapRouter uniswapV3Router;
address uniswapSwapRouter02; // we only use low level call
}
struct SpokePoolDepositParams {
address depositor;
address recipient;
address inputToken;
address outputToken;
uint256 inputAmount;
uint256 outputAmount;
uint256 destinationChainId;
address exclusiveRelayer;
uint32 fillDeadline;
uint32 exclusivityDeadline;
bytes message;
}
struct UniswapV3ExactInputParams {
address inputToken;
address outputToken;
bytes path;
uint256 inputAmount;
uint256 outputAmountMinimum;
}
struct UniswapV3ExactOutputParams {
address inputToken;
address outputToken;
bytes path;
uint256 outputAmount;
uint256 inputAmountMaximum;
}
struct UniswapSwapRouter02ExactInputParams {
address inputToken;
address outputToken;
uint256 inputAmount;
bytes swapData;
}
struct UniswapSwapRouter02ExactOutputParams {
address inputToken;
address outputToken;
uint256 inputAmountMaximum;
bytes swapData;
}
struct AggregationRouterExactInputParams {
address approvalTarget; // to support okx aggregator token approval
address aggregator;
address inputToken;
address outputToken;
uint256 inputAmount;
bytes swapData;
}
struct SwapExactInputParams {
address inputToken;
address outputToken;
uint256 inputAmount;
uint256 outputAmountMinimum;
SwapType swapType;
bytes swapData;
}
//
// STATE
//
// keccak256(abi.encode(uint256(keccak256("perp.storage.spotOrderGateway")) - 1)) & ~bytes32(uint256(0xff));
bytes32 constant _SPOT_ORDER_GATEWAY_STORAGE_LOCATION =
0x87abb921a05c7261eb13a9fc71e9bb1efd6ea591279f12e236b4164dc8fc2900;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address permit2_,
address spokePool_,
address uniswapV3Router_, // only v3
address uniswapSwapRouter02_ // v2 + v3
) external initializer {
__ReentrancyGuard_init();
// __Ownable2Step_init();
// __Ownable_init(msg.sender);
_getSpotOrderGatewayStorage().permit2 = ISignatureTransfer(permit2_);
_getSpotOrderGatewayStorage().spokePool = IV3SpokePool(spokePool_);
_getSpotOrderGatewayStorage().uniswapV3Router = ISwapRouter(uniswapV3Router_);
_getSpotOrderGatewayStorage().uniswapSwapRouter02 = uniswapSwapRouter02_;
}
/// @inheritdoc ISettlementContract
function initiate(
CrossChainOrder calldata order,
bytes calldata signature,
bytes calldata fillerData
) external nonReentrant {
if (order.settlementContract != address(this)) {
revert LibError.InvalidSettlementContract(order.settlementContract);
}
if (order.originChainId != block.chainid.toUint32()) {
revert LibError.InvalidOriginChainId(order.originChainId);
}
(AcrossOrderData memory acrossOrderData, AcrossFillerData memory orderFillerData) = (
abi.decode(order.orderData, (AcrossOrderData)),
abi.decode(fillerData, (AcrossFillerData))
);
SpotOrderGatewayStorage storage $ = _getSpotOrderGatewayStorage();
bytes32 permitHash = getPermitHash(order);
if ($.isOrderDeposited[permitHash]) {
revert LibError.CrossChainOrderAlreadyInitiated(permitHash);
}
$.isOrderDeposited[permitHash] = true;
// verify Permit2 signature and pull user funds into this contract
// it's possible that transferredInputAmount != acrossOrderData.inputAmount for some rebase tokens
_processPermit2Order(order, acrossOrderData, signature);
// same-chain orders only need swap, no interaction with Across
if (order.originChainId == acrossOrderData.destinationChainId) {
// NOTE: we use acrossOrderData.outputAmount as outputAmountMinimum, if not enough, swap will revert.
// and user always receives exactly acrossOrderData.outputAmount,
// the surplus amount is bonus for relayer
(, uint256 surplusOutputAmount) = _swapExactInput(
acrossOrderData.inputToken,
acrossOrderData.outputToken,
acrossOrderData.inputAmount,
acrossOrderData.outputAmount,
acrossOrderData.recipient,
address(this),
orderFillerData.swapType,
orderFillerData.swapData
);
_disperseSurplusToken(
IERC20Metadata(acrossOrderData.outputToken),
surplusOutputAmount,
orderFillerData.surplusDisperseRatio,
_sender(),
acrossOrderData.recipient
);
emit SameChainOrderFilled(
acrossOrderData.inputToken,
acrossOrderData.outputToken,
acrossOrderData.inputAmount,
acrossOrderData.outputAmount,
order.swapper,
acrossOrderData.recipient,
permitHash
);
return;
}
// only Across supported assets can be bridged, otherwise, need to swap first
if (acrossOrderData.bridgeToken == address(0)) {
revert LibError.InvalidBridgeToken();
}
uint256 acrossDepositInputAmount; // the actual amount we deposit to Across
if (acrossOrderData.inputToken == acrossOrderData.bridgeToken) {
if (acrossOrderData.bridgeAmountOutMinimum != acrossOrderData.inputAmount) {
revert LibError.MismatchedBridgeAmount(
acrossOrderData.bridgeAmountOutMinimum,
acrossOrderData.inputAmount
);
}
// if buy: swap USDC to XXX, ex: 3000 USDC to 1 ETH
// spotOrder.inputToken = USDC on origin chain
// spotOrder.inputAmount = 3000
// spotOrder.bridgeToken = USDC on origin chain
// spotOrder.bridgeAmount = 3000
// spotOrder.outputToken = WETH on destination chain
// spotOrder.outputAmount = 0.95 ETH (with slippage)
// across.inputToken = USDC on origin chain
// across.inputAmount = 3000
// across.outputToken = WETH on destination chain
// across.outputAmount = 0.95 ETH (with slippage)
// no need to swap to bridgeToken, it already is
acrossDepositInputAmount = acrossOrderData.inputAmount;
} else {
if (acrossOrderData.bridgeAmountOutMinimum != acrossOrderData.outputAmount) {
revert LibError.MismatchedBridgeAmount(
acrossOrderData.bridgeAmountOutMinimum,
acrossOrderData.outputAmount
);
}
// if sell: swap XXX to USDC, ex: 1 ETH to 2900 USDC
// spotOrder.inputToken = ETH
// spotOrder.inputAmount: 1 ETH
// spotOrder.bridgeToken = USDC on origin chain
// spotOrder.bridgeAmount: 2900
// spotOrder.outputToken = USDC on destination chain
// spotOrder.outputAmount = 2900
// across.inputToken = USDC on origin chain
// across.inputAmount = 2900
// across.outputToken = USDC on destination chain
// across.outputAmount = 2900
// swap it to bridgeToken before depositing to SpokePool
// NOTE: we use acrossOrderData.bridgeAmountOutMinimum (== acrossOrderData.outputAmount) as outputAmountMinimum, if not enough, swap will revert.
// The swapped amount should >= acrossOrderData.bridgeAmountOutMinimum, the surplus amount will be the profit for filler after across repayment
(acrossDepositInputAmount, ) = _swapExactInput(
acrossOrderData.inputToken,
acrossOrderData.bridgeToken,
acrossOrderData.inputAmount,
acrossOrderData.bridgeAmountOutMinimum,
address(this), // no need to transfer since we will deposit to Across later
address(this),
orderFillerData.swapType,
orderFillerData.swapData
);
}
uint32 depositId = $.spokePool.numberOfDeposits();
// if inputToken is not supported by Across, it will revert with DisabledRoute
_spokePoolDeposit(
SpokePoolDepositParams({
depositor: order.swapper,
recipient: acrossOrderData.recipient,
inputToken: acrossOrderData.bridgeToken,
outputToken: acrossOrderData.outputToken,
inputAmount: acrossDepositInputAmount,
outputAmount: acrossOrderData.outputAmount,
destinationChainId: acrossOrderData.destinationChainId,
exclusiveRelayer: orderFillerData.exclusiveRelayer,
fillDeadline: order.fillDeadline,
exclusivityDeadline: acrossOrderData.exclusivityDeadline,
message: acrossOrderData.message
})
);
uint32 depositIdAfter = $.spokePool.numberOfDeposits();
if (depositIdAfter != depositId + 1) {
revert LibError.DepositIdMismatch(depositId, depositIdAfter);
}
_emitDeposited(
order,
acrossOrderData,
acrossDepositInputAmount,
depositId,
orderFillerData.exclusiveRelayer,
permitHash
);
}
// we don't actually use this function, but it's required by the interface
/// @inheritdoc ISettlementContract
function resolve(
CrossChainOrder calldata order,
bytes calldata fillerData
) external view returns (ResolvedCrossChainOrder memory) {
if (order.settlementContract != address(this)) {
revert LibError.InvalidSettlementContract(order.settlementContract);
}
if (order.originChainId != block.chainid) {
revert LibError.InvalidOriginChainId(order.originChainId);
}
(AcrossOrderData memory acrossOrder, AcrossFillerData memory orderFillerData) = (
abi.decode(order.orderData, (AcrossOrderData)),
abi.decode(fillerData, (AcrossFillerData))
);
Input[] memory inputs = new Input[](1);
inputs[0] = Input({ token: acrossOrder.inputToken, amount: acrossOrder.inputAmount });
Output[] memory outputs = new Output[](1);
outputs[0] = Output({
token: acrossOrder.outputToken,
amount: acrossOrder.outputAmount,
recipient: acrossOrder.recipient,
chainId: acrossOrder.destinationChainId
});
// We assume that no swap needed and filler takes repayment on the origin chain in which case the filler output
// will always be equal to the input amount. If the filler requests repayment somewhere else then
// the filler output will be equal to the input amount less a fee based on the chain they request
// repayment on.
Output[] memory fillerOutputs = new Output[](1);
fillerOutputs[0] = Output({
token: acrossOrder.inputToken,
amount: acrossOrder.inputAmount,
recipient: orderFillerData.exclusiveRelayer,
chainId: block.chainid.toUint32()
});
ResolvedCrossChainOrder memory resolvedOrder = ResolvedCrossChainOrder({
settlementContract: address(this),
swapper: order.swapper,
nonce: order.nonce,
originChainId: order.originChainId,
initiateDeadline: order.initiateDeadline,
fillDeadline: order.fillDeadline,
swapperInputs: inputs,
swapperOutputs: outputs,
fillerOutputs: fillerOutputs
});
return resolvedOrder;
}
function swapExactInput(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmountMinimum,
SwapType swapType,
bytes calldata swapData
) external nonReentrant returns (uint256 amountOut) {
_pullTokenFrom(IERC20Metadata(inputToken), _sender(), inputAmount);
(amountOut, ) = _swapExactInput(
inputToken,
outputToken,
inputAmount,
outputAmountMinimum,
_sender(),
_sender(),
swapType,
swapData
);
return amountOut;
}
function disperseSurplusAndFillRelay(
IV3SpokePool.V3RelayData calldata relayData,
uint256 repaymentChainId,
address repaymentAddress,
uint256 surplusDisperseAmount
) external {
address outputToken = relayData.outputToken.toAddress();
address recipient = relayData.recipient.toAddress();
_pullTokenFrom(IERC20Metadata(outputToken), _sender(), relayData.outputAmount + surplusDisperseAmount);
SpotOrderGatewayStorage storage $ = _getSpotOrderGatewayStorage();
IERC20Metadata(outputToken).forceApprove(address($.spokePool), relayData.outputAmount);
$.spokePool.fillRelay(relayData, repaymentChainId, repaymentAddress.toBytes32());
if (surplusDisperseAmount > 0) {
IERC20Metadata(outputToken).safeTransfer(recipient, surplusDisperseAmount);
emit SurplusDispersed(recipient, outputToken, surplusDisperseAmount);
}
}
function swapExactInputAndFillRelay(
SwapExactInputParams calldata swapExactInputParams,
IV3SpokePool.V3RelayData calldata relayData,
uint256 repaymentChainId,
address repaymentAddress,
uint32 surplusDisperseRatio
) external {
if (swapExactInputParams.outputAmountMinimum != relayData.outputAmount) {
revert LibError.MismatchedFillAmount(swapExactInputParams.outputAmountMinimum, relayData.outputAmount);
}
_pullTokenFrom(IERC20Metadata(swapExactInputParams.inputToken), _sender(), swapExactInputParams.inputAmount);
(, uint256 surplusOutputAmount) = _swapExactInput(
swapExactInputParams.inputToken,
swapExactInputParams.outputToken,
swapExactInputParams.inputAmount,
swapExactInputParams.outputAmountMinimum,
address(this),
address(this),
swapExactInputParams.swapType,
swapExactInputParams.swapData
);
_disperseSurplusToken(
IERC20Metadata(swapExactInputParams.outputToken),
surplusOutputAmount,
surplusDisperseRatio,
_sender(),
relayData.recipient.toAddress()
);
SpotOrderGatewayStorage storage $ = _getSpotOrderGatewayStorage();
IERC20Metadata(swapExactInputParams.outputToken).forceApprove(address($.spokePool), relayData.outputAmount);
$.spokePool.fillRelay(relayData, repaymentChainId, repaymentAddress.toBytes32());
}
function swapExactOutput(
address inputToken,
address outputToken,
uint256 outputAmount,
uint256 inputAmountMaximum,
SwapType swapType,
bytes calldata swapData
) external nonReentrant returns (uint256 amountIn) {
_pullTokenFrom(IERC20Metadata(inputToken), _sender(), inputAmountMaximum);
return
_swapExactOutput(inputToken, outputToken, outputAmount, inputAmountMaximum, _sender(), swapType, swapData);
}
function permit2() external view returns (address) {
return address(_getSpotOrderGatewayStorage().permit2);
}
function spokePool() external view returns (address) {
return address(_getSpotOrderGatewayStorage().spokePool);
}
function uniswapV3Router() external view returns (address) {
return address(_getSpotOrderGatewayStorage().uniswapV3Router);
}
function uniswapSwapRouter02() external view returns (address) {
return address(_getSpotOrderGatewayStorage().uniswapSwapRouter02);
}
function isOrderDeposited(bytes32 permitHash) external view returns (bool) {
return _getSpotOrderGatewayStorage().isOrderDeposited[permitHash];
}
//
// PUBLIC
//
function getPermitHash(CrossChainOrder memory order) public view returns (bytes32) {
AcrossOrderData memory acrossOrderData = abi.decode(order.orderData, (AcrossOrderData));
ISignatureTransfer.PermitTransferFrom memory permit = ISignatureTransfer.PermitTransferFrom({
permitted: ISignatureTransfer.TokenPermissions({
token: acrossOrderData.inputToken,
amount: acrossOrderData.inputAmount
}),
nonce: order.nonce,
deadline: order.initiateDeadline
});
return
_hashTypedData(
_hashWithWitness(
permit,
ERC7683Permit2Lib.hashOrder(order, ERC7683Permit2Lib.hashOrderData(acrossOrderData)),
ERC7683Permit2Lib.PERMIT2_ORDER_TYPE
)
);
}
function verifyOrderSignature(CrossChainOrder memory order, bytes calldata signature) external view {
SignatureVerification.verify(signature, getPermitHash(order), order.swapper);
}
//
// INTERNAL
//
function _spokePoolDeposit(SpokePoolDepositParams memory params) internal {
SpotOrderGatewayStorage storage $ = _getSpotOrderGatewayStorage();
IERC20Metadata(params.inputToken).forceApprove(address($.spokePool), params.inputAmount);
$.spokePool.deposit(
params.depositor.toBytes32(),
params.recipient.toBytes32(),
params.inputToken.toBytes32(),
params.outputToken.toBytes32(),
params.inputAmount,
params.outputAmount,
params.destinationChainId,
params.exclusiveRelayer.toBytes32(),
block.timestamp.toUint32(), // quoteTimestamp
params.fillDeadline,
params.exclusivityDeadline,
params.message
);
}
function _emitDeposited(
CrossChainOrder memory order,
AcrossOrderData memory acrossOrderData,
uint256 bridgeAmount,
uint32 depositId,
address exclusiveRelayer,
bytes32 permitHash
) internal {
emit Deposited(
acrossOrderData.inputToken,
acrossOrderData.outputToken,
acrossOrderData.bridgeToken,
acrossOrderData.inputAmount,
acrossOrderData.outputAmount,
bridgeAmount,
acrossOrderData.destinationChainId,
depositId,
order.swapper,
acrossOrderData.recipient,
exclusiveRelayer,
permitHash
);
}
function _processPermit2Order(
CrossChainOrder memory order,
AcrossOrderData memory acrossOrderData,
bytes memory signature
) internal {
ISignatureTransfer.PermitTransferFrom memory permit = ISignatureTransfer.PermitTransferFrom({
permitted: ISignatureTransfer.TokenPermissions({
token: acrossOrderData.inputToken,
amount: acrossOrderData.inputAmount
}),
nonce: order.nonce,
deadline: order.initiateDeadline
});
ISignatureTransfer.SignatureTransferDetails memory signatureTransferDetails = ISignatureTransfer
.SignatureTransferDetails({ to: address(this), requestedAmount: acrossOrderData.inputAmount });
IERC20Metadata inputToken = IERC20Metadata(acrossOrderData.inputToken);
uint256 balanceBefore = inputToken.balanceOf(address(this));
// Pull user funds.
_getSpotOrderGatewayStorage().permit2.permitWitnessTransferFrom(
permit,
signatureTransferDetails,
order.swapper,
ERC7683Permit2Lib.hashOrder(order, ERC7683Permit2Lib.hashOrderData(acrossOrderData)), // witness data hash
ERC7683Permit2Lib.PERMIT2_ORDER_TYPE, // witness data type string
signature
);
uint256 transferredAmount = inputToken.balanceOf(address(this)) - balanceBefore;
if ((acrossOrderData.inputAmount - transferredAmount) >= RebaseTokenToleranceWei) {
revert LibError.MismatchedTransferAmount(transferredAmount, acrossOrderData.inputAmount);
}
}
function _hashTypedData(bytes32 dataHash) internal view returns (bytes32) {
return
keccak256(abi.encodePacked("\x19\x01", _getSpotOrderGatewayStorage().permit2.DOMAIN_SEPARATOR(), dataHash));
}
function _hashWithWitness(
ISignatureTransfer.PermitTransferFrom memory permit,
bytes32 witness,
string memory witnessTypeString
) internal view returns (bytes32) {
bytes32 typeHash = keccak256(
abi.encodePacked(PermitHash._PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, witnessTypeString)
);
bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
return
keccak256(
abi.encode(typeHash, tokenPermissionsHash, address(this), permit.nonce, permit.deadline, witness)
);
}
function _hashTokenPermissions(
ISignatureTransfer.TokenPermissions memory permitted
) internal pure returns (bytes32) {
return keccak256(abi.encode(PermitHash._TOKEN_PERMISSIONS_TYPEHASH, permitted));
}
//
// PRIVATE
//
function _swapExactOutput(
address inputToken,
address outputToken,
uint256 outputAmount,
uint256 inputAmountMaximum,
address recipient,
SwapType swapType,
bytes memory swapData
) internal returns (uint256 amountIn) {
IERC20Metadata tokenOut = IERC20Metadata(outputToken);
uint256 outputTokenBalanceBefore = tokenOut.balanceOf(address(this));
if (swapType == SwapType.UNISWAP_V3_SWAP_ROUTER) {
amountIn = _uniswapV3ExactOutput(
UniswapV3ExactOutputParams({
inputToken: inputToken,
outputToken: outputToken,
path: swapData,
outputAmount: outputAmount,
inputAmountMaximum: inputAmountMaximum
})
);
} else if (swapType == SwapType.UNISWAP_SWAP_ROUTER_02) {
amountIn = _uniswapSwapRouter02ExactOutput(
UniswapSwapRouter02ExactOutputParams({
inputToken: inputToken,
outputToken: outputToken,
inputAmountMaximum: inputAmountMaximum,
swapData: swapData
})
);
} else {
// unknown swap type
// or
// swapType == SKIP_SWAP since it should not go to this function no matter how
revert LibError.InvalidSwapType();
}
// just in case if token balance check inside _uniswapSwapRouter02ExactOutput() is wrong
if (amountIn == 0) {
revert LibError.ZeroAmount();
}
if (amountIn > inputAmountMaximum) {
revert LibError.ExcessiveInputAmount(amountIn, inputAmountMaximum);
}
// bonus for relayer
uint256 remainInputAmount = inputAmountMaximum - amountIn;
if (remainInputAmount > 0) {
IERC20Metadata(inputToken).safeTransfer(_sender(), remainInputAmount);
}
// verify there is actually outputAmount being transferred into this contract,
// to prevent malicious caller uses swap functions to drain the existing tokens on this contract
// see https://github.com/perpetual-protocol/lugia-contract/pull/559
uint256 transferredAmount = tokenOut.balanceOf(address(this)) - outputTokenBalanceBefore;
if (transferredAmount < outputAmount) {
revert LibError.InsufficientExactOutputAmount(transferredAmount, outputAmount);
}
tokenOut.safeTransfer(recipient, outputAmount);
// bonus for relayer
uint256 remainOutputAmount = transferredAmount - outputAmount;
if (remainOutputAmount > 0) {
tokenOut.safeTransfer(_sender(), remainOutputAmount);
}
emit TokenSwapped(
inputToken,
outputToken,
amountIn,
outputAmount,
recipient,
remainInputAmount,
remainOutputAmount
);
return amountIn;
}
function _swapExactInput(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmountMinimum,
address recipient,
address excessiveOutputRecipient,
SwapType swapType,
bytes memory swapData
) internal returns (uint256 amountOut, uint256 surplusOutputAmount) {
// NOTE: `recipient inside swapData` must always be SpotOrderGateway,
// this is not the same as `recipient passed into _swapExactInput()`
if (swapType == SwapType.UNISWAP_V3_SWAP_ROUTER) {
amountOut = _uniswapV3ExactInput(
UniswapV3ExactInputParams({
inputToken: inputToken,
outputToken: outputToken,
path: swapData,
inputAmount: inputAmount,
outputAmountMinimum: outputAmountMinimum
})
);
} else if (swapType == SwapType.UNISWAP_SWAP_ROUTER_02) {
amountOut = _uniswapSwapRouter02ExactInput(
UniswapSwapRouter02ExactInputParams({
inputToken: inputToken,
outputToken: outputToken,
inputAmount: inputAmount,
swapData: swapData
})
);
} else if (swapType == SwapType.ONEINCH_AGGREGATION_ROUTER_V6) {
amountOut = _aggregationRouterExactInput(
AggregationRouterExactInputParams({
approvalTarget: OneInchAggregationRouterV6,
aggregator: OneInchAggregationRouterV6,
inputToken: inputToken,
outputToken: outputToken,
inputAmount: inputAmount,
swapData: swapData
})
);
} else if (swapType == SwapType.KYBER_META_AGGREGATION_ROUTER_V2) {
amountOut = _aggregationRouterExactInput(
AggregationRouterExactInputParams({
approvalTarget: KyberMetaAggregationRouterV2,
aggregator: KyberMetaAggregationRouterV2,
inputToken: inputToken,
outputToken: outputToken,
inputAmount: inputAmount,
swapData: swapData
})
);
} else if (swapType == SwapType.OKX_AGGREGATOR) {
amountOut = _aggregationRouterExactInput(
AggregationRouterExactInputParams({
approvalTarget: _getOkxTokenApprovalTarget(),
aggregator: _getOkxAggregator(),
inputToken: inputToken,
outputToken: outputToken,
inputAmount: inputAmount,
swapData: swapData
})
);
} else {
// unknown swap type
// or
// swapType == SKIP_SWAP since it should not go to this function no matter how
revert LibError.InvalidSwapType();
}
if (amountOut >= outputAmountMinimum) {
IERC20Metadata tokenOut = IERC20Metadata(outputToken);
// surplus output amount is the bonus for relayer when swap on same chain
if (amountOut > outputAmountMinimum) {
surplusOutputAmount = amountOut - outputAmountMinimum;
if (excessiveOutputRecipient != address(this)) {
tokenOut.safeTransfer(excessiveOutputRecipient, surplusOutputAmount);
}
}
// NOTE: recipient could be different based on the order type:
// - same-chain swap order -> initiate():
// - recipient: user
// - cross-chain buy order -> swapExactInput():
// - recipient: filler
// - cross-chain sell order -> initiate():
// - recipient: SpotOrderGateway, so no need to transfer since we will deposit to Across later
if (recipient != address(this)) {
tokenOut.safeTransfer(recipient, outputAmountMinimum);
}
} else {
revert LibError.InsufficientOutputAmount(amountOut, outputAmountMinimum);
}
// these are tokens and amounts we swap on DEX
emit TokenSwapped(inputToken, outputToken, inputAmount, amountOut, recipient, 0, surplusOutputAmount);
return (amountOut, surplusOutputAmount);
}
function _aggregationRouterExactInput(
AggregationRouterExactInputParams memory params
) internal returns (uint256 amountOut) {
IERC20Metadata(params.inputToken).forceApprove(params.approvalTarget, params.inputAmount);
IERC20Metadata outputToken = IERC20Metadata(params.outputToken);
uint256 outputTokenBalanceBefore = outputToken.balanceOf(address(this));
(bool success, bytes memory data) = params.aggregator.call{ value: 0 }(params.swapData);
if (!success) {
revert LibError.AggregationRouterSwapError(data);
}
uint256 outputTokenBalanceAfter = outputToken.balanceOf(address(this));
// amountOut
return outputTokenBalanceAfter - outputTokenBalanceBefore;
}
function _uniswapSwapRouter02ExactInput(
UniswapSwapRouter02ExactInputParams memory params
) internal returns (uint256 amountOut) {
address uniswapSwapRouter02_ = _getSpotOrderGatewayStorage().uniswapSwapRouter02;
IERC20Metadata(params.inputToken).forceApprove(uniswapSwapRouter02_, params.inputAmount);
IERC20Metadata outputToken = IERC20Metadata(params.outputToken);
uint256 outputTokenBalanceBefore = outputToken.balanceOf(address(this));
(bool success, bytes memory data) = uniswapSwapRouter02_.call{ value: 0 }(params.swapData);
if (!success) {
revert LibError.UniswapSwapError(data);
}
uint256 outputTokenBalanceAfter = outputToken.balanceOf(address(this));
// amountOut
return outputTokenBalanceAfter - outputTokenBalanceBefore;
}
function _uniswapSwapRouter02ExactOutput(
UniswapSwapRouter02ExactOutputParams memory params
) internal returns (uint256 amountIn) {
address uniswapSwapRouter02_ = _getSpotOrderGatewayStorage().uniswapSwapRouter02;
IERC20Metadata inputToken = IERC20Metadata(params.inputToken);
inputToken.forceApprove(uniswapSwapRouter02_, params.inputAmountMaximum);
uint256 inputTokenBalanceBefore = inputToken.balanceOf(address(this));
// params.swapData may contains amountInMax if it's calling `swapTokensForExactTokens`
// in this case, swapData.amountInMax could be larger than params.inputAmountMaximum
// if it's larger, then the actual swap amount could be larger than params.inputAmountMaximum
// it will revert when UniswapRouter02 transferring inputToken that's larger than allowance
(bool success, bytes memory data) = uniswapSwapRouter02_.call{ value: 0 }(params.swapData);
if (!success) {
revert LibError.UniswapSwapError(data);
}
uint256 inputTokenBalanceAfter = inputToken.balanceOf(address(this));
// amountIn
return inputTokenBalanceBefore - inputTokenBalanceAfter;
}
function _uniswapV3ExactInput(UniswapV3ExactInputParams memory params) internal returns (uint256 amountOut) {
ISwapRouter uniswapV3Router_ = _getSpotOrderGatewayStorage().uniswapV3Router;
IERC20Metadata(params.inputToken).forceApprove(address(uniswapV3Router_), params.inputAmount);
return
uniswapV3Router_.exactInput(
ISwapRouter.ExactInputParams({
path: params.path,
recipient: address(this),
deadline: block.timestamp,
amountIn: params.inputAmount,
amountOutMinimum: params.outputAmountMinimum
})
);
}
function _uniswapV3ExactOutput(UniswapV3ExactOutputParams memory params) internal returns (uint256 amountIn) {
ISwapRouter uniswapV3Router_ = _getSpotOrderGatewayStorage().uniswapV3Router;
IERC20Metadata tokenIn = IERC20Metadata(params.inputToken);
tokenIn.forceApprove(address(uniswapV3Router_), params.inputAmountMaximum);
amountIn = uniswapV3Router_.exactOutput(
ISwapRouter.ExactOutputParams({
path: params.path,
recipient: address(this),
deadline: block.timestamp,
amountOut: params.outputAmount,
amountInMaximum: params.inputAmountMaximum
})
);
return amountIn;
}
function _pullTokenFrom(IERC20Metadata token, address from, uint256 amount) private {
// NOTE: this transferredAmount check isn't compatible with tax token
uint256 balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
uint256 transferredAmount = token.balanceOf(address(this)) - balanceBefore;
if (transferredAmount != amount) {
revert LibError.WrongTransferAmount(transferredAmount, amount);
}
}
function _disperseSurplusToken(
IERC20Metadata token,
uint256 surplusAmount,
uint32 surplusDisperseRatio,
address filler,
address trader
) private {
if (surplusDisperseRatio > ONE_PERCENT) {
revert LibError.InvalidSurplusDisperseRatio(surplusDisperseRatio);
}
uint256 surplusToTrader = (surplusAmount * surplusDisperseRatio) / ONE_PERCENT;
if (trader != address(this) && surplusToTrader > 0) {
token.safeTransfer(trader, surplusToTrader);
emit SurplusDispersed(trader, address(token), surplusToTrader);
}
uint256 remainSurplus = surplusAmount - surplusToTrader;
if (filler != address(this) && remainSurplus > 0) {
token.safeTransfer(filler, remainSurplus);
}
}
function _getSpotOrderGatewayStorage() private pure returns (SpotOrderGatewayStorage storage $) {
assembly {
$.slot := _SPOT_ORDER_GATEWAY_STORAGE_LOCATION
}
}
// NOTE: okx has different aggregator for each chain, we need to get the correct one based on the chainid
function _getOkxAggregator() private view returns (address) {
// https://www.okx.com/web3/build/docs/waas/dex-smart-contract
if (block.chainid == 1) {
return address(0x7D0CcAa3Fac1e5A943c5168b6CEd828691b46B36);
} else if (block.chainid == 10) {
return address(0xf332761c673b59B21fF6dfa8adA44d78c12dEF09);
} else if (block.chainid == 42161) {
return address(0xf332761c673b59B21fF6dfa8adA44d78c12dEF09);
} else if (block.chainid == 8453) {
return address(0x6b2C0c7be2048Daa9b5527982C29f48062B34D58);
} else {
revert LibError.UnsupportedChainId(block.chainid);
}
}
function _getOkxTokenApprovalTarget() private view returns (address) {
// https://www.okx.com/web3/build/docs/waas/dex-smart-contract
if (block.chainid == 1) {
return address(0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f);
} else if (block.chainid == 10) {
return address(0x68D6B739D2020067D1e2F713b999dA97E4d54812);
} else if (block.chainid == 42161) {
return address(0x70cBb871E8f30Fc8Ce23609E9E0Ea87B6b222F58);
} else if (block.chainid == 8453) {
return address(0x57df6092665eb6058DE53939612413ff4B09114E);
} else {
revert LibError.UnsupportedChainId(block.chainid);
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 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 ReentrancyGuardUpgradeable is Initializable {
// 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the 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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 {
using Address for address;
/**
* @dev An operation with an ERC20 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 Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
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.
*/
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.
*/
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 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).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
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 silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@openzeppelin/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}
across-protocol/contracts/contracts/interfaces/V3SpokePoolInterface.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
// Contains structs and functions used by SpokePool contracts to facilitate universal settlement.
interface V3SpokePoolInterface {
/**************************************
* ENUMS *
**************************************/
// Fill status tracks on-chain state of deposit, uniquely identified by relayHash.
enum FillStatus {
Unfilled,
RequestedSlowFill,
Filled
}
// Fill type is emitted in the FilledRelay event to assist Dataworker with determining which types of
// fills to refund (e.g. only fast fills) and whether a fast fill created a sow fill excess.
enum FillType {
FastFill,
// Fast fills are normal fills that do not replace a slow fill request.
ReplacedSlowFill,
// Replaced slow fills are fast fills that replace a slow fill request. This type is used by the Dataworker
// to know when to send excess funds from the SpokePool to the HubPool because they can no longer be used
// for a slow fill execution.
SlowFill
}
// Slow fills are requested via requestSlowFill and executed by executeSlowRelayLeaf after a bundle containing
// the slow fill is validated.
/**************************************
* STRUCTS *
**************************************/
// This struct represents the data to fully specify a **unique** relay submitted on this chain.
// This data is hashed with the chainId() and saved by the SpokePool to prevent collisions and protect against
// replay attacks on other chains. If any portion of this data differs, the relay is considered to be
// completely distinct.
struct V3RelayData {
// The bytes32 that made the deposit on the origin chain.
bytes32 depositor;
// The recipient bytes32 on the destination chain.
bytes32 recipient;
// This is the exclusive relayer who can fill the deposit before the exclusivity deadline.
bytes32 exclusiveRelayer;
// Token that is deposited on origin chain by depositor.
bytes32 inputToken;
// Token that is received on destination chain by recipient.
bytes32 outputToken;
// The amount of input token deposited by depositor.
uint256 inputAmount;
// The amount of output token to be received by recipient.
uint256 outputAmount;
// Origin chain id.
uint256 originChainId;
// The id uniquely identifying this deposit on the origin chain.
uint256 depositId;
// The timestamp on the destination chain after which this deposit can no longer be filled.
uint32 fillDeadline;
// The timestamp on the destination chain after which any relayer can fill the deposit.
uint32 exclusivityDeadline;
// Data that is forwarded to the recipient.
bytes message;
}
// Same as V3RelayData but using addresses instead of bytes32 & depositId is uint32.
// Will be deprecated in favor of V3RelayData in the future.
struct V3RelayDataLegacy {
address depositor;
address recipient;
address exclusiveRelayer;
address inputToken;
address outputToken;
uint256 inputAmount;
uint256 outputAmount;
uint256 originChainId;
uint32 depositId;
uint32 fillDeadline;
uint32 exclusivityDeadline;
bytes message;
}
// Contains parameters passed in by someone who wants to execute a slow relay leaf.
struct V3SlowFill {
V3RelayData relayData;
uint256 chainId;
uint256 updatedOutputAmount;
}
// Contains information about a relay to be sent along with additional information that is not unique to the
// relay itself but is required to know how to process the relay. For example, "updatedX" fields can be used
// by the relayer to modify fields of the relay with the depositor's permission, and "repaymentChainId" is specified
// by the relayer to determine where to take a relayer refund, but doesn't affect the uniqueness of the relay.
struct V3RelayExecutionParams {
V3RelayData relay;
bytes32 relayHash;
uint256 updatedOutputAmount;
bytes32 updatedRecipient;
bytes updatedMessage;
uint256 repaymentChainId;
}
// Packs together parameters emitted in FilledRelay because there are too many emitted otherwise.
// Similar to V3RelayExecutionParams, these parameters are not used to uniquely identify the deposit being
// filled so they don't have to be unpacked by all clients.
struct V3RelayExecutionEventInfo {
bytes32 updatedRecipient;
bytes32 updatedMessageHash;
uint256 updatedOutputAmount;
FillType fillType;
}
// Represents the parameters required for a V3 deposit operation in the SpokePool.
struct DepositV3Params {
bytes32 depositor;
bytes32 recipient;
bytes32 inputToken;
bytes32 outputToken;
uint256 inputAmount;
uint256 outputAmount;
uint256 destinationChainId;
bytes32 exclusiveRelayer;
uint256 depositId;
uint32 quoteTimestamp;
uint32 fillDeadline;
uint32 exclusivityParameter;
bytes message;
}
/**************************************
* EVENTS *
**************************************/
event FundsDeposited(
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 indexed destinationChainId,
uint256 indexed depositId,
uint32 quoteTimestamp,
uint32 fillDeadline,
uint32 exclusivityDeadline,
bytes32 indexed depositor,
bytes32 recipient,
bytes32 exclusiveRelayer,
bytes message
);
event RequestedSpeedUpDeposit(
uint256 updatedOutputAmount,
uint256 indexed depositId,
bytes32 indexed depositor,
bytes32 updatedRecipient,
bytes updatedMessage,
bytes depositorSignature
);
event FilledRelay(
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 repaymentChainId,
uint256 indexed originChainId,
uint256 indexed depositId,
uint32 fillDeadline,
uint32 exclusivityDeadline,
bytes32 exclusiveRelayer,
bytes32 indexed relayer,
bytes32 depositor,
bytes32 recipient,
bytes32 messageHash,
V3RelayExecutionEventInfo relayExecutionInfo
);
event RequestedSlowFill(
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 indexed originChainId,
uint256 indexed depositId,
uint32 fillDeadline,
uint32 exclusivityDeadline,
bytes32 exclusiveRelayer,
bytes32 depositor,
bytes32 recipient,
bytes32 messageHash
);
event ClaimedRelayerRefund(
bytes32 indexed l2TokenAddress,
bytes32 indexed refundAddress,
uint256 amount,
address indexed caller
);
/**************************************
* FUNCTIONS *
**************************************/
function deposit(
bytes32 depositor,
bytes32 recipient,
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 destinationChainId,
bytes32 exclusiveRelayer,
uint32 quoteTimestamp,
uint32 fillDeadline,
uint32 exclusivityDeadline,
bytes calldata message
) external payable;
function depositV3(
address depositor,
address recipient,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 destinationChainId,
address exclusiveRelayer,
uint32 quoteTimestamp,
uint32 fillDeadline,
uint32 exclusivityDeadline,
bytes calldata message
) external payable;
function depositNow(
bytes32 depositor,
bytes32 recipient,
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 destinationChainId,
bytes32 exclusiveRelayer,
uint32 fillDeadlineOffset,
uint32 exclusivityDeadline,
bytes calldata message
) external payable;
function depositV3Now(
address depositor,
address recipient,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 destinationChainId,
address exclusiveRelayer,
uint32 fillDeadlineOffset,
uint32 exclusivityDeadline,
bytes calldata message
) external payable;
function unsafeDeposit(
bytes32 depositor,
bytes32 recipient,
bytes32 inputToken,
bytes32 outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 destinationChainId,
bytes32 exclusiveRelayer,
uint256 depositNonce,
uint32 quoteTimestamp,
uint32 fillDeadline,
uint32 exclusivityParameter,
bytes calldata message
) external payable;
function speedUpDeposit(
bytes32 depositor,
uint256 depositId,
uint256 updatedOutputAmount,
bytes32 updatedRecipient,
bytes calldata updatedMessage,
bytes calldata depositorSignature
) external;
function speedUpV3Deposit(
address depositor,
uint256 depositId,
uint256 updatedOutputAmount,
address updatedRecipient,
bytes calldata updatedMessage,
bytes calldata depositorSignature
) external;
function fillRelay(
V3RelayData calldata relayData,
uint256 repaymentChainId,
bytes32 repaymentAddress
) external;
function fillV3Relay(V3RelayDataLegacy calldata relayData, uint256 repaymentChainId) external;
function fillRelayWithUpdatedDeposit(
V3RelayData calldata relayData,
uint256 repaymentChainId,
bytes32 repaymentAddress,
uint256 updatedOutputAmount,
bytes32 updatedRecipient,
bytes calldata updatedMessage,
bytes calldata depositorSignature
) external;
function requestSlowFill(V3RelayData calldata relayData) external;
function executeSlowRelayLeaf(
V3SlowFill calldata slowFillLeaf,
uint32 rootBundleId,
bytes32[] calldata proof
) external;
function claimRelayerRefund(bytes32 l2TokenAddress, bytes32 refundAddress) external;
/**************************************
* ERRORS *
**************************************/
error DisabledRoute();
error InvalidQuoteTimestamp();
error InvalidFillDeadline();
error InvalidExclusiveRelayer();
error MsgValueDoesNotMatchInputAmount();
error NotExclusiveRelayer();
error NoSlowFillsInExclusivityWindow();
error RelayFilled();
error InvalidSlowFillRequest();
error ExpiredFillDeadline();
error InvalidMerkleProof();
error InvalidChainId();
error InvalidMerkleLeaf();
error ClaimedMerkleLeaf();
error InvalidPayoutAdjustmentPct();
error WrongERC7683OrderId();
error LowLevelCallFailed(bytes data);
error InsufficientSpokePoolBalanceToExecuteLeaf();
error NoRelayerRefundToClaim();
/**************************************
* LEGACY EVENTS *
**************************************/
// Note: these events are unused, but included in the ABI for ease of migration.
event V3FundsDeposited(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 indexed destinationChainId,
uint32 indexed depositId,
uint32 quoteTimestamp,
uint32 fillDeadline,
uint32 exclusivityDeadline,
address indexed depositor,
address recipient,
address exclusiveRelayer,
bytes message
);
event RequestedSpeedUpV3Deposit(
uint256 updatedOutputAmount,
uint32 indexed depositId,
address indexed depositor,
address updatedRecipient,
bytes updatedMessage,
bytes depositorSignature
);
// Legacy struct only used to preserve the FilledV3Relay event definition.
struct LegacyV3RelayExecutionEventInfo {
address updatedRecipient;
bytes updatedMessage;
uint256 updatedOutputAmount;
FillType fillType;
}
event FilledV3Relay(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 repaymentChainId,
uint256 indexed originChainId,
uint32 indexed depositId,
uint32 fillDeadline,
uint32 exclusivityDeadline,
address exclusiveRelayer,
address indexed relayer,
address depositor,
address recipient,
bytes message,
LegacyV3RelayExecutionEventInfo relayExecutionInfo
);
event RequestedV3SlowFill(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount,
uint256 indexed originChainId,
uint32 indexed depositId,
uint32 fillDeadline,
uint32 exclusivityDeadline,
address exclusiveRelayer,
address depositor,
address recipient,
bytes message
);
}
across-protocol/contracts/contracts/libraries/AddressConverters.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
library Bytes32ToAddress {
/**************************************
* ERRORS *
**************************************/
error InvalidBytes32();
function toAddress(bytes32 _bytes32) internal pure returns (address) {
checkAddress(_bytes32);
return address(uint160(uint256(_bytes32)));
}
function toAddressUnchecked(bytes32 _bytes32) internal pure returns (address) {
return address(uint160(uint256(_bytes32)));
}
function checkAddress(bytes32 _bytes32) internal pure {
if (uint256(_bytes32) >> 160 != 0) {
revert InvalidBytes32();
}
}
}
library AddressToBytes32 {
function toBytes32(address _address) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_address)));
}
}
multicaller/LibMulticaller.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title LibMulticaller
* @author vectorized.eth
* @notice Library to read the `msg.sender` of the multicaller with sender contract.
*/
library LibMulticaller {
/**
* @dev The address of the multicaller contract.
*/
address internal constant MULTICALLER = 0x000000000088228fCF7b8af41Faf3955bD0B3A41;
/**
* @dev The address of the multicaller with sender contract.
*/
address internal constant MULTICALLER_WITH_SENDER = 0x00000000002Fd5Aeb385D324B580FCa7c83823A0;
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`.
*/
function multicallerSender() internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
if iszero(
staticcall(
gas(), // Remaining gas.
MULTICALLER_WITH_SENDER, // The multicaller.
0x00, // Start of calldata in memory.
0x00, // Length of calldata.
0x00, // Start of returndata in memory.
0x20 // Length of returndata.
)
) { revert(0, 0) } // For better gas estimation.
result := mul(mload(0x00), eq(returndatasize(), 0x20))
}
}
/**
* @dev Returns the caller of `aggregateWithSender` on `MULTICALLER_WITH_SENDER`,
* if the current context's `msg.sender` is `MULTICALLER_WITH_SENDER`.
* Otherwise, returns `msg.sender`.
*/
function sender() internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := caller()
if eq(result, MULTICALLER_WITH_SENDER) {
if iszero(
staticcall(
gas(), // Remaining gas.
MULTICALLER_WITH_SENDER, // The multicaller with sender.
0x00, // Start of calldata in memory.
0x00, // Length of calldata.
0x00, // Start of returndata in memory.
0x20 // Length of returndata.
)
) { revert(0, 0) } // For better gas estimation.
result := mul(mload(0x00), eq(returndatasize(), 0x20))
}
}
}
}
permit2/src/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}
permit2/src/interfaces/IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
permit2/src/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1271 {
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash Hash of the data to be signed
/// @param signature Signature byte array associated with _data
/// @return magicValue The bytes4 magic value 0x1626ba7e
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
permit2/src/interfaces/ISignatureTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
/// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
/// @param maxAmount The maximum amount a spender can request to transfer
error InvalidAmount(uint256 maxAmount);
/// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
/// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
error LengthMismatch();
/// @notice Emits an event when the owner successfully invalidates an unordered nonce.
event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);
/// @notice The token and amount details for a transfer signed in the permit transfer signature
struct TokenPermissions {
// ERC20 token address
address token;
// the maximum amount that can be spent
uint256 amount;
}
/// @notice The signed permit message for a single token transfer
struct PermitTransferFrom {
TokenPermissions permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice Specifies the recipient address and amount for batched transfers.
/// @dev Recipients and amounts correspond to the index of the signed token permissions array.
/// @dev Reverts if the requested amount is greater than the permitted signed amount.
struct SignatureTransferDetails {
// recipient address
address to;
// spender requested amount
uint256 requestedAmount;
}
/// @notice Used to reconstruct the signed permit message for multiple token transfers
/// @dev Do not need to pass in spender address as it is required that it is msg.sender
/// @dev Note that a user still signs over a spender address
struct PermitBatchTransferFrom {
// the tokens and corresponding amounts permitted for a transfer
TokenPermissions[] permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
/// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
/// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
/// @dev It returns a uint256 bitmap
/// @dev The index, or wordPosition is capped at type(uint248).max
function nonceBitmap(address, uint256) external view returns (uint256);
/// @notice Transfers a token using a signed permit message
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param signature The signature to verify
function permitTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers a token using a signed permit message
/// @notice Includes extra data provided by the caller to verify signature over
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @dev Reverts if the requested amount is greater than the permitted signed amount
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails The spender's requested transfer details for the permitted token
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitTransferFrom memory permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param signature The signature to verify
function permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice Transfers multiple tokens using a signed permit message
/// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
/// @notice Includes extra data provided by the caller to verify signature over
/// @param permit The permit data signed over by the owner
/// @param owner The owner of the tokens to transfer
/// @param transferDetails Specifies the recipient and requested amount for the token transfer
/// @param witness Extra data to include when checking the user signature
/// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
/// @param signature The signature to verify
function permitWitnessTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
/// @notice Invalidates the bits specified in mask for the bitmap at the word position
/// @dev The wordPos is maxed at type(uint248).max
/// @param wordPos A number to index the nonceBitmap at
/// @param mask A bitmap masked against msg.sender's current bitmap at the word position
function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}
permit2/src/libraries/PermitHash.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IAllowanceTransfer} from "../interfaces/IAllowanceTransfer.sol";
import {ISignatureTransfer} from "../interfaces/ISignatureTransfer.sol";
library PermitHash {
bytes32 public constant _PERMIT_DETAILS_TYPEHASH =
keccak256("PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)");
bytes32 public constant _PERMIT_SINGLE_TYPEHASH = keccak256(
"PermitSingle(PermitDetails details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
);
bytes32 public constant _PERMIT_BATCH_TYPEHASH = keccak256(
"PermitBatch(PermitDetails[] details,address spender,uint256 sigDeadline)PermitDetails(address token,uint160 amount,uint48 expiration,uint48 nonce)"
);
bytes32 public constant _TOKEN_PERMISSIONS_TYPEHASH = keccak256("TokenPermissions(address token,uint256 amount)");
bytes32 public constant _PERMIT_TRANSFER_FROM_TYPEHASH = keccak256(
"PermitTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
);
bytes32 public constant _PERMIT_BATCH_TRANSFER_FROM_TYPEHASH = keccak256(
"PermitBatchTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline)TokenPermissions(address token,uint256 amount)"
);
string public constant _TOKEN_PERMISSIONS_TYPESTRING = "TokenPermissions(address token,uint256 amount)";
string public constant _PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB =
"PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,";
string public constant _PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB =
"PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,";
function hash(IAllowanceTransfer.PermitSingle memory permitSingle) internal pure returns (bytes32) {
bytes32 permitHash = _hashPermitDetails(permitSingle.details);
return
keccak256(abi.encode(_PERMIT_SINGLE_TYPEHASH, permitHash, permitSingle.spender, permitSingle.sigDeadline));
}
function hash(IAllowanceTransfer.PermitBatch memory permitBatch) internal pure returns (bytes32) {
uint256 numPermits = permitBatch.details.length;
bytes32[] memory permitHashes = new bytes32[](numPermits);
for (uint256 i = 0; i < numPermits; ++i) {
permitHashes[i] = _hashPermitDetails(permitBatch.details[i]);
}
return keccak256(
abi.encode(
_PERMIT_BATCH_TYPEHASH,
keccak256(abi.encodePacked(permitHashes)),
permitBatch.spender,
permitBatch.sigDeadline
)
);
}
function hash(ISignatureTransfer.PermitTransferFrom memory permit) internal view returns (bytes32) {
bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
return keccak256(
abi.encode(_PERMIT_TRANSFER_FROM_TYPEHASH, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline)
);
}
function hash(ISignatureTransfer.PermitBatchTransferFrom memory permit) internal view returns (bytes32) {
uint256 numPermitted = permit.permitted.length;
bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
for (uint256 i = 0; i < numPermitted; ++i) {
tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
}
return keccak256(
abi.encode(
_PERMIT_BATCH_TRANSFER_FROM_TYPEHASH,
keccak256(abi.encodePacked(tokenPermissionHashes)),
msg.sender,
permit.nonce,
permit.deadline
)
);
}
function hashWithWitness(
ISignatureTransfer.PermitTransferFrom memory permit,
bytes32 witness,
string calldata witnessTypeString
) internal view returns (bytes32) {
bytes32 typeHash = keccak256(abi.encodePacked(_PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, witnessTypeString));
bytes32 tokenPermissionsHash = _hashTokenPermissions(permit.permitted);
return keccak256(abi.encode(typeHash, tokenPermissionsHash, msg.sender, permit.nonce, permit.deadline, witness));
}
function hashWithWitness(
ISignatureTransfer.PermitBatchTransferFrom memory permit,
bytes32 witness,
string calldata witnessTypeString
) internal view returns (bytes32) {
bytes32 typeHash =
keccak256(abi.encodePacked(_PERMIT_BATCH_WITNESS_TRANSFER_FROM_TYPEHASH_STUB, witnessTypeString));
uint256 numPermitted = permit.permitted.length;
bytes32[] memory tokenPermissionHashes = new bytes32[](numPermitted);
for (uint256 i = 0; i < numPermitted; ++i) {
tokenPermissionHashes[i] = _hashTokenPermissions(permit.permitted[i]);
}
return keccak256(
abi.encode(
typeHash,
keccak256(abi.encodePacked(tokenPermissionHashes)),
msg.sender,
permit.nonce,
permit.deadline,
witness
)
);
}
function _hashPermitDetails(IAllowanceTransfer.PermitDetails memory details) private pure returns (bytes32) {
return keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, details));
}
function _hashTokenPermissions(ISignatureTransfer.TokenPermissions memory permitted)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(_TOKEN_PERMISSIONS_TYPEHASH, permitted));
}
}
permit2/src/libraries/SignatureVerification.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IERC1271} from "../interfaces/IERC1271.sol";
library SignatureVerification {
/// @notice Thrown when the passed in signature is not a valid length
error InvalidSignatureLength();
/// @notice Thrown when the recovered signer is equal to the zero address
error InvalidSignature();
/// @notice Thrown when the recovered signer does not equal the claimedSigner
error InvalidSigner();
/// @notice Thrown when the recovered contract signature is incorrect
error InvalidContractSignature();
bytes32 constant UPPER_BIT_MASK = (0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
function verify(bytes calldata signature, bytes32 hash, address claimedSigner) internal view {
bytes32 r;
bytes32 s;
uint8 v;
if (claimedSigner.code.length == 0) {
if (signature.length == 65) {
(r, s) = abi.decode(signature, (bytes32, bytes32));
v = uint8(signature[64]);
} else if (signature.length == 64) {
// EIP-2098
bytes32 vs;
(r, vs) = abi.decode(signature, (bytes32, bytes32));
s = vs & UPPER_BIT_MASK;
v = uint8(uint256(vs >> 255)) + 27;
} else {
revert InvalidSignatureLength();
}
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) revert InvalidSignature();
if (signer != claimedSigner) revert InvalidSigner();
} else {
bytes4 magicValue = IERC1271(claimedSigner).isValidSignature(hash, signature);
if (magicValue != IERC1271.isValidSignature.selector) revert InvalidContractSignature();
}
}
}
src/common/ContextBase.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.24;
import { LibMulticaller } from "multicaller/LibMulticaller.sol";
abstract contract ContextBase {
function _sender() internal view virtual returns (address) {
return LibMulticaller.sender();
}
}
src/common/LibConstant.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.24;
// used for all internal accounting in the protocol
// will not be updated after deployment
uint8 constant INTERNAL_DECIMALS = 18;
// Used for internal precision and ratio
uint256 constant WAD = 10 ** INTERNAL_DECIMALS;
// one percent in spot order gateway
uint32 constant ONE_PERCENT = 1e6;
src/common/LibError.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.24;
library LibError {
//
// Common
//
error Unauthorized(); // this is for general unauthorized error
error AuthorizerNotAllow(address authorizer, address authorized); // this is for AuthorizationUpgradeable error
error InvalidRatio(uint256 ratio);
error InvalidMaker(uint256 marketId, address maker);
error InvalidSender(address sender);
error ZeroAmount();
error NotEnoughFreeCollateral(uint256 marketId, address trader);
error NotWhitelistedAuthorization();
error MismatchedTransferAmount(uint256 actual, uint256 target);
error ZeroAddress();
error WrongTransferAmount(uint256 actual, uint256 target);
error MinMarginRatioExceeded(int256 marinRatio, int256 minMarginRatio);
//
// BorrowingFee
//
error InvalidPosition();
error InvalidTaker(address taker);
//
// Config
//
error MarketExists(uint256 marketId);
error MakerExists(uint256 marketId, address maker);
error MakerHasPosition(uint256 marketId, address maker, int256 posSize);
error ZeroRatio();
error InvalidFeeRate(uint256 feeRate);
//
// CircuitBreaker
//
error NotAProtectedContract();
error NotAdmin();
error InvalidAdminAddress();
error NoLockedFunds();
error RateLimited();
error NotRateLimited();
error TokenNotRateLimited();
error CooldownPeriodNotReached();
error NativeTransferFailed();
error InvalidRecipientAddress();
error InvalidGracePeriodEnd();
error ProtocolWasExploited();
error NotExploited();
//
// ClearingHouse
//
error DeadlineExceeded();
error InsufficientOutputAmount(uint256 actual, uint256 target);
error ExcessiveInputAmount(uint256 actual, uint256 target);
error NotLiquidatable(uint256 marketId, address trader);
error ExcessiveLiquidationPositionSize(
uint256 marketId,
address trader,
uint256 liquidationPositionSize,
uint256 positionSize
);
error CannotLiquidateWhitelistedMaker();
error QuoteResult(int256 base, int256 quote, uint256 makerFee, uint256 protocolFee);
error NotInstantMaker();
error InvalidMakerData();
error ExcessiveRelayFee(address trader, address relayer, uint256 relayFee, uint256 maxRelayFee);
error PriceOutOfBound(uint256 tradePrice, uint256 lowerPrice, uint256 upperPrice);
error LessThanMinOpenNotional(address trader, int256 openNotioanl);
error SelfTrade();
//
// DelayOrderGateway
//
error OrderNotExisted(uint256 orderId);
error OrderExecutedTooEarly();
error InvalidOrderType();
error InvalidDeadline(uint256 deadline);
error InvalidWithdrawalRatio();
//
// OrderGateway
//
error ExceedOrderAmount(bytes32 permitHash, uint256 totalFilledAmount);
error OrderMarketMismatched(
bytes32 takerOrderPermitHash,
uint256 takerMarketId,
bytes32 makerOrderPermitHash,
uint256 makerMarketId
);
error FilledAmountMismatched(bytes32 permitHash, uint256 orderFilledAmount, uint256 clearingHouseFilledAmount);
error OrderHasExpired(bytes32 permitHash);
error OrderSideMismatched(bytes32 takerOrderPermitHash, bytes32 makerOderPermitHash);
error UnableToFillFok(bytes32 permitHash);
error SettleOrderParamsLengthError(); // only support length 1 for now
error OrderSignatureOwnerError(bytes32 permitHash, bytes reason);
error OrderWasCanceled(bytes32 permitHash);
error ReduceOnlySideMismatch(bytes32 permitHash, int256 orderAmount, int256 takerPositionSize);
error UnableToReduceOnly(bytes32 permitHash, uint256 orderAmountAbs, uint256 takerPositionSizeAbs);
error OrderAmountZero(bytes32 permitHash);
//
// SpotOrderGateway
//
error InvalidSettlementContract(address settlementContract);
error InvalidOriginChainId(uint32 chainId);
error CrossChainOrderAlreadyInitiated(bytes32 orderHash);
error DepositIdMismatch(uint256 depositIdBefore, uint256 depositIdAfter);
error InvalidSwapType();
error InvalidBridgeToken();
error MismatchedBridgeAmount(uint256 actual, uint256 target);
error UniswapSwapError(bytes errorData);
error AggregationRouterSwapError(bytes errorData);
error InsufficientExactOutputAmount(uint256 actual, uint256 target);
error UnsupportedChainId(uint256 chainId);
error MismatchedFillAmount(uint256 actual, uint256 target);
error InvalidSurplusDisperseRatio(uint32 surplusDisperseRatio);
// SystemStatus
//
error SystemIsSuspended();
error MarketIsSuspended(uint256 marketId);
//
// Vault
//
error InvalidMarket(uint256 marketId);
error ZeroTakerPositionSize();
error DepositCapExceeded();
//
// SpotHedgeBaseMaker
//
error UnexpectedPerpPrecision(uint8 actual, uint8 expected);
// Unexpected first token of the given Uniswap V3 path.
error UnexpectedPathTokenIn(address decodedTokenIn, address expectedTokenIn);
// Unexpected last token of the given Uniswap V3 path.
error UnexpectedPathTokenOut(address decodedTokenOut, address expectedTokenOut);
// The pool specified by the given Uniswap V3 path does not exist (zero address).
error ZeroPoolAddress(address tokenIn, address tokenOut, uint24 fee);
// The given swap path (as defined by token in/out) was not set.
error PathNotSet(address tokenIn, address tokenOut);
error NotEnoughMargin();
error NotImplemented(bool isBaseToQuote, bool isExactInput, uint256 amount);
error NegativeOrZeroVaultValueInBase(int256 vaultValueInBase);
error NotEnoughSpotBaseTokens(uint256 withdraw, uint256 balance);
error HasOpenPosition(int256 positionSize);
//
// IOracleAdapter
//
error OracleDataRequired(bytes32 priceFeedId, bytes reason);
error OracleFeeRequired(uint feeAmount);
error IllegalPriceFeed(bytes32 priceFeedId);
//
// OracleMaker
//
error NegativeOrZeroMargin();
error InvalidSignedRatio(int256 ratio);
error NegativeOrZeroVaultValueInQuote(int256 vaultValue);
//
// FundModel
//
/// @param fund how much fund trader has
/// @param delta how much delta it want to decrease. must be negative
error InsufficientFund(address trader, uint256 fund, int256 delta);
//
// LibLimiter
//
error InvalidMinimumLiquidityThreshold();
error LimiterAlreadyInitialized();
error LimiterNotInitialized();
//
// PythOracleAdapter
//
// Failed to withdraw oracle fee to owner.
error WithdrawOracleFeeFailed(uint256 amount);
//
// NekoCoin
//
error NonZeroBalance();
error NotWhitelisted(address account);
error MintToNotWhitelisted(address recipient);
error RecycleReceiverNotSet();
error RecordStartTimeNotSet();
error RecordStartTimeAlreadySet();
//
// PnlPoolBuffer
//
error NotEnoughForBorrow(uint256 requestedXCD, uint256 balanceXCD);
}
src/external/uniswap-v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Forked from https://github.com/Uniswap/v3-core due to incompatible compiler dependencies.
pragma solidity 0.8.24;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
src/external/uniswap-v3-periphery/contracts/interfaces/ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.24;
pragma abicoder v2;
import { IUniswapV3SwapCallback } from "../../../../external/uniswap-v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
src/spotOrderGateway/ERC7683Across.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import { CrossChainOrder } from "./LegacyERC7683.sol";
enum SwapType {
SKIP_SWAP, // NOTE: re-bridge orders will use this
UNISWAP_V3_SWAP_ROUTER,
UNISWAP_SWAP_ROUTER_02,
ONEINCH_AGGREGATION_ROUTER_V6,
KYBER_META_AGGREGATION_ROUTER_V2,
OKX_AGGREGATOR
}
// Data unique to every CrossChainOrder settled on Across
struct AcrossOrderData {
address inputToken;
uint256 inputAmount;
address outputToken;
uint256 outputAmount;
address bridgeToken;
uint256 bridgeAmountOutMinimum;
uint32 destinationChainId;
address recipient;
uint32 exclusivityDeadline;
bytes message;
}
// relayer should prepare these data when doing initiate()
struct AcrossFillerData {
address exclusiveRelayer;
// for swap to across acceptable token
SwapType swapType;
bytes swapData;
uint32 surplusDisperseRatio;
}
/**
* @notice ERC7683Permit2Lib knows how to process a particular type of external Permit2Order so that it can be used in Across.
* @dev This library is responsible for definining the ERC712 type strings/hashes and performing hashes on the types.
*/
library ERC7683Permit2Lib {
bytes private constant ACROSS_ORDER_DATA_TYPE =
abi.encodePacked(
"AcrossOrderData(",
"address inputToken,",
"uint256 inputAmount,",
"address outputToken,",
"uint256 outputAmount,",
"address bridgeToken,",
"uint256 bridgeAmountOutMinimum,",
"uint32 destinationChainId,",
"address recipient,",
"uint32 exclusivityDeadline,",
"bytes message)"
);
bytes32 private constant ACROSS_ORDER_DATA_TYPE_HASH = keccak256(ACROSS_ORDER_DATA_TYPE);
bytes internal constant CROSS_CHAIN_ORDER_TYPE =
abi.encodePacked(
"CrossChainOrder(",
"address settlerContract,",
"address swapper,",
"uint256 nonce,",
"uint32 originChainId,",
"uint32 initiateDeadline,",
"uint32 fillDeadline,",
"AcrossOrderData orderData)",
ACROSS_ORDER_DATA_TYPE
);
bytes internal constant PERMIT2_CROSS_CHAIN_ORDER_TYPE =
abi.encodePacked(
ACROSS_ORDER_DATA_TYPE,
"CrossChainOrder(",
"address settlerContract,",
"address swapper,",
"uint256 nonce,",
"uint32 originChainId,",
"uint32 initiateDeadline,",
"uint32 fillDeadline,",
"AcrossOrderData orderData)",
TOKEN_PERMISSIONS_TYPE
);
bytes32 internal constant CROSS_CHAIN_ORDER_TYPE_HASH = keccak256(CROSS_CHAIN_ORDER_TYPE);
string private constant TOKEN_PERMISSIONS_TYPE = "TokenPermissions(address token,uint256 amount)";
string internal constant PERMIT2_ORDER_TYPE =
string(abi.encodePacked("CrossChainOrder witness)", PERMIT2_CROSS_CHAIN_ORDER_TYPE));
// Hashes an order to get an order hash. Needed for permit2.
function hashOrder(CrossChainOrder memory order, bytes32 orderDataHash) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
CROSS_CHAIN_ORDER_TYPE_HASH,
order.settlementContract,
order.swapper,
order.nonce,
order.originChainId,
order.initiateDeadline,
order.fillDeadline,
orderDataHash
)
);
}
function hashOrderData(AcrossOrderData memory orderData) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
ACROSS_ORDER_DATA_TYPE_HASH,
orderData.inputToken,
orderData.inputAmount,
orderData.outputToken,
orderData.outputAmount,
orderData.bridgeToken,
orderData.bridgeAmountOutMinimum,
orderData.destinationChainId,
orderData.recipient,
orderData.exclusivityDeadline,
keccak256(orderData.message)
)
);
}
}
src/spotOrderGateway/IV3SpokePool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import { V3SpokePoolInterface } from "across-protocol/contracts/contracts/interfaces/V3SpokePoolInterface.sol";
// we mainly use this custom interface to expose functions we need from SpokePool
// for instance, numberOfDeposits() is not in V3SpokePoolInterface, so cannot use it
interface IV3SpokePool is V3SpokePoolInterface {
function numberOfDeposits() external view returns (uint32);
function fillStatuses(bytes32 relayHash) external view returns (uint256);
}
src/spotOrderGateway/LegacyERC7683.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/// @notice Tokens sent by the swapper as inputs to the order
struct Input {
/// @dev The address of the ERC20 token on the origin chain
address token;
/// @dev The amount of the token to be sent
uint256 amount;
}
/// @notice Tokens that must be receive for a valid order fulfillment
struct Output {
/// @dev The address of the ERC20 token on the destination chain
/// @dev address(0) used as a sentinel for the native token
address token;
/// @dev The amount of the token to be sent
uint256 amount;
/// @dev The address to receive the output tokens
address recipient;
/// @dev The destination chain for this output
uint32 chainId;
}
/// @title CrossChainOrder type
/// @notice Standard order struct to be signed by swappers, disseminated to fillers, and submitted to settlement contracts
struct CrossChainOrder {
/// @dev The contract address that the order is meant to be settled by.
/// Fillers send this order to this contract address on the origin chain
address settlementContract;
/// @dev The address of the user who is initiating the swap,
/// whose input tokens will be taken and escrowed
address swapper;
/// @dev Nonce to be used as replay protection for the order
uint256 nonce;
/// @dev The chainId of the origin chain
uint32 originChainId;
/// @dev The timestamp by which the order must be initiated
uint32 initiateDeadline;
/// @dev The timestamp by which the order must be filled on the destination chain
uint32 fillDeadline;
/// @dev Arbitrary implementation-specific data
/// Can be used to define tokens, amounts, destination chains, fees, settlement parameters,
/// or any other order-type specific information
bytes orderData;
}
/// @title ResolvedCrossChainOrder type
/// @notice An implementation-generic representation of an order
/// @dev Defines all requirements for filling an order by unbundling the implementation-specific orderData.
/// @dev Intended to improve integration generalization by allowing fillers to compute the exact input and output information of any order
struct ResolvedCrossChainOrder {
/// @dev The contract address that the order is meant to be settled by.
address settlementContract;
/// @dev The address of the user who is initiating the swap
address swapper;
/// @dev Nonce to be used as replay protection for the order
uint256 nonce;
/// @dev The chainId of the origin chain
uint32 originChainId;
/// @dev The timestamp by which the order must be initiated
uint32 initiateDeadline;
/// @dev The timestamp by which the order must be filled on the destination chain(s)
uint32 fillDeadline;
/// @dev The inputs to be taken from the swapper as part of order initiation
Input[] swapperInputs;
/// @dev The outputs to be given to the swapper as part of order fulfillment
Output[] swapperOutputs;
/// @dev The outputs to be given to the filler as part of order settlement
Output[] fillerOutputs;
}
/// @title ISettlementContract
/// @notice Standard interface for settlement contracts
interface ISettlementContract {
/// @notice Initiates the settlement of a cross-chain order
/// @dev To be called by the filler
/// @param order The CrossChainOrder definition
/// @param signature The swapper's signature over the order
/// @param fillerData Any filler-defined data required by the settler
function initiate(CrossChainOrder memory order, bytes memory signature, bytes memory fillerData) external;
/// @notice Resolves a specific CrossChainOrder into a generic ResolvedCrossChainOrder
/// @dev Intended to improve standardized integration of various order types and settlement contracts
/// @param order The CrossChainOrder definition
/// @param fillerData Any filler-defined data required by the settler
/// @return ResolvedCrossChainOrder hydrated order data including the inputs and outputs of the order
function resolve(
CrossChainOrder memory order,
bytes memory fillerData
) external view returns (ResolvedCrossChainOrder memory);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.