Verified contractExactMIT
SingleTokenEscrow
Address0x8e5ffbd9009bef84f8aeddd114defa8c55074d29
- Balance
0 ETH
- Transactions
35
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 300 runs
- EVM version
- prague
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,326,600
- Creation transaction
- 0x85c6efc4ee…0102c474e9
12 files
- apps/Solidus/singleTokenEscrow/contracts/SingleTokenEscrow.solmain16.69 KB
- apps/Solidus/singleTokenEscrow/contracts/interfaces/ISingleTokenEscrow.sol4.64 KB
- libs/ERC20/interfaces/IERC20.sol4.8 KB
- libs/FundRecovery/FundRecoveryCore.sol3.11 KB
- libs/Ownable/Ownable.sol1.04 KB
- libs/Ownable/OwnableCore.sol4.32 KB
- libs/Ownable/OwnableView.sol980 B
- libs/Pausable/Pausable.sol761 B
- libs/Pausable/PausableCore.sol3.6 KB
- libs/Pausable/PausableView.sol1.07 KB
- libs/Pausable/interfaces/IPausable.sol877 B
- libs/ReentrancyGuard/ReentrancyGuardCore.sol1.81 KB
apps/Solidus/singleTokenEscrow/contracts/SingleTokenEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IERC20} from 'libs/ERC20/interfaces/IERC20.sol';
import {FundRecoveryCore} from 'libs/FundRecovery/FundRecoveryCore.sol';
import {Ownable} from 'libs/Ownable/Ownable.sol';
import {Pausable} from 'libs/Pausable/Pausable.sol';
import {ReentrancyGuardCore} from 'libs/ReentrancyGuard/ReentrancyGuardCore.sol';
import {ISingleTokenEscrow} from './interfaces/ISingleTokenEscrow.sol';
/**
* @custom:security-contact [email protected]
* @title SingleTokenEscrow
* @author SYGNUM AG - Blockchain team 3301
* @notice A non-upgradeable, owner-controlled escrow that holds a single ERC20 token and settles
* deals between a buyer and a seller
* @dev The owner is the only caller allowed to create, fund, release, cancel or sweep deals; buyer
* and seller never call this contract directly. Ownership is one-step (accepted risk: a
* mistyped transfer or a transfer to the zero address orphans the book permanently).
*/
contract SingleTokenEscrow is
ISingleTokenEscrow,
Ownable,
Pausable,
ReentrancyGuardCore,
FundRecoveryCore
{
/* ======== CUSTOM ERRORS ======== */
error AmountCannotBeZero();
error ReferenceCannotBeEmpty();
error SameBuyerAndSeller();
error InvalidParty(address party);
error DealAlreadyExists(bytes32 dealId);
error InvalidDealStatus(bytes32 dealId, Status status);
error InsufficientAvailableBalance(
uint256 availableBalance,
uint256 required
);
error TokenTransferFailed();
/* ======== EVENTS ======== */
event DealCreated(
bytes32 indexed dealId,
address indexed buyer,
address indexed seller,
uint256 shoppingAmount,
string shoppingReferenceId
);
event DealFunded(bytes32 indexed dealId, uint256 shoppingAmount);
event DealReleased(
bytes32 indexed dealId,
address indexed seller,
uint256 shoppingAmount
);
event DealCancelled(
bytes32 indexed dealId,
address indexed buyer,
uint256 refundedAmount
);
/* ======== STATE VARIABLES ======== */
IERC20 public immutable override token;
uint256 private _totalLocked;
mapping(bytes32 dealId => Deal deal) private _deals;
/* ======== CONSTRUCTOR ======== */
/**
* @notice Deploys the escrow for a single ERC20 token, owned by `_owner`
* @dev Reverts only if `_owner` or `_token` is the zero address. `_token` is deliberately NOT
* interface-checked: ERC20 has no ERC165 interface id, `name`/`symbol`/`decimals` are
* optional, and widely held tokens are non-conforming (USDT's `transfer` returns no
* data), so any constructor-time probe rejects good tokens while a hostile contract can
* answer every view call and still refuse to transfer. Deploying one immutable instance
* per token makes the owner the curator, exactly as Uniswap, Aave and Morpho leave token
* validation to whoever creates the pool or market. A wrong `_token` yields a dead
* instance holding nothing, so the funds at risk are zero; the guarantee that matters is
* enforced where it is provable, on the `token.transfer` results in `releaseDeal` and
* `cancelDeal`.
* @param _owner The address to be granted ownership of this instance
* @param _token The ERC20 token this instance holds and settles in
*/
constructor(address _owner, address _token) {
if (_owner == address(0)) revert ZeroAddress();
if (_token == address(0)) revert ZeroAddress();
token = IERC20(_token);
_ownable_init(_owner);
}
/* ======== EXTERNAL/PUBLIC VIEW/PURE FUNCTIONS ======== */
/**
* @notice Returns the total amount currently locked across all funded deals
* @dev This is an accounting figure only. `sweep` does not adjust it and is not bounded by it,
* so after a sweep that moves locked funds this value can exceed the contract's balance.
* @return The total locked amount
*/
function totalLocked() external view returns (uint256) {
return _totalLocked;
}
/**
* @notice Returns the deal stored under a deal id
* @dev An unknown id returns a zeroed record with `statusName` "None"; it does not revert. The
* status is exposed only as its label so the deal reads plainly on an explorer; the label
* is built here and never stored.
* @param _dealId The deal id to look up
* @return The deal record with its readable status label
*/
function getDeal(
bytes32 _dealId
) external view returns (DealDetails memory) {
Deal storage _deal = _deals[_dealId];
return
DealDetails({
buyer: _deal.buyer,
statusName: _statusName(_deal.status),
seller: _deal.seller,
shoppingAmount: _deal.shoppingAmount,
shoppingReferenceId: _deal.shoppingReferenceId
});
}
/**
* @notice Computes the deterministic deal id for a given deal
* @dev `_shoppingReferenceId` MUST be unique per order. The four inputs always map to the same
* id, so a repeated reference collapses onto an existing deal and `createDeal` reverts with
* `DealAlreadyExists` - permanently, because a deal's status never regresses. That
* determinism is deliberate: a `createDeal` retried after a dropped transaction cannot mint a
* second deal for the same order.
* @param _buyer The buyer address
* @param _seller The seller address
* @param _shoppingAmount The amount the buyer is escrowing
* @param _shoppingReferenceId The off-chain reference id for the deal, unique per order
* @return The computed deal id
*/
function computeDealId(
address _buyer,
address _seller,
uint256 _shoppingAmount,
string calldata _shoppingReferenceId
) public pure returns (bytes32) {
return
keccak256(
abi.encode(
_buyer,
_seller,
_shoppingAmount,
_shoppingReferenceId
)
);
}
/* ======== EXTERNAL/PUBLIC STATE-CHANGING FUNCTIONS ======== */
/**
* @notice Creates a new deal and returns its deal id
* @dev Only callable by the owner. Reverts if the amount is zero, the reference is empty, the
* buyer and seller are the same address, either party is invalid, or a deal already
* exists under the computed id. See `computeDealId` for the per-order uniqueness
* requirement on `_shoppingReferenceId`.
* @param _buyer The buyer address
* @param _seller The seller address
* @param _shoppingAmount The amount the buyer is escrowing
* @param _shoppingReferenceId The off-chain reference id for the deal, unique per order
* @return _dealId The created deal's deal id
*/
function createDeal(
address _buyer,
address _seller,
uint256 _shoppingAmount,
string calldata _shoppingReferenceId
) external onlyOwner whenNotPaused returns (bytes32 _dealId) {
if (_shoppingAmount == 0) revert AmountCannotBeZero();
if (bytes(_shoppingReferenceId).length == 0) {
revert ReferenceCannotBeEmpty();
}
if (_buyer == _seller) revert SameBuyerAndSeller();
_validateParty(_buyer);
_validateParty(_seller);
_dealId = computeDealId(
_buyer,
_seller,
_shoppingAmount,
_shoppingReferenceId
);
if (_deals[_dealId].status != Status.None) {
revert DealAlreadyExists(_dealId);
}
_deals[_dealId] = Deal({
buyer: _buyer,
status: Status.Created,
seller: _seller,
shoppingAmount: _shoppingAmount,
shoppingReferenceId: _shoppingReferenceId
});
emit DealCreated(
_dealId,
_buyer,
_seller,
_shoppingAmount,
_shoppingReferenceId
);
}
/**
* @notice Confirms that a created deal has been funded and locks its amount
* @dev Only callable by the owner. Reverts if the deal is not in the `Created` status or the
* contract's available balance (balance minus already-locked amounts) is below the deal's
* amount. `nonReentrant` is required although this function makes no state-changing
* external call: while `releaseDeal` or `cancelDeal` is inside `token.transfer`, `_totalLocked`
* has already been reduced but the balance has not, so a re-entrant call here would read
* an inflated available balance and lock a deal against money that is leaving.
*
* ACCEPTED RISK - the available-balance check below proves only that this contract holds
* enough unlocked balance; it does NOT prove that this deal's buyer is the party who paid
* it. The backend MUST match the buyer's `Transfer` event to `_dealId` before calling,
* otherwise one buyer's payment can be used to fund a different buyer's deal and the
* first buyer's own confirmation will then fail. Recorded in the accepted-risk table; see
* the app README Security Considerations.
* @param _dealId The deal id of the deal to confirm
*/
function confirmFunding(
bytes32 _dealId
) external onlyOwner whenNotPaused nonReentrant {
Deal storage _deal = _deals[_dealId];
if (_deal.status != Status.Created) {
revert InvalidDealStatus(_dealId, _deal.status);
}
uint256 _balance = token.balanceOf(address(this));
// Clamp rather than underflow: after an issuer `forceTransfer`/`burnFrom`, or a `sweep`
// that moved locked funds, the balance can sit below `_totalLocked`, and zero available
// balance is the correct reading in that state.
uint256 _available = _balance > _totalLocked
? _balance - _totalLocked
: 0;
if (_available < _deal.shoppingAmount) {
revert InsufficientAvailableBalance(
_available,
_deal.shoppingAmount
);
}
_deal.status = Status.Funded;
_totalLocked += _deal.shoppingAmount;
emit DealFunded(_dealId, _deal.shoppingAmount);
}
/**
* @notice Releases a funded deal's locked amount to the seller
* @dev Only callable by the owner. Reverts if the deal is not in the `Funded` status.
* @param _dealId The deal id of the deal to release
*/
function releaseDeal(
bytes32 _dealId
) external onlyOwner whenNotPaused nonReentrant {
Deal storage _deal = _deals[_dealId];
if (_deal.status != Status.Funded) {
revert InvalidDealStatus(_dealId, _deal.status);
}
_deal.status = Status.Released;
_totalLocked -= _deal.shoppingAmount;
emit DealReleased(_dealId, _deal.seller, _deal.shoppingAmount);
if (!token.transfer(_deal.seller, _deal.shoppingAmount)) {
revert TokenTransferFailed();
}
}
/**
* @notice Cancels a created or funded deal, refunding the buyer if it was funded
* @dev Only callable by the owner. Reverts if the deal is not in the `Created` or `Funded`
* status.
* @param _dealId The deal id of the deal to cancel
*/
function cancelDeal(
bytes32 _dealId
) external onlyOwner whenNotPaused nonReentrant {
Deal storage _deal = _deals[_dealId];
Status _status = _deal.status;
if (_status != Status.Created && _status != Status.Funded) {
revert InvalidDealStatus(_dealId, _status);
}
_deal.status = Status.Cancelled;
if (_status == Status.Created) {
emit DealCancelled(_dealId, _deal.buyer, 0);
return;
}
_totalLocked -= _deal.shoppingAmount;
emit DealCancelled(_dealId, _deal.buyer, _deal.shoppingAmount);
if (!token.transfer(_deal.buyer, _deal.shoppingAmount)) {
revert TokenTransferFailed();
}
}
/**
* @notice Moves any token balance, or native ETH, held by this contract to a recipient
* @dev Only callable by the owner. DANGER - this function is deliberately unguarded: it has no
* `_totalLocked` bound, so it can move funds locked against funded deals, and it has no
* pause guard, so it works while the contract is paused. It is the only escape hatch of a
* non-upgradeable contract: a bug in `releaseDeal`/`cancelDeal`, or a deal that can never be
* cancelled because the buyer's CHFD holder record is frozen, would otherwise strand the
* money permanently.
*
* After a sweep that moves locked funds, `_totalLocked` exceeds the balance, so `releaseDeal`
* and `cancelDeal` on funded deals revert until the shortfall is pushed back and
* `confirmFunding` reads zero available balance. This is the same end state as an issuer
* `forceTransfer`/`burnFrom` and is recovered the same way.
*
* `_token == address(0)` moves native ETH. This contract declares no `receive()` or
* `fallback()`, so it can only hold ETH that was force-fed (`selfdestruct`, or a
* pre-funded CREATE2 address).
*
* For the escrowed token the recipient is additionally constrained by the issuer, not by
* this contract: a CHFD transfer to an address that is not a registered, active holder
* with limit headroom reverts inside the token, so the owner cannot move CHFD to an
* arbitrary address. Foreign tokens and native ETH carry no such constraint.
* @param _token The token to move, or the zero address for native ETH
* @param _to The recipient address
* @param _amount The amount to move
*/
function sweep(
address _token,
address payable _to,
uint256 _amount
) external onlyOwner nonReentrant {
if (_to == address(0)) revert ZeroAddress();
if (_amount == 0) revert AmountCannotBeZero();
_recoverFunds(_token, _to, _amount);
}
/**
* @notice Pauses the contract, blocking createDeal, confirmFunding, releaseDeal and cancelDeal
* @dev Only callable by the owner. `Pausable` supplies an `external virtual pause`/`unpause`
* pair with no authorization; this override replaces both, so the deployed contract has
* exactly one `pause()` selector and it is `onlyOwner`. The base bodies are unreachable -
* nothing calls `super.pause()` and Solidity gives no base implementation its own
* selector. The `override` keyword must stay: removing these two functions would compile
* and re-expose the unguarded pair, which is what
* `EscrowPauseAndOwnership.t.sol::testRevertsWhenPauseCalledByNonOwner` pins. A contract
* copying this one MUST keep both overrides or inherit `PausableView` instead.
* `sweep` is deliberately not paused.
*/
function pause() external override onlyOwner {
_pause();
}
/**
* @notice Unpauses the contract, re-enabling createDeal, confirmFunding, releaseDeal and cancelDeal
* @dev Only callable by the owner. See `pause` for why the `override` on both must stay.
*/
function unpause() external override onlyOwner {
_unpause();
}
/* ======== PRIVATE VIEW/PURE FUNCTIONS ======== */
/**
* @notice Returns the readable label of a deal status
* @param _status The status to label
* @return The status label
*/
function _statusName(Status _status) private pure returns (string memory) {
if (_status == Status.Created) return 'Created';
if (_status == Status.Funded) return 'Funded';
if (_status == Status.Released) return 'Released';
if (_status == Status.Cancelled) return 'Cancelled';
return 'None';
}
/**
* @notice Validates that a party is neither the zero address, the owner nor this contract
* @dev Reverts with InvalidParty if the check fails.
* @param _party The address to validate
*/
function _validateParty(address _party) private view {
if (
_party == address(0) || _party == owner() || _party == address(this)
) {
revert InvalidParty(_party);
}
}
}
apps/Solidus/singleTokenEscrow/contracts/interfaces/ISingleTokenEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IERC20} from 'libs/ERC20/interfaces/IERC20.sol';
/**
* @custom:security-contact [email protected]
* @title ISingleTokenEscrow
* @notice Interface for SingleTokenEscrow contract
* @dev Declares the enum, struct and function signatures shared by SingleTokenEscrow. Errors and
* events are declared in the implementing contract, not here.
*/
interface ISingleTokenEscrow {
/* ======== TYPES ======== */
enum Status {
None,
Created,
Funded,
Released,
Cancelled
}
struct Deal {
address buyer;
Status status;
address seller;
uint256 shoppingAmount;
string shoppingReferenceId;
}
/// @dev View-only shape returned by `getDeal`: the stored `Deal` with its status as a label.
struct DealDetails {
address buyer;
string statusName;
address seller;
uint256 shoppingAmount;
string shoppingReferenceId;
}
/* ======== EXTERNAL/PUBLIC VIEW FUNCTIONS ======== */
/**
* @notice Returns the ERC20 token this escrow instance holds and settles in
* @return The escrowed token
*/
function token() external view returns (IERC20);
/**
* @notice Returns the total amount currently locked across all funded deals
* @dev An accounting figure only; `sweep` neither adjusts it nor is bounded by it.
* @return The total locked amount
*/
function totalLocked() external view returns (uint256);
/**
* @notice Returns the deal stored under a deal id
* @dev An unknown id returns a zeroed record with `statusName` "None"; it does not revert.
* @param _dealId The deal id to look up
* @return The deal record with its readable status label
*/
function getDeal(
bytes32 _dealId
) external view returns (DealDetails memory);
/**
* @notice Computes the deterministic deal id for a given deal
* @dev `_shoppingReferenceId` MUST be unique per order; a repeated reference collapses onto an
* existing deal and `createDeal` then reverts with `DealAlreadyExists`.
* @param _buyer The buyer address
* @param _seller The seller address
* @param _shoppingAmount The amount the buyer is escrowing
* @param _shoppingReferenceId The off-chain reference id for the deal, unique per order
* @return The computed deal id
*/
function computeDealId(
address _buyer,
address _seller,
uint256 _shoppingAmount,
string calldata _shoppingReferenceId
) external pure returns (bytes32);
/* ======== EXTERNAL/PUBLIC STATE-CHANGING FUNCTIONS ======== */
/**
* @notice Creates a new deal and returns its deal id
* @param _buyer The buyer address
* @param _seller The seller address
* @param _shoppingAmount The amount the buyer is escrowing
* @param _shoppingReferenceId The off-chain reference id for the deal, unique per order
* @return The created deal's deal id
*/
function createDeal(
address _buyer,
address _seller,
uint256 _shoppingAmount,
string calldata _shoppingReferenceId
) external returns (bytes32);
/**
* @notice Confirms that a created deal has been funded and locks its amount
* @dev Funding is attributed off-chain; the caller must match the buyer's transfer to the deal
* before calling. See the implementation's NatSpec for the recorded accepted risk.
* @param _dealId The deal id of the deal to confirm
*/
function confirmFunding(bytes32 _dealId) external;
/**
* @notice Releases a funded deal's locked amount to the seller
* @param _dealId The deal id of the deal to release
*/
function releaseDeal(bytes32 _dealId) external;
/**
* @notice Cancels a created or funded deal, refunding the buyer if it was funded
* @param _dealId The deal id of the deal to cancel
*/
function cancelDeal(bytes32 _dealId) external;
/**
* @notice Moves any token balance, or native ETH, held by this contract to a recipient
* @dev Unguarded by design: no `totalLocked` bound and no pause guard, so it can move locked
* deal funds and works while paused. See the implementation's NatSpec.
* @param _token The token to move, or the zero address for native ETH
* @param _to The recipient address
* @param _amount The amount to move
*/
function sweep(
address _token,
address payable _to,
uint256 _amount
) external;
}
libs/ERC20/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/**
* @custom:security-contact [email protected]
* @title IERC20
* @author SYGNUM AG - Blockchain team 3301
* @dev Interface of the ERC-20 standard as defined in the ERC with extensions:
* 1. EIP-2612 permit functionality for gasless approvals
* 2. Standard metadata functions (name, symbol, decimals)
*
* This interface matches the implementation in ERC20.sol
*/
interface IERC20 {
/* ========== EVENTS ========== */
/**
* @dev Emitted when `amount` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `amount` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/* ========== STATE VARIABLES ========== */
/**
* @dev Returns the name of the token.
* Part of the ERC20 optional metadata extension.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
* Part of the ERC20 optional metadata extension.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
* Part of the ERC20 optional metadata extension.
*/
function decimals() external view returns (uint8);
/**
* @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 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 Returns the current nonce for `owner`.
* This value is used in EIP-2612 permit function and must be
* included whenever a signature is generated.
*
* Every successful call to {permit} increases the owner's nonce by one,
* preventing signature reuse.
*/
function nonces(address _owner) external view returns (uint256);
/* ========== FUNCTIONS ========== */
/**
* @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 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);
/**
* @dev EIP-2612 permit function to approve token spending with a signature
* instead of msg.sender calling approve directly.
*
* Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* Requirements:
* - `deadline` must not have expired
* - `v`, `r` and `s` must form a valid secp256k1 signature from `owner`
* - The signature must use the current nonce of `owner` (see {nonces})
*
* Emits an {Approval} event.
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
}libs/FundRecovery/FundRecoveryCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IERC20} from "libs/ERC20/interfaces/IERC20.sol";
/**
* @custom:security-contact [email protected]
* @title FundRecoveryCore
* @author SYGNUM AG - Blockchain team 3301
* @notice Core fund recovery implementation for recovering native tokens and ERC20 tokens
* @dev This library provides the core logic for recovering funds from contracts.
* It handles both native tokens (ETH) and ERC20 tokens, including fee-on-transfer tokens.
* Contracts inheriting from this can call the internal _recoverFunds function.
*/
abstract contract FundRecoveryCore {
/* ======== ERRORS ======== */
error TransferFailed();
/* ======== EVENTS ======== */
event FundsRecovered(address indexed token, address indexed to, uint256 requestedAmount, uint256 actualAmountReceived);
/* ======== INTERNAL STATE-CHANGING FUNCTIONS ======== */
/**
* @notice Recovers funds from the contract
* @dev If _token is address(0), recovers native token (ETH), else recovers ERC20 tokens
* For ERC-20 tokens, the emitted amounts include both the requested amount and the actual amount received,
* which may differ for fee-on-transfer tokens.
* @param _token The token address (zero for native)
* @param _to The recipient address
* @param _amount The amount to recover (in wei for native ETH, in token's smallest unit for ERC-20)
*/
function _recoverFunds(address _token, address payable _to, uint256 _amount) internal {
bool _success;
uint256 _actualAmountReceived;
if (_token == address(0)) {
// Recover native token (ETH)
(_success,) = _to.call{value: _amount}("");
if (!_success) {
revert TransferFailed();
}
_actualAmountReceived = _amount;
} else {
// Recover ERC20 token
// Measure actual amount received for fee-on-transfer tokens
IERC20 _tokenContract = IERC20(_token);
uint256 _balanceBefore = _tokenContract.balanceOf(_to);
// Use low-level call to handle all token types:
// - Tokens that revert
// - Tokens that return false
// - Non-standard tokens that don't return a value (like USDT)
bytes memory _returndata;
// solhint-disable-next-line avoid-low-level-calls
(_success, _returndata) = _token.call(
abi.encodeWithSelector(IERC20.transfer.selector, _to, _amount)
);
// Check if call succeeded and validate return data
// Success means: call succeeded AND (no return data OR return data decodes to true)
if (!_success || (_returndata.length > 0 && !abi.decode(_returndata, (bool)))) {
revert TransferFailed();
}
uint256 _balanceAfter = _tokenContract.balanceOf(_to);
_actualAmountReceived = _balanceAfter - _balanceBefore;
}
emit FundsRecovered(_token, _to, _amount, _actualAmountReceived);
}
}
libs/Ownable/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {OwnableView} from "libs/Ownable/OwnableView.sol";
/**
* @custom:security-contact [email protected]
* @title Ownable
* @notice Standard Ownable implementation that extends OwnableView
* and exposes the public interface functions.
* @dev Contracts inheriting from this will have a single owner who can transfer or renounce ownership.
* The onlyOwner modifier can be used to restrict access to owner-only functions.
*/
abstract contract Ownable is OwnableView {
/* ========== EXTERNAL/PUBLIC STATE-CHANGING FUNCTIONS ========== */
/**
* @notice Transfers contract ownership to a new address.
* @dev Only callable by the current owner. Emits an {OwnershipTransferred} event.
* The new owner can be the zero address, effectively renouncing ownership.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
}
libs/Ownable/OwnableCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/**
* @custom:security-contact [email protected]
* @title OwnableCore
* @notice Core ownership implementation with slot storage pattern
* @dev This contract provides the core ownership logic without exposing public functions.
* Contracts inheriting from this will have a single owner who can transfer or renounce ownership.
* This is the core implementation that should be inherited by contracts that need custom ownership logic.
*/
abstract contract OwnableCore {
/* ======== STATE VARIABLES ======== */
/**
* @dev OWNABLE_CORE_STORAGE_SLOT is a constant used to locate the OwnableStorage struct in storage for OwnableCore.
* This ensures a unique storage slot for the owner address, minimizing collision risks with other storage variables in the contract.
* The value is calculated as keccak256(abi.encode(uint256(keccak256("OwnableCore.OwnableStorage")) - 1)) & ~bytes32(uint256(0xff)).
*/
bytes32 private constant OWNABLE_CORE_STORAGE_SLOT =
0xc7b1b7135718030d8106708ba7b85afbbbc3e628f0b452126ba684db45f79e00;
/// @custom:storage-location erc7201:OwnableCore.OwnableStorage
struct OwnableStorage {
address owner;
}
/* ========== ERRORS ========== */
error OnlyOwner();
error ZeroAddress();
/* ========== EVENTS ========== */
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/* ========== INTERNAL VIEW FUNCTIONS ========== */
/**
* @notice Returns the address of the current owner
* @return The address of the current owner
*/
function _owner() internal view returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $.owner;
}
/* ========== INTERNAL INITIALIZER ========== */
/**
* @notice Initializes the Ownable contract by setting the initial owner.
* @dev Should be called by the inheriting contract's initializer or constructor.
* This function sets the `owner` state variable to the provided `_initialOwner` address.
* Idempotent: Only initializes if owner is not already set (default value is address(0)).
* This preserves existing ownership during upgrades - new init data will not override existing owner.
* @param _initialOwner The address that will be granted ownership of the contract.
*/
function _ownable_init(address _initialOwner) internal {
OwnableStorage storage $ = _getOwnableStorage();
if ($.owner == address(0)) {
$.owner = _initialOwner;
emit OwnershipTransferred(address(0), _initialOwner);
}
}
/* ========== MODIFIERS ========== */
/**
* @notice Restricts function access to only the owner of the contract.
* @dev Reverts with OnlyOwner if called by any account other than the owner.
* Use this modifier to protect functions that should only be callable by the contract owner.
*/
modifier onlyOwner() {
OwnableStorage storage $ = _getOwnableStorage();
if ($.owner != msg.sender) {
revert OnlyOwner();
}
_;
}
/* ========== INTERNAL STATE-CHANGING FUNCTIONS ========== */
/**
* @notice Transfers contract ownership to a new address.
* @dev Emits an {OwnershipTransferred} event.
* The new owner can be the zero address, effectively renouncing ownership.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
OwnableStorage storage $ = _getOwnableStorage();
address _oldOwner = $.owner;
$.owner = _newOwner;
emit OwnershipTransferred(_oldOwner, _newOwner);
}
/* ======== PRIVATE VIEW/PURE FUNCTIONS ======== */
/**
* @notice Retrieves the OwnableStorage struct from the storage slot
* @dev Returns the OwnableStorage struct
*/
function _getOwnableStorage()
private
pure
returns (OwnableStorage storage $)
{
// Use assembly to simply slot the storage location into a variable
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := OWNABLE_CORE_STORAGE_SLOT
}
}
}
libs/Ownable/OwnableView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {OwnableCore} from "libs/Ownable/OwnableCore.sol";
/**
* @custom:security-contact [email protected]
* @title OwnableView
* @author SYGNUM AG - Blockchain team 3301
* @notice View-only Ownable implementation that exposes owner function
* @dev This contract provides read-only access to ownership state without
* allowing ownership modifications. It's designed for contracts that need
* to query owner but should not modify ownership directly.
*/
abstract contract OwnableView is OwnableCore {
/*//////////////////////////////////////////////////////////////
EXTERNAL/PUBLIC VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Returns the address of the current owner
* @return The address of the current owner
*/
function owner() public view returns (address) {
return _owner();
}
}
libs/Pausable/Pausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { PausableView } from "./PausableView.sol";
/**
* @custom:security-contact [email protected]
* @title Pausable
* @notice Pausable contract that exposes the pause state
* @dev Inherits from PausableView and provides state-changing functions
*/
abstract contract Pausable is PausableView {
/**
* @notice Pauses the contract
* @dev Virtual function that can be overridden to add authorization checks
*/
function pause() external virtual {
_pause();
}
/**
* @notice Unpauses the contract
* @dev Virtual function that can be overridden to add authorization checks
*/
function unpause() external virtual {
_unpause();
}
}libs/Pausable/PausableCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/**
* @custom:security-contact [email protected]
* @title PausableCore
* @notice Core pausing implementation with slot storage pattern
* @dev This contract provides the core pausing logic without any authorization assumptions.
* Contracts inheriting from this will be able to pause and unpause functionality
* using the whenNotPaused and whenPaused modifiers. This is the core implementation
* that should be inherited by contracts that need pausing functionality.
*/
abstract contract PausableCore {
/* ======== STATE VARIABLES ======== */
/**
* @dev PAUSABLE_CORE_STORAGE_SLOT is a constant used to locate the PausableStorage struct in storage for PausableCore.
* This ensures a unique storage slot for the paused state, minimizing collision risks with other storage variables in the contract.
* The value is calculated as keccak256(abi.encode(uint256(keccak256("PausableCore.PausableStorage")) - 1)) & ~bytes32(uint256(0xff)).
*/
bytes32 private constant PAUSABLE_CORE_STORAGE_SLOT =
0xfedd7b171e5aaf71411eb61c81513b977191128c387240284b4edb396fcbdb00;
/// @custom:storage-location erc7201:PausableCore.PausableStorage
struct PausableStorage {
bool paused;
}
/* ========== ERRORS ========== */
error ContractPaused();
error ContractNotPaused();
/* ========== EVENTS ========== */
event Paused();
event Unpaused();
/* ========== INTERNAL VIEW FUNCTIONS ========== */
/**
* @notice Returns the current pause state
* @return True if the contract is paused, false otherwise
*/
function _isPaused() internal view returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $.paused;
}
/* ========== MODIFIERS ========== */
/**
* @notice Modifier to make a function callable only when the contract is not paused
* @dev Reverts with ContractPaused if the contract is paused
*/
modifier whenNotPaused() {
if (_isPaused()) {
revert ContractPaused();
}
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused
* @dev Reverts with ContractNotPaused if the contract is not paused
*/
modifier whenPaused() {
if (!_isPaused()) {
revert ContractNotPaused();
}
_;
}
/* ========== INTERNAL STATE-CHANGING FUNCTIONS ========== */
/**
* @notice Pauses the contract
* @dev Sets the paused state to true and emits a Paused event
*/
function _pause() internal whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$.paused = true;
emit Paused();
}
/**
* @notice Unpauses the contract
* @dev Sets the paused state to false and emits an Unpaused event
*/
function _unpause() internal whenPaused {
PausableStorage storage $ = _getPausableStorage();
$.paused = false;
emit Unpaused();
}
/* ======== PRIVATE VIEW/PURE FUNCTIONS ======== */
/**
* @notice Retrieves the PausableStorage struct from the storage slot
* @dev Returns the PausableStorage struct
*/
function _getPausableStorage()
private
pure
returns (PausableStorage storage $)
{
// Use assembly to simply slot the storage location into a variable
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := PAUSABLE_CORE_STORAGE_SLOT
}
}
}
libs/Pausable/PausableView.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {PausableCore} from "libs/Pausable/PausableCore.sol";
import {IPausable} from "libs/Pausable/interfaces/IPausable.sol";
/**
* @custom:security-contact [email protected]
* @title PausableView
* @author SYGNUM AG - Blockchain team 3301
* @notice View-only Pausable implementation that exposes pause state
* @dev This contract provides read-only access to pause state without
* allowing pause modifications. It's designed for contracts that need
* to query pause state but should not modify state directly.
*/
abstract contract PausableView is PausableCore, IPausable {
/*//////////////////////////////////////////////////////////////
EXTERNAL/PUBLIC VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Returns whether the contract is paused
* @return True if the contract is paused, false otherwise
*/
function isPaused() public view returns (bool) {
return _isPaused();
}
}
libs/Pausable/interfaces/IPausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/**
* @custom:security-contact [email protected]
* @title IPausable
* @notice Interface for pausable functionality
* @dev Defines the external interface for contracts that can be paused and unpaused
*/
interface IPausable {
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice Returns whether the contract is paused
* @return True if the contract is paused, false otherwise
*/
function isPaused() external view returns (bool);
/* ======== STATE-CHANGING FUNCTIONS ======== */
/**
* @notice Pauses the contract
* @dev Only callable by authorized accounts (e.g., pausers)
*/
function pause() external;
/**
* @notice Unpauses the contract
* @dev Only callable by authorized accounts (e.g., pausers)
*/
function unpause() external;
}libs/ReentrancyGuard/ReentrancyGuardCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/**
* @custom:security-contact [email protected]
* @title ReentrancyGuardCore
* @notice Core reentrancy guard implementation using transient storage (EIP-1153)
* @dev This contract provides the core reentrancy protection logic without any authorization assumptions.
* Contracts inheriting from this will be able to protect functions from reentrancy using the nonReentrant modifier.
*/
abstract contract ReentrancyGuardCore {
/* ======== STATE VARIABLES ======== */
/**
* @dev Transient storage key for reentrancy status.
* Derived from keccak256(abi.encode(uint256(keccak256("ReentrancyGuardCore.ReentrancyGuardStorage")) - 1))
* & ~bytes32(uint256(0xff)).
*/
bytes32 private constant REENTRANCY_GUARD_CORE_STORAGE_SLOT =
0xdbb3608ae93cf44fa644001005ac283fa89940819ddf78b12f82ad744dd22200;
/* ========== ERRORS ========== */
error ReentrancyGuardReentrantCall();
/* ========== MODIFIERS ========== */
/**
* @notice Prevents a contract from calling itself, directly or indirectly
* @dev Reverts with ReentrancyGuardReentrantCall if a reentrant call is detected.
* Uses transient storage (TSTORE/TLOAD) which auto-resets at end of transaction.
*/
modifier nonReentrant() {
// solhint-disable-next-line no-inline-assembly
assembly {
if tload(REENTRANCY_GUARD_CORE_STORAGE_SLOT) {
mstore(0x00, 0x3ee5aeb5) // ReentrancyGuardReentrantCall()
revert(0x1c, 0x04)
}
tstore(REENTRANCY_GUARD_CORE_STORAGE_SLOT, 1)
}
_;
// solhint-disable-next-line no-inline-assembly
assembly {
tstore(REENTRANCY_GUARD_CORE_STORAGE_SLOT, 0)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 300,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@chainlink-contracts-1.3.0/=dependencies/@chainlink-contracts-1.3.0/",
"@gnosis-pm-safe-contracts-1.3.0/=dependencies/@gnosis-pm-safe-contracts-1.3.0/",
"forge-std/=dependencies/forge-std-1.9.4/src/",
"safe-global-safe-smart-account-1.4.1-3/=dependencies/safe-global-safe-smart-account-1.4.1-3/",
"solmate-6.8.0/=dependencies/solmate-6.8.0/",
"forge-std-1.9.4/=dependencies/forge-std-1.9.4/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.