Verified contractExactMIT
AtumModule
Address0x7e203c8c568cfbcad41658a51ec07c0af4af5735
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.29
- Same code
Only this contract
Details
- Compiler
- solc 0.8.29+commit.ab55807c
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- shanghai
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,392,866
- Creation transaction
- 0x990c2a4dc3…81b36d27f1
19 files
- src/modules/contrib/bridges/AtumModule.solmain29.81 KB
- node_modules/@openzeppelin/contracts/access/Ownable.sol3.1 KB
- node_modules/@openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC1271.sol654 B
- node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC165.sol192 B
- node_modules/@openzeppelin/contracts/interfaces/IERC20.sol181 B
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/Pausable.sol2.71 KB
- node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol7.82 KB
- node_modules/@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol2.34 KB
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol870 B
- src/abstracts/ActionModuleBase.sol4.61 KB
- src/interfaces/IActionModule.sol4.38 KB
- src/interfaces/IAtumModule.sol13.02 KB
- src/libraries/Errors.sol13.87 KB
- src/types/DataTypes.sol7.14 KB
src/modules/contrib/bridges/AtumModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.29;
import { IAtumModule } from "../../../interfaces/IAtumModule.sol";
import { IActionModule } from "../../../interfaces/IActionModule.sol";
import { ActionModuleBase } from "../../../abstracts/ActionModuleBase.sol";
import { DataTypes } from "../../../types/DataTypes.sol";
import { Errors } from "../../../libraries/Errors.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SignatureChecker } from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import { Ownable2Step, Ownable } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
/// @title AtumModule
/// @custom:tier contrib
/// @custom:maintainer @atum-labs ([email protected])
/// @custom:audit-status unaudited
/// @notice Minimal PaymentRails-bound Atum payment contract and ERC-1271 Permit2 owner.
/// @dev Each module deployment is permanently bound to one immutable PaymentRails. The module
/// is funded by that PaymentRails through `execute`, emits the current available source
/// balance and destination details for an offchain Atum keeper, and accepts generic
/// Permit2 digests at its ERC-1271 surface. That surface decides one thing -- whether the
/// authorized keeper signed the hash -- and one thing about the caller: only an address in
/// `isAuthorizedSignatureCaller` gets an answer, seeded with Permit2 at construction
/// (Certora M-01). Everything about the digest's CONTENTS is the constructing
/// application's to enforce, because ERC-1271 supplies no preimage to check them against.
///
/// The module does not call Atum Escrow, compute request ids, compute fulfillment
/// amounts, decode Atum witness data, inspect Escrow state, classify payment
/// outcomes, reserve per-payment balances, or store per-payment recovery metadata.
/// The keeper derives source chain/source asset/request id and selects fulfillment
/// terms offchain.
///
/// `execute` is a PaymentRails funding action and payment availability signal, not a
/// complete Atum payment order. It moves additional source tokens into the module
/// and emits the module's full current balance for that token. The keeper should
/// create Atum payment requests from the available source balance, not merely from
/// the amount pulled by one PaymentRails action. Failed deposits, Escrow refunds, and
/// unused source balances remain in the module and can be picked up by a later
/// keeper request.
///
/// Because that sweep pays out the whole balance, `execute` will NOT stage a second
/// destination on top of a non-empty balance: it records the route the current balance was
/// pulled for in `stagedRoute` and returns a failed result if PaymentRails is reconfigured
/// to a different one while funds are still held (Certora L-04). `validate` applies the same
/// guard, so a preview cannot report success for a call `execute` would refuse. Drain or
/// sweep first, then reconfigure.
///
/// That guard treats a zero balance as settlement, which a refund can falsify. It is scoped
/// to funds the module is CURRENTLY holding and makes no claim about funds that left and came
/// back: a refund arriving after the next route is staged is swept under that new route, and
/// the guard then also refuses the corrective change back. See {IAtumModule.stagedRoute} for
/// the full statement. Which destination a payment reaches is a keeper property throughout.
///
/// Keeper operating flow:
/// - Watch {AtumIntentCreated}; when emitted, read/use `availableSourceAmount` and
/// prepare a payment request for the available source balance.
/// - Watch Atum Escrow refund events and module token balances; when refunded
/// funds return, call `syncAllowance(token)` and then initiate a new payment request
/// for the current module balance. The allowance does not track inbound transfers, so
/// without the sync the refund is visible but not pullable (Certora L-02).
/// - Invalidate abandoned floating Permit2 digests before signing replacement
/// requests when those stale digests must not remain usable.
///
/// Pause is a rare fail-safe control for return-to-PaymentRails recovery. It blocks
/// new `execute` calls, ERC-1271 validation and `syncAllowance`, makes `validate` fail, and
/// enables return-to-PaymentRails recovery. It does not revoke Permit2 approvals, invalidate
/// digests permanently, block inbound refunds or direct transfers, prove refund
/// attribution, or undo already consumed Permit2 nonces.
contract AtumModule is IAtumModule, ActionModuleBase, Ownable2Step, Pausable {
using SafeERC20 for IERC20;
using SignatureChecker for address;
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev EIP-1271 magic value returned for valid signatures.
bytes4 internal constant EIP1271_MAGIC_VALUE = 0x1626ba7e;
/// @dev EIP-1271 failure value returned for invalid signatures.
bytes4 internal constant EIP1271_FAILURE_VALUE = 0xffffffff;
/*//////////////////////////////////////////////////////////////////////////
IMMUTABLE STATE
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IAtumModule
address public immutable override permit2;
/// @inheritdoc IAtumModule
address public immutable override paymentRails;
/*//////////////////////////////////////////////////////////////////////////
MUTABLE STATE
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IAtumModule
address public override keeper;
/// @dev Permit2 digests that must no longer satisfy ERC-1271 checks.
mapping(bytes32 digest => bool invalidated) private _invalidatedPermitDigests;
/// @inheritdoc IAtumModule
mapping(address caller => bool authorized) public override isAuthorizedSignatureCaller;
/// @inheritdoc IAtumModule
/// @dev The source amount Permit2 is currently approved to pull, used to cap that allowance
/// instead of granting `type(uint256).max`. Set by `execute` and `syncAllowance` to the
/// module's CURRENT balance, and reset to 0 by `returnTokenBalance` (which also revokes
/// the Permit2 allowance to 0).
///
/// NOT a cumulative counter. It was one until Certora L-03/I-05: the allowance followed
/// the counter while the emitted intent followed the balance, and the two necessarily
/// disagreed in both directions -- the counter too high after Permit2 pulled, too low
/// after a refund or a donation, the latter bricking the keeper's request against a
/// smaller allowance. All three now derive from one quantity, so the invariant is
/// `pendingAmount[token] == allowance(this, permit2) == balanceOf(this)` as of the last
/// `execute` or `syncAllowance`.
mapping(address token => uint256 amount) public override pendingAmount;
/// @inheritdoc IAtumModule
mapping(address token => bytes32 route) public override stagedRoute;
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////*/
/// @param _permit2 Permit2 contract used by Atum Escrow on this source chain.
/// @param _paymentRails Immutable PaymentRails allowed to call `execute`.
/// @param _owner Module owner authorized to manage operations and keeper rotation.
/// @param _keeper Keeper whose signatures validate Atum Permit2 digests.
constructor(address _permit2, address _paymentRails, address _owner, address _keeper) Ownable(_owner) {
if (_permit2 == address(0)) revert Errors.AtumModule_ZeroPermit2();
if (_paymentRails == address(0)) revert Errors.AtumModule_ZeroPaymentRails();
if (_keeper == address(0)) revert Errors.AtumModule_ZeroKeeper();
// Explicit, where it used to be a side effect. The constructor previously called
// `DOMAIN_SEPARATOR()` on this address and stored the result in an immutable that nothing
// ever read -- dead state the audit did not flag. Removing it would also have removed the
// EOA rejection it incidentally provided (the call reverts against an address with no
// code), so the check is stated directly instead. Caching a domain separator would have
// been wrong to keep in any case: Permit2 rebuilds its separator when `chainid` changes,
// so a value fixed at construction goes stale across a fork.
if (_permit2.code.length == 0) revert Errors.AtumModule_Permit2NotContract(_permit2);
permit2 = _permit2;
paymentRails = _paymentRails;
keeper = _keeper;
// The initial keeper is the hot key that authorises moving every token this module holds,
// and it was previously assigned without ever being emitted (Certora I-03): `KeeperSet`
// only fired on rotation, so an indexer reconstructing "who could sign for this module"
// had no record of the first one. Emitting from zero makes the whole keeper history
// recoverable from logs alone.
emit KeeperSet(address(0), _keeper);
// Permit2 is the only contract that has any business asking this module to endorse a
// signature (Certora M-01). Seeded here rather than left to a follow-up call so a freshly
// deployed module is never briefly willing to answer anyone.
isAuthorizedSignatureCaller[_permit2] = true;
emit SignatureCallerSet(_permit2, true);
}
/// @notice Disabled: this module must always retain an owner.
/// @dev Certora I-02. `Ownable.renounceOwnership` would set the owner to `address(0)` and
/// permanently disable keeper rotation, pause/unpause, `returnTokenBalance` and
/// `setSignatureCaller`. The recovery path is `onlyOwner whenPaused`, so renouncing
/// while paused and holding tokens strands them with no way out, and the ERC-1271
/// caller set would be frozen at whatever it happened to hold. There is no situation
/// in which this module wants no owner, so the function reverts rather than being
/// left as a footgun.
function renounceOwnership() public view override onlyOwner {
revert Errors.AtumModule_RenounceOwnershipDisabled();
}
/*//////////////////////////////////////////////////////////////////////////
NON-CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IActionModule
function execute(
address token,
uint256 amount,
bytes calldata params
)
external
override(ActionModuleBase, IActionModule)
whenNotPaused
returns (DataTypes.ExecutionResult memory result)
{
if (msg.sender != paymentRails) {
revert Errors.AtumModule_NotPaymentRails(msg.sender, paymentRails);
}
(bool valid, string memory reason, DataTypes.AtumPaymentParams memory paymentParams) =
_validatePaymentParams(token, amount, params);
if (!valid) {
return _failedResult(token, reason);
}
if (!_hasSufficientBalance(token, amount)) {
return _failedResult(token, "Insufficient balance");
}
// Certora L-04: a route change must not silently redirect funds already staged for the
// previous one.
//
// The module holds one fungible balance per token and the keeper is documented to sweep
// ALL of it (see the note on refunds below), so tokens pulled while Route A was configured
// are indistinguishable from tokens pulled under Route B. Change the PaymentRails config
// between an intent and its settlement and the next intent advertises the whole balance
// against the new destination -- including the funds staged for the old one.
//
// Certora's own recommendation was to emit only the newly-pulled amount, but that
// contradicts the documented sweep the report quotes under L-02: refunds and failed
// deposits are meant to be picked up by a later request. Both cannot hold. This keeps the
// sweep and makes the collision impossible instead, by refusing to stage a second route
// on top of a non-empty balance. Drain or sweep first, then reconfigure.
//
// Keyed on the decoded destination triple rather than the raw `params` bytes, so the guard
// tracks the ROUTE and not its encoding.
if (_routeChangedWhileStaged(token, paymentParams)) {
return _failedResult(token, "Route changed while funds are staged");
}
_pullExactToken(token, amount);
stagedRoute[token] = keccak256(abi.encode(paymentParams));
// ONE quantity drives the allowance, the emitted intent and `pendingAmount`: the balance
// the module actually holds right now (Certora L-03 + I-05).
//
// Before this, the allowance followed a monotonic counter (`pendingAmount += amount`,
// never decremented) while the intent followed `balanceOf`. Those are different numbers
// and they drifted apart in BOTH directions:
//
// * after Permit2 pulled, the balance dropped and the counter did not, so the module
// advertised an allowance over funds it no longer held;
// * after an Escrow refund or a 1-wei donation, the balance rose above the counter, so
// the keeper read the larger number off the event, requested it, and Permit2's
// `transferFrom` reverted against the smaller allowance -- which bricked a fresh
// module for the price of one wei.
//
// Deriving all three from the balance makes the post-condition trivially true:
// `pendingAmount[token] == allowance(permit2) == balanceOf(this)`. A donation is then
// harmless rather than fatal -- it is simply money the module really has, which is what
// the sweep behaviour documented on `execute` already assumes.
uint256 available = IERC20(token).balanceOf(address(this));
pendingAmount[token] = available;
IERC20(token).forceApprove(permit2, available);
emit Permit2ApprovalSet(token, permit2, available);
emit AtumIntentCreated(
token,
available,
paymentParams.destinationChain,
paymentParams.destinationAccount,
paymentParams.destinationAsset
);
return _successResult(0, token, "");
}
/// @inheritdoc IAtumModule
function setKeeper(address newKeeper) external onlyOwner {
if (newKeeper == address(0)) revert Errors.AtumModule_ZeroKeeper();
address oldKeeper = keeper;
keeper = newKeeper;
emit KeeperSet(oldKeeper, newKeeper);
}
/// @inheritdoc IAtumModule
function pause() external onlyOwner {
_pause();
}
/// @inheritdoc IAtumModule
function unpause() external onlyOwner {
_unpause();
}
/// @inheritdoc IAtumModule
/// @dev Exists because the allowance used to be reachable ONLY through `execute`, and
/// `execute` requires a positive pull from PaymentRails (Certora L-02). When Escrow
/// refunds into the module while PaymentRails is empty, there is then no way to point
/// Permit2 at the returned funds: the keeper can see them and cannot request them, and
/// the only exit is the owner pausing and sweeping everything back. That converts a
/// routine refund into an owner-gated incident.
///
/// `onlyKeeper`, not permissionless: raising the allowance grants nothing on its own,
/// since Permit2 still needs a keeper signature to move anything, but the keeper is the
/// party that is actually blocked and restricting it is the cheaper argument to make.
/// This is also the modifier's first real use -- it was dead code (Certora I-01), and
/// giving it a caller is a better resolution than deleting it.
///
/// `whenNotPaused` so it cannot fight `returnTokenBalance`, which is `whenPaused` and
/// deliberately revokes the allowance to zero.
function syncAllowance(address token) external onlyKeeper whenNotPaused returns (uint256 available) {
if (token == address(0)) revert Errors.AtumModule_ZeroToken();
available = IERC20(token).balanceOf(address(this));
pendingAmount[token] = available;
IERC20(token).forceApprove(permit2, available);
emit Permit2ApprovalSet(token, permit2, available);
}
/// @inheritdoc IAtumModule
function invalidateDigest(bytes32 digest) external onlyKeeperOrOwner {
_invalidateDigest(digest);
}
/// @inheritdoc IAtumModule
function invalidateDigests(bytes32[] calldata digests) external onlyKeeperOrOwner {
uint256 length = digests.length;
for (uint256 i; i < length; ++i) {
_invalidateDigest(digests[i]);
}
}
/// @inheritdoc IAtumModule
function returnTokenBalance(address token) external onlyOwner whenPaused returns (uint256 amountReturned) {
amountReturned = _returnTokenBalance(token);
}
/// @inheritdoc IAtumModule
function returnTokenBalances(address[] calldata tokens) external onlyOwner whenPaused {
uint256 length = tokens.length;
for (uint256 i; i < length; ++i) {
_returnTokenBalance(tokens[i]);
}
}
/*//////////////////////////////////////////////////////////////////////////
EIP-1271 SURFACE
//////////////////////////////////////////////////////////////////////////*/
/// @notice Validates that `signature` was signed by the module keeper for `hash`.
/// @dev Keeper authorship only, for authorized callers only. See the body note for what an
/// integrating application must do for that to be safe (Certora M-01).
function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4) {
// Certora M-01. This checks only that the keeper signed `hash`. ERC-1271 gives no
// preimage, so it cannot tell whether `hash` was meant for THIS module -- modules
// sharing a keeper all validate the same (hash, signature) pair.
//
// An application validating signatures here must bind the module address itself: in the
// signed payload, taken from the account it debits and not a caller-supplied field, or
// in a separately signed artifact checked before this result is used. Permit2 does
// neither -- its digest omits the owner and its nonces are per owner, which is the
// reported exploit. Escrow supplies the binding: `depositId`, keccak256(depositor,
// depositSignature, nonce), must match a reserver-signed ReserveWitness checked first.
if (paused() || !isAuthorizedSignatureCaller[msg.sender] || _invalidatedPermitDigests[hash]) {
return EIP1271_FAILURE_VALUE;
}
if (keeper.isValidSignatureNow(hash, signature)) {
return EIP1271_MAGIC_VALUE;
}
return EIP1271_FAILURE_VALUE;
}
/// @inheritdoc IAtumModule
function setSignatureCaller(address caller, bool authorized) external onlyOwner {
if (caller == address(0)) revert Errors.AtumModule_ZeroSignatureCaller();
isAuthorizedSignatureCaller[caller] = authorized;
emit SignatureCallerSet(caller, authorized);
}
/*//////////////////////////////////////////////////////////////////////////
CONSTANT FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IActionModule
function validate(
address token,
uint256 amount,
bytes calldata params
)
external
view
override(ActionModuleBase, IActionModule)
returns (bool isValid, string memory reason)
{
if (paused()) {
return (false, "Module paused");
}
DataTypes.AtumPaymentParams memory paymentParams;
(isValid, reason, paymentParams) = _validatePaymentParams(token, amount, params);
if (!isValid) {
return (false, reason);
}
if (!_hasSufficientBalance(token, amount)) {
return (false, "Insufficient balance");
}
if (_routeChangedWhileStaged(token, paymentParams)) {
return (false, "Route changed while funds are staged");
}
return (true, "");
}
/// @inheritdoc IAtumModule
function isPermitDigestInvalidated(bytes32 digest) external view returns (bool) {
return _invalidatedPermitDigests[digest];
}
/// @inheritdoc IActionModule
function estimateOutput(
address token,
uint256 amount,
bytes calldata params
)
external
view
override(ActionModuleBase, IActionModule)
returns (uint256 estimatedOutput, address outputToken)
{
if (paused()) {
return (0, token);
}
(bool valid,,) = _validatePaymentParams(token, amount, params);
if (!valid) {
return (0, token);
}
return (0, token);
}
/// @inheritdoc IActionModule
function moduleType() external pure override(ActionModuleBase, IActionModule) returns (string memory) {
return "ATUM_PAYMENT";
}
/// @inheritdoc IAtumModule
function encodeParams(DataTypes.AtumPaymentParams calldata params) external pure returns (bytes memory encoded) {
return abi.encode(params.destinationChain, params.destinationAccount, params.destinationAsset);
}
/// @inheritdoc IAtumModule
function decodeParams(bytes calldata encoded) public pure returns (DataTypes.AtumPaymentParams memory params) {
(params.destinationChain, params.destinationAccount, params.destinationAsset) =
abi.decode(encoded, (string, string, string));
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
function _validatePaymentParams(
address token,
uint256 amount,
bytes calldata params
)
private
view
returns (bool valid, string memory reason, DataTypes.AtumPaymentParams memory paymentParams)
{
if (token == address(0)) {
return (false, "Zero token", paymentParams);
}
if (amount == 0) {
return (false, "Zero payment amount", paymentParams);
}
(valid, reason, paymentParams) = _decodeAndValidatePaymentParams(params);
if (!valid) {
return (false, reason, paymentParams);
}
return (true, "", paymentParams);
}
function _decodeAndValidatePaymentParams(bytes calldata params)
private
view
returns (bool valid, string memory reason, DataTypes.AtumPaymentParams memory paymentParams)
{
if (params.length < 96) {
return (false, "Invalid params encoding", paymentParams);
}
try this.decodeParams(params) returns (DataTypes.AtumPaymentParams memory decoded) {
paymentParams = decoded;
} catch {
return (false, "Invalid params encoding", paymentParams);
}
if (bytes(paymentParams.destinationChain).length == 0) {
return (false, "Empty destination chain", paymentParams);
}
if (bytes(paymentParams.destinationAccount).length == 0) {
return (false, "Empty destination account", paymentParams);
}
if (bytes(paymentParams.destinationAsset).length == 0) {
return (false, "Empty destination asset", paymentParams);
}
if (!_hasChainPrefix(paymentParams.destinationAsset, paymentParams.destinationChain)) {
return (false, "Destination asset chain mismatch", paymentParams);
}
return (true, "", paymentParams);
}
/// @dev The L-04 guard, shared by `execute` and `validate` so a preview cannot report success
/// for a call the same block would reject. Both callers read this BEFORE any pull, so the
/// two see identical state and the mirror is exact rather than approximate.
function _routeChangedWhileStaged(
address token,
DataTypes.AtumPaymentParams memory paymentParams
)
private
view
returns (bool)
{
bytes32 staged = stagedRoute[token];
if (staged == bytes32(0)) return false;
return staged != keccak256(abi.encode(paymentParams)) && IERC20(token).balanceOf(address(this)) > 0;
}
function _pullExactToken(address token, uint256 amount) private {
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
// Certora I-06: the received side was checked, the SENDER side was not. A token that
// debits the sender more than it credits the recipient -- a sender-paid fee -- leaves
// PaymentRails down `amount + fee` while this function sees exactly `amount` arrive and
// reports success. The loss is real and silent, and PaymentRails' own accounting then
// understates it. Measuring both sides makes the module's "exact transfer" claim true in
// the direction it was not.
uint256 senderBalanceBefore = IERC20(token).balanceOf(msg.sender);
// Route through the base class helper so error paths fall through into the
// module's `_failedResult` / revert surface consistently (#11). The
// exact-balance check below still defends against fee-on-transfer tokens.
bool transferred = _safeTransferFrom(token, msg.sender, address(this), amount);
if (!transferred) {
revert Errors.AtumModule_UnsupportedTokenReceivedAmount(amount, 0);
}
uint256 received = IERC20(token).balanceOf(address(this)) - balanceBefore;
if (received != amount) {
revert Errors.AtumModule_UnsupportedTokenReceivedAmount(amount, received);
}
// Guarded: a token that mints to the sender inside `transferFrom`, or a self-transfer,
// could leave the sender's balance level or higher. Underflow would revert opaquely.
uint256 senderBalanceAfter = IERC20(token).balanceOf(msg.sender);
uint256 debited = senderBalanceBefore > senderBalanceAfter ? senderBalanceBefore - senderBalanceAfter : 0;
if (debited != amount) {
revert Errors.AtumModule_UnsupportedTokenDebitedAmount(amount, debited);
}
}
function _invalidateDigest(bytes32 digest) private {
if (digest == bytes32(0)) revert Errors.AtumModule_ZeroDigest();
_invalidatedPermitDigests[digest] = true;
emit PermitDigestInvalidated(digest);
}
function _returnTokenBalance(address token) private returns (uint256 amountReturned) {
if (token == address(0)) revert Errors.AtumModule_ZeroToken();
amountReturned = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(paymentRails, amountReturned);
// Recovery sweep clears the pending-amount tracker and revokes the
// Permit2 allowance so an already-signed-but-uninvalidated digest can't
// re-pull anything that arrives later (refund, mistaken transfer).
pendingAmount[token] = 0;
// The balance is now zero, so the L-04 guard would pass regardless; clearing keeps the
// recorded route from outliving the funds it described.
stagedRoute[token] = bytes32(0);
IERC20(token).forceApprove(permit2, 0);
emit Permit2ApprovalSet(token, permit2, 0);
emit TokenBalanceReturned(token, paymentRails, amountReturned);
}
function _hasChainPrefix(string memory asset, string memory chain) private pure returns (bool) {
bytes memory assetBytes = bytes(asset);
bytes memory chainBytes = bytes(chain);
if (chainBytes.length == 0 || assetBytes.length <= chainBytes.length || assetBytes[chainBytes.length] != "/") {
return false;
}
for (uint256 i; i < chainBytes.length; ++i) {
if (assetBytes[i] != chainBytes[i]) {
return false;
}
}
return true;
}
modifier onlyKeeper() {
if (msg.sender != keeper) revert Errors.AtumModule_NotKeeper(msg.sender, keeper);
_;
}
/// @dev Owner already has stronger powers (`pause`, `setKeeper`, `returnTokenBalance`);
/// digest invalidation belongs in the same trust tier so the owner doesn't have
/// to rotate the keeper just to cancel a stale digest.
modifier onlyKeeperOrOwner() {
if (msg.sender != keeper && msg.sender != owner()) {
revert Errors.AtumModule_NotKeeper(msg.sender, keeper);
}
_;
}
}
node_modules/@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
node_modules/@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
node_modules/@openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 `hash`
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
node_modules/@openzeppelin/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);
}
node_modules/@openzeppelin/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";
node_modules/@openzeppelin/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";
node_modules/@openzeppelin/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);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
node_modules/@openzeppelin/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);
}
}
}
node_modules/@openzeppelin/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));
}
}
node_modules/@openzeppelin/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/abstracts/ActionModuleBase.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.29;
import { IActionModule } from "../interfaces/IActionModule.sol";
import { DataTypes } from "../types/DataTypes.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title ActionModuleBase
/// @notice Abstract base contract providing common functionality for all action modules
/// @dev Inheriting contracts must implement execute(), validate(), estimateOutput(), and moduleType()
/// @dev Provides helper functions for common operations like balance checks and error handling
abstract contract ActionModuleBase is IActionModule {
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////////////////
INTERNAL HELPERS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Checks if the caller has sufficient balance of a token.
/// @param token The token address to check.
/// @param amount The required amount.
/// @return True if caller has sufficient balance, false otherwise.
function _hasSufficientBalance(address token, uint256 amount) internal view returns (bool) {
return IERC20(token).balanceOf(msg.sender) >= amount;
}
/// @notice Creates a failed ExecutionResult with a reason.
/// @param token The token being processed (used as outputToken in failure).
/// @param reason The failure reason message.
/// @return result ExecutionResult with success=false.
function _failedResult(
address token,
string memory reason
)
internal
pure
returns (DataTypes.ExecutionResult memory result)
{
return DataTypes.ExecutionResult({
success: false, amountOut: 0, outputToken: token, data: "", failureReason: reason
});
}
/// @notice Creates a successful ExecutionResult.
/// @param amountOut The amount of output token produced.
/// @param outputToken The address of the output token.
/// @param data Additional module-specific data.
/// @return result ExecutionResult with success=true.
function _successResult(
uint256 amountOut,
address outputToken,
bytes memory data
)
internal
pure
returns (DataTypes.ExecutionResult memory result)
{
return DataTypes.ExecutionResult({
success: true, amountOut: amountOut, outputToken: outputToken, data: data, failureReason: ""
});
}
/// @notice Validates that an address is not zero.
/// @param addr The address to validate.
/// @return True if address is not zero, false otherwise.
function _isValidAddress(address addr) internal pure returns (bool) {
return addr != address(0);
}
/// @notice Safely transfers tokens from caller to recipient.
/// @dev Uses OZ's trySafeTransferFrom to handle non-standard ERC20 tokens (e.g. USDT)
/// that do not return a bool on transferFrom.
/// @param token The token to transfer.
/// @param from The sender address.
/// @param to The recipient address.
/// @param amount The amount to transfer.
/// @return success True if transfer succeeded, false otherwise.
function _safeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
return IERC20(token).trySafeTransferFrom(from, to, amount);
}
/*//////////////////////////////////////////////////////////////////////////
REQUIRED INTERFACE IMPLEMENTATIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IActionModule
function execute(
address token,
uint256 amount,
bytes calldata params
)
external
virtual
returns (DataTypes.ExecutionResult memory result);
/// @inheritdoc IActionModule
function validate(
address token,
uint256 amount,
bytes calldata params
)
external
view
virtual
returns (bool isValid, string memory reason);
/// @inheritdoc IActionModule
function estimateOutput(
address token,
uint256 amount,
bytes calldata params
)
external
view
virtual
returns (uint256 estimatedOutput, address outputToken);
/// @inheritdoc IActionModule
function moduleType() external pure virtual returns (string memory);
}
src/interfaces/IActionModule.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.29;
import { DataTypes } from "../types/DataTypes.sol";
/// @title IActionModule
/// @notice Base interface for all action modules in the PaymentRails system.
/// @dev Modules are called by {PaymentRails} to execute pre-configured token actions (swap, bridge,
/// forward, etc.). The PaymentRails validates preconditions, approves tokens to the module, and calls
/// {execute}. Modules return {DataTypes.ExecutionResult} indicating success or failure.
///
/// All execution parameters are owner-configured in the static `params` — the permissionless
/// executor supplies nothing beyond `(token, amount)`. This design eliminates caller-controlled
/// attack surfaces at the architecture level.
///
/// Synchronous modules (ForwardModule, DexSwapModule) should remain stateless. Asynchronous modules
/// (CowSwapModule) may store order metadata for lifecycle tracking.
///
/// Notes:
/// - Modules receive exact-amount token approval from PaymentRails.
/// - {PaymentRails.previewExecution} calls {validate} for dry-run checks; the {PaymentRails.executeAction}
/// path does NOT call {validate} — only {execute}.
/// - Modules should return {DataTypes.ExecutionResult} with `success = false` instead of reverting
/// when possible.
interface IActionModule {
/// @notice Execute the configured action for a token.
/// @dev Called by PaymentRails after validation and token approval. The module must transfer tokens
/// from PaymentRails (msg.sender) using `transferFrom`.
///
/// Notes:
/// - `msg.sender` is always the PaymentRails contract.
/// - PaymentRails has approved this module to spend exactly `amount` of `token`.
/// - Prefer returning `ExecutionResult` with `success = false` over reverting.
///
/// @param token The input token address.
/// @param amount The amount of tokens to process.
/// @param params Module-specific parameters (ABI-encoded via the module's `encodeParams`).
/// @return result Execution result with success status and output details.
function execute(
address token,
uint256 amount,
bytes calldata params
)
external
returns (DataTypes.ExecutionResult memory result);
/// @notice Validate whether execution would succeed without modifying state.
/// @dev Called by {PaymentRails.previewExecution} for pre-flight checks. Modules should validate
/// their own parameters and preconditions but NOT token balance or enabled status (PaymentRails
/// handles those).
///
/// Notes:
/// - Must be a view function.
/// - Should mirror the validation logic in {execute}.
///
/// @param token The input token address.
/// @param amount The amount of tokens to process.
/// @param params Module-specific parameters.
/// @return isValid Whether execution would succeed.
/// @return reason Human-readable reason if invalid (empty string if valid).
function validate(
address token,
uint256 amount,
bytes calldata params
)
external
view
returns (bool isValid, string memory reason);
/// @notice Estimate the output amount for an action.
/// @dev Called by {PaymentRails.previewExecution} to show expected output. Estimates may differ from
/// actual execution due to price slippage, liquidity changes, or fees.
///
/// Notes:
/// - Should be a view or pure function.
/// - For constant-output modules (forward), output equals input.
///
/// @param token The input token address.
/// @param amount The amount of tokens to process.
/// @param params Module-specific parameters.
/// @return estimatedOutput Estimated output amount.
/// @return outputToken Address of the output token.
function estimateOutput(
address token,
uint256 amount,
bytes calldata params
)
external
view
returns (uint256 estimatedOutput, address outputToken);
/// @notice Returns a human-readable identifier for this module type (e.g., "FORWARD", "SWAP",
/// "BRIDGE").
/// @dev Used by {PaymentRails.configureToken} to validate the module. Must return a non-empty string.
///
/// @return Module type identifier string.
function moduleType() external pure returns (string memory);
}
src/interfaces/IAtumModule.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.29;
import { IActionModule } from "./IActionModule.sol";
import { DataTypes } from "../types/DataTypes.sol";
import { IERC1271 } from "@openzeppelin/contracts/interfaces/IERC1271.sol";
/// @title IAtumModule
/// @notice Minimal PaymentRails-bound Atum payment contract and ERC-1271 Permit2 owner.
/// @dev One module deployment is bound to one immutable PaymentRails. The PaymentRails funds the
/// contract through `execute`; the module emits the current available source
/// balance and destination details for an offchain keeper, and accepts raw Permit2
/// digests at its ERC-1271 surface. Those digests are validated as presented, against the
/// keeper alone, and only for callers in {isAuthorizedSignatureCaller} (Certora M-01).
///
/// The module does not compute request ids, source assets, fulfillment amounts,
/// or fees. The keeper derives source details from the log context and prepares
/// Atum payment requests from the module's available token balance offchain.
///
/// Failed deposits, refunds, and unused source balances remain in the module. The
/// keeper should watch {AtumIntentCreated}, Atum Escrow refund events, and module
/// token balances to initiate new payment requests from the available balance. For
/// funds that arrive outside `execute`, the keeper must call {syncAllowance} first:
/// the Permit2 allowance does not move with the balance, so an unsynced refund is
/// visible but not pullable.
interface IAtumModule is IActionModule, IERC1271 {
/// @notice Emitted when the module approves Permit2 for a source token.
event Permit2ApprovalSet(address indexed token, address indexed permit2, uint256 amount);
/// @notice Emitted when the owner rotates the keeper.
event KeeperSet(address indexed oldKeeper, address indexed newKeeper);
/// @notice Emitted when the keeper permanently rejects a Permit2 digest.
event PermitDigestInvalidated(bytes32 indexed digest);
/// @notice Emitted when a contract is authorized or de-authorized to call {isValidSignature}.
/// @dev Also emitted from the constructor for Permit2, so the full set is recoverable from
/// logs alone rather than only its later edits (the shape Certora I-03 asked for).
event SignatureCallerSet(address indexed caller, bool authorized);
/// @notice Emitted when the owner returns a module-held token balance to the immutable PaymentRails.
event TokenBalanceReturned(address indexed token, address indexed paymentRails, uint256 amount);
/// @notice Emitted when source funds are available for an Atum payment request.
/// @param token Source token available in the module.
/// @param availableSourceAmount Current module token balance the keeper should use for the payment request.
/// @param destinationChain CAIP-2 destination chain identifier.
/// @param destinationAccount Destination account identifier for the Atum payment request.
/// @param destinationAsset CAIP-19 destination asset identifier for the Atum payment request.
event AtumIntentCreated(
address indexed token,
uint256 availableSourceAmount,
string destinationChain,
string destinationAccount,
string destinationAsset
);
/// @notice Permit2 contract used by Atum Escrow on this source chain.
function permit2() external view returns (address);
/// @notice Immutable PaymentRails allowed to call `execute` and receive fail-safe recovery returns.
function paymentRails() external view returns (address);
/// @notice Keeper that authorises Permit2 digests and invalidates abandoned ones.
/// @dev Signs the Permit2 digest as Permit2 builds it. The module applies no wrap, so the
/// keeper's signing policy can still read the `PermitWitnessTransferFrom` struct it is
/// approving. Also the sole caller of {syncAllowance}.
function keeper() external view returns (address);
/// @notice Whether `caller` may receive an answer from `isValidSignature`.
/// @dev Certora M-01. Permit2 is authorized at construction; anything else is an explicit
/// owner decision. An unauthorized caller gets the ERC-1271 failure value, including
/// an `eth_call` with no `from` -- keeper tooling that simulates must set `from` to an
/// authorized address or it will read a false negative.
function isAuthorizedSignatureCaller(address caller) external view returns (bool);
/// @notice Owner-only authorization of a contract that may call {isValidSignature}.
/// @dev Certora M-01, and specifically the part of it that is NOT about Permit2. A keeper
/// signature is a bearer token at every ERC-1271 surface treating this module as a
/// signer, and the report is explicit that "the problem is not specific to Permit2".
/// Restricting the caller bounds a signature to applications that were deliberately
/// trusted.
///
/// IT DOES NOT PREVENT THE REPLAY BY ITSELF. Two modules sharing a keeper sit behind
/// the SAME Permit2, so both authorize it and both validate the same
/// `(hash, signature)` pair if asked. What prevents it is Atum Escrow: `depositId` is
/// `keccak256(depositor, depositSignature, nonce)` and must equal the `depositId` in a
/// reserve witness the RESERVER signed, so replaying against a second module needs a
/// fresh reserver signature naming it. Escrow checks that before calling Permit2.
///
/// Which is exactly why this allowlist matters: it makes Escrow the only application
/// that can reach this surface, so that argument covers every path rather than one.
///
/// Adding venues is an expected use of this function, not an exceptional one -- the
/// module is meant to be pointable at wherever funds need to go. What does NOT come
/// with a new venue is the replay protection above. Before authorizing one, establish
/// where in ITS flow this module's address is bound, the way Escrow binds it through
/// `depositId`; if nothing does, a keeper signature is replayable between every module
/// sharing that keeper through that venue, and distinct keepers is all that is left.
function setSignatureCaller(address caller, bool authorized) external;
/// @notice Destination route the currently-staged balance was pulled for, as
/// `keccak256(abi.encode(AtumPaymentParams))`. Zero when nothing is staged.
/// @dev Certora L-04. `execute` refuses a different route while the token balance is
/// non-zero, because the module holds one fungible balance per token and the keeper
/// sweeps all of it -- so funds staged for one destination would otherwise be payable to
/// the next one configured. `validate` applies the same guard, so a preview cannot
/// report success for a call `execute` would refuse. Cleared by `returnTokenBalance`.
///
/// SCOPE, STATED NARROWLY BECAUSE THE OVER-READING IS DANGEROUS. This closes exactly one
/// thing: a PaymentRails reconfiguration silently redirecting a balance the module is
/// holding and has not yet released. It is NOT settlement attribution, and it does not
/// make the module request-scoped. Specifically:
///
/// * It is cleared only by `returnTokenBalance`, never by settlement -- the module gets
/// no notification of a Permit2 pull. After Escrow drains the balance the record still
/// names the old route while the balance is zero, so the `balanceOf > 0` term lets the
/// next route stage over it.
/// * An Escrow refund arriving after that point merges into one fungible balance and is
/// swept under the NEW route, whether by `syncAllowance`, by a further `execute`, or
/// after a `returnTokenBalance` sweep and unpause. The module cannot tell refunded
/// funds apart from fresh ones.
/// * The guard is symmetric, so it also refuses the CORRECTIVE change: once a refund for
/// the old route sits under the new route's record, pointing PaymentRails back at the
/// old route fails too. The on-chain exit is pause + `returnTokenBalance`, which
/// returns funds to PaymentRails rather than paying them out.
///
/// Destination selection is a keeper property, not a module invariant. The module never
/// enforced where funds go: {AtumIntentCreated} is a signal, the keeper builds the
/// Permit2 request off-chain, and {syncAllowance} deliberately does not stage a route.
/// Attributing a refund to the request that produced it is keeper work, and the keeper
/// has the request ids and Escrow events needed to do it.
function stagedRoute(address token) external view returns (bytes32);
/// @notice Re-points the Permit2 allowance at the module's current balance.
/// @dev Keeper-only recovery path for funds that arrive outside `execute` -- Escrow refunds
/// and failed deposits. Without it those funds are unreachable whenever PaymentRails
/// has nothing left to pull, because the allowance was only ever refreshed by `execute`
/// (Certora L-02). Returns the new allowance, which equals the module's balance.
///
/// Callable only by the keeper and only while NOT paused, so it cannot contend with
/// `returnTokenBalance`, which is owner-only while paused and revokes the allowance to
/// zero. Does not change {stagedRoute}: it restores the allowance and does not stage a
/// new destination.
function syncAllowance(address token) external returns (uint256 available);
/// @notice Returns whether a Permit2 digest has been permanently invalidated.
/// @dev Keyed on the digest exactly as Permit2 presents it to `isValidSignature`.
function isPermitDigestInvalidated(bytes32 digest) external view returns (bool);
/// @notice Source amount per token that Permit2 is currently approved to pull.
/// @dev Set by `execute` and `syncAllowance` to the module's CURRENT balance, and reset to 0
/// by `returnTokenBalance` (which also revokes Permit2 to 0). It is NOT a cumulative
/// counter: it was one until Certora L-03/I-05, and a monotonic counter necessarily
/// disagrees with the balance in both directions -- too high after Permit2 pulls, too
/// low after a refund or a donation, the latter bricking the keeper's request against a
/// smaller allowance. The invariant now is
/// `pendingAmount(token) == IERC20(token).allowance(this, permit2) == balanceOf(this)`
/// as of the last `execute` or `syncAllowance`.
function pendingAmount(address token) external view returns (uint256);
/// @notice Owner-only keeper rotation.
function setKeeper(address newKeeper) external;
/// @notice Owner-only pause.
/// @dev While paused, `execute` is blocked, `validate` fails, ERC-1271 validation rejects
/// all signatures, {syncAllowance} is blocked, and return-to-PaymentRails recovery is
/// enabled.
function pause() external;
/// @notice Owner-only unpause after abandoned floating Permit2 digests have been invalidated or expired.
function unpause() external;
/// @notice Keeper- or owner-callable permanent invalidation of an abandoned Permit2 digest.
/// @dev Pass the Permit2 digest -- the same value Permit2 presents to `isValidSignature`.
function invalidateDigest(bytes32 digest) external;
/// @notice Keeper- or owner-callable permanent invalidation of multiple abandoned Permit2 digests.
/// @dev Permit2 digests, as for {invalidateDigest}.
function invalidateDigests(bytes32[] calldata digests) external;
/// @notice Owner-only paused recovery that returns the full current token balance to the immutable PaymentRails.
/// @dev Also resets {pendingAmount} and {stagedRoute} to zero and revokes the Permit2
/// allowance, so no recorded approval or destination outlives the funds it described.
function returnTokenBalance(address token) external returns (uint256 amountReturned);
/// @notice Owner-only paused recovery: returns full current balances for multiple tokens to the immutable
/// PaymentRails.
function returnTokenBalances(address[] calldata tokens) external;
/// @notice ABI-encodes Atum payment params for `PaymentRails.configureToken`.
function encodeParams(DataTypes.AtumPaymentParams calldata params) external pure returns (bytes memory encoded);
/// @notice Decodes Atum payment params from `PaymentRails.configureToken`.
function decodeParams(bytes calldata encoded) external pure returns (DataTypes.AtumPaymentParams memory params);
}
src/libraries/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.29;
/// @title Errors
/// @notice Centralized error definitions for the Receivables PaymentRails system
/// @dev All custom errors are defined here for gas efficiency and maintainability
library Errors {
/*//////////////////////////////////////////////////////////////////////////
PAYMENT RAILS ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when attempting to configure a token with zero address
error PaymentRails_ZeroTokenAddress();
/// @notice Thrown when clearing a token configuration but providing a non-zero module address
/// @dev When actionType is empty (clearing config), actionModule must be address(0)
error PaymentRails_NoneActionRequiresZeroModule();
/// @notice Thrown when configuring a token action with zero module address
/// @dev When actionType is set, actionModule must be a valid contract address
error PaymentRails_ZeroModuleAddress();
/// @notice Thrown when the action module contract doesn't implement required interface
error PaymentRails_InvalidModule();
/// @notice Thrown when module validation call fails
/// @dev This occurs when moduleType() call reverts or returns invalid data
error PaymentRails_ModuleValidationFailed();
/// @notice Thrown when attempting to execute action on a disabled token
/// @dev Token must have enabled=true in its configuration
error PaymentRails_TokenNotEnabled();
/// @notice Thrown when attempting to execute but no action is configured
/// @dev This occurs when actionType is empty string
error PaymentRails_NoActionConfigured();
/// @notice Thrown when execution amount is below the configured minimum balance threshold
/// @param amount Attempted execution amount
/// @param minBalance Required minimum balance
error PaymentRails_BelowMinimumBalance(uint256 amount, uint256 minBalance);
/// @notice Thrown when attempting to execute with zero amount
error PaymentRails_ZeroAmount();
/// @notice Thrown when paymentRails's token balance is insufficient for the requested amount
/// @param balance PaymentRails's current token balance
/// @param amount Requested execution amount
error PaymentRails_InsufficientBalance(uint256 balance, uint256 amount);
/// @notice Thrown when sweepNative() is called with no native balance to sweep.
error PaymentRails_ZeroNativeBalance();
/// @notice Thrown when sweeping native value to the zero address.
error PaymentRails_ZeroRecipient();
/// @notice Thrown when the sweep recipient refused the native value.
/// @param recipient The address that refused the value.
error PaymentRails_NativeTransferFailed(address recipient);
/*//////////////////////////////////////////////////////////////////////////
DEX SWAP MODULE ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the router address is the zero address in the constructor.
error DexSwapModule_ZeroRouter();
/// @notice Thrown when the router address has no deployed code in the constructor.
/// @param router The EOA address that was rejected.
error DexSwapModule_RouterNotContract(address router);
/// @notice Thrown when the router has code but does not expose a Uniswap V3 `factory()`.
/// @param router The address that failed the Uniswap router probe.
error DexSwapModule_RouterNotUniswap(address router);
/// @notice Thrown when actual swap output is below the oracle-computed floor.
/// @param amountOut Actual output from the swap.
/// @param oracleFloor Oracle-computed minimum after applying `maxSlippageBps`.
error DexSwapModule_InsufficientOutput(uint256 amountOut, uint256 oracleFloor);
/*//////////////////////////////////////////////////////////////////////////
OWNERSHIP ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when renounceOwnership() is called on PaymentRails.
/// @dev Ownership renunciation is permanently disabled to prevent locking the contract.
error PaymentRails_OwnershipCannotBeRenounced();
/*//////////////////////////////////////////////////////////////////////////
COWSWAP MODULE ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the CowSwap GPv2Settlement address is the zero address
error CowSwapModule_ZeroCowSettlement();
/// @notice Thrown when the PaymentRails address is the zero address in the constructor
error CowSwapModule_ZeroPaymentRails();
/// @notice Thrown when attempting to act on an orderId that was never created
/// @param orderId The unknown order digest
error CowSwapModule_UnknownOrder(bytes32 orderId);
/// @notice Thrown when cancelOrder is called on an order that is already cancelled
/// @param orderId The order digest
error CowSwapModule_OrderAlreadyCancelled(bytes32 orderId);
/// @notice Thrown when cancelOrder is called on an order already filled by a CowSwap solver
/// @dev Verified via GPv2Settlement.filledAmount(orderUid) >= meta.sellAmount
/// @param orderId The order digest
error CowSwapModule_OrderAlreadyFilled(bytes32 orderId);
/// @notice Thrown when renounceOwnership() is called on CowSwapModule.
/// @dev Ownership renunciation is permanently disabled because it would lock
/// all pending orders' sell tokens with no way to cancel them.
error CowSwapModule_OwnershipCannotBeRenounced();
/*//////////////////////////////////////////////////////////////////////////
PAYMENT RAILS FACTORY ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when attempting to deploy a PaymentRails with owner set to the zero address.
error PaymentRailsFactory_ZeroOwner();
/// @notice Thrown when renouncing ownership of the factory is attempted.
error PaymentRailsFactory_OwnershipCannotBeRenounced();
/*//////////////////////////////////////////////////////////////////////////
COWSWAP MODULE FACTORY ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the GPv2Settlement address is the zero address in the factory constructor.
error CowSwapModuleFactory_ZeroCowSettlement();
/// @notice Thrown when the GPv2Settlement address has no deployed code in the factory constructor.
/// @param settlement The EOA address that was rejected.
error CowSwapModuleFactory_SettlementNotContract(address settlement);
/// @notice Thrown when a non-zero sequencer uptime feed has no deployed code in the factory
/// constructor. `address(0)` stays valid — it is the L1 profile.
/// @param sequencerUptimeFeed The EOA address that was rejected.
error CowSwapModuleFactory_SequencerFeedNotContract(address sequencerUptimeFeed);
/// @notice Thrown when the sequencer grace period is zero or implausibly large on the L2
/// profile. Zero would reduce every deployed module's grace check to `uint256 < 0`, which is
/// never true, silently disabling the guard fleet-wide.
/// @param sequencerGracePeriod The value that was rejected.
error CowSwapModuleFactory_InvalidGracePeriod(uint256 sequencerGracePeriod);
/// @notice Thrown when a non-zero sequencer grace period is paired with no uptime feed. The
/// grace period is measured from the feed's `startedAt`, so without a feed it is dead config
/// that still reads as protection through `sequencerGracePeriod()`.
/// @param sequencerGracePeriod The value that was rejected.
error CowSwapModuleFactory_GracePeriodWithoutFeed(uint256 sequencerGracePeriod);
/// @notice Thrown when attempting to deploy a CowSwapModule with owner set to the zero address.
error CowSwapModuleFactory_ZeroOwner();
/// @notice Thrown when attempting to deploy a CowSwapModule with PaymentRails set to the zero address.
error CowSwapModuleFactory_ZeroPaymentRails();
/// @notice Thrown when the target PaymentRails address has no deployed code.
/// @param paymentRails The address that was rejected.
error CowSwapModuleFactory_PaymentRailsNotContract(address paymentRails);
/// @notice Thrown when renouncing ownership of the factory is attempted.
error CowSwapModuleFactory_OwnershipCannotBeRenounced();
/*//////////////////////////////////////////////////////////////////////////
CCTP BRIDGE MODULE ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the TokenMessengerV2 address is the zero address in the constructor.
error CCTPBridgeModule_ZeroTokenMessenger();
/// @notice Thrown when the USDC address is the zero address in the constructor.
error CCTPBridgeModule_ZeroUSDC();
/*//////////////////////////////////////////////////////////////////////////
ATUM PAYMENT MODULE ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the Permit2 address is the zero address in the constructor.
error AtumModule_ZeroPermit2();
/// @notice Thrown when the Permit2 address supplied to an AtumModule has no code.
/// @dev The module used to reject an EOA only as a side effect of calling DOMAIN_SEPARATOR()
/// on it in the constructor. That call was dead state (it was stored and never read) and
/// has been removed, so the check it accidentally provided is now explicit. The factory
/// has an equivalent check of its own; this one covers modules constructed directly.
error AtumModule_Permit2NotContract(address permit2);
/// @notice Thrown when `renounceOwnership` is called on an AtumModule.
/// @dev The module must always retain an owner: keeper rotation, pause/unpause, the
/// `onlyOwner whenPaused` recovery sweep and `setSignatureCaller` all depend on one
/// existing. Renouncing would also freeze the ERC-1271 caller set permanently.
error AtumModule_RenounceOwnershipDisabled();
/// @notice Thrown when a transfer debited the sender by something other than `amount`.
/// @dev Certora I-06. The received amount was already checked; this covers the other side,
/// where a sender-paid fee leaves PaymentRails down more than the module gained.
error AtumModule_UnsupportedTokenDebitedAmount(uint256 expected, uint256 debited);
/// @notice Thrown when the immutable PaymentRails address is the zero address in the constructor.
error AtumModule_ZeroPaymentRails();
/// @notice Thrown when a caller is not the immutable PaymentRails.
/// @param caller Unauthorized caller.
/// @param paymentRails Immutable PaymentRails authorized to call.
error AtumModule_NotPaymentRails(address caller, address paymentRails);
/// @notice Thrown when the keeper address is the zero address.
error AtumModule_ZeroKeeper();
/// @notice Thrown when a caller is not the current keeper.
/// @param caller Unauthorized caller.
/// @param keeper Current keeper authorized to call.
error AtumModule_NotKeeper(address caller, address keeper);
/// @notice Thrown when authorizing the zero address as an ERC-1271 caller.
/// @dev Certora M-01. `address(0)` is what an `eth_call` with no `from` presents as, so
/// authorizing it would hand the magic value to every off-chain probe.
error AtumModule_ZeroSignatureCaller();
/// @notice Thrown when a token address is zero.
error AtumModule_ZeroToken();
/// @notice Thrown when attempting to invalidate the zero digest.
error AtumModule_ZeroDigest();
/// @notice Thrown when the module receives less or more than the exact amount requested.
/// @param expected Amount requested from the PaymentRails.
/// @param actual Balance delta observed by the module.
error AtumModule_UnsupportedTokenReceivedAmount(uint256 expected, uint256 actual);
/*//////////////////////////////////////////////////////////////////////////
ATUM PAYMENT MODULE FACTORY ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the factory is constructed with a zero Permit2 address.
error AtumModuleFactory_ZeroPermit2();
/// @notice Thrown when the factory is constructed with a Permit2 address that has no code.
/// @param permit2 The address supplied as Permit2.
error AtumModuleFactory_Permit2NotContract(address permit2);
/// @notice Thrown when a module is created with a zero owner address.
error AtumModuleFactory_ZeroOwner();
/// @notice Thrown when a module is created with a zero PaymentRails address.
error AtumModuleFactory_ZeroPaymentRails();
/// @notice Thrown when a module is created with a zero keeper address.
error AtumModuleFactory_ZeroKeeper();
/// @notice Thrown when renouncing ownership of the factory is attempted.
error AtumModuleFactory_OwnershipCannotBeRenounced();
/// @notice Thrown when the supplied PaymentRails address has no code.
/// @dev Creation is owner-gated, so this is a wiring check on what the owner passes, not an
/// authorization: an undelegated EOA or a typo fails by name instead of yielding a module
/// that nothing can ever call. An EIP-7702-delegated EOA has code and passes.
error AtumModuleFactory_PaymentRailsNotContract(address paymentRails);
}
src/types/DataTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.29;
/// @title DataTypes
/// @notice Centralized type definitions for the Receivables PaymentRails system.
library DataTypes {
/*//////////////////////////////////////////////////////////////////////////
PAYMENT RAILS TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Configuration for a token's action in the PaymentRails.
struct TokenConfig {
string actionType;
address actionModule;
bool enabled;
uint256 minBalance;
bytes moduleParams;
}
/*//////////////////////////////////////////////////////////////////////////
ACTION MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Result of an action execution, returned by all module execute() functions.
struct ExecutionResult {
bool success;
uint256 amountOut;
address outputToken;
bytes data;
string failureReason;
}
/*//////////////////////////////////////////////////////////////////////////
FORWARD MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Forward configuration parameters.
struct ForwardParams {
address recipient;
uint256 minAmount;
}
/*//////////////////////////////////////////////////////////////////////////
DEX SWAP MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Static configuration for DEX swaps (stored in PaymentRails.moduleParams).
/// @dev Oracle feeds are mandatory. Both feeds MUST use the same quote currency (e.g., both
/// TOKEN/USD) — mixing produces a silently incorrect oracle floor.
/// @dev `maxSlippageBps` is the value-protection lever; size `maxAmount` to the pool's actual
/// liquidity (not its fee tier), and never loosen slippage to force size through a thin pool.
struct DexSwapParams {
/// @dev The required output token; must differ from the input token.
address targetToken;
/// @dev Uniswap V3 pool fee tier in hundredths of a bip (3000 = 0.30% = 30 bps).
uint24 fee;
/// @dev Max slippage vs the Chainlink oracle, in bps. Must exceed `fee`/100 + price impact.
uint16 maxSlippageBps;
/// @dev Chainlink feed for the sell token. Mandatory; same quote currency as buy feed.
address sellTokenPriceFeed;
/// @dev Chainlink feed for the buy token. Mandatory; same quote currency as sell feed.
address buyTokenPriceFeed;
/// @dev Max age of a Chainlink answer before it is rejected as stale, in seconds.
uint256 maxStaleness;
/// @dev Seconds added to `block.timestamp` to form the swap deadline. Must be non-zero.
uint256 swapDeadlineSeconds;
/// @dev Per-call sandwich-profitability ceiling (token decimals); 0 = no limit. Keeper passes
/// min(balance, maxAmount). This caps PER-SWAP profitability, NOT aggregate MEV — the
/// aggregate value bound is maxSlippageBps (the oracle floor). Size below
/// ~feeTier * IN-RANGE (active-tick) liquidity — NOT pool TVL — so each individual swap
/// is unprofitable to sandwich; re-evaluate if liquidity migrates to another fee tier.
/// Stable / low-fee pools: a tight maxSlippageBps alone keeps extractable slack below gas.
uint256 maxAmount;
}
/*//////////////////////////////////////////////////////////////////////////
COWSWAP MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Parameters for configuring a CowSwap order-book swap.
/// @dev Oracle feeds are mandatory and MUST share the same quote currency (see DexSwapParams).
/// buyAmount is computed on-chain: `oracleExpected * (10000 - maxSlippageBps) / 10000`.
struct CowSwapParams {
address targetToken;
uint16 maxSlippageBps;
address sellTokenPriceFeed;
address buyTokenPriceFeed;
uint256 maxStaleness;
uint32 validityDuration;
bytes32 appData;
}
/// @notice On-chain metadata stored per CowSwap order, keyed by orderId (GPv2Order digest).
/// @dev validTo stored directly to avoid uint32 recomputation overflow.
/// SETTLED state is derived live from GPv2Settlement.filledAmount().
struct CowOrderMetadata {
address paymentRails;
address sellToken;
address buyToken;
uint256 sellAmount;
uint32 validTo;
bool cancelled;
}
/*//////////////////////////////////////////////////////////////////////////
CCTP BRIDGE MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Routing parameters for a CCTP bridge action, stored in PaymentRails's moduleParams.
/// @dev destinationDomain is CCTP domain ID (NOT EVM chain ID). maxFeeBps is used to compute
/// the maxFee passed to Circle's TokenMessengerV2 at execution time:
/// `maxFee = amount * maxFeeBps / 10_000`. This replaces a static maxFee to match Circle's
/// percentage-based fee model and scale correctly with any bridge amount.
struct CCTPBridgeParams {
/// @dev CCTP domain ID of the destination chain (NOT an EVM chain ID).
uint32 destinationDomain;
/// @dev Recipient address on the destination chain, left-padded to bytes32.
bytes32 mintRecipient;
/// @dev Address allowed to call `receiveMessage` on the destination. `bytes32(0)` = anyone.
bytes32 destinationCaller;
/// @dev Fee ceiling in basis points. `maxFee = amount * maxFeeBps / 10_000`.
uint16 maxFeeBps;
/// @dev 1000 for fast (confirmed) or 2000 for standard (finalized) finality.
uint32 minFinalityThreshold;
/// @dev Arbitrary bytes for destination-chain post-mint automation. Empty = no hook.
bytes hookData;
}
/*//////////////////////////////////////////////////////////////////////////
ATUM PAYMENT MODULE TYPES
//////////////////////////////////////////////////////////////////////////*/
/// @notice Parameters stored in PaymentRails's moduleParams for an Atum payment action.
/// @dev These fields are emitted for the off-chain Atum keeper. The module does
/// not interpret Atum Escrow routes or witness formats.
/// @param destinationChain CAIP-2 destination chain identifier, e.g. `eip155:8453`.
/// @param destinationAccount Destination account identifier for the Atum payment request.
/// @param destinationAsset CAIP-19 destination asset identifier for the Atum payment request.
struct AtumPaymentParams {
string destinationChain;
string destinationAccount;
string destinationAsset;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"forge-std/=node_modules/forge-std/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.