Verified contractPartialMIT
PoidhV3
Address0xe731dfadbff20542e10d09d26fc71445c70d4232
- Balance
1.466141 ETH
- Transactions
691
- Compiler
solc 0.8.24
- Same code
1 more contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,088,349
- Creation transaction
- 0x5f0ed49370…a8ab64ff22
6 files
- src/PoidhV3.solmain29.76 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- src/interfaces/IPoidhClaimNFT.sol697 B
src/PoidhV3.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IPoidhClaimNFT} from "./interfaces/IPoidhClaimNFT.sol";
/// @title PoidhV3
/// @notice POIDH bounty protocol (solo + open bounties) with weighted voting and pull-payments.
/// @dev Security design goals:
/// - All ETH exits are pull-based via `pendingWithdrawals` + `withdraw()` / `withdrawTo()`.
/// - Claim NFTs are escrowed in this contract and transferred with `transferFrom` (no callbacks).
/// - All external, state-changing entrypoints are `nonReentrant`.
contract PoidhV3 is ReentrancyGuard {
/// =========================
/// === Constants / Config ===
/// =========================
uint256 public constant FEE_BPS = 250; // 2.5%
uint256 public constant BPS_DENOM = 10_000;
uint256 public immutable MIN_BOUNTY_AMOUNT;
uint256 public immutable MIN_CONTRIBUTION;
/// @notice Max participant slots for an open bounty (issuer included at slot 0).
uint256 public constant MAX_PARTICIPANTS = 150;
/// @notice Voting duration for open bounty votes.
uint256 public votingPeriod = 2 days;
/// @notice Fee recipient (credited via pull withdrawals).
address public immutable treasury;
/// @notice Claim NFT contract used for claim escrow and transfers.
IPoidhClaimNFT public immutable poidhNft;
/// ==================
/// === Data Types ===
/// ==================
struct Bounty {
uint256 id;
address issuer;
string name;
string description;
uint256 amount;
address claimer; // 0 = active, issuer = cancelled/closed, other = accepted
uint256 createdAt;
uint256 claimId; // accepted claim id (0 if none)
}
struct Claim {
uint256 id;
address issuer;
uint256 bountyId;
address bountyIssuer;
string name;
string description;
uint256 createdAt;
bool accepted;
}
struct Votes {
uint256 yes;
uint256 no;
uint256 deadline;
}
/// ======================
/// === Storage / State ===
/// ======================
Bounty[] public bounties;
Claim[] public claims;
uint256 public bountyCounter;
uint256 public claimCounter; // claimId 0 reserved sentinel
mapping(address user => uint256[] bountyIds) public userBounties;
mapping(address user => uint256[] claimIds) public userClaims;
mapping(uint256 bountyId => uint256[] claimIds) public bountyClaims;
/// @notice Open bounty participants (issuer always at index 0).
mapping(uint256 bountyId => address[] participantAddresses) public participants;
/// @notice Contribution amounts aligned with `participants[bountyId]`.
mapping(uint256 bountyId => uint256[] participantContributionAmounts) public participantAmounts;
/// @notice Stack of reusable participant slot indices (vacated slots) for each bounty.
/// @dev Prevents permanent MAX_PARTICIPANTS exhaustion when people withdraw.
mapping(uint256 bountyId => uint256[] freeSlotIndices) private freeParticipantSlots;
/// @notice contributor => (index + 1) in participants for O(1) lookup.
/// @dev Zero means "no active slot currently assigned".
mapping(uint256 bountyId => mapping(address contributor => uint256 indexPlus1)) private
contributorIndexPlus1;
/// @notice Whether an open bounty has EVER had an external contributor (non-issuer).
mapping(uint256 bountyId => bool hadExternalContributor) public everHadExternalContributor;
/// @notice Current claim being voted on (0 if none).
mapping(uint256 bountyId => uint256 claimId) public bountyCurrentVotingClaim;
/// @notice Vote totals + deadline for the active round.
mapping(uint256 bountyId => Votes votes) public bountyVotingTracker;
/// @notice Vote round id increments each time voting starts on a bounty.
mapping(uint256 bountyId => uint256 roundId) public voteRound;
/// @notice Voter => last round id they voted in for a bounty.
mapping(uint256 bountyId => mapping(address voter => uint256 roundId)) private lastVotedRound;
/// @notice Snapshotted weights at vote start (address => weight).
mapping(uint256 bountyId => mapping(address participant => uint256 weight)) public
voteWeightSnapshot;
/// @notice The round id that a snapshot entry belongs to.
/// @dev This fixes the "stale snapshot" issue: old weights cannot be reused in later rounds.
mapping(uint256 bountyId => mapping(address participant => uint256 roundId)) private
voteWeightSnapshotRound;
/// @notice Pull payment balances.
mapping(address account => uint256 amount) public pendingWithdrawals;
/// =================
/// === Events ===
/// =================
event BountyCreated(
uint256 indexed id,
address indexed issuer,
string title,
string description,
uint256 amount,
uint256 createdAt,
bool isOpenBounty,
uint256 round
);
event ClaimCreated(
uint256 indexed id,
address indexed issuer,
uint256 indexed bountyId,
address bountyIssuer,
string title,
string description,
uint256 createdAt,
string imageUri,
uint256 round
);
event ClaimAccepted(
uint256 indexed bountyId,
uint256 indexed claimId,
address indexed claimIssuer,
address bountyIssuer,
uint256 bountyAmount,
uint256 payout,
uint256 fee,
uint256 round
);
event BountyJoined(
uint256 indexed bountyId,
address indexed participant,
uint256 amount,
uint256 latestBountyBalance,
uint256 round
);
event BountyCancelled(uint256 indexed bountyId, address indexed issuer, uint256 issuerRefund, uint256 round);
event WithdrawFromOpenBounty(
uint256 indexed bountyId,
address indexed participant,
uint256 amount,
uint256 latestBountyAmount,
uint256 round
);
event Withdrawal(address indexed user, uint256 amount);
event WithdrawalTo(address indexed user, address indexed to, uint256 amount);
event VotingStarted(
uint256 indexed bountyId,
uint256 indexed claimId,
uint256 deadline,
uint256 issuerYesWeight,
uint256 round
);
event VoteCast(
address indexed voter,
uint256 indexed bountyId,
uint256 indexed claimId,
bool support,
uint256 weight,
uint256 round
);
event VotingResolved(
uint256 indexed bountyId, uint256 indexed claimId, bool passed, uint256 yes, uint256 no, uint256 round
);
event RefundClaimed(uint256 indexed bountyId, address indexed participant, uint256 amount, uint256 round);
/// =================
/// === Errors ===
/// =================
error NoEther();
error MinimumBountyNotMet();
error MinimumContributionNotMet();
error BountyNotFound();
error ClaimNotFound();
error VotingOngoing();
error VotingEnded();
error NoVotingPeriodSet();
error BountyClaimed();
error BountyClosed();
error NotOpenBounty();
error NotSoloBounty();
error WrongCaller();
error IssuerCannotClaim();
error IssuerCannotWithdraw();
error NotActiveParticipant();
error AlreadyVoted();
error ClaimAlreadyAccepted();
error NothingToWithdraw();
error TransferFailed();
error InsufficientBalance();
error MaxParticipantsReached();
error NotCancelledOpenBounty();
error VoteWouldPass();
error InvalidStartClaimIndex();
error ContractsCannotCreateBounties();
error InvalidTreasury(address treasury);
error InvalidPoidhNft(address poidhNft);
error InvalidWithdrawTo(address to);
error DirectEtherNotAccepted();
error InvalidMinBountyAmount(uint256 amount);
error InvalidMinContribution(uint256 amount);
/// =========================
/// === Internal Requires ===
/// =========================
function _requireBountyExists(uint256 bountyId) internal view {
if (bountyId >= bountyCounter) revert BountyNotFound();
}
function _requireBountyNotFinalized(uint256 bountyId) internal view {
Bounty storage bounty = bounties[bountyId];
if (bounty.claimer == bounty.issuer) revert BountyClosed();
if (bounty.claimer != address(0)) revert BountyClaimed();
}
/// @dev Active = exists, not finalized, and no active vote.
function _requireActiveBounty(uint256 bountyId) internal view {
if (bountyId >= bountyCounter) revert BountyNotFound();
if (bountyCurrentVotingClaim[bountyId] != 0) revert VotingOngoing();
Bounty storage bounty = bounties[bountyId];
if (bounty.claimer == bounty.issuer) revert BountyClosed();
if (bounty.claimer != address(0)) revert BountyClaimed();
}
function _requireOpenBounty(uint256 bountyId) internal view {
if (participants[bountyId].length == 0) revert NotOpenBounty();
}
/// @return currentClaim the claim id currently in voting
function _requireVoteActive(uint256 bountyId) internal view returns (uint256 currentClaim) {
currentClaim = bountyCurrentVotingClaim[bountyId];
if (currentClaim == 0) revert NoVotingPeriodSet();
Votes memory v = bountyVotingTracker[bountyId];
if (block.timestamp >= v.deadline) revert VotingEnded();
}
/// =====================
/// === Initialization ===
/// =====================
/// @param _poidhNft The claim NFT contract address.
/// @param _treasury Fee recipient (credited via pull withdrawals).
/// @param _startClaimIndex The first real claim id; must be `>= 1` (claim id `0` is reserved).
/// @param _minBountyAmount Minimum bounty value for creation.
/// @param _minContribution Minimum contribution for joining open bounties.
constructor(
address _poidhNft,
address _treasury,
uint256 _startClaimIndex,
uint256 _minBountyAmount,
uint256 _minContribution
) {
if (_treasury == address(0)) revert InvalidTreasury(_treasury);
if (_poidhNft == address(0) || _poidhNft.code.length == 0) revert InvalidPoidhNft(_poidhNft);
if (_startClaimIndex == 0) revert InvalidStartClaimIndex();
if (_minBountyAmount == 0) revert InvalidMinBountyAmount(_minBountyAmount);
if (_minContribution == 0) revert InvalidMinContribution(_minContribution);
poidhNft = IPoidhClaimNFT(_poidhNft);
treasury = _treasury;
MIN_BOUNTY_AMOUNT = _minBountyAmount;
MIN_CONTRIBUTION = _minContribution;
claimCounter = _startClaimIndex;
for (uint256 i = 0; i < _startClaimIndex; i++) {
claims.push(
Claim({
id: i,
issuer: address(0),
bountyId: 0,
bountyIssuer: address(0),
name: "",
description: "",
createdAt: 0,
accepted: false
})
);
}
}
/// =========================
/// === Pull withdrawals ===
/// =========================
/// @notice Withdraw the caller's pending balance to `msg.sender`.
/// @dev Uses CEI and `nonReentrant` to harden against reentrancy during ETH receive hooks.
function withdraw() external nonReentrant {
uint256 amount = pendingWithdrawals[msg.sender];
if (amount == 0) revert NothingToWithdraw();
pendingWithdrawals[msg.sender] = 0;
(bool ok,) = msg.sender.call{value: amount}("");
if (!ok) revert TransferFailed();
emit Withdrawal(msg.sender, amount);
}
/// @notice Withdraw the caller's pending balance to `to`.
/// @dev Useful when `msg.sender` is a contract that cannot receive ETH directly.
/// Emits both `Withdrawal` (legacy/indexer compatibility) and `WithdrawalTo` (destination).
function withdrawTo(address payable to) external nonReentrant {
if (to == address(0)) revert InvalidWithdrawTo(to);
uint256 amount = pendingWithdrawals[msg.sender];
if (amount == 0) revert NothingToWithdraw();
pendingWithdrawals[msg.sender] = 0;
(bool ok,) = to.call{value: amount}("");
if (!ok) revert TransferFailed();
emit Withdrawal(msg.sender, amount);
emit WithdrawalTo(msg.sender, to, amount);
}
/// =======================
/// === Bounty Creation ===
/// =======================
/// @notice Create a solo bounty (issuer-only funding; issuer accepts a claim directly).
/// @dev EOAs only (`msg.sender == tx.origin`) to prevent contract issuers becoming NFT sinks.
function createSoloBounty(string calldata name, string calldata description)
external
payable
nonReentrant
{
if (msg.sender != tx.origin) revert ContractsCannotCreateBounties();
if (msg.value == 0) revert NoEther();
if (msg.value < MIN_BOUNTY_AMOUNT) revert MinimumBountyNotMet();
_createBounty(name, description, false);
}
/// @notice Create an open bounty (multiple contributors; claim acceptance uses voting).
/// @dev EOAs only (`msg.sender == tx.origin`) to prevent contract issuers becoming NFT sinks.
function createOpenBounty(string calldata name, string calldata description)
external
payable
nonReentrant
{
if (msg.sender != tx.origin) revert ContractsCannotCreateBounties();
if (msg.value == 0) revert NoEther();
if (msg.value < MIN_BOUNTY_AMOUNT) revert MinimumBountyNotMet();
uint256 bountyId = _createBounty(name, description, true);
participants[bountyId].push(msg.sender);
participantAmounts[bountyId].push(msg.value);
contributorIndexPlus1[bountyId][msg.sender] = 1;
}
/// @dev Internal bounty creation shared by solo + open bounties.
function _createBounty(
string calldata name,
string calldata description,
bool isOpenBounty
)
internal
returns (uint256 bountyId)
{
bountyId = bountyCounter;
bounties.push(
Bounty({
id: bountyId,
issuer: msg.sender,
name: name,
description: description,
amount: msg.value,
claimer: address(0),
createdAt: block.timestamp,
claimId: 0
})
);
userBounties[msg.sender].push(bountyId);
bountyCounter++;
emit BountyCreated(
bountyId, msg.sender, name, description, msg.value, block.timestamp, isOpenBounty, voteRound[bountyId]
);
}
/// =============================
/// === Open Bounty Funding ===
/// =============================
/// @notice Contribute ETH to an open bounty.
/// @dev Reverts while voting is active. Enforces `MIN_CONTRIBUTION` and `MAX_PARTICIPANTS`.
function joinOpenBounty(uint256 bountyId) external payable nonReentrant {
_requireActiveBounty(bountyId);
_requireOpenBounty(bountyId);
if (msg.value == 0) revert NoEther();
if (msg.value < MIN_CONTRIBUTION) revert MinimumContributionNotMet();
Bounty storage bounty = bounties[bountyId];
if (msg.sender == bounty.issuer) revert WrongCaller();
uint256 idxPlus1 = contributorIndexPlus1[bountyId][msg.sender];
if (idxPlus1 == 0) {
uint256 idx;
uint256[] storage freeSlots = freeParticipantSlots[bountyId];
if (freeSlots.length > 0) {
idx = freeSlots[freeSlots.length - 1];
freeSlots.pop();
participants[bountyId][idx] = msg.sender;
participantAmounts[bountyId][idx] = msg.value;
} else {
address[] storage p = participants[bountyId];
if (p.length >= MAX_PARTICIPANTS) revert MaxParticipantsReached();
p.push(msg.sender);
participantAmounts[bountyId].push(msg.value);
idx = p.length - 1;
}
contributorIndexPlus1[bountyId][msg.sender] = idx + 1;
} else {
uint256 idx = idxPlus1 - 1;
if (participants[bountyId][idx] != msg.sender) revert NotActiveParticipant();
participantAmounts[bountyId][idx] += msg.value;
}
everHadExternalContributor[bountyId] = true;
bounty.amount += msg.value;
emit BountyJoined(bountyId, msg.sender, msg.value, bounty.amount, voteRound[bountyId]);
}
/// @notice Withdraw the caller's entire contribution from an open bounty (credited to pending).
/// @dev Reverts while voting is active.
function withdrawFromOpenBounty(uint256 bountyId) external nonReentrant {
_requireActiveBounty(bountyId);
_requireOpenBounty(bountyId);
Bounty storage bounty = bounties[bountyId];
if (msg.sender == bounty.issuer) revert IssuerCannotWithdraw();
uint256 idxPlus1 = contributorIndexPlus1[bountyId][msg.sender];
if (idxPlus1 == 0) revert NotActiveParticipant();
uint256 idx = idxPlus1 - 1;
if (participants[bountyId][idx] != msg.sender) revert NotActiveParticipant();
uint256 amount = participantAmounts[bountyId][idx];
if (amount == 0) revert NotActiveParticipant();
participantAmounts[bountyId][idx] = 0;
participants[bountyId][idx] = address(0);
bounty.amount -= amount;
if (idx != 0) freeParticipantSlots[bountyId].push(idx);
contributorIndexPlus1[bountyId][msg.sender] = 0;
pendingWithdrawals[msg.sender] += amount;
emit WithdrawFromOpenBounty(bountyId, msg.sender, amount, bounty.amount, voteRound[bountyId]);
}
/// =================
/// === Cancellation ===
/// =================
/// @notice Cancel a solo bounty and credit the issuer refund to pending withdrawals.
function cancelSoloBounty(uint256 bountyId) external nonReentrant {
_requireActiveBounty(bountyId);
if (participants[bountyId].length != 0) revert NotSoloBounty();
Bounty storage bounty = bounties[bountyId];
if (msg.sender != bounty.issuer) revert WrongCaller();
uint256 amount = bounty.amount;
bounty.claimer = bounty.issuer;
bounty.amount = 0;
pendingWithdrawals[msg.sender] += amount;
emit BountyCancelled(bountyId, msg.sender, amount, voteRound[bountyId]);
}
/// @notice Cancel an open bounty in constant time; contributors must claim refunds themselves.
function cancelOpenBounty(uint256 bountyId) external nonReentrant {
_requireActiveBounty(bountyId);
_requireOpenBounty(bountyId);
Bounty storage bounty = bounties[bountyId];
if (msg.sender != bounty.issuer) revert WrongCaller();
bounty.claimer = bounty.issuer;
uint256 issuerAmount = participantAmounts[bountyId][0];
if (issuerAmount > 0) {
participantAmounts[bountyId][0] = 0;
participants[bountyId][0] = address(0);
bounty.amount -= issuerAmount;
pendingWithdrawals[bounty.issuer] += issuerAmount;
}
emit BountyCancelled(bountyId, msg.sender, issuerAmount, voteRound[bountyId]);
}
/// @notice Claim the caller's refund from a cancelled open bounty (credited to pending).
function claimRefundFromCancelledOpenBounty(uint256 bountyId) external nonReentrant {
_requireBountyExists(bountyId);
Bounty storage bounty = bounties[bountyId];
if (participants[bountyId].length == 0) revert NotOpenBounty();
if (bounty.claimer != bounty.issuer) revert NotCancelledOpenBounty();
uint256 idxPlus1 = contributorIndexPlus1[bountyId][msg.sender];
if (idxPlus1 == 0) revert NotActiveParticipant();
uint256 idx = idxPlus1 - 1;
if (participants[bountyId][idx] != msg.sender) revert NotActiveParticipant();
uint256 amount = participantAmounts[bountyId][idx];
if (amount == 0) revert NotActiveParticipant();
participantAmounts[bountyId][idx] = 0;
participants[bountyId][idx] = address(0);
bounty.amount -= amount;
if (idx != 0) freeParticipantSlots[bountyId].push(idx);
contributorIndexPlus1[bountyId][msg.sender] = 0;
pendingWithdrawals[msg.sender] += amount;
emit RefundClaimed(bountyId, msg.sender, amount, voteRound[bountyId]);
}
/// =====================
/// === Claim Creation ===
/// =====================
/// @notice Create a claim for a bounty and mint the claim NFT into escrow.
/// @dev Claims are minted to this contract via `PoidhClaimNFT.mintToEscrow` (no `_safeMint`).
function createClaim(
uint256 bountyId,
string calldata name,
string calldata description,
string calldata uri
) external nonReentrant {
_requireActiveBounty(bountyId);
address bountyIssuer = bounties[bountyId].issuer;
if (msg.sender == bountyIssuer) revert IssuerCannotClaim();
uint256 claimId = claimCounter;
uint256 round = voteRound[bountyId];
claims.push(
Claim({
id: claimId,
issuer: msg.sender,
bountyId: bountyId,
bountyIssuer: bountyIssuer,
name: name,
description: description,
createdAt: block.timestamp,
accepted: false
})
);
poidhNft.mintToEscrow(claimId, uri);
userClaims[msg.sender].push(claimId);
bountyClaims[bountyId].push(claimId);
claimCounter++;
emit ClaimCreated(
claimId,
msg.sender,
bountyId,
bountyIssuer,
name,
description,
block.timestamp,
uri,
round
);
}
/// =====================
/// === Voting (Open) ===
/// =====================
/// @notice Start a new vote round on an open bounty claim (issuer-only).
/// @dev Snapshots contribution weights at the moment voting starts; joins/withdrawals are blocked.
function submitClaimForVote(uint256 bountyId, uint256 claimId) external nonReentrant {
_requireActiveBounty(bountyId);
_requireOpenBounty(bountyId);
if (claimId >= claimCounter) revert ClaimNotFound();
Bounty memory bounty = bounties[bountyId];
if (msg.sender != bounty.issuer) revert WrongCaller();
Claim memory claim = claims[claimId];
if (claim.issuer == address(0)) revert ClaimNotFound();
if (claim.bountyId != bountyId) revert ClaimNotFound();
if (claim.accepted) revert ClaimAlreadyAccepted();
voteRound[bountyId] += 1;
uint256 roundId = voteRound[bountyId];
address[] memory p = participants[bountyId];
uint256[] memory amounts = participantAmounts[bountyId];
for (uint256 i = 0; i < p.length; i++) {
address a = p[i];
uint256 w = amounts[i];
if (a != address(0) && w > 0) {
voteWeightSnapshot[bountyId][a] = w;
voteWeightSnapshotRound[bountyId][a] = roundId;
}
}
uint256 issuerWeight = amounts[0];
if (issuerWeight == 0) revert NotActiveParticipant();
bountyCurrentVotingClaim[bountyId] = claimId;
uint256 deadline = block.timestamp + votingPeriod;
bountyVotingTracker[bountyId] = Votes({yes: issuerWeight, no: 0, deadline: deadline});
lastVotedRound[bountyId][msg.sender] = roundId;
emit VotingStarted(bountyId, claimId, deadline, issuerWeight, roundId);
}
/// @notice Vote for/against the currently submitted claim on an open bounty.
/// @dev Uses a round-scoped weight snapshot taken at `submitClaimForVote`.
function voteClaim(uint256 bountyId, bool vote) external nonReentrant {
_requireBountyExists(bountyId);
uint256 currentClaim = _requireVoteActive(bountyId);
if (participants[bountyId].length == 0) revert NotOpenBounty();
uint256 roundId = voteRound[bountyId];
if (lastVotedRound[bountyId][msg.sender] == roundId) revert AlreadyVoted();
if (voteWeightSnapshotRound[bountyId][msg.sender] != roundId) revert NotActiveParticipant();
uint256 weight = voteWeightSnapshot[bountyId][msg.sender];
if (weight == 0) revert NotActiveParticipant();
lastVotedRound[bountyId][msg.sender] = roundId;
Votes storage v = bountyVotingTracker[bountyId];
if (vote) v.yes += weight;
else v.no += weight;
emit VoteCast(msg.sender, bountyId, currentClaim, vote, weight, roundId);
}
/// @notice Resolve a vote after its deadline (permissionless).
/// @dev If the vote passes, accepts the claim (finalizes state, credits withdrawals, transfers NFT).
function resolveVote(uint256 bountyId) external nonReentrant {
if (participants[bountyId].length == 0) revert NotOpenBounty();
uint256 currentClaim = bountyCurrentVotingClaim[bountyId];
if (currentClaim == 0) revert NoVotingPeriodSet();
Votes memory v = bountyVotingTracker[bountyId];
if (block.timestamp < v.deadline) revert VotingOngoing();
bool passed = v.yes > ((v.no + v.yes) / 2);
if (passed) {
_acceptClaim(bountyId, currentClaim);
} else {
bountyCurrentVotingClaim[bountyId] = 0;
delete bountyVotingTracker[bountyId];
emit VotingResolved(bountyId, currentClaim, false, v.yes, v.no, voteRound[bountyId]);
}
}
/// @notice ABI-compat reset, but cannot discard a winning vote.
function resetVotingPeriod(uint256 bountyId) external nonReentrant {
_requireBountyExists(bountyId);
_requireBountyNotFinalized(bountyId);
if (participants[bountyId].length == 0) revert NotOpenBounty();
uint256 currentClaim = bountyCurrentVotingClaim[bountyId];
if (currentClaim == 0) revert NoVotingPeriodSet();
Votes memory v = bountyVotingTracker[bountyId];
if (block.timestamp < v.deadline) revert VotingOngoing();
bool wouldPass = v.yes > ((v.no + v.yes) / 2);
if (wouldPass) revert VoteWouldPass();
bountyCurrentVotingClaim[bountyId] = 0;
delete bountyVotingTracker[bountyId];
emit VotingResolved(bountyId, currentClaim, false, v.yes, v.no, voteRound[bountyId]);
}
/// =====================
/// === Acceptance ===
/// =====================
/// @notice Accept a claim on a solo bounty, or on an open bounty that never had an external contributor.
/// @dev Open bounties with any external contributor must use the vote flow.
function acceptClaim(uint256 bountyId, uint256 claimId) external nonReentrant {
_requireActiveBounty(bountyId);
if (claimId >= claimCounter) revert ClaimNotFound();
Bounty memory bounty = bounties[bountyId];
if (participants[bountyId].length == 0) {
if (msg.sender != bounty.issuer) revert WrongCaller();
_acceptClaim(bountyId, claimId);
return;
}
if (everHadExternalContributor[bountyId]) revert NotSoloBounty();
if (msg.sender != bounty.issuer) revert WrongCaller();
_acceptClaim(bountyId, claimId);
}
/// @dev Finalizes the bounty and claim, credits pending withdrawals, then transfers the claim NFT.
function _acceptClaim(uint256 bountyId, uint256 claimId) internal {
Bounty storage bounty = bounties[bountyId];
Claim storage claim = claims[claimId];
if (claim.issuer == address(0)) revert ClaimNotFound();
if (claim.bountyId != bountyId) revert ClaimNotFound();
if (claim.accepted) revert ClaimAlreadyAccepted();
if (bounty.amount > address(this).balance) revert InsufficientBalance();
address claimIssuer = claim.issuer;
address bountyIssuer = bounty.issuer;
uint256 bountyAmount = bounty.amount;
uint256 round = voteRound[bountyId];
uint256 fee = (bountyAmount * FEE_BPS) / BPS_DENOM;
uint256 payout = bountyAmount - fee;
bounty.claimer = claimIssuer;
bounty.claimId = claimId;
bounty.amount = 0;
claim.accepted = true;
uint256 currentVotingClaim = bountyCurrentVotingClaim[bountyId];
Votes memory voteSnap = bountyVotingTracker[bountyId];
bountyCurrentVotingClaim[bountyId] = 0;
delete bountyVotingTracker[bountyId];
pendingWithdrawals[claimIssuer] += payout;
pendingWithdrawals[treasury] += fee;
emit ClaimAccepted(bountyId, claimId, claimIssuer, bountyIssuer, bountyAmount, payout, fee, round);
poidhNft.transferFrom(address(this), bountyIssuer, claimId);
if (currentVotingClaim != 0) {
emit VotingResolved(bountyId, claimId, true, voteSnap.yes, voteSnap.no, round);
}
}
/// =====================
/// === View Helpers ===
/// =====================
function getBountiesLength() external view returns (uint256) {
return bounties.length;
}
function getBounties(uint256 offset) external view returns (Bounty[] memory) {
Bounty[] memory result = new Bounty[](10);
uint256 counter;
for (uint256 i = bounties.length; i > offset && counter < 10; i--) {
result[counter] = bounties[i - 1];
counter++;
}
return result;
}
function getClaimsByBountyId(uint256 bountyId, uint256 offset)
external
view
returns (Claim[] memory)
{
uint256[] memory ids = bountyClaims[bountyId];
Claim[] memory result = new Claim[](10);
uint256 counter;
for (uint256 i = ids.length; i > offset && counter < 10; i--) {
result[counter] = claims[ids[i - 1]];
counter++;
}
return result;
}
function getBountiesByUser(address user, uint256 offset) external view returns (Bounty[] memory) {
uint256[] memory ids = userBounties[user];
Bounty[] memory result = new Bounty[](10);
uint256 counter;
for (uint256 i = ids.length; i > offset && counter < 10; i--) {
result[counter] = bounties[ids[i - 1]];
counter++;
}
return result;
}
function getClaimsByUser(address user, uint256 offset) external view returns (Claim[] memory) {
uint256[] memory ids = userClaims[user];
Claim[] memory result = new Claim[](10);
uint256 counter;
for (uint256 i = ids.length; i > offset && counter < 10; i--) {
result[counter] = claims[ids[i - 1]];
counter++;
}
return result;
}
function getParticipants(uint256 bountyId)
external
view
returns (address[] memory, uint256[] memory)
{
return (participants[bountyId], participantAmounts[bountyId]);
}
function getParticipantsPaged(uint256 bountyId, uint256 offset, uint256 limit)
external
view
returns (address[] memory addrs, uint256[] memory amts)
{
address[] memory p = participants[bountyId];
uint256[] memory a = participantAmounts[bountyId];
if (offset >= p.length) return (new address[](0), new uint256[](0));
uint256 end = offset + limit;
if (end > p.length) end = p.length;
uint256 n = end - offset;
addrs = new address[](n);
amts = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
addrs[i] = p[offset + i];
amts[i] = a[offset + i];
}
}
/// @dev Prevent accidental ETH transfers that are not attributed to a bounty/refund.
receive() external payable {
revert DirectEtherNotAccepted();
}
}
lib/openzeppelin-contracts/contracts/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);
}
lib/openzeppelin-contracts/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;
}
}
lib/openzeppelin-contracts/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
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/interfaces/IPoidhClaimNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title IPoidhClaimNFT
/// @notice Minimal interface for the POIDH claim NFT contract used by `PoidhV3`.
interface IPoidhClaimNFT is IERC721 {
/// @notice Mint a claim NFT to the POIDH contract (escrow) and set its tokenURI.
/// @dev Implementations should avoid ERC721Receiver callback reentrancy by using `_mint`
/// rather than `_safeMint`.
/// @param tokenId The token id to mint (typically the PoidhV3 claim id).
/// @param uri The tokenURI to store for the minted token.
function mintToEscrow(uint256 tokenId, string calldata uri) external;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.