Verified contractExactMIT
ZKPaymentLink
Address0xa2f51c5dd428d2a97f6626d03db8b2f75b5de69b
- Balance
0.004693 ETH
- Transactions
106
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 99,999 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,648,535
- Creation transaction
- 0xc47b0063b3…6bbe01cc2f
14 files
- contract/ZKPaymentLink.solmain22.72 KB
- contract/IGroth16Verifier.sol1.05 KB
- contract/ZKPaymentLinkHelpers.sol5.91 KB
- node_modules/@openzeppelin/contracts/access/AccessControl.sol7.03 KB
- node_modules/@openzeppelin/contracts/access/IAccessControl.sol3.34 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC165.sol193 B
- node_modules/@openzeppelin/contracts/interfaces/IERC20.sol182 B
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol879 B
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 B
contract/ZKPaymentLink.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./IGroth16Verifier.sol";
import "./ZKPaymentLinkHelpers.sol";
/// @title ZKPaymentLink
/// @author Bitcoin.com
/// @notice Anonymous payment links using Groth16 ZK proofs.
///
/// @dev Commitment scheme (Poseidon-based, ZK-friendly):
///
/// Deposit side (client):
/// secret = random 32 bytes
/// nullifier = random 32 bytes
/// commitment = Poseidon(nullifier, secret) ← stored on-chain
/// Link URL: /claim/zk?id=<id>&chain=<chainId>&s=<secret>&n=<nullifier>
///
/// Claim side (client generates proof, depositId + chainId known from URL):
/// nullifierHash = Poseidon(nullifier, depositId, chainId) ← bound to chain + deposit
/// proof = Groth16{ private: (secret, nullifier),
/// public: (commitment, nullifierHash, recipient, depositId, chainId) }
/// Single tx: claimZK(depositId, nullifierHash, recipient, proofA, proofB, proofC)
///
/// Security (two attack vectors closed):
/// 1. Commitment-cloning DoS: nullifierHash includes depositId — a proof generated
/// for deposit #10 cannot be replayed against a cloned commitment at deposit #11.
/// 2. Cross-chain replay: nullifierHash includes chainId — a proof used to claim
/// on Arbitrum cannot be force-relayed to Ethereum Mainnet.
///
/// @dev Only standard ERC-20s are supported; fee-on-transfer and rebasing tokens are not.
contract ZKPaymentLink is AccessControl, ReentrancyGuard, ZKPaymentLinkHelpers {
using SafeERC20 for IERC20;
address public constant ZERO_ADDRESS = address(0);
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
uint16 public constant MAX_FEE_BPS = 1000; // 10 %
uint256 public constant MAX_DEADLINE_DURATION = 365 days;
uint256 public constant MAX_BULK_SIZE = 200; // OOG guard for bulk operations
IGroth16Verifier public immutable verifier;
uint16 public feeRateBps;
address public feeJar;
uint256 public totalReservedETH;
uint256 public accumulatedETHFees;
/// @dev Storage layout (4 slots, optimised for packing):
/// Slot 1 — amount (32 bytes)
/// Slot 2 — commitment (32 bytes)
/// Slot 3 — depositor (20) + deadline (8) + lockedFeeBps (2) + claimed (1) = 31 bytes packed
/// Slot 4 — token (20 bytes)
struct ZKDeposit {
uint256 amount; // Slot 1 — full slot
bytes32 commitment; // Slot 2 — full slot (Poseidon(nullifier, secret))
address depositor; // Slot 3 ─┐
uint64 deadline; // │ packed: 20+8+2+1 = 31 bytes
uint16 lockedFeeBps; // │ snapshotted at deposit; immune to admin changes
bool claimed; // ─┘
address token; // Slot 4 — address(0) = native ETH
}
mapping(uint256 id => ZKDeposit deposit) public deposits;
mapping(address depositor => uint256[] ids) private depositorIds;
mapping(bytes32 nullifierHash => bool spent) public spentNullifiers;
mapping(address token => uint256 reserved) public totalReservedERC20;
mapping(address token => uint256 fees) public accumulatedERC20Fees;
uint256 public nextId;
// ── Errors (validation errors + events in ZKPaymentLinkHelpers) ─────────
error InvalidProof();
error FeeOnTransferNotSupported();
error TransferFailed(address to, uint256 amount);
error UnEvenETHSplit();
error SweepFailed();
// ── Modifiers ───────────────────────────────────────────────────────────
modifier whenNonZeroAddress(
address _addr
) {
_requireNonZeroAddress(
_addr,
ZERO_ADDRESS
);
_;
}
modifier whenNonZeroAmount(
uint256 _amount
) {
_requireNonZeroAmount(
_amount
);
_;
}
modifier whenValidDeadline(
uint256 _deadline
) {
_requireValidDeadline(
_deadline,
MAX_DEADLINE_DURATION
);
_;
}
modifier whenValidCommitment(
bytes32 _commitment
) {
_requireValidCommitment(
_commitment
);
_;
}
// ── Constructor ──────────────────────────────────────────────────────
constructor(
address _admin,
address _verifier
) {
_requireNonZeroAddress(
_admin,
ZERO_ADDRESS
);
_requireNonZeroAddress(
_verifier,
ZERO_ADDRESS
);
_grantRole(
DEFAULT_ADMIN_ROLE,
_admin
);
_grantRole(
ADMIN_ROLE,
_admin
);
verifier = IGroth16Verifier(
_verifier
);
feeJar = _admin;
}
// ── Single Deposits ──────────────────────────────────────────────────
/// @notice Deposit native ETH. The commitment is Poseidon(nullifier, secret),
/// computed client-side using circomlibjs.
function depositETH(
uint256 _deadline,
bytes32 _commitment
)
external
payable
whenValidDeadline(_deadline)
whenValidCommitment(_commitment)
returns (uint256 id)
{
_requireNonZeroAmount(
msg.value
);
id = _createDeposit(
msg.sender,
ZERO_ADDRESS,
msg.value,
_deadline,
_commitment
);
totalReservedETH += msg.value;
emit Deposited(
id, msg.sender,
ZERO_ADDRESS,
msg.value,
_deadline,
_commitment
);
}
/// @notice Deposit an ERC-20 token. The commitment is Poseidon(nullifier, secret),
/// computed client-side using circomlibjs.
function depositERC20(
address _token,
uint256 _amount,
uint256 _deadline,
bytes32 _commitment
)
external
whenNonZeroAddress(_token)
whenNonZeroAmount(_amount)
whenValidDeadline(_deadline)
whenValidCommitment(_commitment)
returns (uint256 id)
{
id = _createDeposit(
msg.sender,
_token,
_amount,
_deadline,
_commitment
);
totalReservedERC20[_token] += _amount;
_pullERC20(
_token,
msg.sender,
_amount
);
emit Deposited(
id,
msg.sender,
_token, _amount,
_deadline,
_commitment
);
}
// ── Bulk Deposits ────────────────────────────────────────────────────
/// @notice Create multiple ETH ZK deposit links in a single transaction.
/// @param _deadlines Per-link expiry timestamps (length N)
/// @param _commitments Per-link Poseidon(nullifier, secret) commitments (length N)
function bulkDepositETH(
uint256[] calldata _deadlines,
bytes32[] calldata _commitments
)
external
payable
nonReentrant
returns (uint256[] memory ids)
{
uint256 n = _commitments.length;
_requireNonEmptyArray(n);
_requireArrayNotTooLarge(
n,
MAX_BULK_SIZE
);
_requireArrayLengthsMatch(
_deadlines.length,
n
);
_requireNonZeroAmount(
msg.value
);
if (msg.value % n != 0) {
revert UnEvenETHSplit();
}
uint256 amountEach = msg.value / n;
ids = new uint256[](n);
for (uint256 i; i < n; ++i) {
_requireValidDeadline(
_deadlines[i],
MAX_DEADLINE_DURATION
);
_requireValidCommitment(
_commitments[i]
);
uint256 id = _createDeposit(
msg.sender,
ZERO_ADDRESS,
amountEach,
_deadlines[i],
_commitments[i]
);
ids[i] = id;
emit Deposited(
id,
msg.sender,
ZERO_ADDRESS,
amountEach,
_deadlines[i],
_commitments[i]
);
}
totalReservedETH += msg.value;
}
/// @notice Create multiple ERC-20 ZK deposit links in a single transaction.
/// @param _token ERC-20 token address
/// @param _amountEach Token amount per link (caller approves amountEach * N total)
/// @param _deadlines Per-link expiry timestamps (length N)
/// @param _commitments Per-link Poseidon(nullifier, secret) commitments (length N)
function bulkDepositERC20(
address _token,
uint256 _amountEach,
uint256[] calldata _deadlines,
bytes32[] calldata _commitments
)
external
nonReentrant
whenNonZeroAddress(_token)
whenNonZeroAmount(_amountEach)
returns (uint256[] memory ids)
{
uint256 n = _commitments.length;
_requireNonEmptyArray(n);
_requireArrayNotTooLarge(
n,
MAX_BULK_SIZE
);
_requireArrayLengthsMatch(
_deadlines.length,
n
);
ids = new uint256[](n);
for (uint256 i; i < n; ++i) {
_requireValidDeadline(
_deadlines[i],
MAX_DEADLINE_DURATION
);
_requireValidCommitment(
_commitments[i]
);
uint256 id = _createDeposit(
msg.sender,
_token,
_amountEach,
_deadlines[i],
_commitments[i]
);
ids[i] = id;
emit Deposited(
id,
msg.sender,
_token,
_amountEach,
_deadlines[i],
_commitments[i]
);
}
uint256 totalAmount = _amountEach
* n;
totalReservedERC20[_token] += totalAmount;
_pullERC20(
_token,
msg.sender,
totalAmount
);
}
// ── Single Claim ──────────────────────────────────────────────────────
/// @notice Claim a ZK anonymous deposit in a single transaction.
///
/// @param _depositId The deposit to claim
/// @param _nullifierHash Poseidon(nullifier, depositId, chainId) — prevents double-spend,
/// binds the proof to this deposit and this chain
/// @param _recipient Address to receive funds (must match the value in the proof)
/// @param _proofA Groth16 proof component A [2]
/// @param _proofB Groth16 proof component B [2][2]
/// @param _proofC Groth16 proof component C [2]
///
/// @dev Public signals passed to the verifier (must match circuit order):
/// [0] = depositCommitment (from on-chain storage)
/// [1] = nullifierHash (Poseidon(nullifier, depositId, chainId))
/// [2] = recipient (uint160, provided by caller)
/// [3] = depositId (the deposit being claimed)
/// [4] = chainId (block.chainid — prevents cross-chain replay)
function claimZK(
uint256 _depositId,
bytes32 _nullifierHash,
address _recipient,
uint256[2] calldata _proofA,
uint256[2][2] calldata _proofB,
uint256[2] calldata _proofC
)
external
nonReentrant
{
_claimOne(
_depositId,
_nullifierHash,
_recipient,
_proofA,
_proofB,
_proofC
);
}
// ── Reclaim (depositor, after expiry) ────────────────────────────────
function withdraw(
uint256 _depositId
)
external
nonReentrant
{
_withdrawOne(
_depositId
);
}
function bulkWithdraw(
uint256[] calldata _depositIds
)
external
nonReentrant
{
uint256 n = _depositIds.length;
_requireNonEmptyArray(n);
_requireArrayNotTooLarge(
n,
MAX_BULK_SIZE
);
for (uint256 i; i < n; ++i) {
_withdrawOne(
_depositIds[i]
);
}
}
// ── Views ─────────────────────────────────────────────────────────────
/// @notice Returns all deposit IDs created by `depositor`.
/// For depositors with many links, prefer getDepositorIdsPaginated.
function getDepositorIds(
address _depositor
)
external
view
returns (uint256[] memory)
{
return depositorIds[_depositor];
}
/// @notice Paginated view of deposit IDs for a depositor.
/// @param _depositor Address to query
/// @param _offset Index to start from (0-based)
/// @param _limit Maximum number of IDs to return
/// @return page Slice of deposit IDs
/// @return total Total number of deposits for this depositor
function getDepositorIdsPaginated(
address _depositor,
uint256 _offset,
uint256 _limit
)
external
view
returns (
uint256[] memory page,
uint256 total
)
{
uint256[] storage all = depositorIds[
_depositor
];
total = all.length;
if (_offset >= total || _limit == 0) {
return (new uint256[](0), total);
}
uint256 end = _offset + _limit > total
? total
: _offset + _limit;
page = new uint256[](
end - _offset
);
for (uint256 i; i < page.length; ++i) {
page[i] = all[_offset + i];
}
}
// ── Admin ─────────────────────────────────────────────────────────────
function setFeeRate(
uint16 _newRateBps
)
external
onlyRole(ADMIN_ROLE)
{
_requireMaxFeeBps(
_newRateBps,
MAX_FEE_BPS
);
feeRateBps = _newRateBps;
emit FeeRateUpdated(
_newRateBps
);
}
function setFeeJar(
address _newJar
)
external
onlyRole(ADMIN_ROLE)
{
_requireValidFeeJar(
_newJar,
ZERO_ADDRESS,
address(this)
);
feeJar = _newJar;
emit FeeJarUpdated(
_newJar
);
}
function claimETHFees()
external
{
uint256 amount = accumulatedETHFees;
if (amount == 0) {
return;
}
accumulatedETHFees = 0;
(bool ok, ) = feeJar.call{
value: amount
}("");
if (!ok) {
revert SweepFailed();
}
emit FeesClaimed(
ZERO_ADDRESS,
amount
);
}
function claimERC20Fees(
address _token
)
external
{
uint256 amount = accumulatedERC20Fees[
_token
];
if (amount == 0) {
return;
}
accumulatedERC20Fees[_token] = 0;
IERC20(_token).safeTransfer(
feeJar,
amount
);
emit FeesClaimed(
_token,
amount
);
}
function sweepLooseETH()
external
onlyRole(ADMIN_ROLE)
{
uint256 loose = address(this).balance
- totalReservedETH
- accumulatedETHFees;
if (loose == 0) {
return;
}
(bool ok, ) = feeJar.call{
value: loose
}("");
if (!ok) {
revert SweepFailed();
}
emit LooseFundsSwept(
ZERO_ADDRESS,
loose
);
}
/// @notice Sweep ERC-20 tokens sent directly to the contract (not via deposit) to feeJar.
function sweepLooseERC20(
address _token
)
external
onlyRole(ADMIN_ROLE)
{
uint256 contractBal = IERC20(_token).balanceOf(
address(this)
);
uint256 loose = contractBal
- totalReservedERC20[_token]
- accumulatedERC20Fees[_token];
if (loose == 0) return;
IERC20(_token).safeTransfer(
feeJar,
loose
);
emit LooseFundsSwept(
_token,
loose
);
}
// ── Internal ──────────────────────────────────────────────────────────
function _createDeposit(
address _depositor,
address _token,
uint256 _amount,
uint256 _deadline,
bytes32 _commitment
)
internal
returns (uint256 id)
{
id = nextId++;
ZKDeposit storage dep = deposits[id];
dep.amount = _amount;
dep.commitment = _commitment;
dep.depositor = _depositor;
dep.deadline = uint64(_deadline);
dep.lockedFeeBps = feeRateBps;
dep.token = _token;
depositorIds[_depositor].push(id);
}
function _claimOne(
uint256 _depositId,
bytes32 _nullifierHash,
address _recipient,
uint256[2] calldata _proofA,
uint256[2][2] calldata _proofB,
uint256[2] calldata _proofC
)
internal
{
_requireNullifierNotSpent(
spentNullifiers[
_nullifierHash
]
);
ZKDeposit storage dep = deposits[
_depositId
];
uint256 amount = dep.amount;
_requireDepositExists(
dep.depositor,
ZERO_ADDRESS
);
_requireNonZeroAmount(
amount
);
_requireNotClaimed(
dep.claimed
);
_requireNotExpired(
dep.deadline
);
uint256[5] memory pubSignals = [
uint256(dep.commitment),
uint256(_nullifierHash),
uint256(uint160(_recipient)),
_depositId,
block.chainid
];
if (verifier.verifyProof(
_proofA,
_proofB,
_proofC,
pubSignals
) == false) {
revert InvalidProof();
}
spentNullifiers[_nullifierHash] = true;
dep.claimed = true;
address tokenAddr = dep.token;
(
uint256 payout,
uint256 fee
) = _calculateFee(
amount,
dep.lockedFeeBps
);
if (tokenAddr == ZERO_ADDRESS) {
totalReservedETH -= amount;
if (fee != 0) {
accumulatedETHFees += fee;
}
} else {
totalReservedERC20[tokenAddr] -= amount;
if (fee != 0) {
accumulatedERC20Fees[tokenAddr] += fee;
}
}
_transfer(
tokenAddr,
_recipient,
payout
);
emit Claimed(
_depositId,
_recipient,
payout,
fee,
_nullifierHash
);
}
function _withdrawOne(
uint256 _depositId
)
internal
{
ZKDeposit storage dep = deposits[
_depositId
];
_requireDepositExists(
dep.depositor,
ZERO_ADDRESS
);
_requireDepositor(
dep.depositor,
msg.sender
);
_requireNotClaimed(
dep.claimed
);
_requireExpired(
dep.deadline
);
dep.claimed = true;
uint256 amount = dep.amount;
address tokenAddr = dep.token;
if (tokenAddr == ZERO_ADDRESS) {
totalReservedETH -= amount;
} else {
totalReservedERC20[tokenAddr] -= amount;
}
_transfer(
tokenAddr,
msg.sender,
amount
);
emit Withdrawn(
_depositId,
msg.sender
);
}
function _pullERC20(
address _token,
address _from,
uint256 _amount
)
internal
{
_requireNonZeroAddress(
_token,
ZERO_ADDRESS
);
_requireNonZeroAmount(
_amount
);
uint256 balBefore = IERC20(_token).balanceOf(
address(this)
);
IERC20(_token).safeTransferFrom(
_from,
address(this),
_amount
);
if (IERC20(_token).balanceOf(address(this)) != balBefore + _amount) {
revert FeeOnTransferNotSupported();
}
}
function _transfer(
address _token,
address _to,
uint256 _amount
)
internal
{
if (_token == ZERO_ADDRESS) {
(bool ok, ) = _to.call{
value: _amount
}("");
if (ok == false) revert TransferFailed(
_to,
_amount
);
} else {
IERC20(_token).safeTransfer(
_to,
_amount
);
}
}
receive() external payable {}
}
contract/IGroth16Verifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/**
* @title IGroth16Verifier
* @notice Interface for the auto-generated Groth16 Solidity verifier produced by snarkjs.
*
* Generate the concrete implementation by running:
* cd circuits && ./build.sh
*
* The generated contract will be written to contract/Groth16Verifier.sol.
*
* Public signal layout (must match circuit output order):
* _pubSignals[0] = depositCommitment (Poseidon(nullifier, secret))
* _pubSignals[1] = nullifierHash (Poseidon(nullifier, depositId, chainId))
* _pubSignals[2] = recipient (uint160 of recipient address)
* _pubSignals[3] = depositId (the specific deposit this proof is bound to)
* _pubSignals[4] = chainId (EVM chain ID — prevents cross-chain replay)
*/
interface IGroth16Verifier {
function verifyProof(
uint256[2] calldata _pA,
uint256[2][2] calldata _pB,
uint256[2] calldata _pC,
uint256[5] memory _pubSignals
) external view returns (bool);
}
contract/ZKPaymentLinkHelpers.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title ZKPaymentLinkHelpers
/// @notice Base contract with validation and fee helpers; inherit to use without prefix.
/// @dev All functions revert with custom errors. Derived contract supplies constants (ZERO_ADDRESS, etc.).
abstract contract ZKPaymentLinkHelpers {
// ── Errors (consistent revert data) ────────────────────────────────────
error ZeroAddress();
error ZeroAmount();
error InvalidDeadline();
error InvalidCommitment();
error DepositNotFound();
error AlreadyClaimed();
error Expired();
error NotExpired();
error NotDepositor();
error NullifierSpent();
error MaxFeeExceeded();
error ArrayLengthMismatch();
error EmptyArray();
error ArrayTooLarge();
// ── Events ──────────────────────────────────────────────────────────────
event Deposited(
uint256 indexed id,
address indexed depositor,
address token,
uint256 amount,
uint256 deadline,
bytes32 commitment
);
event Claimed(
uint256 indexed id,
address indexed recipient,
uint256 amount,
uint256 feeTaken,
bytes32 nullifierHash
);
event Withdrawn(
uint256 indexed id,
address indexed depositor
);
event FeeRateUpdated(
uint16 newRateBps
);
event FeeJarUpdated(
address newJar
);
event FeesClaimed(
address indexed token,
uint256 amount
);
event LooseFundsSwept(
address indexed token,
uint256 amount
);
// ── Validation (pure) ───────────────────────────────────────────────────
function _requireNonZeroAddress(
address _addr,
address _zero
)
internal
pure
{
if (_addr == _zero) {
revert ZeroAddress();
}
}
function _requireNonZeroAmount(
uint256 _amount
)
internal
pure
{
if (_amount == 0) {
revert ZeroAmount();
}
}
function _requireValidCommitment(
bytes32 _commitment
)
internal
pure
{
if (_commitment == bytes32(0)) {
revert InvalidCommitment();
}
}
function _requireNonEmptyArray(
uint256 _length
)
internal
pure
{
if (_length == 0) {
revert EmptyArray();
}
}
function _requireArrayLengthsMatch(
uint256 _a,
uint256 _b
)
internal
pure
{
if (_a != _b) {
revert ArrayLengthMismatch();
}
}
function _requireArrayNotTooLarge(
uint256 _length,
uint256 _max
)
internal
pure
{
if (_length > _max) {
revert ArrayTooLarge();
}
}
function _requireValidFeeJar(
address _jar,
address _zero,
address _self
)
internal
pure
{
if (_jar == _zero || _jar == _self) {
revert ZeroAddress();
}
}
function _requireMaxFeeBps(
uint16 _bps,
uint16 _max
)
internal
pure
{
if (_bps > _max) {
revert MaxFeeExceeded();
}
}
function _requireDepositExists(
address _depositor,
address _zero
)
internal
pure
{
if (_depositor == _zero) {
revert DepositNotFound();
}
}
function _requireNotClaimed(
bool _claimed
)
internal
pure
{
if (_claimed) {
revert AlreadyClaimed();
}
}
function _requireNullifierNotSpent(
bool _spent
)
internal
pure
{
if (_spent) {
revert NullifierSpent();
}
}
function _requireDepositor(
address _depositor,
address _sender
)
internal
pure
{
if (_depositor != _sender) {
revert NotDepositor();
}
}
// ── Validation (view: use block.timestamp) ─────────────────────────────
function _requireValidDeadline(
uint256 _deadline,
uint256 _maxDuration
)
internal
view
{
if (
_deadline <= block.timestamp ||
_deadline > block.timestamp + _maxDuration
) {
revert InvalidDeadline();
}
}
function _requireNotExpired(
uint256 _deadline
)
internal
view
{
if (block.timestamp > _deadline) {
revert Expired();
}
}
function _requireExpired(
uint256 _deadline
)
internal
view
{
if (block.timestamp <= _deadline) {
revert NotExpired();
}
}
// ── Pure helpers ───────────────────────────────────────────────────────
/// @return payout Amount after fee
/// @return fee Fee amount (0 if _lockedFeeBps is 0)
function _calculateFee(
uint256 _amount,
uint16 _lockedFeeBps
)
internal
pure
returns (uint256 payout, uint256 fee)
{
if (_lockedFeeBps == 0) {
return (_amount, 0);
}
fee = _amount
* _lockedFeeBps
/ 10_000;
payout = _amount
- fee;
}
}
node_modules/@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
node_modules/@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
node_modules/@openzeppelin/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);
}
node_modules/@openzeppelin/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";
node_modules/@openzeppelin/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";
node_modules/@openzeppelin/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);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
node_modules/@openzeppelin/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": 99999,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.