Verified contractExactMIT
Swapic
Address0xb3f66517bec4cc5a8e799db2dda4c810befcc917
- Balance
0 ETH
- Transactions
13
- 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
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,335,795
- Creation transaction
- 0x236d9895ab…f366dcda81
27 files
- src/Swapic.solmain11.09 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol653 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol2.34 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/CctpReceiver.sol5.29 KB
- src/Runner.sol13.64 KB
- src/SwapicTypes.sol2.1 KB
- src/interfaces/ICctpReceiver.sol2.24 KB
- src/interfaces/ICctpV2.sol436 B
- src/interfaces/ICkHelper.sol346 B
- src/interfaces/IERC3009.sol827 B
- src/interfaces/IRunner.sol3.14 KB
- src/interfaces/IScaler.sol429 B
- src/interfaces/ISignatureTransfer.sol822 B
- src/interfaces/ISwapic.sol3.62 KB
- src/interfaces/IWrappedNative.sol168 B
- src/libraries/Envelope.sol2.68 KB
- src/libraries/OrderHash.sol4.37 KB
src/Swapic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {NATIVE, PERMIT2, Order, GaslessAuth, Permit2Auth, Door} from "./SwapicTypes.sol";
import {ISwapic} from "./interfaces/ISwapic.sol";
import {IRunner} from "./interfaces/IRunner.sol";
import {IERC3009} from "./interfaces/IERC3009.sol";
import {IWrappedNative} from "./interfaces/IWrappedNative.sol";
import {ISignatureTransfer} from "./interfaces/ISignatureTransfer.sol";
import {OrderHash} from "./libraries/OrderHash.sol";
import {Runner} from "./Runner.sol";
import {CctpReceiver} from "./CctpReceiver.sol";
/// One per chain; its constructor deploys the CCTP receiver and the Runner.
/// It calls only: the token pull and balance reads, permit, Permit2, the
/// 3009 receive, the wrapped native token's deposit, and `runner.execute`.
contract Swapic is ISwapic {
using SafeERC20 for IERC20;
/// completes Permit2's PermitWitnessTransferFrom typehash stub
string internal constant WITNESS_TYPE =
"OrderWitness witness)OrderWitness(bytes32 orderId)TokenPermissions(address token,uint256 amount)";
bytes32 internal constant WITNESS_TYPEHASH = keccak256("OrderWitness(bytes32 orderId)");
address public immutable runner;
address public immutable cctpReceiver;
address public immutable wrappedNative;
address public owner;
address public pendingOwner;
address public guardian;
address public canister;
bool public paused;
mapping(bytes32 => bool) public used;
uint256 private _lock = 1;
modifier nonReentrant() {
if (_lock != 1) revert Reentrancy();
_lock = 2;
_;
_lock = 1;
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
/// `tokenMessenger` is CCTP's TokenMessengerV2; `wrappedNative` the
/// chain's WETH (WPOL on Polygon); `ckHelper` the ck minter's deposit
/// helper on Ethereum, zero elsewhere.
constructor(
address usdc,
address messageTransmitter,
address tokenMessenger,
address wrappedNative_,
address ckHelper,
address owner_,
address guardian_,
address canister_
) {
if (owner_ == address(0) || canister_ == address(0)) revert BadParams();
owner = owner_;
guardian = guardian_;
canister = canister_;
wrappedNative = wrappedNative_;
address receiver = address(new CctpReceiver(address(this), usdc, messageTransmitter, tokenMessenger));
cctpReceiver = receiver;
runner = address(new Runner(address(this), receiver, ckHelper, wrappedNative_));
emit OwnershipTransferred(address(0), owner_);
emit GuardianSet(guardian_);
emit CanisterSet(canister_);
}
// ------------------------------------------------------------------
// doors
// ------------------------------------------------------------------
function run(Order calldata o) external payable nonReentrant returns (bytes32 id) {
if (o.payer != msg.sender) revert NotPayer();
id = _open(o);
uint256 inBaseline;
if (o.tokenIn == NATIVE) {
// wrapped here, so the steps never see ether they did not make
if (msg.value != o.amountIn) revert BadValue();
address w = wrappedNative;
inBaseline = IERC20(w).balanceOf(runner);
IWrappedNative(w).deposit{value: msg.value}();
IERC20(w).safeTransfer(runner, o.amountIn);
_arrived(w, runner, inBaseline, o.amountIn);
} else {
if (msg.value != 0) revert BadValue();
inBaseline = IERC20(o.tokenIn).balanceOf(runner);
IERC20(o.tokenIn).safeTransferFrom(msg.sender, runner, o.amountIn);
_arrived(o.tokenIn, runner, inBaseline, o.amountIn);
}
emit OrderStarted(id, o.ref, o.payer, o.tokenIn, o.amountIn, o.memo);
IRunner(runner).execute(o, id, inBaseline);
}
function runWithPermit2(Order calldata o, Permit2Auth calldata a) external nonReentrant returns (bytes32 id) {
if (o.payer != msg.sender) revert NotPayer();
if (o.tokenIn == NATIVE) revert BadValue();
id = _open(o);
uint256 inBaseline = IERC20(o.tokenIn).balanceOf(runner);
_pullPermit2(o, id, a.nonce, a.deadline, a.signature);
_arrived(o.tokenIn, runner, inBaseline, o.amountIn);
emit OrderStarted(id, o.ref, o.payer, o.tokenIn, o.amountIn, o.memo);
IRunner(runner).execute(o, id, inBaseline);
}
function runFor(Order calldata o, GaslessAuth calldata a) external nonReentrant returns (bytes32 id) {
if (msg.sender != canister) revert NotCanister();
if (o.tokenIn == NATIVE) revert BadValue();
id = _open(o);
IERC20 token = IERC20(o.tokenIn);
uint256 inBaseline = token.balanceOf(runner);
if (a.door == Door.Auth3009) {
(uint8 v, bytes32 r, bytes32 s) = _split(a.signature);
// a token whose fallback takes any selector makes this a silent
// no-op: only the measured receipt counts
uint256 own = token.balanceOf(address(this));
IERC3009(o.tokenIn).receiveWithAuthorization(
o.payer, address(this), o.amountIn, a.validAfter, a.validBefore, id, v, r, s
);
_arrived(o.tokenIn, address(this), own, o.amountIn);
token.safeTransfer(runner, o.amountIn);
} else if (a.door == Door.Permit2612) {
// the permit carries no authority (a front-run of it sets the very
// allowance needed); the payer's acceptance of `id` does
if (!_accepted(o, id, a.acceptance)) revert NotAccepted();
if (a.signature.length == 65) {
(uint8 v, bytes32 r, bytes32 s) = _split(a.signature);
try IERC20Permit(o.tokenIn).permit(o.payer, address(this), o.amountIn, o.deadline, v, r, s) {} catch {}
}
token.safeTransferFrom(o.payer, runner, o.amountIn);
} else {
_pullPermit2(o, id, a.nonce, a.deadline, a.signature);
}
_arrived(o.tokenIn, runner, inBaseline, o.amountIn);
emit OrderStarted(id, o.ref, o.payer, o.tokenIn, o.amountIn, o.memo);
IRunner(runner).execute(o, id, inBaseline);
}
/// Not paused, in time, never seen: the id is spent before any pull.
function _open(Order calldata o) internal returns (bytes32 id) {
if (paused) revert IsPaused();
if (block.timestamp > o.deadline) revert Expired();
id = OrderHash.orderId(o, block.chainid, address(this));
if (used[id]) revert Used();
used[id] = true;
}
/// Exactly `amount` of `token` reached `holder` since `base`.
function _arrived(address token, address holder, uint256 base, uint256 amount) internal view {
if (IERC20(token).balanceOf(holder) != base + amount) revert NotReceived();
}
function _pullPermit2(Order calldata o, bytes32 id, uint256 nonce, uint256 deadline, bytes calldata signature)
internal
{
ISignatureTransfer(PERMIT2).permitWitnessTransferFrom(
ISignatureTransfer.PermitTransferFrom({
permitted: ISignatureTransfer.TokenPermissions({token: o.tokenIn, amount: o.amountIn}),
nonce: nonce,
deadline: deadline
}),
ISignatureTransfer.SignatureTransferDetails({to: runner, requestedAmount: o.amountIn}),
o.payer,
keccak256(abi.encode(WITNESS_TYPEHASH, id)),
WITNESS_TYPE,
signature
);
}
/// The payer's own key first, so an EIP-7702 account's key still speaks
/// for it; only then, for a payer with code, its ERC-1271 answer.
function _accepted(Order calldata o, bytes32 id, bytes calldata signature) internal view returns (bool) {
bytes32 digest = OrderHash.acceptanceDigest(o, id, block.chainid, address(this));
(address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, signature);
if (err == ECDSA.RecoverError.NoError && recovered == o.payer) return true;
return o.payer.code.length > 0 && SignatureChecker.isValidERC1271SignatureNow(o.payer, digest, signature);
}
function _split(bytes calldata sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
if (sig.length != 65) revert NotAccepted();
r = bytes32(sig[0:32]);
s = bytes32(sig[32:64]);
v = uint8(sig[64]);
}
// ------------------------------------------------------------------
// views
// ------------------------------------------------------------------
function orderId(Order calldata o) external view returns (bytes32) {
return OrderHash.orderId(o, block.chainid, address(this));
}
function acceptanceDigest(Order calldata o) external view returns (bytes32) {
return OrderHash.acceptanceDigest(
o, OrderHash.orderId(o, block.chainid, address(this)), block.chainid, address(this)
);
}
function locked() external view returns (bool) {
return _lock != 1;
}
function eip712Domain()
external
view
returns (bytes1, string memory, string memory, uint256, address, bytes32, uint256[] memory)
{
return (hex"0f", OrderHash.NAME, OrderHash.VERSION, block.chainid, address(this), bytes32(0), new uint256[](0));
}
// ------------------------------------------------------------------
// administration
// ------------------------------------------------------------------
function pause() external {
if (msg.sender != guardian && msg.sender != owner) revert NotGuardianOrOwner();
paused = true;
emit Paused(msg.sender);
}
function unpause() external onlyOwner {
paused = false;
emit Unpaused(msg.sender);
}
function setGuardian(address guardian_) external onlyOwner {
guardian = guardian_;
emit GuardianSet(guardian_);
}
function setCanister(address canister_) external onlyOwner {
if (canister_ == address(0)) revert BadParams();
canister = canister_;
emit CanisterSet(canister_);
}
function transferOwnership(address newOwner) external onlyOwner {
pendingOwner = newOwner;
emit OwnershipTransferStarted(owner, newOwner);
}
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotOwner();
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
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
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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 Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @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
* {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
}
(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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
*/
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
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.20;
import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like
* Argent and Safe Wallet (previously Gnosis Safe).
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
if (signer.code.length == 0) {
(address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
return err == ECDSA.RecoverError.NoError && recovered == signer;
} else {
return isValidERC1271SignatureNow(signer, hash, signature);
}
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC-1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/CctpReceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Recipe, Action} from "./SwapicTypes.sol";
import {ICctpReceiver} from "./interfaces/ICctpReceiver.sol";
import {ISwapic} from "./interfaces/ISwapic.sol";
import {IRunner} from "./interfaces/IRunner.sol";
import {IMessageTransmitterV2} from "./interfaces/ICctpV2.sol";
import {Envelope} from "./libraries/Envelope.sol";
/// Holds nothing between transactions: every mint it claims leaves in the
/// same call, to the Runner or to the recipient.
contract CctpReceiver is ICctpReceiver {
using SafeERC20 for IERC20;
/// CCTP v2 message layout (Circle evm-cctp-contracts): the header's
/// recipient at 76 and destination caller at 108, the body at 148, the
/// burn message's mint recipient at body + 36, its hook data at body + 228.
uint256 internal constant RECIPIENT_AT = 76;
uint256 internal constant CALLER_AT = 108;
uint256 internal constant MINT_RECIPIENT_AT = 148 + 36;
uint256 internal constant ENVELOPE_AT = 148 + 228;
uint256 internal constant LENGTH = ENVELOPE_AT + Envelope.LENGTH;
address public immutable swapic;
address public immutable usdc;
address public immutable transmitter;
address public immutable tokenMessenger;
uint256 private _lock = 1;
modifier nonReentrant() {
if (_lock != 1) revert Reentrancy();
_lock = 2;
_;
_lock = 1;
}
constructor(address swapic_, address usdc_, address transmitter_, address tokenMessenger_) {
swapic = swapic_;
usdc = usdc_;
transmitter = transmitter_;
tokenMessenger = tokenMessenger_;
}
function completeCctp(bytes calldata message, bytes calldata attestation, Recipe calldata recipe)
external
nonReentrant
{
ISwapic s = ISwapic(swapic);
if (s.paused()) revert IsPaused();
Envelope.Data memory e = _envelope(message);
if (e.action == Action.Deliver) revert WrongAction();
if (
e.action == Action.CkDeposit
&& (recipe.target != address(0) || recipe.data.length != 0 || recipe.scaler != address(0))
) revert BadRecipe();
if (block.timestamp > e.deadline) revert DeadlinePassed();
if (msg.sender != s.canister() && msg.sender != e.recipient) revert NotCanisterOrRecipient();
IERC20 token = IERC20(usdc);
uint256 base = token.balanceOf(address(this));
uint256 minted = _receive(message, attestation, base);
address runner = s.runner();
token.forceApprove(runner, minted);
IRunner(runner).fill(usdc, minted, message[ENVELOPE_AT:], recipe);
token.forceApprove(runner, 0);
if (token.balanceOf(address(this)) != base) revert LeftOver();
}
function release(bytes calldata message, bytes calldata attestation) external nonReentrant {
Envelope.Data memory e = _envelope(message);
if (block.timestamp <= e.deadline) revert DeadlineNotPassed();
uint256 minted = _receive(message, attestation, IERC20(usdc).balanceOf(address(this)));
IERC20(usdc).safeTransfer(e.recipient, minted);
emit Released(e.ref, e.recipient, minted);
}
/// Decodes the envelope of any Swapic-sized message, Deliver included. It
/// does not say the receiver will act on it: `claimable` does.
function envelopeOf(bytes calldata message) external pure returns (Envelope.Data memory) {
if (message.length != LENGTH) revert BadMessage();
return Envelope.decode(message[ENVELOPE_AT:]);
}
/// The envelope of a message `completeCctp` and `release` will act on, under
/// the same header and mint recipient checks; reverts otherwise.
function claimable(bytes calldata message) external view returns (Envelope.Data memory) {
return _envelope(message);
}
/// The envelope of a Circle burn message that only this contract may
/// receive and that mints to it. Pinning the header recipient to the
/// TokenMessenger keeps any other message handler (code that runs between
/// the baseline and the mint) out.
function _envelope(bytes calldata message) internal view returns (Envelope.Data memory) {
if (message.length != LENGTH) revert BadMessage();
bytes32 me = bytes32(uint256(uint160(address(this))));
if (
bytes32(message[RECIPIENT_AT:RECIPIENT_AT + 32]) != bytes32(uint256(uint160(tokenMessenger)))
|| bytes32(message[CALLER_AT:CALLER_AT + 32]) != me
|| bytes32(message[MINT_RECIPIENT_AT:MINT_RECIPIENT_AT + 32]) != me
) revert BadMessage();
return Envelope.decode(message[ENVELOPE_AT:]);
}
/// What the transmitter minted here in this call.
function _receive(bytes calldata message, bytes calldata attestation, uint256 base)
internal
returns (uint256 minted)
{
if (!IMessageTransmitterV2(transmitter).receiveMessage(message, attestation)) revert BadMessage();
minted = IERC20(usdc).balanceOf(address(this)) - base;
if (minted == 0) revert NothingMinted();
}
}
src/Runner.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {NATIVE, PERMIT2, Order, Step, Write, Payout, Recipe, Action} from "./SwapicTypes.sol";
import {IRunner} from "./interfaces/IRunner.sol";
import {ISwapic} from "./interfaces/ISwapic.sol";
import {IScaler} from "./interfaces/IScaler.sol";
import {ICkHelper} from "./interfaces/ICkHelper.sol";
import {Envelope} from "./libraries/Envelope.sol";
/// The hands. Every balance it checks is relative to the start of the call,
/// so a donation changes nothing; every approval it grants is exact and
/// reset after the call it was for.
contract Runner is IRunner {
using SafeERC20 for IERC20;
/// A self-call starved anywhere below it leaves `fill` about 1/64 of the
/// gas for every frame between them (63/64 rule), so a starved arrival
/// ends with at most 1/8 left for routers up to eight frames deep; the
/// envelope's signed `minGas` covers deeper ones. An action that fails by
/// burning all the gas it is given also reverts, at any gas limit.
uint256 internal constant STARVED = 8;
address public immutable swapic;
address public immutable cctpReceiver;
address public immutable ckHelper;
/// an order with `tokenIn == NATIVE` arrives wrapped in this token
address public immutable wrappedNative;
uint256 private _lock = 1;
modifier nonReentrant() {
if (_lock != 1) revert Reentrancy();
_lock = 2;
_;
_lock = 1;
}
constructor(address swapic_, address cctpReceiver_, address ckHelper_, address wrappedNative_) {
swapic = swapic_;
cctpReceiver = cctpReceiver_;
ckHelper = ckHelper_;
wrappedNative = wrappedNative_;
}
receive() external payable {}
// ------------------------------------------------------------------
// source: the signed steps
// ------------------------------------------------------------------
/// Swapic's only. The lock is the Runner's own: Swapic is not locked while
/// a CCTP arrival runs `fill`, so without it a recipe could call `run` and
/// nest a whole order inside the arrival.
function execute(Order calldata o, bytes32 id, uint256 inBaseline) external nonReentrant {
if (msg.sender != swapic) revert OnlySwapic();
if (o.payout.token != address(0)) _checkRecipient(o.payout.recipient);
(address[] memory tokens, uint256[] memory base) = _baselines(o, inBaseline);
uint256 n = o.steps.length;
for (uint256 i; i < n; ++i) {
_step(o.steps[i], tokens, base);
}
Payout calldata p = o.payout;
if (p.token != address(0)) {
uint256 out = _delta(p.token, tokens, base);
if (out < p.minOut) revert Short();
_pay(p.token, p.recipient, out, p.minOut);
emit PaidOut(id, p.recipient, p.token, out);
}
for (uint256 i; i < tokens.length; ++i) {
if (_balance(tokens[i]) != base[i]) revert LeftOver();
}
}
/// The tracked tokens (tokenIn, every step token, the payout token, each
/// once) and their balances at the start of this order. A NATIVE tokenIn
/// arrived wrapped, so the wrapped token is tracked in its place.
function _baselines(Order calldata o, uint256 inBaseline)
internal
view
returns (address[] memory tokens, uint256[] memory base)
{
uint256 n = o.steps.length;
tokens = new address[](n + 2);
base = new uint256[](n + 2);
address tokenIn = o.tokenIn == NATIVE ? wrappedNative : o.tokenIn;
uint256 count;
for (uint256 i; i < n + 2; ++i) {
address t = i == 0 ? tokenIn : i == n + 1 ? o.payout.token : o.steps[i - 1].token;
if (t == address(0)) continue;
bool seen;
for (uint256 j; j < count; ++j) {
if (tokens[j] == t) {
seen = true;
break;
}
}
if (seen) continue;
tokens[count] = t;
if (t == tokenIn) base[count] = inBaseline;
else if (t == NATIVE) base[count] = address(this).balance;
else base[count] = IERC20(t).balanceOf(address(this));
++count;
}
assembly ("memory-safe") {
mstore(tokens, count)
mstore(base, count)
}
}
function _step(Step calldata s, address[] memory tokens, uint256[] memory base) internal {
address token = s.token;
bytes memory data = s.data;
uint256 d;
if (token == address(0)) {
if (s.writes.length != 0) revert BadWrite();
} else {
d = _delta(token, tokens, base);
if (d < s.min) revert Short();
_write(data, s.writes, d);
}
// after the writes: a write may cover the selector
_guard(s.target, data);
if (token == NATIVE) {
_call(s.target, d, data);
} else if (token != address(0)) {
IERC20(token).forceApprove(s.target, d);
_call(s.target, 0, data);
IERC20(token).forceApprove(s.target, 0);
} else {
_call(s.target, 0, data);
}
}
function _write(bytes memory data, Write[] calldata ws, uint256 d) internal pure {
uint256 len = data.length;
for (uint256 i; i < ws.length; ++i) {
uint256 at = ws[i].at;
uint256 minus = ws[i].minus;
if (at + 32 > len || d < minus) revert BadWrite();
uint256 v = d - minus;
assembly ("memory-safe") {
mstore(add(add(data, 32), at), v)
}
}
}
function _delta(address token, address[] memory tokens, uint256[] memory base) internal view returns (uint256) {
for (uint256 i; i < tokens.length; ++i) {
if (tokens[i] == token) return _balance(token) - base[i];
}
revert BadStep();
}
// ------------------------------------------------------------------
// arrival
// ------------------------------------------------------------------
function fill(address token, uint256 amount, bytes calldata envelope, Recipe calldata recipe)
external
nonReentrant
{
ISwapic s = ISwapic(swapic);
if (s.paused()) revert IsPaused();
// a door is pulling tokens into this contract right now
if (s.locked()) revert Reentrancy();
Envelope.Data memory e = Envelope.decode(envelope);
if (e.action == Action.Deliver) revert WrongAction();
_checkRecipient(e.recipient);
// else whoever picks the recipe could pay the arriving token to
// themselves and still pass
if (e.action == Action.Swap && (e.minOut == 0 || e.tokenOut == address(0) || e.tokenOut == token)) {
revert BadArrival();
}
uint256 base = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 received = IERC20(token).balanceOf(address(this)) - base;
if (_act(token, received, base, e, recipe)) return;
IERC20(token).safeTransfer(e.recipient, received);
emit Refunded(e.ref, e.recipient, token, received);
}
/// The action in an undoable self-call (no returndata copied). The signed
/// `minGas` must be left for it; a self-call starved anyway is the
/// caller's doing, not a failed action: both revert so the arrival can be
/// retried with more gas.
function _act(address token, uint256 received, uint256 base, Envelope.Data memory e, Recipe calldata recipe)
internal
returns (bool ok)
{
bytes memory cd = e.action == Action.Swap
? abi.encodeCall(this.swapAll, (token, received, base, e, recipe))
: abi.encodeCall(this.ckDepositAll, (token, received, base, e));
uint256 before = gasleft();
// the self-call receives at most 63/64 of what is left here
if (before - before / 64 < e.minGas) revert OutOfGas();
assembly ("memory-safe") {
ok := call(gas(), address(), 0, add(cd, 32), mload(cd), 0, 0)
}
if (!ok && gasleft() <= before / STARVED) revert OutOfGas();
}
/// All of `received` spent, at least `minOut` of tokenOut, all of it paid.
function swapAll(address token, uint256 received, uint256 base, Envelope.Data calldata e, Recipe calldata r)
external
returns (uint256 out)
{
if (msg.sender != address(this)) revert OnlySelf();
bytes memory data = r.data;
if (r.scaler != address(0)) {
bool ok;
(ok, data) = IScaler(r.scaler).getScaledInputData(data, received);
if (!ok) revert BadStep();
}
if (r.target == token) revert BadStep();
_guard(r.target, data);
address tokenOut = e.tokenOut;
uint256 outBase = _balance(tokenOut);
IERC20(token).forceApprove(r.target, received);
_call(r.target, 0, data);
IERC20(token).forceApprove(r.target, 0);
if (IERC20(token).balanceOf(address(this)) != base) revert LeftOver();
out = _balance(tokenOut) - outBase;
if (out < e.minOut) revert Short();
_pay(tokenOut, e.recipient, out, e.minOut);
emit Delivered(e.ref, e.recipient, tokenOut, received, out);
}
function ckDepositAll(address token, uint256 received, uint256 base, Envelope.Data calldata e) external {
if (msg.sender != address(this)) revert OnlySelf();
if (ckHelper == address(0)) revert NoHelper();
IERC20(token).forceApprove(ckHelper, received);
ICkHelper(ckHelper).depositErc20(token, received, e.principal, e.subaccount);
IERC20(token).forceApprove(ckHelper, 0);
if (IERC20(token).balanceOf(address(this)) != base) revert LeftOver();
emit CkDeposited(e.ref, e.principal, e.subaccount, received);
}
// ------------------------------------------------------------------
// shared
// ------------------------------------------------------------------
/// Rule 2: never our own contracts or Permit2, never an address without
/// code, never a call that moves or grants someone else's allowance.
function _guard(address target, bytes memory data) internal view {
if (
target == swapic || target == address(this) || target == cctpReceiver || target == PERMIT2
|| target.code.length == 0
) revert BadStep();
if (data.length >= 4) {
bytes4 sel;
assembly ("memory-safe") {
sel := mload(add(data, 32))
}
if (_grants(sel)) revert BadStep();
}
}
/// Calls that move someone else's tokens or leave a standing right with
/// someone (the Runner makes its own exact approvals, so no step needs one).
function _grants(bytes4 sel) internal pure returns (bool) {
return sel == 0x23b872dd // transferFrom
|| sel == 0x095ea7b3 // approve
|| sel == 0x39509351 // increaseAllowance
|| sel == 0xd505accf // permit
|| sel == 0xa22cb465 // setApprovalForAll
|| sel == 0xd73dd623 // increaseApproval
|| sel == 0x959b8c3f // ERC-777 holder authorization
|| sel == 0x3177029f // ERC-1363 approveAndCall(address,uint256)
|| sel == 0xcae9ca51 // ERC-1363 approveAndCall(address,uint256,bytes)
|| sel == 0xdaea85c5 // DSToken approve(address)
|| sel == 0x558a7297 // ERC-6909 grant for all ids
|| sel == 0x426a8493 // ERC-6909 approve(address,uint256,uint256)
|| sel == 0x5df8122f // ERC-1820 setManager
|| sel == 0x29965a1d // ERC-1820 setInterfaceImplementer
|| sel == 0x110496e5 // Comet allow
|| sel == 0xeecea000 // Morpho setAuthorization
|| sel == 0xc04a8a10 // Aave approveDelegation
|| sel == 0xfa6e671d // Balancer setRelayerApproval
|| sel == 0xa3b22fc4; // Maker hope
}
/// Never nowhere, never one of our own contracts (funds there are stuck
/// or takeable by anyone).
function _checkRecipient(address to) internal view {
if (to == address(0) || to == swapic || to == address(this) || to == cctpReceiver) revert BadRecipient();
}
function _balance(address token) internal view returns (uint256) {
return token == NATIVE ? address(this).balance : IERC20(token).balanceOf(address(this));
}
/// All of `amount` to `to`, who must end up with at least `minOut` of an
/// ERC-20 as received (a fee-on-transfer token pays less than it sends).
function _pay(address token, address to, uint256 amount, uint256 minOut) internal {
if (token == NATIVE) {
_call(to, amount, "");
return;
}
uint256 before = IERC20(token).balanceOf(to);
IERC20(token).safeTransfer(to, amount);
if (IERC20(token).balanceOf(to) - before < minOut) revert Short();
}
/// No returndata copied (return-bomb safe); a failure reverts.
function _call(address target, uint256 value, bytes memory data) internal {
bool ok;
assembly ("memory-safe") {
ok := call(gas(), target, value, add(data, 32), mload(data), 0, 0)
}
if (!ok) revert CallFailed();
}
}
src/SwapicTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
// Ether, wherever a token address is expected.
address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// Uniswap's Permit2: a door for Swapic, a banned target for the Runner.
address constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// Writes (delta - minus) as one uint256 word at byte `at` of a step's data.
/// `at` is any byte offset, not a word index.
struct Write {
uint32 at;
uint256 minus;
}
/// One call the Runner makes. `token` ERC-20: the Runner approves `target`
/// exactly its delta of `token`; `token == NATIVE`: it sends that delta as
/// value; `token == 0`: no approval, no value, no writes.
struct Step {
address target;
bytes data;
address token;
uint256 min;
Write[] writes;
}
/// `token == 0`: no payout (cross-chain orders).
struct Payout {
address token;
address recipient;
uint256 minOut;
}
/// `memo`: a pool deposit's encoded terms, whose keccak256 is `ref`; empty on
/// every other order. Swapic only signs it into the id and emits it.
struct Order {
bytes32 ref;
address payer;
address tokenIn;
uint256 amountIn;
uint256 deadline;
Step[] steps;
Payout payout;
bytes memo;
}
enum Door {
Auth3009,
Permit2612,
Permit2
}
/// Auth3009: `validAfter`, `validBefore` and `signature` (r ++ s ++ v).
/// Permit2612: `signature` is the permit (swallowed if it fails) and
/// `acceptance` the payer's QuoteAcceptance signature. Permit2: `nonce`,
/// `deadline` and `signature` of the witness transfer.
struct GaslessAuth {
Door door;
uint256 validAfter;
uint256 validBefore;
uint256 nonce;
uint256 deadline;
bytes signature;
bytes acceptance;
}
struct Permit2Auth {
uint256 nonce;
uint256 deadline;
bytes signature;
}
enum Action {
Deliver,
Swap,
CkDeposit
}
/// The arrival swap. `scaler == 0`: `data` as is; else `data` is first
/// rescaled to the amount that arrived.
struct Recipe {
address target;
bytes data;
address scaler;
}
src/interfaces/ICctpReceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Recipe} from "../SwapicTypes.sol";
import {Envelope} from "../libraries/Envelope.sol";
/// The only CCTP code: the `mintRecipient` and `destinationCaller` of every
/// CCTP Swap and CkDeposit burn. It claims the message and hands exactly what
/// was minted to `Runner.fill`, or after the deadline to the recipient.
interface ICctpReceiver {
/// After the deadline: the minted USDC went to the recipient.
event Released(bytes32 indexed ref, address indexed recipient, uint256 amount);
error IsPaused();
error Reentrancy();
error BadMessage();
error WrongAction();
error BadRecipe();
error DeadlinePassed();
error DeadlineNotPassed();
error NotCanisterOrRecipient();
error LeftOver();
error NothingMinted();
function swapic() external view returns (address);
function usdc() external view returns (address);
function transmitter() external view returns (address);
function tokenMessenger() external view returns (address);
/// Before the envelope's deadline, by the canister or the envelope's
/// recipient: receives the message, then `Runner.fill` on exactly what
/// was minted with `recipe` (empty for CkDeposit). The message must be a
/// burn for the local TokenMessenger, with this contract as destination
/// caller and mint recipient, and mint something.
function completeCctp(bytes calldata message, bytes calldata attestation, Recipe calldata recipe) external;
/// After the envelope's deadline, by anyone, even paused: receives the
/// message and pays all that was minted to the envelope's recipient.
function release(bytes calldata message, bytes calldata attestation) external;
/// The envelope of any Swapic-sized CCTP v2 message (bytes 376 to 696),
/// Deliver included. It does not say the receiver will act on it.
function envelopeOf(bytes calldata message) external pure returns (Envelope.Data memory);
/// The envelope of a message `completeCctp` and `release` will act on
/// (same header and mint recipient checks); reverts otherwise.
function claimable(bytes calldata message) external view returns (Envelope.Data memory);
}
src/interfaces/ICctpV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// CCTP v2 MessageTransmitterV2 (`0x81D40F21F12A8F0E3252Bccb954D722d4c464B64`).
interface IMessageTransmitterV2 {
/// selector 0x57ecfd28. Mints `amount - feeExecuted` to the message's mint
/// recipient; only the destination caller may call it when that is set.
function receiveMessage(bytes calldata message, bytes calldata attestation) external returns (bool);
}
src/interfaces/ICkHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// The ck minter's ERC-20 deposit helper on Ethereum: it pulls `amount` of
/// `erc20Address` from the caller for the minter and logs the beneficiary.
interface ICkHelper {
function depositErc20(address erc20Address, uint256 amount, bytes32 principal, bytes32 subaccount) external;
}
src/interfaces/IERC3009.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// EIP-3009 transfer with authorization, the one member the vault uses.
///
/// `receiveWithAuthorization` is the relayer-safe half of the standard: the token
/// requires `to == msg.sender`, so an authorization made out to this vault can
/// only ever be submitted by this vault. The nonce is an arbitrary 32 byte value
/// in a used-or-not map rather than a counter, which is what lets the vault put
/// the quote hash there and get a quote binding the standard pays nothing extra
/// for.
interface IERC3009 {
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
src/interfaces/IRunner.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Order, Recipe} from "../SwapicTypes.sol";
import {Envelope} from "../libraries/Envelope.sol";
/// Runs the signed steps of an order (only Swapic may ask) and every arrival
/// (anyone may ask, paying with their own tokens). Nobody approves it, it
/// holds nothing between transactions, and every outcome is all or nothing.
interface IRunner {
/// A same-chain order paid `amount` of `token` to `recipient`.
event PaidOut(bytes32 indexed id, address indexed recipient, address token, uint256 amount);
/// An arrival of `amountIn` was swapped whole into `amountOut` of `tokenOut`.
event Delivered(
bytes32 indexed ref, address indexed recipient, address tokenOut, uint256 amountIn, uint256 amountOut
);
event CkDeposited(bytes32 indexed ref, bytes32 indexed principal, bytes32 subaccount, uint256 amount);
/// The arrival action failed: all of the arrived `token` went to `recipient`.
event Refunded(bytes32 indexed ref, address indexed recipient, address token, uint256 amount);
error OnlySwapic();
error OnlySelf();
error Reentrancy();
error IsPaused();
error BadStep();
error BadWrite();
error Short();
error LeftOver();
error CallFailed();
error WrongAction();
error BadArrival();
error BadRecipient();
error NoHelper();
error OutOfGas();
function swapic() external view returns (address);
function cctpReceiver() external view returns (address);
function ckHelper() external view returns (address);
function wrappedNative() external view returns (address);
/// Only Swapic, after it pulled `amountIn` into the Runner. `inBaseline`
/// is the Runner's `tokenIn` balance before that pull (for a NATIVE
/// tokenIn: of the wrapped native token, which is what arrived).
function execute(Order calldata order, bytes32 id, uint256 inBaseline) external;
/// Anyone (Eco's executor, the CCTP receiver, any rail that can approve
/// and call): pulls `amount` of `token` from the caller, then acts on
/// exactly what arrived as the envelope says. Swap: through `recipe`, all
/// of it into at least `minOut` of `tokenOut`, all paid to the recipient;
/// CkDeposit: all of it into the ck helper. If the action fails, all of
/// what arrived goes to the recipient instead. Reverts (so nothing
/// arrives) when paused, while a Swapic door runs, on a bad or Deliver
/// envelope or a bad recipient, when less than the envelope's `minGas`
/// is left for the action or the action was starved of gas (`OutOfGas`,
/// retry with more), or if the refund transfer itself fails.
function fill(address token, uint256 amount, bytes calldata envelope, Recipe calldata recipe) external;
/// Self-call only: the undoable halves of `fill`.
function swapAll(address token, uint256 received, uint256 base, Envelope.Data calldata e, Recipe calldata recipe)
external
returns (uint256 out);
function ckDepositAll(address token, uint256 received, uint256 base, Envelope.Data calldata e) external;
}
src/interfaces/IScaler.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// KyberSwap's InputScalingHelper (`0x2f577A41BeC1BE1152AeEA12e73b7391d15f655D`
/// on Base, Arbitrum and Ethereum): rewrites router calldata built for one
/// input amount to `newAmount`.
interface IScaler {
function getScaledInputData(bytes calldata inputData, uint256 newAmount)
external
view
returns (bool isSuccess, bytes memory data);
}
src/interfaces/ISignatureTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// Minimal subset of Permit2's SignatureTransfer surface used by the vault.
interface ISignatureTransfer {
struct TokenPermissions {
address token;
uint256 amount;
}
struct PermitTransferFrom {
TokenPermissions permitted;
uint256 nonce;
uint256 deadline;
}
struct SignatureTransferDetails {
address to;
uint256 requestedAmount;
}
function permitWitnessTransferFrom(
PermitTransferFrom calldata permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes32 witness,
string calldata witnessTypeString,
bytes calldata signature
) external;
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
src/interfaces/ISwapic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Order, GaslessAuth, Permit2Auth} from "../SwapicTypes.sol";
/// The door: the only contract users approve. It takes exactly the signed
/// `amountIn` from the payer, once per order, hands it to the Runner, and
/// makes no other call.
interface ISwapic {
/// `memo` is the order's own, so its terms can be read back from the chain.
event OrderStarted(
bytes32 indexed id,
bytes32 indexed ref,
address indexed payer,
address tokenIn,
uint256 amountIn,
bytes memo
);
event Paused(address by);
event Unpaused(address by);
event GuardianSet(address guardian);
event CanisterSet(address canister);
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
error IsPaused();
error Expired();
error Used();
error NotPayer();
error NotCanister();
error NotOwner();
error NotGuardianOrOwner();
error BadValue();
error NotAccepted();
error BadParams();
error Reentrancy();
error NotReceived();
/// By the payer. `tokenIn == NATIVE`: `msg.value == amountIn`, wrapped
/// into `wrappedNative()` and handed to the Runner as that token (the
/// steps are built for it); else `msg.value == 0` and Swapic pulls
/// `amountIn` from the payer.
function run(Order calldata order) external payable returns (bytes32 id);
/// By the payer, ERC-20 only: a Permit2 witness transfer (witness = id).
function runWithPermit2(Order calldata order, Permit2Auth calldata auth) external returns (bytes32 id);
/// By the canister, ERC-20 only, through one of three gasless doors, each
/// bound to `id`: the 3009 nonce, the 2612 QuoteAcceptance, the Permit2
/// witness.
function runFor(Order calldata order, GaslessAuth calldata auth) external returns (bytes32 id);
function orderId(Order calldata order) external view returns (bytes32);
/// What the payer signs on the 2612 door.
function acceptanceDigest(Order calldata order) external view returns (bytes32);
function used(bytes32 id) external view returns (bool);
function runner() external view returns (address);
function cctpReceiver() external view returns (address);
function wrappedNative() external view returns (address);
function paused() external view returns (bool);
/// true while a door runs: the Runner refuses `fill` meanwhile, so no
/// callback during a pull can act on the payer's tokens in flight
function locked() external view returns (bool);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function guardian() external view returns (address);
/// the canister's EVM address
function canister() external view returns (address);
/// EIP-5267: the domain of the order id and the QuoteAcceptance.
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
function pause() external;
function unpause() external;
function setGuardian(address guardian) external;
function setCanister(address canister) external;
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
src/interfaces/IWrappedNative.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// WETH9 and its kin (WPOL on Polygon).
interface IWrappedNative {
function deposit() external payable;
}
src/libraries/Envelope.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Action} from "../SwapicTypes.sol";
/// The sealed arrival instruction: `abi.encode` of 10 static words, 320
/// bytes, word i at byte 32 * i:
///
/// 0 uint8 version 3
/// 1 bytes32 ref Order.ref
/// 2 uint8 action 0 Deliver, 1 Swap, 2 CkDeposit
/// 3 uint64 deadline end of the canister-or-recipient window (CCTP)
/// 4 address recipient tokenOut receiver and refund receiver
/// 5 address tokenOut Swap only (NATIVE for ether)
/// 6 uint256 minOut Swap only, in tokenOut
/// 7 bytes32 principal CkDeposit only
/// 8 bytes32 subaccount CkDeposit only
/// 9 uint64 minGas gas `fill` must have left for the action
///
/// In a CCTP v2 message it starts at byte 376; in an Eco route it is the
/// `envelope` argument of `Runner.fill`.
library Envelope {
uint256 internal constant VERSION = 3;
uint256 internal constant LENGTH = 320;
struct Data {
uint8 version;
bytes32 ref;
Action action;
uint64 deadline;
address recipient;
address tokenOut;
uint256 minOut;
bytes32 principal;
bytes32 subaccount;
uint64 minGas;
}
error BadEnvelope();
function encode(Data memory d) internal pure returns (bytes memory) {
return abi.encode(d);
}
/// Exactly 320 bytes, version 3, every narrow word clean.
function decode(bytes calldata b) internal pure returns (Data memory d) {
if (b.length != LENGTH) revert BadEnvelope();
(
uint256 version,
bytes32 ref,
uint256 action,
uint256 deadline,
uint256 recipient,
uint256 tokenOut,
uint256 minOut,
bytes32 principal,
bytes32 subaccount,
uint256 minGas
) = abi.decode(b, (uint256, bytes32, uint256, uint256, uint256, uint256, uint256, bytes32, bytes32, uint256));
if (
version != VERSION || action > uint256(Action.CkDeposit) || deadline > type(uint64).max
|| recipient > type(uint160).max || tokenOut > type(uint160).max || minGas > type(uint64).max
) revert BadEnvelope();
d = Data({
version: uint8(version),
ref: ref,
action: Action(action),
deadline: uint64(deadline),
recipient: address(uint160(recipient)),
tokenOut: address(uint160(tokenOut)),
minOut: minOut,
principal: principal,
subaccount: subaccount,
minGas: uint64(minGas)
});
}
}
src/libraries/OrderHash.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Order, Step, Write, Payout} from "../SwapicTypes.sol";
/// The order fingerprint: the EIP-712 digest of the whole Order under the
/// domain {name "Swapic", version "3", chainId, verifyingContract = Swapic}.
/// Referenced types are appended alphabetically, `bytes` (a step's data, the
/// memo) hashed, arrays hashed as keccak of the concatenated struct hashes, so
/// viem's `hashTypedData` and alloy's `eip712_signing_hash` reproduce it.
library OrderHash {
string internal constant NAME = "Swapic";
string internal constant VERSION = "3";
bytes32 internal constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
string internal constant ORDER_TYPE =
"Order(bytes32 ref,address payer,address tokenIn,uint256 amountIn,uint256 deadline,Step[] steps,Payout payout,bytes memo)";
string internal constant PAYOUT_TYPE = "Payout(address token,address recipient,uint256 minOut)";
string internal constant STEP_TYPE = "Step(address target,bytes data,address token,uint256 min,Write[] writes)";
string internal constant WRITE_TYPE = "Write(uint32 at,uint256 minus)";
string internal constant ACCEPTANCE_TYPE =
"QuoteAcceptance(bytes32 orderId,address payer,address tokenIn,uint256 amountIn,uint256 deadline)";
bytes32 internal constant ORDER_TYPEHASH =
keccak256(abi.encodePacked(ORDER_TYPE, PAYOUT_TYPE, STEP_TYPE, WRITE_TYPE));
bytes32 internal constant PAYOUT_TYPEHASH = keccak256(bytes(PAYOUT_TYPE));
bytes32 internal constant STEP_TYPEHASH = keccak256(abi.encodePacked(STEP_TYPE, WRITE_TYPE));
bytes32 internal constant WRITE_TYPEHASH = keccak256(bytes(WRITE_TYPE));
bytes32 internal constant ACCEPTANCE_TYPEHASH = keccak256(bytes(ACCEPTANCE_TYPE));
function domainSeparator(uint256 chainId, address swapic) internal pure returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId, swapic));
}
function hashWrite(Write calldata w) internal pure returns (bytes32) {
return keccak256(abi.encode(WRITE_TYPEHASH, w.at, w.minus));
}
function hashStep(Step calldata s) internal pure returns (bytes32) {
uint256 n = s.writes.length;
bytes32[] memory ws = new bytes32[](n);
for (uint256 i; i < n; ++i) {
ws[i] = hashWrite(s.writes[i]);
}
return keccak256(
abi.encode(STEP_TYPEHASH, s.target, keccak256(s.data), s.token, s.min, keccak256(abi.encodePacked(ws)))
);
}
function hashPayout(Payout calldata p) internal pure returns (bytes32) {
return keccak256(abi.encode(PAYOUT_TYPEHASH, p.token, p.recipient, p.minOut));
}
function hashOrder(Order calldata o) internal pure returns (bytes32) {
uint256 n = o.steps.length;
bytes32[] memory ss = new bytes32[](n);
for (uint256 i; i < n; ++i) {
ss[i] = hashStep(o.steps[i]);
}
return keccak256(
abi.encode(
ORDER_TYPEHASH,
o.ref,
o.payer,
o.tokenIn,
o.amountIn,
o.deadline,
keccak256(abi.encodePacked(ss)),
hashPayout(o.payout),
keccak256(o.memo)
)
);
}
function digest(bytes32 separator, bytes32 structHash) internal pure returns (bytes32 d) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"1901")
mstore(add(ptr, 0x02), separator)
mstore(add(ptr, 0x22), structHash)
d := keccak256(ptr, 0x42)
}
}
function orderId(Order calldata o, uint256 chainId, address swapic) internal pure returns (bytes32) {
return digest(domainSeparator(chainId, swapic), hashOrder(o));
}
/// What the payer signs on the 2612 door.
function acceptanceDigest(Order calldata o, bytes32 id, uint256 chainId, address swapic)
internal
pure
returns (bytes32)
{
return digest(
domainSeparator(chainId, swapic),
keccak256(abi.encode(ACCEPTANCE_TYPEHASH, id, o.payer, o.tokenIn, o.amountIn, o.deadline))
);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.