Verified contractExactMIT
PoolTreasury
Address0xe4d41dfbd858bf0a0b8a5847d6ab11d7cde7442e
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,178,719
- Creation transaction
- 0xa56aea8e9c…26b9840bec
5 files
- project/contracts/treasury/PoolTreasury.solmain14.8 KB
- npm/@openzeppelin/[email protected]/token/ERC721/IERC721.sol4.93 KB
- npm/@openzeppelin/[email protected]/utils/ReentrancyGuard.sol4.77 KB
- npm/@openzeppelin/[email protected]/utils/StorageSlot.sol4.18 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
project/contracts/treasury/PoolTreasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @title PoolTreasury
* @notice Autonomous treasury for the MADE ecosystem.
*
* @dev CRITICAL: This contract has NO admin keys. NO owner. NO pause.
* NO emergency withdraw. Once deployed, it runs forever autonomously.
*
* Funded purely by:
* 1. Stamp fees from CreationRegistry ($0.20 per ring)
*
* Outflows:
* 1. Monthly distribution to active creators (80% of balance)
* 2. Batch caller rewards (0.001 ETH per processBatch call)
*
* Distribution formula:
* "Your share = (rings you added this month / total rings this month) × distributable"
*
* Dust tracking (Fix: precision issues):
* Rounding errors from integer division are tracked in `undistributedDust`.
* Dust rolls into the next month's distribution instead of being lost.
*
* Batch caller reward (Fix 6):
* Anyone who calls CreationRegistry.processBatch() gets paid 0.001 ETH.
* This ensures the system runs forever even without the team.
*
* Uses pull pattern: sets claimable amounts, doesn't push ETH.
* Protected by ReentrancyGuard (Fix 2).
*/
contract PoolTreasury is ReentrancyGuard {
// ─────────────────────────────────────────────────────────────────────────
// Constants
// ─────────────────────────────────────────────────────────────────────────
/// @notice Time between distributions
uint256 public constant DISTRIBUTION_INTERVAL = 30 days;
/// @notice Percentage of pool distributed each month
uint256 public constant DISTRIBUTION_PERCENTAGE = 80;
/// @notice ETH reward for batch callers (Fix 6)
uint256 public constant BATCH_CALLER_REWARD = 0.001 ether;
// ─────────────────────────────────────────────────────────────────────────
// State Variables
// ─────────────────────────────────────────────────────────────────────────
/// @notice MADECore contract address
address public immutable madeCore;
/// @notice CreationRegistry contract address
address public immutable registryContract;
/// @notice Timestamp of last distribution
uint256 public lastDistributionTimestamp;
/// @notice Total ETH ever distributed
uint256 public totalDistributed;
/// @notice Current month counter
uint256 public currentMonth;
/// @notice Accumulated rounding dust from distributions
uint256 public undistributedDust;
/// @notice Monthly ring counts per token: month => tokenId => rings added
mapping(uint256 => mapping(uint256 => uint256)) public monthlyRings;
/// @notice Total rings added in a month
mapping(uint256 => uint256) public monthlyTotalRings;
/// @notice Active participant token IDs per month
mapping(uint256 => uint256[]) public monthlyParticipants;
/// @notice Dedup: whether token is already a participant this month
mapping(uint256 => mapping(uint256 => bool)) private _isParticipant;
/// @notice Total earnings per holder address
mapping(address => uint256) public totalEarnings;
/// @notice Already claimed per holder
mapping(address => uint256) public claimedEarnings;
// ─────────────────────────────────────────────────────────────────────────
// Events
// ─────────────────────────────────────────────────────────────────────────
event FundsReceived(address indexed sender, uint256 amount);
event RingsRecorded(uint256 indexed tokenId, uint256 month, uint256 count);
event DistributionCompleted(uint256 indexed month, uint256 amount, uint256 recipientCount);
event EarningsClaimed(address indexed holder, uint256 amount);
event BatchCallerRewarded(address indexed caller, uint256 amount);
// ─────────────────────────────────────────────────────────────────────────
// Errors
// ─────────────────────────────────────────────────────────────────────────
error OnlyRegistry();
error DistributionNotReady();
error NothingToClaim();
error TransferFailed();
error InsufficientBalance();
// ─────────────────────────────────────────────────────────────────────────
// Constructor
// ─────────────────────────────────────────────────────────────────────────
constructor(address _madeCore, address _registry) {
madeCore = _madeCore;
registryContract = _registry;
lastDistributionTimestamp = block.timestamp;
}
// ─────────────────────────────────────────────────────────────────────────
// Receive ETH
// ─────────────────────────────────────────────────────────────────────────
receive() external payable {
emit FundsReceived(msg.sender, msg.value);
}
// ─────────────────────────────────────────────────────────────────────────
// Ring Recording
// ─────────────────────────────────────────────────────────────────────────
/**
* @notice Record ring additions for monthly distribution.
* @dev Called by CreationRegistry during batch processing.
* @param tokenId The MADE token that added rings.
* @param count Number of rings added.
*/
function recordRings(uint256 tokenId, uint256 count) external {
if (msg.sender != registryContract) revert OnlyRegistry();
uint256 month = currentMonth;
monthlyRings[month][tokenId] += count;
monthlyTotalRings[month] += count;
if (!_isParticipant[month][tokenId]) {
_isParticipant[month][tokenId] = true;
monthlyParticipants[month].push(tokenId);
}
emit RingsRecorded(tokenId, month, count);
}
// ─────────────────────────────────────────────────────────────────────────
// Batch Caller Reward — Fix 6
// ─────────────────────────────────────────────────────────────────────────
/**
* @notice Pay the batch caller reward. Only callable by CreationRegistry.
* @dev Best-effort: if treasury doesn't have enough ETH, does not revert.
* The batch processing itself is more important than the reward.
* @param caller The address to pay the reward to.
*/
function payBatchCallerReward(address caller) external nonReentrant {
if (msg.sender != registryContract) revert OnlyRegistry();
if (address(this).balance >= BATCH_CALLER_REWARD) {
(bool sent,) = caller.call{value: BATCH_CALLER_REWARD}("");
if (sent) {
emit BatchCallerRewarded(caller, BATCH_CALLER_REWARD);
}
// If send fails, silently continue — reward is best-effort
}
}
// ─────────────────────────────────────────────────────────────────────────
// Distribution — Fix: Dust tracking
// ─────────────────────────────────────────────────────────────────────────
/**
* @notice Execute monthly distribution.
* @dev Callable by anyone after DISTRIBUTION_INTERVAL elapsed.
*
* Distribution = 80% of (current balance + accumulated dust).
* Dust = distributable - sum(all shares). Rolled into next month.
*
* Uses pull pattern: credits totalEarnings[owner], doesn't push ETH.
*/
function distribute() external nonReentrant {
if (block.timestamp < lastDistributionTimestamp + DISTRIBUTION_INTERVAL) {
revert DistributionNotReady();
}
uint256 month = currentMonth;
uint256 totalRings = monthlyTotalRings[month];
// No activity this month: advance and return
if (totalRings == 0) {
lastDistributionTimestamp = block.timestamp;
currentMonth++;
emit DistributionCompleted(month, 0, 0);
return;
}
// Calculate distributable: 80% of balance + accumulated dust
uint256 poolBalance = address(this).balance;
uint256 distributable = ((poolBalance + undistributedDust) * DISTRIBUTION_PERCENTAGE) / 100;
uint256 recipientCount = monthlyParticipants[month].length;
uint256 actualDistributed = 0;
// Calculate each participant's share
for (uint256 i = 0; i < recipientCount;) {
uint256 tokenId = monthlyParticipants[month][i];
uint256 tokenRings = monthlyRings[month][tokenId];
uint256 share = (distributable * tokenRings) / totalRings;
actualDistributed += share;
// Look up token owner to credit earnings
(bool success, bytes memory data) = madeCore.staticcall(
abi.encodeWithSignature("ownerOf(uint256)", tokenId)
);
if (success && data.length >= 32) {
address owner = abi.decode(data, (address));
totalEarnings[owner] += share;
}
unchecked { ++i; }
}
// Track dust: rounding errors roll into next month
undistributedDust = distributable - actualDistributed;
totalDistributed += actualDistributed;
lastDistributionTimestamp = block.timestamp;
currentMonth++;
emit DistributionCompleted(month, actualDistributed, recipientCount);
}
// ─────────────────────────────────────────────────────────────────────────
// Claims — Fix 2: ReentrancyGuard
// ─────────────────────────────────────────────────────────────────────────
/**
* @notice Claim accumulated pool earnings.
* @dev Pull pattern. Protected by ReentrancyGuard.
*/
function claim() external nonReentrant {
uint256 unclaimed = totalEarnings[msg.sender] - claimedEarnings[msg.sender];
if (unclaimed == 0) revert NothingToClaim();
// CEI: update state before external call
claimedEarnings[msg.sender] = totalEarnings[msg.sender];
(bool success,) = msg.sender.call{value: unclaimed}("");
if (!success) revert TransferFailed();
emit EarningsClaimed(msg.sender, unclaimed);
}
// ─────────────────────────────────────────────────────────────────────────
// View Functions
// ─────────────────────────────────────────────────────────────────────────
function getCurrentPoolSize() external view returns (uint256) {
return address(this).balance;
}
function getNextDistributionDate() external view returns (uint256) {
return lastDistributionTimestamp + DISTRIBUTION_INTERVAL;
}
function getUnclaimedEarnings(address holder) external view returns (uint256) {
return totalEarnings[holder] - claimedEarnings[holder];
}
function getCurrentMonthParticipants() external view returns (uint256) {
return monthlyParticipants[currentMonth].length;
}
function getEarnings(address holder) external view returns (
uint256 total,
uint256 claimed,
uint256 unclaimed
) {
total = totalEarnings[holder];
claimed = claimedEarnings[holder];
unclaimed = total - claimed;
}
function getPoolInfo() external view returns (
uint256 totalBalance,
uint256 _totalDistributed,
uint256 lastDistribution,
uint256 nextDistribution,
uint256 dust
) {
totalBalance = address(this).balance;
_totalDistributed = totalDistributed;
lastDistribution = lastDistributionTimestamp;
nextDistribution = lastDistributionTimestamp + DISTRIBUTION_INTERVAL;
dust = undistributedDust;
}
}
npm/@openzeppelin/[email protected]/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
npm/@openzeppelin/[email protected]/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;
}
}
npm/@openzeppelin/[email protected]/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
}
}
}
npm/@openzeppelin/[email protected]/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,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.