Verified contractExactMIT
HTLCErc20
Address0x6c38bf44a327bf36bfbefcedc514c0fb3fec6748
- Balance
0 ETH
- Transactions
116
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,331,929
- Creation transaction
- 0x0755b7ea10…ba7d16b871
11 files
- src/HTLCErc20.solmain28.08 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol7.82 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
src/HTLCErc20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @notice A swap's storage key: keccak256 over all six swap parameters (see
/// `HTLCErc20.computeKey`). One key identifies one swap everywhere —
/// it indexes `swaps` and `preimages` here and is the identifier carried
/// by every lifecycle event.
type SwapKey is bytes32;
/// @title HTLCErc20
/// @notice Hash Time-Locked Contract for trustless ERC20 atomic swaps
/// @dev Uses SHA-256 for preimage hashing to stay compatible with Bitcoin HTLC scripts.
/// Each swap's lifecycle state is kept in storage permanently (None → Active →
/// Redeemed/Refunded), and a redeem also stores the revealed preimage — so an
/// observer can classify a settled swap and recover its preimage with a single
/// state read instead of scanning event logs.
/// All swap parameters must be supplied on redeem/refund and are verified via hash.
/// The `claimAddress` is part of the swap key and only that address can redeem
/// (directly via msg.sender or via EIP-712 signature), preventing front-running.
/// @dev The owner's only powers are `recoverExcessToken` and `recoverEther`.
/// `lockedAmounts` accounts for every token unit owed to an active swap, and
/// `recoverExcessToken` can move only the balance above it, so no owner action
/// can reach swap funds.
contract HTLCErc20 is Ownable2Step {
using SafeERC20 for IERC20;
uint8 public constant VERSION = 7;
// -- EIP-712 --
//
// The domain's version string tracks VERSION. Signers must use the same value,
// or the recovered claimAddress will not match and settlement reverts.
bytes32 public constant TYPEHASH_REDEEM = keccak256(
"Redeem(bytes32 preimage,uint256 amount,address token,address sender,uint256 timelock,address caller,address destination,address sweepToken,uint256 minAmountOut,bytes32 callsHash)"
);
bytes32 public constant TYPEHASH_REFUND =
keccak256("Refund(bytes32 preimageHash,uint256 amount,address token,address sender,uint256 timelock)");
bytes32 public constant TYPEHASH_REHASH = keccak256(
"Rehash(bytes32 preimageHash,uint256 amount,address token,address sender,uint256 timelock,bytes32 newPreimageHash,uint256 newTimelock)"
);
bytes32 public immutable DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256("HTLCErc20"),
keccak256("7"),
block.chainid,
address(this)
)
);
// -- Errors --
error Reentrancy();
error ZeroAmount();
error ZeroClaimAddress();
error ZeroRefundAddress();
error ZeroRecipient();
/// @dev The timelock must already lie in the future at creation…
error TimelockTooSoon();
/// @dev …and must have passed before a unilateral refund.
error TimelockNotExpired();
/// @dev A rehash may extend the timelock but never shorten it: the claim side keeps
/// at least the window it was promised at creation.
error TimelockShortened();
/// @dev Recovery found no balance beyond what active swaps are owed.
error NoExcess();
error EtherTransferFailed();
error OwnershipRequired();
/// @dev Settlement needs the key Active; the state names which lifecycle
/// stage the swap is actually in (None = never created, or already
/// Redeemed / Refunded).
error SwapNotActive(SwapKey key, SwapState state);
/// @dev Creation needs the key unused; the state names what occupies it
/// (Active, or a terminal state whose terms are spent).
error SwapExists(SwapKey key, SwapState state);
// -- State --
/// @notice Lifecycle of a swap. Terminal states are never deleted, so a key's
/// history stays readable from storage forever. Rehashed is terminal for
/// the key, not for the lock: the tokens live on under the new key named
/// by the `SwapRehashed` event.
enum SwapState {
None,
Active,
Redeemed,
Refunded,
Rehashed
}
/// @dev Swap lifecycle state, by swap key. A key that ever reached a terminal
/// state can never be created again: the preimage of a redeemed key is
/// public, so a second swap under the same key would be claimable by
/// anyone watching the chain.
mapping(SwapKey => SwapState) public swaps;
/// @dev Token units owed to active swaps, per token. Rises on create, falls on every
/// settlement, so the contract's balance minus this is owed to nobody.
mapping(address => uint256) public lockedAmounts;
/// @dev The preimage a redeem revealed, by swap key (the same key as `swaps`).
/// Zero until redeemed; the state enum, not this value, is the authority
/// on whether a redeem happened.
mapping(SwapKey => bytes32) public preimages;
// -- Events --
/// @dev `key` commits to every swap parameter and is a swap's unique identifier.
/// `preimageHash` is not unique — any number of swaps may share one, each with
/// its own terms. Consumers must match a swap on `key`, never on `preimageHash`.
event SwapCreated(
bytes32 indexed preimageHash,
address indexed refundAddress,
address indexed claimAddress,
address token,
uint256 amount,
uint256 timelock,
SwapKey key
);
event SwapRedeemed(bytes32 indexed preimageHash, SwapKey indexed key, bytes32 preimage);
event SwapRefunded(bytes32 indexed preimageHash, SwapKey indexed key);
/// @dev The lock under `key` continues under `newKey` with a new hash and timelock;
/// amount, token, sender and claimAddress are unchanged. No `SwapCreated` is
/// emitted for `newKey` — this is the only record of its origin.
event SwapRehashed(bytes32 indexed preimageHash, SwapKey indexed key, SwapKey indexed newKey, bytes32 newPreimageHash);
event ExcessTokenRecovered(address indexed token, address indexed to, uint256 amount);
event EtherRecovered(address indexed to, uint256 amount);
// -- Constructor --
constructor(address initialOwner) Ownable(initialOwner) {}
// -- Reentrancy guard via transient storage (EIP-1153) --
modifier nonReentrant() {
assembly ("memory-safe") {
if tload(0) {
mstore(0, 0xab143c06) // Reentrancy()
revert(0x1c, 0x04)
}
tstore(0, 1)
}
_;
assembly ("memory-safe") {
tstore(0, 0)
}
}
// -- External functions --
/// @notice Lock ERC20 tokens into a new hash time-locked swap
/// @dev Convenience wrapper — uses msg.sender as the sender (refund address)
/// @param preimageHash SHA-256 hash of the secret preimage — an indexed event topic,
/// not an identifier: swaps may share one, and `key` tells them apart
/// @param amount Token amount to lock (caller must have approved this contract)
/// @param token ERC20 token address to lock
/// @param claimAddress Address authorized to redeem the locked tokens
/// @param timelock Unix timestamp after which the sender can reclaim tokens
function create(
bytes32 preimageHash,
uint256 amount,
address token,
address claimAddress,
uint256 timelock
) external nonReentrant {
_create(preimageHash, amount, token, msg.sender, claimAddress, timelock);
}
/// @notice Lock ERC20 tokens with an explicit refund address
/// @dev Tokens are always pulled from msg.sender. The refundAddress param controls
/// who can call refund — useful for coordinators/routers acting on behalf of a user.
/// @param preimageHash SHA-256 hash of the secret preimage
/// @param amount Token amount to lock (caller must have approved this contract)
/// @param token ERC20 token address to lock
/// @param refundAddress Address that can refund after timelock (does not have to be msg.sender)
/// @param claimAddress Address authorized to redeem the locked tokens
/// @param timelock Unix timestamp after which the refund address can reclaim tokens
function create(
bytes32 preimageHash,
uint256 amount,
address token,
address refundAddress,
address claimAddress,
uint256 timelock
) external nonReentrant {
_create(preimageHash, amount, token, refundAddress, claimAddress, timelock);
}
/// @notice Redeem tokens by revealing the correct preimage (direct claim)
/// @dev Only the designated claimAddress can call this — msg.sender is used as
/// claimAddress in the key lookup. Tokens are sent to msg.sender.
/// @param preimage Secret whose SHA-256 hash matches the preimageHash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param sender Address that created the swap
/// @param timelock Timelock that was set at creation
function redeem(
bytes32 preimage,
uint256 amount,
address token,
address sender,
uint256 timelock
) external nonReentrant {
bytes32 preimageHash = sha256(abi.encodePacked(preimage));
// msg.sender is used as claimAddress — only the designated address can claim
SwapKey key = _key(preimageHash, amount, token, sender, msg.sender, timelock);
SwapState state = swaps[key];
if (state != SwapState.Active) revert SwapNotActive(key, state);
swaps[key] = SwapState.Redeemed;
preimages[key] = preimage;
lockedAmounts[token] -= amount;
emit SwapRedeemed(preimageHash, key, preimage);
IERC20(token).safeTransfer(msg.sender, amount);
}
/// @notice Redeem tokens using an EIP-712 signature from the claimAddress (gasless / delegated)
/// @dev Anyone can call this function. The claimAddress is recovered from the signature
/// which includes msg.sender as the authorized caller, destination, sweepToken,
/// minAmountOut, and callsHash. Tokens are sent to msg.sender (not claimAddress).
/// All execution parameters are cryptographically bound to the signature, so the
/// outcome is guaranteed by the signer regardless of who submits the transaction.
/// @param preimage Secret whose SHA-256 hash matches the preimageHash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param sender Address that created the swap
/// @param timelock Timelock that was set at creation
/// @param destination Address where the caller intends to route tokens after redeem
/// @param sweepToken Token the caller will sweep to destination (bound to signature)
/// @param minAmountOut Minimum amount of sweepToken required (bound to signature)
/// @param callsHash Hash of the calls array (bound to signature, prevents call substitution)
/// @param v ECDSA recovery id
/// @param r ECDSA signature component
/// @param s ECDSA signature component
/// @return claimAddress The address recovered from the signature
function redeemBySig(
bytes32 preimage,
uint256 amount,
address token,
address sender,
uint256 timelock,
address destination,
address sweepToken,
uint256 minAmountOut,
bytes32 callsHash,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant returns (address claimAddress) {
bytes32 preimageHash = sha256(abi.encodePacked(preimage));
// Scoped to reduce stack depth: compute digest and recover signer
{
bytes32 structHash = keccak256(
abi.encode(
TYPEHASH_REDEEM, preimage, amount, token, sender, timelock,
msg.sender, destination, sweepToken, minAmountOut, callsHash
)
);
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
claimAddress = ECDSA.recover(digest, v, r, s);
}
SwapKey key = _key(preimageHash, amount, token, sender, claimAddress, timelock);
SwapState state = swaps[key];
if (state != SwapState.Active) revert SwapNotActive(key, state);
swaps[key] = SwapState.Redeemed;
preimages[key] = preimage;
lockedAmounts[token] -= amount;
emit SwapRedeemed(preimageHash, key, preimage);
// Tokens go to msg.sender (the authorized caller), not claimAddress
IERC20(token).safeTransfer(msg.sender, amount);
}
/// @notice Reclaim tokens after the timelock has expired
/// @dev Convenience wrapper — tokens are sent back to msg.sender
/// @param preimageHash The preimage hash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param claimAddress Claim address that was set at creation
/// @param timelock Timelock that was set at creation
function refund(
bytes32 preimageHash,
uint256 amount,
address token,
address claimAddress,
uint256 timelock
) external nonReentrant {
_refund(preimageHash, amount, token, msg.sender, claimAddress, timelock);
IERC20(token).safeTransfer(msg.sender, amount);
}
/// @notice Refund an expired swap on the sender's behalf; the tokens go to the sender
/// @dev Permissionless: anyone may call once the timelock has passed, and the only
/// thing the caller decides is to pay the gas. The key names `sender`, and the
/// tokens can only go there, so a wrong `sender` addresses a swap that does not
/// exist rather than redirecting one that does. Lets a service sweep expired
/// locks back to depositors who cannot submit a transaction themselves.
/// @param preimageHash The preimage hash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param sender Sender (refund address) that was set at creation; receives the tokens
/// @param claimAddress Claim address that was set at creation
/// @param timelock Timelock that was set at creation
function refundFor(
bytes32 preimageHash,
uint256 amount,
address token,
address sender,
address claimAddress,
uint256 timelock
) external nonReentrant {
_refund(preimageHash, amount, token, sender, claimAddress, timelock);
IERC20(token).safeTransfer(sender, amount);
}
/// @notice Reclaim tokens after the timelock has expired, sending to a specified destination
/// @dev msg.sender must still be the original sender (enforced via the hash).
/// Useful for sending tokens to a coordinator/router for further processing.
/// @param preimageHash The preimage hash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param claimAddress Claim address that was set at creation
/// @param timelock Timelock that was set at creation
/// @param destination Address to receive the refunded tokens
function refund(
bytes32 preimageHash,
uint256 amount,
address token,
address claimAddress,
uint256 timelock,
address destination
) external nonReentrant {
_refund(preimageHash, amount, token, msg.sender, claimAddress, timelock);
IERC20(token).safeTransfer(destination, amount);
}
/// @notice Refund before the timelock: the sender calls, the claimAddress signs
/// @dev Collaborative refund. Both parties consent — the sender by being msg.sender
/// (exactly as in `refund`), the claimAddress by an EIP-712 signature over the
/// swap terms with `sender = msg.sender`. The signature only waives the timelock;
/// it moves nothing on its own. A claimAddress that signs and then calls with
/// itself as sender addresses a key it never funded, so it cannot route the
/// locked tokens to itself. Tokens go to msg.sender.
/// No expiry on the signature, on purpose: it is bound to one key, and that key
/// can leave Active exactly once, so every signature over it dies with the first
/// settlement that lands.
/// @param preimageHash The preimage hash used at creation (not the preimage — the
/// sender does not know it)
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param timelock Timelock that was set at creation
/// @param v ECDSA recovery id
/// @param r ECDSA signature component
/// @param s ECDSA signature component
/// @return claimAddress The address recovered from the signature
function refundBySig(
bytes32 preimageHash,
uint256 amount,
address token,
uint256 timelock,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant returns (address claimAddress) {
{
bytes32 structHash =
keccak256(abi.encode(TYPEHASH_REFUND, preimageHash, amount, token, msg.sender, timelock));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
claimAddress = ECDSA.recover(digest, v, r, s);
}
SwapKey key = _key(preimageHash, amount, token, msg.sender, claimAddress, timelock);
SwapState state = swaps[key];
if (state != SwapState.Active) revert SwapNotActive(key, state);
swaps[key] = SwapState.Refunded;
lockedAmounts[token] -= amount;
emit SwapRefunded(preimageHash, key);
IERC20(token).safeTransfer(msg.sender, amount);
}
/// @notice Replace the hash lock and timelock of an active swap, keeping the tokens locked
/// @dev Collaborative rehash, consented to exactly like `refundBySig`: the sender by
/// being msg.sender, the claimAddress by an EIP-712 signature over the old terms
/// (with `sender = msg.sender`) and the new ones. Lets a swap whose far side
/// failed (an unpayable Lightning invoice, say) be retried under a fresh hash
/// without unwinding the lock. Nothing is transferred and `lockedAmounts` does
/// not move: the old key becomes Rehashed and the new key Active, with the same
/// amount, token, sender and claimAddress.
/// The new timelock must lie in the future, as at creation, and must not be
/// shorter than the current one: a rehash never shortens the timelock, so the
/// claimAddress keeps at least the claim window it was promised, whatever it
/// signed. Equal or later is accepted.
/// No `SwapCreated` fires for the new key — consumers follow `SwapRehashed`.
/// The new key is taken on a first-come basis like any other: a third party who
/// learns the agreed terms can `create` under them first and make this call
/// revert with `SwapExists`. That costs them a lock the claimAddress may redeem
/// and leaves the original untouched, so the parties simply agree on fresh terms.
/// @param preimageHash The preimage hash used at creation
/// @param amount Amount that was locked
/// @param token Token that was locked
/// @param timelock Timelock that was set at creation
/// @param newPreimageHash Preimage hash the lock continues under
/// @param newTimelock Timelock the lock continues under
/// @param v ECDSA recovery id
/// @param r ECDSA signature component
/// @param s ECDSA signature component
/// @return claimAddress The address recovered from the signature
/// @return newKey The key the lock continues under
function rehash(
bytes32 preimageHash,
uint256 amount,
address token,
uint256 timelock,
bytes32 newPreimageHash,
uint256 newTimelock,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant returns (address claimAddress, SwapKey newKey) {
if (newTimelock <= block.timestamp) revert TimelockTooSoon();
if (newTimelock < timelock) revert TimelockShortened();
{
bytes32 structHash = keccak256(
abi.encode(
TYPEHASH_REHASH, preimageHash, amount, token, msg.sender, timelock, newPreimageHash, newTimelock
)
);
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
claimAddress = ECDSA.recover(digest, v, r, s);
}
SwapKey key = _key(preimageHash, amount, token, msg.sender, claimAddress, timelock);
SwapState state = swaps[key];
if (state != SwapState.Active) revert SwapNotActive(key, state);
newKey = _key(newPreimageHash, amount, token, msg.sender, claimAddress, newTimelock);
// Same rule as create: a settled key's terms are spent, an active one is taken.
SwapState newState = swaps[newKey];
if (newState != SwapState.None) revert SwapExists(newKey, newState);
swaps[key] = SwapState.Rehashed;
swaps[newKey] = SwapState.Active;
emit SwapRehashed(preimageHash, key, newKey, newPreimageHash);
}
// -- Owner functions --
/// @notice Recover the token balance held beyond what active swaps are owed
/// @dev An ERC20 transfer into this contract cannot be refused, so the balance can
/// exceed `lockedAmounts[token]`. Only that difference is movable: the subtraction
/// floors at what every active swap is owed, so no call here can reduce the balance
/// below the amount its settlements will need.
/// @param token Token to recover the excess of
/// @param to Recipient of the recovered tokens
function recoverExcessToken(address token, address to) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroRecipient();
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 locked = lockedAmounts[token];
if (balance <= locked) revert NoExcess();
uint256 excess = balance - locked;
emit ExcessTokenRecovered(token, to, excess);
IERC20(token).safeTransfer(to, excess);
}
/// @notice Recover ether held by this contract
/// @dev No function here is payable, so a balance can only come from a force-send
/// (selfdestruct, coinbase, or a transfer to the address before deployment). None of
/// it belongs to a swap, so the full balance is recoverable.
/// @param to Recipient of the recovered ether
function recoverEther(address payable to) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroRecipient();
uint256 balance = address(this).balance;
if (balance == 0) revert NoExcess();
emit EtherRecovered(to, balance);
(bool sent,) = to.call{value: balance}("");
if (!sent) revert EtherTransferFailed();
}
/// @dev Disabled: recovery is owner-gated, so an ownerless contract could never release
/// a mis-sent balance again. Use `transferOwnership` / `acceptOwnership` instead.
function renounceOwnership() public pure override {
revert OwnershipRequired();
}
// -- View functions --
/// @notice Check whether a swap with the given parameters is active
function isActive(
bytes32 preimageHash,
uint256 amount,
address token,
address sender,
address claimAddress,
uint256 timelock
) external view returns (bool) {
return swaps[_key(preimageHash, amount, token, sender, claimAddress, timelock)] == SwapState.Active;
}
/// @notice A swap's lifecycle state and (if redeemed) its revealed preimage,
/// by swap key — one read classifies a settled swap without log scans
/// @param key The swap key (see `computeKey`, or the `key` field of `SwapCreated`)
function swapState(SwapKey key) external view returns (SwapState state, bytes32 preimage) {
return (swaps[key], preimages[key]);
}
/// @notice Compute the storage key for a swap from its parameters
function computeKey(
bytes32 preimageHash,
uint256 amount,
address token,
address sender,
address claimAddress,
uint256 timelock
) external pure returns (SwapKey) {
return _key(preimageHash, amount, token, sender, claimAddress, timelock);
}
// -- Internal --
function _refund(
bytes32 preimageHash,
uint256 amount,
address token,
address sender,
address claimAddress,
uint256 timelock
) internal {
if (block.timestamp < timelock) revert TimelockNotExpired();
SwapKey key = _key(preimageHash, amount, token, sender, claimAddress, timelock);
SwapState state = swaps[key];
if (state != SwapState.Active) revert SwapNotActive(key, state);
swaps[key] = SwapState.Refunded;
lockedAmounts[token] -= amount;
emit SwapRefunded(preimageHash, key);
}
function _create(
bytes32 preimageHash,
uint256 amount,
address token,
address refundAddress,
address claimAddress,
uint256 timelock
) internal {
if (amount == 0) revert ZeroAmount();
if (timelock <= block.timestamp) revert TimelockTooSoon();
// Neither party may be address(0). It is the address a failed signature recovery
// resolves to, so it must never be a claimAddress that a key commits to, and a
// zero refundAddress could never reclaim the swap once its timelock expires.
if (claimAddress == address(0)) revert ZeroClaimAddress();
if (refundAddress == address(0)) revert ZeroRefundAddress();
SwapKey key = _key(preimageHash, amount, token, refundAddress, claimAddress, timelock);
// Also rejects settled keys: the key's terms are spent — a redeemed key's
// preimage is public, so tokens locked under it again would be claimable
// by anyone. New swaps must use a fresh preimageHash (or other terms).
SwapState state = swaps[key];
if (state != SwapState.None) revert SwapExists(key, state);
swaps[key] = SwapState.Active;
lockedAmounts[token] += amount;
emit SwapCreated(preimageHash, refundAddress, claimAddress, token, amount, timelock, key);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
/// @dev Compute the storage key from all swap parameters using assembly for gas efficiency
function _key(
bytes32 preimageHash,
uint256 amount,
address token,
address refundAddress,
address claimAddress,
uint256 timelock
) internal pure returns (SwapKey) {
bytes32 result;
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, preimageHash)
mstore(add(ptr, 0x20), amount)
mstore(add(ptr, 0x40), token)
mstore(add(ptr, 0x60), refundAddress)
mstore(add(ptr, 0x80), claimAddress)
mstore(add(ptr, 0xa0), timelock)
result := keccak256(ptr, 0xc0)
}
return SwapKey.wrap(result);
}
}
lib/openzeppelin-contracts/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);
}
}
lib/openzeppelin-contracts/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);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/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;
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/",
"forge-std/=lib/forge-std/src/",
"permit2/=lib/permit2/src/",
"ds-test/=lib/permit2/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solmate/=lib/permit2/lib/solmate/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.