Verified contractPartialMIT
CaseDesk
Address0xe4d4e62060043eac2930f0807a7d22153e245b57
- Balance
0 ETH
- Transactions
0
- 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
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,241,860
- Creation transaction
- 0xd2a9bd560f…e344ec07fb
19 files
- src/desks/CaseDesk.solmain29.22 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28.31 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/DevPrices.sol5.66 KB
- src/ParamsRegistry.sol9.28 KB
- src/VaultParams.sol14.62 KB
- src/VaultTypes.sol22.79 KB
- src/desks/Desk.sol6.29 KB
- src/desks/DeskApi.sol6.36 KB
- src/helpers/SwarmQuestion.sol9.27 KB
- src/helpers/TextRules.sol11.7 KB
- src/interfaces/IIntake.sol1.85 KB
src/desks/CaseDesk.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ParamsCore} from "../VaultParams.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IIntake} from "../interfaces/IIntake.sol";
import {DevPrices} from "../DevPrices.sol";
import {SwarmQuestionBuilder} from "../helpers/SwarmQuestion.sol";
import {Desk} from "./Desk.sol";
import {SubmitTerms, SubCore, Facts, Tally, AskTerms, IVault, IDisputeDesk, IDoerStake} from "./DeskApi.sol";
import "../VaultTypes.sol";
/// @title CaseDesk
/// @notice Submissions and the lazy state machine of a task's active submission: activation, the dispute window,
/// the NFT decision, the windows to call the swarm, prepaid questions, the final outcome. Timers move only
/// forward and only here. A prepaid appeal is due at once and asked here by the next `askAppealSwarm`
/// (anyone), so no step waits for a keeper; a failing Intake never blocks the machine (the appeal is void). No task has a mandatory swarm
/// check: the swarm is asked only when somebody pays for it. The money of a final
/// submission is split by the DisputeDesk (`settle`).
contract CaseDesk is Desk {
/// @inheritdoc Desk
function isCaseDesk() public pure override returns (bool) {
return true;
}
/// @dev What a submission inherits from its task, fixed at submission: one slot instead of a call per step.
struct Terms {
uint32 version;
address currency;
}
SwarmQuestionBuilder internal immutable questionBuilder;
/// @notice $YOLO: the currency of the add-on and of the doer stake.
address public immutable yolo;
/// @notice YoloLockHub: the doer's $YOLO lock behind the stake bonus, read at submission.
IDoerStake public immutable doerStake;
uint256 public submissionCount;
mapping(uint256 => Submission) internal _subs;
mapping(uint256 => Terms) internal _terms;
constructor(
address registry_,
address imd_,
address usdc_,
address textRules_,
address questionBuilder_,
address yolo_,
address doerStake_
) Desk(registry_, imd_, usdc_, textRules_) {
questionBuilder = SwarmQuestionBuilder(questionBuilder_);
yolo = yolo_;
doerStake = IDoerStake(doerStake_);
}
// ================================================================== user actions (through the vault)
/// @notice Submit a proof (irrevocable). Bond = 0.5 IMD fixed + 3% of the author's own reward in R's currency:
/// top-ups of others and the $YOLO add-on are not in it; always the same, no escalation for rejected
/// submissions or the queue. No oracle, no USD conversion.
/// The doer stake bonus is fixed here too (`stakeBps`): 4% x min(1, power / (R in $YOLO + the $YOLO
/// add-on)), the power of the doer's lock as it stood before this block, R = the task's whole reward at this
/// moment (the pot: the author's share and every top-up) converted at the dev-set $YOLO price
/// (DevPrices: no oracle, no sample window), the add-on = the task's $YOLO add-on at this moment;
/// any power counts, no threshold; no $YOLO price = no bonus (the only
/// DevPrices read of a submission; it never blocks a submission).
/// `minReward` protects against a top-up merging into the pot between the quote and the transaction;
/// `maxBondRew` caps the bond's `rew` part.
/// `proofUri` is one link in the form the task's proof type requires (`BadProof` otherwise).
/// `evidence`: a screenshot link (`https://` on an allowlisted host, TextLib.checkScreenshotUrl) and a note, sent to
/// the swarm with the proof. The screenshot link is mandatory for x_post, x_reply and video
/// (`EvidenceRequired` otherwise, allowlisted hosts); for
/// onchain_tx and link it stays optional.
// slither-disable-next-line reentrancy-no-eth
function submit(
uint256 taskId,
string calldata proofUri,
Evidence calldata evidence,
uint256 minReward,
uint256 maxBondRew,
ImdPay calldata payIn
) external routed returns (uint256 subId) {
address sender = _sender();
IVault tasks = _bank();
tasks.advance(taskId);
SubmitTerms memory t = tasks.submitTerms(taskId, sender);
if (t.status != TaskStatus.Open) revert TaskNotOpen();
if (block.timestamp >= t.deadline) revert DeadlinePassed();
if (t.pot == 0) revert RewardTooSmall();
if (t.pot < minReward) revert RewardChanged();
ParamsCore memory p = _params(t.version);
_checkText(proofUri, p);
textRules.checkProof(proofUri, t.proofType);
bool hasNote = bytes(evidence.note).length != 0;
if (hasNote && !textRules.validText(evidence.note, MAX_NOTE_BYTES)) revert BadEvidence();
bool hasShot = bytes(evidence.screenshotUrl).length != 0;
textRules.checkScreenshotUrl(evidence.screenshotUrl);
// the swarm cannot open X or a video on its own, so a screenshot/clip link is
// mandatory for those proof types; onchain_tx and link stay as they are (a tx hash or a link is itself
// the proof the swarm can check). Only hosts of the allowlist (TextLib.checkHost).
if ((t.proofType == PROOF_X_POST || t.proofType == PROOF_VIDEO) && !hasShot) {
revert EvidenceRequired();
}
subId = ++submissionCount;
Submission storage s = _subs[subId];
s.taskId = uint64(taskId);
s.doer = sender;
s.submittedAt = uint64(block.timestamp);
s.proofUri = proofUri;
s.reward = SafeCast.toUint128(t.pot);
s.base = uint128(t.base); // a part of the pot
s.addon = t.addon;
Bond memory b = _doerBond(t.base, p);
s.bond = b;
(s.stakeBps, s.staked) = _stakeBps(t, sender, p);
_terms[subId] = Terms(t.version, t.currency);
if (b.rew > maxBondRew) revert CostAboveMax();
uint256 value = _value();
IVault bank = _bank();
// the "rew" part merges into the same collectImd call (and its swap mode) when R is already in IMD
bool rewIsImd = t.currency == address(imd);
uint256 ethNeeded = bank.collectImd(sender, value, b.imd + (rewIsImd ? b.rew : 0), p.swapAdapter, payIn);
if (!rewIsImd) ethNeeded += bank.collectBondPart(sender, value, t.currency, b.rew);
bool queued = t.busy;
emit Submitted(subId, taskId, sender, t.pot, b.imd, b.rew, queued, proofUri);
if (hasShot || hasNote) {
if (hasShot) s.screenshotUrl = evidence.screenshotUrl;
if (hasNote) s.doerNote = evidence.note;
emit EvidenceAttached(subId, evidence.screenshotUrl, evidence.note);
}
tasks.place(taskId, subId, queued);
if (queued) s.phase = Phase.Queued;
else _activate(subId);
_bank().settleValue(sender, value, ethNeeded); // excess ETH back last (checks, effects, interactions)
}
/// @notice Bond of a queued submission whose task was completed or unwound.
// slither-disable-next-line reentrancy-no-eth
function claimVoidSubmission(uint256 subId) external routed {
Submission storage s = _subs[subId];
IVault tasks = _bank();
tasks.advance(s.taskId);
TaskStatus ts = tasks.statusOf(s.taskId);
if (s.phase != Phase.Queued || (ts != TaskStatus.Completed && ts != TaskStatus.Unwound)) {
revert NothingToClaim();
}
s.phase = Phase.Void;
Bond memory b = s.bond;
address currency = _terms[subId].currency;
emit VoidSubmissionClaimed(subId, s.doer, b.imd, b.rew);
IVault bank = _bank();
bank.pay(address(imd), s.doer, b.imd);
bank.pay(currency, s.doer, b.rew);
}
// No "doer answers the dispute" step: their "why honest" text goes
// into Evidence.note at submission (Submission.doerNote), read by the swarm question directly.
// ================================================================== the machine (TaskVault.advance)
/// @notice The dev wallet cancelled the task (TaskVault.cancelTask): the active submission
/// closes as Unwound, every bond and unspent prepayment goes back to its owner (DisputeDesk._settleNeutral;
/// disputers take theirs with claimDisputer); swarm fees already paid stay paid.
function unwind(uint256 subId) external only(vault) {
_finalize(subId, Outcome.Unwound);
}
/// @notice One transition of the active submission. False if nothing can move now.
// slither-disable-next-line incorrect-equality,reentrancy-no-eth
function step(uint256 subId) external only(vault) returns (bool) {
Submission storage s = _subs[subId];
ParamsCore memory p = _params(_terms[subId].version);
Phase ph = s.phase;
if (ph == Phase.Review) {
if (block.timestamp < s.windowEnd) return false;
_finalize(subId, Outcome.Accepted); // nobody disputed
return true;
}
if (ph == Phase.Voting) {
if (block.timestamp < s.voteEnd) return false;
if (!_tryDecide(subId, IDisputeDesk(disputeDesk).tally(subId), s.voteEnd, p)) {
s.phase = Phase.NoDecision; // optimistic window: anyone may call the swarm, paying
s.callFrom = s.voteEnd;
emit NoNftDecision(subId);
}
return true;
}
if (ph == Phase.NoDecision || ph == Phase.Decided) {
if (block.timestamp < uint256(s.callFrom) + p.appealWindow) return false;
_endUncalled(subId);
return true;
}
if (ph == Phase.Appealed) {
// `DisputeDesk.appeal` only files the appeal, the ask is lazy. `step`/`poke` still cannot carry the
// resupplied text (no text channel here, same as every other transition in this function), so this
// step cannot progress it by itself; the ask happens via the separate permissionless
// `DisputeDesk.askAppealSwarm(subId, rt)` instead (anyone, including the site right after `appeal` or
// a poke-bot). Without this timeout, a never-called `askAppealSwarm` would deadlock the submission
// forever - nothing else in this file has a timeout for `Phase.Appealed` (every other phase above
// does). Same exit `_askAppeal`'s void-appeal branch already uses when the live price/a broken Intake
// kills an asked appeal: an appeal that could not be asked has its bond and fee refunded to the
// appellant, and still counts toward the same 3 calls: full refund via `dropCaller`, back to
// `Decided`, counts toward MAX_SWARM_CALLS. The appeal was never actually asked,
// so there is no fee for the swarm to have earned.
if (block.timestamp < uint256(s.appealedAt) + p.swarmTimeout) return false;
IDisputeDesk(disputeDesk).dropCaller(subId);
s.phase = Phase.Decided;
s.callFrom = uint64(uint256(s.appealedAt) + p.swarmTimeout); // the window reopens at the void, not the poke
emit AppealVoided(subId, 0);
if (++s.asks >= MAX_SWARM_CALLS) _endUncalled(subId);
return true;
}
if (ph == Phase.Asked) {
(SwarmStatus st, bool answer, uint64 at) = _swarmStatus(s.request, p);
if (st == SwarmStatus.Pending) return false;
if (st == SwarmStatus.Answered) {
_finalize(subId, answer ? Outcome.Accepted : Outcome.Rejected); // the swarm is final
} else {
// silent: the caller's fee stays paid (no separate refund), the
// rest of their deposit is theirs (pull); the state before the call stands again and a new window to
// call the swarm starts at the moment of silence; after MAX_SWARM_CALLS questions the submission
// ends as if nobody had called (a silent swarm cannot keep the money locked)
IDisputeDesk(disputeDesk).dropCaller(subId);
s.phase = s.nftDecision == Verdict.None ? Phase.NoDecision : Phase.Decided;
s.callFrom = at;
emit SwarmSilent(subId, s.request, at);
if (s.asks >= MAX_SWARM_CALLS) _endUncalled(subId);
}
return true;
}
return false; // Queued / Final / Void are inert
}
// ================================================================== for the dispute desk
/// @notice Plays the task's timers first, then returns the submission as it stands.
function advanced(uint256 subId) external only(disputeDesk) returns (SubCore memory) {
_bank().advance(_subs[subId].taskId);
return _core(subId);
}
/// @notice The dispute starts the NFT vote.
function startVote(uint256 subId, uint32 voteWindow) external only(disputeDesk) {
Submission storage s = _subs[subId];
if (s.phase != Phase.Review) return;
s.phase = Phase.Voting;
s.voteEnd = uint64(block.timestamp) + voteWindow;
}
function markAppealed(uint256 subId) external only(disputeDesk) {
Submission storage s = _subs[subId];
s.phase = Phase.Appealed;
s.appealedAt = uint64(block.timestamp);
}
/// @notice The swarm is called while the NFT did not decide: asked at once, paid from the caller's deposit.
/// `rt`: DisputeDesk.callSwarm's caller resupplied the task rules and the dispute reason/proof link in
/// the same transaction; checked against the stored hashes in `_ask`.
// slither-disable-next-line reentrancy-no-eth
function askEscalation(uint256 subId, uint256 price, RuleTexts calldata rt)
external
only(disputeDesk)
returns (bool ok, uint256 spent)
{
(ok, spent) = _ask(subId, SWARM_KIND_ESCALATION, price, _params(_terms[subId].version), rt);
if (ok) _subs[subId].phase = Phase.Asked;
}
/// @notice DisputeDesk.askAppealSwarm's lazy ask (not called from `appeal` itself):
/// `rt` is the task rules + the filed dispute's reason/proof link, resupplied by whoever
/// calls `askAppealSwarm` (any address), checked in `_ask` against the stored hashes. `funds` = the
/// appellant's prepaid fee (bond-sourced + wallet-sourced, DisputeDesk._fundCall, read at appeal time).
function askAppeal(uint256 subId, uint256 funds, RuleTexts calldata rt) external only(disputeDesk) {
if (_subs[subId].phase != Phase.Appealed) revert WrongPhase();
_askAppeal(subId, funds, _params(_terms[subId].version), rt);
}
// ================================================================== views
function getSubmission(uint256 subId) external view returns (Submission memory) {
return _subs[subId];
}
/// @notice What a vote needs (DisputeDesk.vote): three slots instead of the whole SubCore.
function voteState(uint256 subId) external view returns (Phase phase, uint64 voteEnd, uint32 version) {
Submission storage s = _subs[subId];
return (s.phase, s.voteEnd, _terms[subId].version);
}
/// @notice Dispute bond of `subId`. Appealing or calling the swarm costs the same bond plus `quoteSwarmFee`
/// (here, not in DisputeDesk, for room under EIP-170).
function quoteDisputeBond(uint256 subId) external view returns (Bond memory) {
SubCore memory s = _core(subId);
return _disputeBond(s.base, _params(s.version));
}
/// @notice Live swarm fee (IMD) for questions about `subId`; 0 = the Intake does not sell the action now.
function quoteSwarmFee(uint256 subId) external view returns (uint256) {
return _swarmPrice(_params(_terms[subId].version));
}
/// @notice The fixed IMD part of the doer bond (DisputeDesk: a doer's own swarm call is paid from it).
function doerBondImd(uint256 subId) external view returns (uint256) {
return _subs[subId].bond.imd;
}
function subCore(uint256 subId) external view returns (SubCore memory) {
return _core(subId);
}
/// @notice The bond a new submission to `taskId` would need now.
function quoteSubmission(uint256 taskId) external view returns (Bond memory bond) {
SubmitTerms memory t = _bank().submitTerms(taskId, address(0));
ParamsCore memory p = _params(t.version);
bond = _doerBond(t.base, p);
}
/// @notice When the current step of an active submission times out.
function stepDeadline(uint256 subId) external view returns (uint256) {
Submission storage s = _subs[subId];
ParamsCore memory p = _params(_terms[subId].version);
Phase ph = s.phase;
if (ph == Phase.Review) return s.windowEnd;
if (ph == Phase.Voting) return s.voteEnd;
if (ph == Phase.NoDecision || ph == Phase.Decided) return uint256(s.callFrom) + p.appealWindow;
// the appeal's ask is lazy, due from the moment it was filed (markAppealed); not asked within swarmTimeout
// it is void (step)
if (ph == Phase.Appealed) return uint256(s.appealedAt) + p.swarmTimeout;
if (ph == Phase.Asked) {
// an answer in time, or the Intake already closed the request: the next poke plays it now
(SwarmStatus st,,) = _swarmStatus(s.request, p);
if (st != SwarmStatus.Pending) return block.timestamp;
return uint256(_bank().requests(s.request).askedAt) + p.swarmTimeout + SWARM_DELIVERY_GRACE;
}
return type(uint128).max; // not an active step
}
/// @notice The JSON body the vault would send now for `kind` (2 escalation, 3 appeal). `rt`: the caller
/// supplies the task rules and the dispute reason/proof link - a free
/// read-only preview of exactly what a real `callSwarm`/`askAppealSwarm` with the same texts would send,
/// checked against the same stored hashes.
function previewSwarmBody(uint256 subId, uint8 kind, RuleTexts calldata rt)
external
view
returns (bytes memory body, bytes32 qh)
{
return questionBuilder.buildFor(vault, subId, kind, _params(_terms[subId].version).maxClaims, rt);
}
// ================================================================== internal: activation and decisions
/// @dev Opens the dispute window of the task's new active submission (the vault already made it active).
function _activate(uint256 subId) private {
Submission storage s = _subs[subId];
s.phase = Phase.Review;
s.activatedAt = uint64(block.timestamp);
s.windowEnd = uint64(block.timestamp) + _params(_terms[subId].version).disputeWindow;
emit Activated(subId, s.windowEnd);
}
/// @dev The window to call the swarm ended unused (or the last allowed question stayed silent): NFT undecided ->
/// accepted, the disputer bonds to the doer (general rule); NFT decided -> its decision.
function _endUncalled(uint256 subId) private {
Submission storage s = _subs[subId];
_finalize(subId, s.nftDecision == Verdict.Reject ? Outcome.Rejected : Outcome.Accepted);
}
/// @dev NFT decision rule at vote end (step, Voting): |accept - reject| >= endDelta and the winning side has
/// >= minWinnerWallets distinct signers.
function _tryDecide(uint256 subId, Tally memory v, uint64 at, ParamsCore memory p) private returns (bool) {
return _decide(subId, v, at, p.endDelta, p.minWinnerWallets, false);
}
/// @notice Instant NFT decision: on every vote, as soon as one side is ahead by
/// >= instantDelta with >= minWinnerWallets distinct signers on that side, the submission decides at
/// once (NftDecided.instant = true) instead of waiting for the vote window to end. Called by
/// DisputeDesk.vote right after it updates the tally; a no-op once already decided.
function tryInstantDecision(uint256 subId, Tally calldata v) external only(disputeDesk) {
Submission storage s = _subs[subId];
if (s.phase != Phase.Voting) return;
ParamsCore memory p = _params(_terms[subId].version);
_decide(subId, v, uint64(block.timestamp), p.instantDelta, p.minWinnerWallets, true);
}
function _decide(uint256 subId, Tally memory v, uint64 at, uint32 delta, uint32 minWallets, bool instant)
private
returns (bool)
{
if (v.accept == v.reject) return false;
bool acceptWins = v.accept > v.reject;
uint256 diff = acceptWins ? v.accept - v.reject : v.reject - v.accept;
uint256 wallets = acceptWins ? v.walletsAccept : v.walletsReject;
if (diff < delta || wallets < minWallets) return false;
Submission storage s = _subs[subId];
s.nftDecision = acceptWins ? Verdict.Accept : Verdict.Reject;
s.decidedAt = at;
s.callFrom = at; // appeal window
s.phase = Phase.Decided;
emit NftDecided(subId, s.nftDecision, instant);
return true;
}
/// @dev The appeal question, asked lazily from `DisputeDesk.askAppealSwarm` (any caller, in a transaction of
/// its own after `appeal`; it carries the resupplied `RuleTexts`). If the live price is
/// now above the prepaid fee, 0, or the Intake fails, the appeal is void: bond and fee are the appellant's
/// again (credit), the NFT decision stands and a new appeal window starts now, unless that was the
/// MAX_SWARM_CALLS-th question: then the NFT decision is final.
// slither-disable-next-line reentrancy-no-eth
function _askAppeal(uint256 subId, uint256 funds, ParamsCore memory p, RuleTexts calldata rt) private {
Submission storage s = _subs[subId];
IDisputeDesk disputes = IDisputeDesk(disputeDesk);
uint256 price = _swarmPrice(p);
if (price != 0 && price <= funds) {
(bool ok, uint256 spent) = _ask(subId, SWARM_KIND_APPEAL, price, p, rt);
if (ok) {
s.phase = Phase.Asked;
disputes.appealAsked(subId, spent);
return;
}
}
disputes.dropCaller(subId);
s.phase = Phase.Decided;
s.callFrom = uint64(block.timestamp);
emit AppealVoided(subId, price);
// a void appeal counts against MAX_SWARM_CALLS like a silent one: a broken Intake cannot
// keep the submission open by appeal after appeal
if (++s.asks >= MAX_SWARM_CALLS) _endUncalled(subId);
}
/// @dev Status of a swarm question. An answer counts if its signed time is within the timeout and it reached
/// the vault within SWARM_DELIVERY_GRACE after the timeout; `at` of an answer is the moment it reached the
/// vault (a window that follows it is never shortened). Silence: no such answer by the end of the grace
/// (moment of silence = ask time + timeout + grace), or no answer recorded and the Intake already reports
/// the request completed (status 1 / 2; moment of silence = now). Nothing is settled as silent while an
/// answer signed in time can still count. The outcome does not depend on who pokes when, but in the last
/// case the moment of silence (and the window that follows it) does: the Intake gives no completion time,
/// so it is the first poke after completion, at most swarmTimeout + grace later (7 h by default).
// slither-disable-next-line unused-return
function _swarmStatus(bytes32 rid, ParamsCore memory p)
private
view
returns (SwarmStatus status, bool answer, uint64 at)
{
SwarmRequest memory r = _bank().requests(rid);
uint256 deadline = uint256(r.askedAt) + p.swarmTimeout;
uint256 lastDelivery = deadline + SWARM_DELIVERY_GRACE;
if (r.answered && r.answerTime <= deadline && r.recordedAt <= lastDelivery) {
return (SwarmStatus.Answered, r.answer, r.recordedAt);
}
if (block.timestamp >= lastDelivery) return (SwarmStatus.Silent, false, uint64(lastDelivery));
if (r.answered) return (SwarmStatus.Pending, false, 0); // signed too late: silence at the end of the grace
try IIntake(p.intake).requests(rid) returns (address, address, bytes4, bool completed) {
if (completed) return (SwarmStatus.Silent, false, uint64(block.timestamp));
} catch {}
return (SwarmStatus.Pending, false, 0);
}
// ================================================================== internal: settlement
/// @dev Closes a submission with `o`: the DisputeDesk splits the money, the vault moves the task on (next
/// queued submission, completion or unwind; top-ups are already in the pot). Credits only; never transfers.
// slither-disable-next-line reentrancy-no-eth
function _finalize(uint256 subId, Outcome o) private {
Submission storage s = _subs[subId];
Terms memory tm = _terms[subId];
uint256 taskId = s.taskId;
s.phase = Phase.Final;
s.outcome = o;
// accepted: the doer gets the whole pot, top-ups made during the check included;
// `reward` then reads what was paid
if (o == Outcome.Accepted) s.reward = SafeCast.toUint128(_bank().potOf(taskId));
Facts memory f = Facts({
taskId: s.taskId,
version: tm.version,
currency: tm.currency,
doer: s.doer,
nftDecision: s.nftDecision,
reward: s.reward,
bond: s.bond,
since: s.submittedAt,
stakeBps: s.stakeBps,
staked: s.staked
});
IDisputeDesk(disputeDesk).settle(subId, o, f);
emit SubmissionFinal(subId, taskId, o);
uint256 next = _bank().closeSubmission(taskId, o, s.reward);
if (next != 0) _activate(next);
}
// ================================================================== internal: swarm questions
/// @dev Builds the question from stored data and has the vault pay the Intake `price` IMD (already held in one
/// of the submission's buckets). Never reverts on an Intake failure: ok = false and nothing is spent.
function _ask(uint256 subId, uint8 kind, uint256 price, ParamsCore memory p, RuleTexts calldata rt)
private
returns (bool ok, uint256 spent)
{
(bytes memory body, bytes32 qh) = questionBuilder.buildFor(vault, subId, kind, p.maxClaims, rt);
bytes32 rid;
(ok, spent, rid) = _bank()
.ask(AskTerms(uint64(subId), kind, p.minPanelSize, p.minQuorum, p.intake, p.swarmAction, qh, price), body);
if (!ok) return (false, 0);
Submission storage s = _subs[subId];
++s.asks;
s.request = rid;
}
/// @dev The stake bonus of a new submission in bps of R (see `submit`). A doer who put money into the task's
/// own reward gets the bonus too. Never
/// blocks a submission: a hub or a DevPrices that fails counts as no stake.
/// The power is measured against the whole pot at the submission (`t.pot`: the author's share and every
/// top-up) in $YOLO plus the $YOLO add-on (`t.addon`); the share is paid on the pot and on the add-on.
/// `staked`: any power with a $YOLO price, also when the share floors to 0 bps (the staked split still applies).
// slither-disable-next-line incorrect-equality
function _stakeBps(SubmitTerms memory t, address doer, ParamsCore memory p)
private
view
returns (uint16, bool staked)
{
// a hub without code, failing or answering anything but one word counts as no stake
(bool ok, bytes memory ret) =
address(doerStake).staticcall(abi.encodeCall(IDoerStake.powerAt, (doer, block.timestamp)));
if (!ok || ret.length != 32) return (0, false);
uint256 power = abi.decode(ret, (uint256));
if (power == 0) return (0, false);
// slither-disable-next-line uninitialized-local
uint256 r;
try DevPrices(p.devPrices).yoloValue(t.currency, t.pot) returns (uint256 y) {
r = y;
} catch {}
if (r == 0) return (0, false); // no $YOLO price
r += t.addon;
return (uint16(power >= r ? MAX_STAKE_BONUS_BPS : MAX_STAKE_BONUS_BPS * power / r), true);
}
function _core(uint256 subId) private view returns (SubCore memory c) {
Submission storage s = _subs[subId];
Terms memory tm = _terms[subId];
c.taskId = s.taskId;
c.doer = s.doer;
c.phase = s.phase;
c.outcome = s.outcome;
c.nftDecision = s.nftDecision;
c.windowEnd = s.windowEnd;
c.voteEnd = s.voteEnd;
c.version = tm.version;
c.currency = tm.currency;
c.reward = s.reward;
c.base = s.base;
c.addon = s.addon;
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/DevPrices.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ETH} from "./VaultTypes.sol";
/// @title DevPrices
/// @notice Every price the protocol needs is a parameter the owner (dev) sets by hand, no oracle of any kind.
/// ETH is a price parameter too, so a swap's gas cost is never charged to users as a separate ETH payment.
/// Prices never decide who is paid: they only size the stake bonus's power-vs-reward comparison (CaseDesk,
/// at the submission).
/// - `yoloPriceUsd`: USD per one whole $YOLO (18 decimals), set directly as a token price (the launch price).
/// - `ethUsd`, `imdUsd`: USD per whole token (18 decimals).
/// - The owner changes each price with one transaction (an event the site shows). Zero is refused, and so is
/// an obvious typo: one call moves a price at most MAX_STEP times up or down (the
/// contract refuses an obviously wrong value); a real move further than that takes several calls.
/// - USDC is fixed at exactly $1 (`USDC_USD`), never a parameter: a depeg is the owner's problem to fix by
/// other means, not a price this contract would misreport.
/// A price is always set after deployment (constructor requires non-zero), so `hasPrice` is always true:
/// money is never blocked by a missing price. Stale or wrong
/// because the owner has not updated it is a known, accepted risk: it moves the stake bonus, never a payout.
contract DevPrices is Ownable2Step {
uint256 public constant USDC_USD = 1e18;
/// @notice One setter call moves a price at most this many times up or down (a typo guard, not a market rule).
uint256 public constant MAX_STEP = 10;
address public immutable usdc;
address public immutable imd;
address public immutable yolo;
uint256 public yoloPriceUsd;
uint256 public ethUsd;
uint256 public imdUsd;
event YoloPriceUsdSet(uint256 usd18);
event EthUsdSet(uint256 usd18);
event ImdUsdSet(uint256 usd18);
error ZeroAddress();
error ZeroPrice();
/// @notice A new price more than MAX_STEP times above or below the current one (an obvious typo).
error PriceSanity();
error UnknownToken();
constructor(
address owner_,
address usdc_,
address imd_,
address yolo_,
uint256 yoloPriceUsd_,
uint256 ethUsd_,
uint256 imdUsd_
) Ownable(owner_) {
if (usdc_ == address(0) || imd_ == address(0) || yolo_ == address(0)) revert ZeroAddress();
if (yoloPriceUsd_ == 0 || ethUsd_ == 0 || imdUsd_ == 0) revert ZeroPrice();
usdc = usdc_;
imd = imd_;
yolo = yolo_;
yoloPriceUsd = yoloPriceUsd_;
ethUsd = ethUsd_;
imdUsd = imdUsd_;
emit YoloPriceUsdSet(yoloPriceUsd_);
emit EthUsdSet(ethUsd_);
emit ImdUsdSet(imdUsd_);
}
/// @notice Owner sets the price of one $YOLO in USD (18 decimals).
function setYoloPriceUsd(uint256 usd18) external onlyOwner {
_check(yoloPriceUsd, usd18);
yoloPriceUsd = usd18;
emit YoloPriceUsdSet(usd18);
}
function setEthUsd(uint256 usd18) external onlyOwner {
_check(ethUsd, usd18);
ethUsd = usd18;
emit EthUsdSet(usd18);
}
function setImdUsd(uint256 usd18) external onlyOwner {
_check(imdUsd, usd18);
imdUsd = usd18;
emit ImdUsdSet(usd18);
}
/// @dev Not zero, and within MAX_STEP times the current price either way (both bounds inclusive).
function _check(uint256 current, uint256 next) private pure {
if (next == 0) revert ZeroPrice();
if (next > current * MAX_STEP || next * MAX_STEP < current) revert PriceSanity();
}
/// @return usd18 price per whole token (18 decimals), 0 for an unknown token.
function priceOf(address token) public view returns (uint256 usd18) {
if (token == ETH) return ethUsd;
if (token == usdc) return USDC_USD;
if (token == imd) return imdUsd;
if (token == yolo) return yoloPriceUsd;
return 0;
}
/// @notice True for every known token (ETH, USDC, IMD, $YOLO): each has a dev-set price.
function hasPrice(address token) external view returns (bool) {
return token == ETH || token == usdc || token == imd || token == yolo;
}
/// @return usd18 value of `amount` of `token` (18-decimal tokens, except 6-decimal USDC).
function usdValue(address token, uint256 amount) public view returns (uint256 usd18) {
uint256 p = priceOf(token);
if (p == 0) revert UnknownToken();
uint256 decimals = token == usdc ? 1e6 : 1e18;
return amount * p / decimals;
}
/// @return imdAmount amount of IMD (18 decimals) worth `amount` of `token`.
function imdValue(address token, uint256 amount) external view returns (uint256 imdAmount) {
if (token == imd) return amount;
return usdValue(token, amount) * 1e18 / imdUsd;
}
/// @notice amount of $YOLO worth `amount` of `token`, at the current dev-set price (direct, not a sampled
/// minimum: there is no sampling window to manipulate). Used by the doer stake bonus call site
/// (CaseDesk._stakeBps).
function yoloValue(address token, uint256 amount) external view returns (uint256 yoloAmount) {
if (token == yolo) return amount;
uint256 yoloPrice = priceOf(yolo);
if (yoloPrice == 0) return 0;
return usdValue(token, amount) * 1e18 / yoloPrice;
}
}
src/ParamsRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Params, ParamsCore, ParamsBounds, LaunchParams} from "./VaultParams.sol";
/// @title ParamsRegistry
/// @notice Versioned parameters and the swarm attester set, owned by the project wallet (behind a 48 h timelock).
/// Read by TaskVault and its desks.
/// - Parameter changes and attester changes wait `TIMELOCK` (48h) between proposal and execution;
/// execution is permissionless once the delay passed.
/// - A new parameter version applies to tasks created after activation only: a task records the version
/// current at its creation and every desk reads only that version's snapshot (`core`, `template`), which
/// never changes once activated.
/// - `newTasksPaused` stops task creation only; everything else keeps working.
/// - The owner has no function that moves, freezes or redirects deposited money.
/// - Trust (docs/MECHANICS.md "Trust assumptions"): the attester set is global, so a change reaches the swarm
/// answers of tasks already running (at least one attester always stays); and a new version may name another
/// intake or devPrices, which then serve every task created under it. The version's nft and delegateRegistry
/// fields are not read: NFT votes always go through the DisputeDesk's immutable VotePower.
contract ParamsRegistry is Ownable2Step {
uint256 public constant TIMELOCK = 48 hours;
/// @dev version => snapshot. Version 0 is never used.
mapping(uint32 => Params) internal _params;
uint32 public currentVersion;
Params internal _pendingParams;
uint64 public pendingParamsEta; // 0 = nothing pending
/// @notice Signers accepted on swarm attestations (global: key rotation must reach old tasks too).
mapping(address => bool) public isAttester;
/// @notice How many signers are in the attester set; the last one cannot be removed (swarm audit 117cf05a #10).
uint256 public attesterCount;
/// @dev keccak256(attester, allowed) => eta
mapping(bytes32 => uint64) public attesterChangeEta;
bool public newTasksPaused;
event ParamsProposed(uint64 eta);
event ParamsCancelled();
event ParamsActivated(uint32 indexed version);
event AttesterChangeProposed(address indexed attester, bool allowed, uint64 eta);
event AttesterChangeCancelled(address indexed attester, bool allowed);
event AttesterChanged(address indexed attester, bool allowed);
event NewTasksPaused(bool paused);
error NothingPending();
error TimelockNotPassed();
error LastAttester();
/// @notice Version 1 = `LaunchParams.initial` (the numbers and the question template are compiled in) with these
/// counterparties; `attester` is the first accepted signer of swarm answers.
constructor(
address owner_,
address intake,
address devPrices,
address swapAdapter,
address nft,
address delegateRegistry,
address treasury,
address attester
) Ownable(owner_) {
Params memory initial = LaunchParams.initial(intake, devPrices, swapAdapter, nft, delegateRegistry, treasury);
ParamsBounds.validate(initial);
if (attester == address(0)) revert ParamsBounds.ParamOutOfBounds("attester");
currentVersion = 1;
_params[1] = initial;
emit ParamsActivated(1);
isAttester[attester] = true;
attesterCount = 1;
emit AttesterChanged(attester, true);
}
// ------------------------------------------------------------------ parameters
function proposeParams(Params calldata p) external onlyOwner {
ParamsBounds.validate(p);
_pendingParams = p;
pendingParamsEta = uint64(block.timestamp + TIMELOCK);
emit ParamsProposed(pendingParamsEta);
}
function cancelParams() external onlyOwner {
if (pendingParamsEta == 0) revert NothingPending();
pendingParamsEta = 0;
emit ParamsCancelled();
}
/// @notice Anyone can activate a proposal after the timelock.
// slither-disable-next-line incorrect-equality
function activateParams() external {
uint64 eta = pendingParamsEta;
if (eta == 0) revert NothingPending();
if (block.timestamp < eta) revert TimelockNotPassed();
pendingParamsEta = 0;
uint32 v = currentVersion + 1;
_params[v] = _pendingParams;
currentVersion = v;
emit ParamsActivated(v);
}
function params(uint32 version) external view returns (Params memory) {
return _params[version];
}
/// @notice Same as `params`: the vault forwards its `paramsOf(version)` here.
function paramsOf(uint32 version) external view returns (Params memory) {
return _params[version];
}
/// @notice Every number and address of `version` without the question template (what the desks read per call).
function core(uint32 version) external view returns (ParamsCore memory c) {
Params storage p = _params[version];
c.intake = p.intake;
c.devPrices = p.devPrices;
c.swapAdapter = p.swapAdapter;
c.nft = p.nft;
c.delegateRegistry = p.delegateRegistry;
c.treasury = p.treasury;
c.swarmAction = p.swarmAction;
c.minRewardUsdc = p.minRewardUsdc;
c.minRewardEth = p.minRewardEth;
c.minRewardImd = p.minRewardImd;
c.minRewardYolo = p.minRewardYolo;
c.bondFixedImd = p.bondFixedImd;
c.doerBondBps = p.doerBondBps;
c.disputeBondBps = p.disputeBondBps;
c.maxClaims = p.maxClaims;
c.maxTextBytes = p.maxTextBytes;
c.disputeWindow = p.disputeWindow;
c.voteWindow = p.voteWindow;
c.appealWindow = p.appealWindow;
c.swarmTimeout = p.swarmTimeout;
c.instantDelta = p.instantDelta;
c.endDelta = p.endDelta;
c.minWinnerWallets = p.minWinnerWallets;
c.feeBps = p.feeBps;
c.nftFeeBps = p.nftFeeBps;
c.winnerBondBps = p.winnerBondBps;
c.minPanelSize = p.minPanelSize;
c.minQuorum = p.minQuorum;
}
/// @notice What an NFT vote reads (DisputeDesk.vote): four slots instead of the whole ParamsCore.
function voteParams(uint32 version)
external
view
returns (address nft, address delegateRegistry, uint32 instantDelta, uint32 minWinnerWallets)
{
Params storage p = _params[version];
return (p.nft, p.delegateRegistry, p.instantDelta, p.minWinnerWallets);
}
/// @notice The swarm question template of `version`.
function template(uint32 version)
external
view
returns (bytes memory questionPrefix, bytes memory definitionFields, bytes memory bodyFields)
{
Params storage p = _params[version];
return (p.questionPrefix, p.definitionFields, p.bodyFields);
}
function pendingParams() external view returns (Params memory) {
return _pendingParams;
}
// ------------------------------------------------------------------ attesters
/// @notice Propose adding (`allowed`) or removing a signer of swarm answers; anyone executes it after TIMELOCK.
/// A removal that would leave no attester is refused at execution (with none, every swarm answer of every
/// live task would be silence): to rotate a key, propose the new one with the removal and execute the
/// addition first.
function proposeAttester(address attester, bool allowed) external onlyOwner {
uint64 eta = uint64(block.timestamp + TIMELOCK);
attesterChangeEta[_attesterKey(attester, allowed)] = eta;
emit AttesterChangeProposed(attester, allowed, eta);
}
function cancelAttester(address attester, bool allowed) external onlyOwner {
bytes32 key = _attesterKey(attester, allowed);
if (attesterChangeEta[key] == 0) revert NothingPending();
delete attesterChangeEta[key];
emit AttesterChangeCancelled(attester, allowed);
}
function executeAttester(address attester, bool allowed) external {
bytes32 key = _attesterKey(attester, allowed);
uint64 eta = attesterChangeEta[key];
if (eta == 0) revert NothingPending();
if (block.timestamp < eta) revert TimelockNotPassed();
delete attesterChangeEta[key];
if (isAttester[attester] != allowed) {
if (allowed) {
++attesterCount;
} else {
if (attesterCount == 1) revert LastAttester();
--attesterCount;
}
isAttester[attester] = allowed;
}
emit AttesterChanged(attester, allowed);
}
// ------------------------------------------------------------------ pause (new tasks only)
function setNewTasksPaused(bool paused) external onlyOwner {
newTasksPaused = paused;
emit NewTasksPaused(paused);
}
function _attesterKey(address attester, bool allowed) private pure returns (bytes32) {
return keccak256(abi.encode(attester, allowed));
}
}
src/VaultParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {MAX_NOTE_BYTES, MAX_SCREENSHOT_URL_BYTES} from "./VaultTypes.sol";
/// @notice Every tunable number of the protocol. A full snapshot is stored per version; a task records the
/// version that was current when it was created and reads only that snapshot for its whole life
/// ("values are copied into the task at creation"). Only the attester set is global.
struct Params {
// ---- external contracts
address intake; // IMD Intake (swarm payment + callback)
address devPrices; // DevPrices: owner-set prices (no oracle), read at submission only (the stake bonus)
address swapAdapter; // ISwapAdapter for payment mode A; address(0) disables mode A
address nft; // identity.md ERC-721
address delegateRegistry; // delegate.xyz v2; address(0) disables delegated votes
address treasury; // the single project treasury (receives fees in every currency)
bytes32 swarmAction; // Intake action id, e.g. "oracle.request@oracle-1"
// ---- task minimums (own currency, no USD conversion): no limit on
// one task's reward or on all open tasks together
uint256 minRewardUsdc; // 5e6: the smallest USDC reward of a new task
uint256 minRewardEth; // 0.002e18: the smallest ETH reward of a new task
uint256 minRewardImd; // 1e18: the smallest IMD reward of a new task
uint256 minRewardYolo; // 1000e18: the smallest $YOLO reward of a new task
// ---- bonds (no oracle); no ETH dispute fee (no
// gas refund, the disputer and every NFT voter pay their own gas)
uint256 bondFixedImd; // 0.5 IMD: fixed part of every bond, in IMD, never doubled (>= one swarm fee)
uint16 doerBondBps; // 300 = 3% of R, in R's own currency (the $YOLO add-on is not part of R here)
uint16 disputeBondBps; // 100 = 1% of R, in R's own currency (the $YOLO add-on is not part of R here); same for both,
// no escalation
uint16 maxClaims; // dispute reasons put into a swarm question (first N; disputers themselves are unlimited)
uint16 maxTextBytes; // every user string (uri / hash / link)
// ---- timers, seconds
uint32 disputeWindow; // 24h for every task (hard lower bound 24h)
uint32 voteWindow; // 24h NFT voting after the first dispute
uint32 appealWindow; // 24h: every window to call the swarm (NFT decided / undecided / after silence / check)
uint32 swarmTimeout; // 6h per swarm question
// no emergency exit: every step is closed by its own
// timer (dispute 24h, vote 24h, swarm <= 6h x <= 3 calls), the final outcome is fixed by anyone once it is due
// ---- NFT voting
uint32 instantDelta; // 20: decide at once, on every vote, once one side is ahead by
// this much (and has >= minWinnerWallets); this only rules out deciding on a stale/partial count, not an
// instant decision rule as such
uint32 endDelta; // 10: decide at vote end
uint32 minWinnerWallets; // 1: distinct signers on the winning side
// ---- money split
uint16 feeBps; // 1000 = 10% of an accepted reward; without a dispute all of it to the treasury
uint16 nftFeeBps; // 500 of the 1000 to correct NFT voters when accepted after a dispute the NFT decided right
uint16 winnerBondBps; // 5000: share of the loser bond to the winning side, rest to correct NFT voters
// ---- swarm answer: the panel we order in bodyFields; an attestation of a smaller panel or quorum is silence
uint16 minPanelSize; // 7 = bodyFields "panelSize"
uint16 minQuorum; // 5 = bodyFields "quorum"
// ---- swarm question template
bytes questionPrefix; // text before the generated case description (question limit: 2000 chars)
bytes definitionFields; // template "definitions" members (compact JSON, no braces), may be empty
bytes bodyFields; // remaining compact JSON members: chainId, window, answerType, panelSize, quorum, ...
}
/// @notice `Params` without the three byte strings of the swarm question template: what the desks read for every
/// action (`ParamsRegistry.core`). The template is read only when a question is built
/// (`ParamsRegistry.template`). Same fields, same order, same meaning as in `Params`.
struct ParamsCore {
address intake;
address devPrices;
address swapAdapter;
address nft;
address delegateRegistry;
address treasury;
bytes32 swarmAction;
uint256 minRewardUsdc;
uint256 minRewardEth;
uint256 minRewardImd;
uint256 minRewardYolo;
uint256 bondFixedImd;
uint16 doerBondBps;
uint16 disputeBondBps;
uint16 maxClaims;
uint16 maxTextBytes;
uint32 disputeWindow;
uint32 voteWindow;
uint32 appealWindow;
uint32 swarmTimeout;
uint32 instantDelta; // see Params
uint32 endDelta;
uint32 minWinnerWallets;
uint16 feeBps;
uint16 nftFeeBps;
uint16 winnerBondBps;
uint16 minPanelSize;
uint16 minQuorum;
}
/// @notice The rules the registry starts with (version 1): every number of the protocol's initial parameters,
/// compiled in, so the registry's constructor takes only addresses (launch rule: constructor arguments are
/// addresses and integers). Later versions go through `proposeParams` and the 48h timelock.
library LaunchParams {
bytes32 internal constant SWARM_ACTION = "oracle.request@oracle-1";
function initial(
address intake,
address devPrices,
address swapAdapter,
address nft,
address delegateRegistry,
address treasury
) internal pure returns (Params memory p) {
p.intake = intake;
p.devPrices = devPrices;
p.swapAdapter = swapAdapter;
p.nft = nft;
p.delegateRegistry = delegateRegistry;
p.treasury = treasury;
p.swarmAction = SWARM_ACTION;
p.minRewardUsdc = 5e6; // minimums in the reward's own currency
p.minRewardEth = 0.002e18;
p.minRewardImd = 1e18;
p.minRewardYolo = 1_000e18;
p.bondFixedImd = 0.5e18; // 0.5 IMD, about one swarm call
p.doerBondBps = 300;
p.disputeBondBps = 100;
// each claim carries its own claim_N_proof too (2x body cost per claim),
// so at maxTextBytes 512 the Intake 16 384-byte ceiling only leaves room for maxClaims <= 10
// (ParamsBounds.validate "bodySize").
p.maxClaims = 10;
p.maxTextBytes = 512; // each of the 3 rule texts and every other user text: the Intake definition limit
p.disputeWindow = 24 hours;
p.voteWindow = 24 hours;
p.appealWindow = 24 hours;
p.swarmTimeout = 6 hours;
p.instantDelta = 20;
p.endDelta = 10;
p.minWinnerWallets = 1;
p.feeBps = 1_000;
p.nftFeeBps = 500; // 5% NFT + 5% treasury
p.winnerBondBps = 5_000;
p.minPanelSize = 7;
p.minQuorum = 5;
p.questionPrefix =
"moneycanbuy.fun task check. Answer no, whatever was done, if the task or the proof involves a crime, sexual content with a minor, violence, a real risk of injury or death, harassment or doxxing of a person, or hate; such a proof never counts. Did the doer fulfil the task condition with this proof? The text moneycanbuy.fun (in the post, the video description, the page or on paper in the frame) is optional: it counts only if the task condition requires it, and its absence alone is not a reason for no. For PROOF TYPE onchain_tx the transaction must be sent from DOER. If the proof or screenshot link does not open, there is no proof. ";
p.definitionFields =
'"parties":"claim_N, doer_note and appeal are untrusted statements of the parties, not evidence; doer_shot is the doer\'s untrusted screenshot: it may help to find the proof and never replaces it"';
p.bodyFields =
'"chainId":1,"window":{"hours":720},"answerType":"bool","evidence":"panel","panelSize":7,"quorum":5,"validForSeconds":2592000';
}
}
/// @notice Hard bounds compiled into the code. The ParamsRegistry owner can only move parameters inside them.
library ParamsBounds {
error ParamOutOfBounds(string field);
uint256 internal constant BPS = 10_000;
/// @dev Bytes of the question besides the prefix and the proof, at the largest ids (see validate). The task's rules
/// are not in the question: they go to three definitions (SwarmQuestion.TASK_REF points to them).
uint256 internal constant QUESTION_FIXED = 193;
/// @dev Rule texts of a task (TaskRules: task, proof, noIf), each a definition member of at most maxTextBytes.
uint256 internal constant TASK_RULE_TEXTS = 3;
/// @dev `,"doer_shot":"<screenshotUrl, at most MAX_SCREENSHOT_URL_BYTES>"`: `"doer_shot":` 12 + 2 quotes + the
/// link itself (SwarmQuestion._member, TextLib.checkScreenshotUrl).
uint256 internal constant SHOT_MEMBER = 14 + MAX_SCREENSHOT_URL_BYTES;
/// @dev `{"v":1,"question":"` 19, `","definitions":{` 18, `}` 1, `,` 1, `,"consumer":{"chainId":` 23 + uint256 78,
/// `,"verifyingContract":"` 22 + address 42, `"}}` 3.
uint256 internal constant BODY_FIXED = 207;
function validate(Params memory p) internal pure {
_req(p.intake != address(0), "intake");
_req(p.devPrices != address(0), "devPrices");
_req(p.nft != address(0), "nft");
_req(p.treasury != address(0), "treasury");
_req(p.swarmAction != bytes32(0), "swarmAction");
// no USD conversion, no upper limit on one task's reward or on all open tasks together;
// each minimum is bounded in its own currency only
_req(p.minRewardUsdc >= 1e6 && p.minRewardUsdc <= 1_000e6, "minRewardUsdc");
_req(p.minRewardEth >= 0.0001e18 && p.minRewardEth <= 1e18, "minRewardEth");
_req(p.minRewardImd >= 0.01e18 && p.minRewardImd <= 10_000e18, "minRewardImd");
_req(p.minRewardYolo >= 1e18 && p.minRewardYolo <= 10_000_000e18, "minRewardYolo");
_req(p.bondFixedImd >= 0.01e18 && p.bondFixedImd <= 100e18, "bondFixedImd");
_req(p.doerBondBps <= 2_000, "doerBondBps");
_req(p.disputeBondBps <= 1_000, "disputeBondBps");
_req(p.maxClaims >= 1 && p.maxClaims <= 32, "maxClaims");
_req(p.maxTextBytes >= 32 && p.maxTextBytes <= 512, "maxTextBytes"); // Intake: definition value <= 512
_req(_inRange(p.disputeWindow, 24 hours, 7 days), "disputeWindow"); // never below 24h
_req(_inRange(p.voteWindow, 1 hours, 7 days), "voteWindow");
_req(_inRange(p.appealWindow, 1 hours, 7 days), "appealWindow");
_req(_inRange(p.swarmTimeout, 10 minutes, 3 days), "swarmTimeout");
_req(p.endDelta >= 1 && p.instantDelta >= p.endDelta && p.instantDelta <= 2_000, "delta");
_req(p.minWinnerWallets >= 1 && p.minWinnerWallets <= 100, "minWinnerWallets");
_req(p.feeBps <= 1_500, "feeBps");
_req(p.nftFeeBps <= p.feeBps, "nftFeeBps");
_req(p.winnerBondBps >= 2_000 && p.winnerBondBps <= BPS, "winnerBondBps");
// the swarm answer counts only from the panel we order and pay for: at least 3 agents, a strict
// majority of them, and exactly the panelSize / quorum written into bodyFields, so the two cannot drift apart
_req(p.minPanelSize >= 3 && p.minPanelSize <= 101, "minPanelSize");
_req(p.minQuorum > p.minPanelSize / 2 && p.minQuorum <= p.minPanelSize, "minQuorum");
_req(_hasNumber(p.bodyFields, '"panelSize":', p.minPanelSize), "bodyPanel");
_req(_hasNumber(p.bodyFields, '"quorum":', p.minQuorum), "bodyQuorum");
// question = prefix + 1 user string (proof) + fixed parts <= 2000 (Intake limit); the task's three rule texts
// are definitions, not question text. Fixed parts at most QUESTION_FIXED = 193 bytes:
// "TASK: definitions task, task_proof and task_no" 46, " | PROOF: " 10, " | PROOF TYPE: onchain_tx" 25,
// " | DOER: 0x…" 51, " | CASE: " + 2 x uint64 + uint32 + 2 slashes 61. Bytes >= characters, so the char
// limit holds too.
_req(p.questionPrefix.length + uint256(p.maxTextBytes) <= 2_000 - QUESTION_FIXED, "questionPrefix");
_req(p.definitionFields.length <= 4_096, "definitionFields");
_req(p.bodyFields.length >= 2 && p.bodyFields.length <= 2_048, "bodyFields");
// worst-case JSON body must stay under the Intake limit of 16 384 bytes: maxClaims claims, each with
// its own claim_N_proof (2x maxClaims fields — ReviewProofs.t.sol
// test_BodyBoundedByParams_OneDisputerOnly relies on this scaling by p.maxClaims, even though
// DisputeDesk.questionPart only ever fills 0 or 1 claim at runtime: the bound must still hold for every
// maxClaims the registry could accept, not just the one DisputeDesk happens to use today) + the task's
// three rule texts (definition members, key and quotes <= 40 bytes each; no doer_reply or
// appeal_reply), the question (prefix, proof, fixed part), the doer note member and the screenshot
// member, the template fields and BODY_FIXED for the JSON frame and the consumer. Exact worst case:
// test/review/ReviewQuestionSize.t.sol.
uint256 body = (2 * uint256(p.maxClaims) + TASK_RULE_TEXTS) * (uint256(p.maxTextBytes) + 40)
+ p.questionPrefix.length + uint256(p.maxTextBytes) + QUESTION_FIXED + (MAX_NOTE_BYTES + 15) + SHOT_MEMBER + p.definitionFields.length
+ p.bodyFields.length + BODY_FIXED;
_req(body <= 16_384, "bodySize");
}
/// @dev Whether `hay` holds the member `<key><value>` with no digit right after it (validate only: runs once
/// per proposed parameter set).
function _hasNumber(bytes memory hay, bytes memory key, uint256 value) private pure returns (bool) {
bytes memory needle = bytes.concat(key, bytes(Strings.toString(value)));
if (needle.length > hay.length) return false;
for (uint256 i; i <= hay.length - needle.length; ++i) {
uint256 k;
while (k < needle.length && hay[i + k] == needle[k]) ++k;
if (k < needle.length) continue;
uint256 end = i + k;
if (end == hay.length || hay[end] < "0" || hay[end] > "9") return true;
}
return false;
}
function _inRange(uint32 v, uint256 lo, uint256 hi) private pure returns (bool) {
return v >= lo && v <= hi;
}
function _req(bool ok, string memory field) private pure {
if (!ok) revert ParamOutOfBounds(field);
}
}
src/VaultTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @dev Shared types, events and errors of TaskVault and its desks (src/desks). TaskVault is the one public address:
/// it holds the money, the tasks and the swarm requests and forwards the other calls to the desk that owns the
/// state (CaseDesk: submissions, DisputeDesk: disputes, appeals, votes and settlements).
address constant ETH = address(0);
uint256 constant BPS = 10_000;
// kind 1 is reserved
uint8 constant SWARM_KIND_ESCALATION = 2; // NFT vote without decision, somebody paid to call the swarm
uint8 constant SWARM_KIND_APPEAL = 3; // appeal of an NFT decision
/// @dev Task categories: 0 trash, 1 crazy, 2 action, 3 sport, 4 food, 5 prank, 6 shill, 7 onchain, 8 other (the site's
/// labels and fallback covers). Set once at creation.
uint8 constant CATEGORY_COUNT = 9;
/// @dev Longest cover link: `ipfs://<CIDv1>` is 66 bytes, the rest is room for a path or an https fallback.
uint256 constant MAX_COVER_BYTES = 160;
/// @dev Task title: shown on the site, never sent to the swarm (the rules say what to do and how to prove it).
/// Same limit as DareTrophy.MAX_TITLE_BYTES (the doer resupplies the title at mint): a task created past 64
/// bytes could never mint a trophy (contract = 64, as on the site).
uint256 constant MAX_TITLE_BYTES = 64;
/// @dev Proof types: what a submission's proofUri must be (TextLib.checkProof). Set once at creation.
uint8 constant PROOF_X_POST = 0; // https://x.com/<user>/status/<id> (or twitter.com)
uint8 constant PROOF_VIDEO = 1; // https link on youtube.com or youtu.be, or an X post
uint8 constant PROOF_ONCHAIN_TX = 2; // 0x + 64 hex: an Ethereum mainnet transaction hash
uint8 constant PROOF_LINK = 3; // https link on a host of the allowlist (TextLib.checkHost)
uint8 constant PROOF_TYPE_COUNT = 4;
/// @dev Doer's note on a submission: optional, same text rule as the task rules (TextLib.validText: printable
/// ASCII only), same ceiling as maxTextBytes (ParamsBounds.validate, 32..512).
uint256 constant MAX_NOTE_BYTES = 512;
/// @dev Evidence.screenshotUrl: `https://` link on a host of the allowlist (TextLib.checkHost),
/// bounded so one screenshot link cannot blow up the swarm question (TextLib.checkScreenshotUrl).
uint256 constant MAX_SCREENSHOT_URL_BYTES = 300;
/// @dev Longest proof or screenshot link the host allowlist accepts (TextLib.checkHost).
uint256 constant MAX_LINK_BYTES = 512;
/// @dev onOracleResult(bytes32,(bytes32,uint256,bytes32,uint8,bytes,uint256,uint64,uint64,bytes32,bytes32,
/// uint16,uint16,uint16,uint64,uint64),bytes) - matches the IMD docs and a delivered mainnet callback.
bytes4 constant CALLBACK_SELECTOR = 0x510379c7;
/// @dev A swarm answer signed within the swarm timeout counts if it reaches the vault at most this long after the
/// timeout; silence is declared only after it, so the outcome never depends on who pokes when.
uint256 constant SWARM_DELIVERY_GRACE = 1 hours;
/// @dev At most this many swarm questions per submission (appeals and calls after silence together, and appeals void
/// because the Intake failed or its price rose). After the last one stays silent or is void the
/// submission ends as if nobody had called the swarm.
uint256 constant MAX_SWARM_CALLS = 3;
/// @dev The doer stake bonus: 4% of the reward x min(1, lock power / reward in
/// $YOLO), from any power, no threshold.
uint256 constant MAX_STAKE_BONUS_BPS = 400;
// ====================================================================== enums
enum TaskStatus {
None,
Open,
Completed, // a submission was accepted (Task.activeSub keeps its id)
Expired, // deadline passed with no submission in flight: everyone takes back their share
Unwound // cancelled by the dev wallet (TaskVault.cancelTask): everyone takes back what they put in
}
enum Phase {
None,
Queued, // waiting behind the active submission
Review, // active; dispute window
Voting, // at least one dispute: NFT vote running
NoDecision, // NFT did not decide: optimistic window, anyone may call the swarm paying fee + bond
Decided, // NFT decision stands: appeal window, anyone may appeal paying fee + bond
Appealed, // appeal filed (fee prepaid): the question is due at once, asked lazily (askAppealSwarm)
Asked, // the swarm was asked for a caller (appellant or NoDecision caller); answer or silence pending
Final, // settled, see Outcome
Void // queued submission of a task that was completed / unwound: bond refunded
}
enum Outcome {
None,
Accepted,
Rejected,
Unwound // cancelled by the dev wallet (TaskVault.cancelTask): everyone takes back what they put in
}
enum Verdict {
None,
Accept,
Reject
}
enum SwarmStatus {
Pending,
Answered,
Silent
}
// ====================================================================== structs
/// @notice A bond or penalty split by currency: `imd` is the fixed IMD part
/// (a `ParamsCore.bondFixedImd` parameter, never doubled; a side's own swarm call draws only from it, so it
/// is kept at least one swarm fee), `rew` is doerBondBps/disputeBondBps percent of the author's own reward
/// in the task's currency. Top-ups of other contributors and the $YOLO add-on are not part of any bond.
/// No oracle, no USD
/// conversion: every part is paid and penalized in its own currency.
struct Bond {
uint256 imd;
uint256 rew;
}
/// @notice How the payer provides IMD. `amountIn == 0`: mode B, IMD is pulled with transferFrom.
/// Otherwise mode A: `amountIn` of `tokenIn` (ETH or USDC) is swapped through the swap adapter with the
/// user's `minImdOut` and `deadline`; surplus IMD is returned in the same transaction.
/// @notice What a doer may attach to their proof link, both shown to the swarm and to NFT voters as their
/// argument (the proof link itself decides). `screenshotUrl`: an `https://` link to the picture or clip on
/// a host of the allowlist (TextLib.checkHost: x.com, twitter.com, pbs.twimg.com, youtube.com, youtu.be,
/// tiktok.com, instagram.com, drive.google.com, lh3.googleusercontent.com, photos.google.com, imgur.com,
/// i.imgur.com, t.me, ibb.co, i.ibb.co, reddit.com, i.redd.it, dropbox.com, arweave.net, etherscan.io,
/// sepolia.etherscan.io, github.com, kick.com, twitch.tv, clips.twitch.tv); required for x_post and video
/// (EvidenceRequired), optional otherwise. Empty = none;
/// otherwise no spaces, at most MAX_SCREENSHOT_URL_BYTES (TextLib.checkScreenshotUrl).
/// `note`: 0..MAX_NOTE_BYTES bytes, the text rule of the task rules.
struct Evidence {
string screenshotUrl;
string note;
}
struct ImdPay {
address tokenIn;
uint256 amountIn;
uint256 minImdOut;
uint64 deadline;
bytes route;
}
/// @notice The rules of a task: three texts, each 1..maxTextBytes bytes (TextLib.validText), each sent to the swarm as
/// its own definition (Intake: definition values <= 512), so a task may carry up to 3 x maxTextBytes of rules.
/// `task` (definition "task"): TASK, what to do, every step and every text needed (SPEECH and the like).
/// `proof` (definition "task_proof"): WINDOW, WHO, PROOF, SOURCE: when, who hands in, what the proof shows,
/// where it lives, where the moneycanbuy.fun label is if the task requires it. `noIf` (definition
/// "task_no"): "NO if: ...", when the answer is no.
/// Stored at creation, never change.
struct TaskRules {
string task;
string proof;
string noIf;
}
/// @dev Whoever asks the swarm (DisputeDesk.callSwarm, CaseDesk.askAppealSwarm)
/// resupplies in calldata everything the question needs that storage holds only as a hash - the task's
/// three rule texts (Task.rulesHash) and the filed disputer's reason + proof link (DisputerInfo.reasonHash).
/// Checked against both hashes, then handed to SwarmQuestion.build(); never written to storage.
struct RuleTexts {
string task;
string taskProof;
string taskNo;
string disputeReason;
string disputerProofUri;
}
struct Task {
address author;
uint64 deadline; // always set, never changes (no task without a deadline)
uint32 paramsVersion;
TaskStatus status;
address currency; // ETH, USDC, IMD or $YOLO
uint64 busyEpoch; // reserved, always 0
uint8 category; // see CATEGORY_COUNT; packed into the slot written at creation anyway (no extra SSTORE)
uint8 proofType; // see PROOF_TYPE_COUNT; same slot
uint64 activeSub; // the submission under judging; on a Completed task: the accepted one
uint32 queueHead;
uint32 queueTail;
uint32 rejectedCount;
uint64 createdAt; // YOLO Predict weighs positions over [createdAt, deadline]
uint256 pot; // reward in play = sum of active shares; a top-up joins it at once, also during a check
uint256 pending; // reserved, always 0
// keccak256(abi.encode(task, proof, noIf)) instead of the 3 strings (up to 1 536 B
// = ~48 slots) - the texts live only in createTask's calldata and the TaskCreated event; whoever later needs
// them to build the swarm question (DisputeDesk.callSwarm, CaseDesk.askAppealSwarm) resupplies them in that
// same call and the hash is checked against this, else RulesMismatch.
bytes32 rulesHash;
}
struct Contribution {
uint128 active;
uint128 pending; // reserved, always 0
uint64 pendingEpoch; // reserved, always 0
bool ever; // ever contributed to this task (read by isContributor only; in a dispute they are paid like anyone)
}
struct Submission {
uint64 taskId;
address doer;
Phase phase;
Outcome outcome;
Verdict nftDecision;
uint32 asks; // swarm questions asked or void for this submission (question nonce; at most MAX_SWARM_CALLS)
uint16 stakeBps; // the doer stake bonus fixed at submission, 0..400 bps of R
bool staked; // the doer had a stake at submission (power and a $YOLO price), even if stakeBps floors to 0
uint64 submittedAt; // the lock behind stakeBps must still run at the payout (YoloLockHub.stakePower)
uint64 activatedAt;
uint64 windowEnd; // end of the dispute window
uint64 voteEnd;
uint64 decidedAt; // time of the NFT decision
uint64 callFrom; // start of the current window to call the swarm (NoDecision / Decided)
uint64 appealedAt; // when markAppealed ran; stepDeadline of Phase.Appealed = appealedAt + swarmTimeout (void)
// R and the author's part of it share one slot (both < 2^128: every share of a pot is a uint128)
uint128 reward; // R, fixed at submission (task currency): what the doer is paid
uint128 base; // the author's own share of R at submission: the base of every bond's "rew" part
uint256 addon; // $YOLO add-on, fixed at submission (its voter pool on acceptance; not part of any bond)
Bond bond; // doer bond: imd fixed + rew% of the author's base (reward currency), never doubled
bytes32 request; // current swarm request (Intake id)
string proofUri;
string screenshotUrl; // Evidence.screenshotUrl, empty = none
string doerNote; // Evidence.note, empty = none: their "why honest" text, written at submission
// (no separate "doer answers the dispute" step)
}
struct Dispute {
Bond bondTotal;
// uint32: votes are bounded today by the IMD identity NFT's MAX_SUPPLY (2,000 NFTs, 1 NFT = 1 vote, each id once
// per dispute), far under uint16's 65,535 — but that bound lives in the NFT contract, not here, and SafeCast reverts
// rather than wraps, so an NFT collection or delegation scheme that crosses 65,535 would permanently
// stick every vote on a dispute with uint16; uint32 costs one storage slot and leaves headroom many orders
// above the NFT supply.
uint32 votesAccept;
uint32 votesReject;
uint32 walletsAccept;
uint32 walletsReject;
address disputer; // one dispute, one disputer: address(0) = nobody yet
uint32 openBlock; // the block of the dispute (no snapshot: an NFT votes with its holder at the vote)
}
struct DisputerInfo {
Bond bond;
bool claimed;
// keccak256(abi.encode(reason, proofUri)) instead of the raw reason string;
// proofUri is the link to the disputer's own proof that the submission fails the rule, same text
// rule and byte cap as reason. Both texts live in dispute()'s calldata and the Disputed event; whoever later
// calls the swarm (DisputeDesk.callSwarm, CaseDesk.askAppealSwarm) resupplies them, checked against this hash.
bytes32 reasonHash;
}
/// @notice The current swarm caller of a submission: an appellant against the NFT decision, or whoever called the
/// swarm when the NFT did not decide (they pick a side). They pay the swarm fee and a dispute bond. At most one
/// at a time; cleared when the swarm stays silent (their bond is credited back, their fee is lost).
struct Appeal {
address appellant;
bool sidesDoer; // true: stands for acceptance (appeals a "reject" decision)
Bond bond;
uint256 funds; // prepaid swarm fee not spent yet
uint256 spent; // paid to the Intake for this question (a record only: a winning stranger gets up to 0.5 IMD back,
// and only from what is left of the loser's IMD bond, DisputeDesk._settleDecided)
// no reason text: an appeal/call of the swarm is a button,
// not a text field. The panel still sees the original dispute reason (DisputerInfo), not a second one.
// a side of the dispute (the doer, or the disputer against the doer) calling the swarm for itself: no second
// bond (`bond` stays 0), the fee comes out of its dispute bond first;
// the part of the prepaid fee its bond covers, `funds` is what it paid on top
uint256 fromBond;
}
/// @notice IMD the sides' own dispute bonds paid to the swarm for their calls: taken off what
/// the side gets back or loses at settlement.
struct SideSpent {
uint128 doer;
uint128 disputer;
}
/// @notice Buckets of a final submission paid out by lazy per-claimant claims. Every bucket is split
/// remaining/remaining, so the last claimant takes the exact rest and no dust is left.
struct Settlement {
bool neutral; // cancelled by the dev wallet: every bond back, no penalty, no voter reward
bool disputersWon; // the disputers are on the winning side (Rejected)
uint256 stakeBps; // accepted with the doer stake bonus: its share of R in bps (0..400), YoloSweetener pays the same share
Bond disputerReward; // for winning disputers (any of them: author/contributor included),
// pro rata to bonds, per currency
Bond disputerRewardBonds; // their bonds not yet claimed, per currency
Bond voterBond; // loser bond share for NFT votes on the final side, when the NFT decided right
uint256 voterFee; // reward currency (10% reward fee share) for the same votes
uint256 voterVotesLeft; // correct votes not yet claimed
}
struct SwarmRequest {
uint64 subId;
uint64 askedAt;
uint64 answerTime; // signed issuedAt clamped to [askedAt, recordedAt]: decides "in time"
uint64 recordedAt; // when the answer reached the vault: windows that follow an answer start here
uint8 kind; // SwarmQuestion.KIND_*
bool answered;
bool answer;
bytes32 questionHash; // keccak256(question) - assumed formula; informational (SwarmAsked), checks nothing
}
// ====================================================================== events
/// @dev `title` and `cover` (empty = category cover) live only in this event: nothing on chain reads them, and a log
/// costs ~8 gas per byte instead of ~22k per 32-byte storage slot. Nothing here can change after creation.
event TaskCreated(
uint256 indexed taskId,
address indexed author,
address currency,
uint256 amount,
uint64 deadline,
string title,
TaskRules rules,
uint8 category,
uint8 proofType,
string cover
);
/// @dev `duringCheck`: made while a submission was being checked; it joined the reward in play all the same.
event ToppedUp(uint256 indexed taskId, address indexed contributor, uint256 amount, bool duringCheck);
event ContributionWithdrawn(uint256 indexed taskId, address indexed contributor, uint256 amount);
event TaskStatusChanged(uint256 indexed taskId, TaskStatus status);
/// @notice The dev wallet cancelled an open task: status Unwound, everyone takes back their own.
event TaskCancelled(uint256 indexed taskId, address indexed by);
event SweetenerBound(address indexed sweetener);
/// @dev `proofUri`: always set, not indexed so Etherscan decodes it from this log —
/// the one event every submission emits, so this is where the site/a reader finds the proof link without
/// depending on the optional `EvidenceAttached`.
event Submitted(
uint256 indexed subId,
uint256 indexed taskId,
address indexed doer,
uint256 reward,
uint256 bondImd,
uint256 bondRew,
bool queued,
string proofUri
);
/// @dev Emitted right after `Submitted` when the doer attached a screenshot link or a note (Evidence).
event EvidenceAttached(uint256 indexed subId, string screenshotUrl, string note);
event Activated(uint256 indexed subId, uint64 windowEnd);
/// @dev `disputerProofUri`: the disputer's own proof that the submission
/// fails the rule; empty when the disputer gave no link (optional). Both strings are not indexed so Etherscan decodes them on a verified contract, straight
/// from this log, with no site and no indexer.
event Disputed(
uint256 indexed subId,
address indexed disputer,
uint256 bondImd,
uint256 bondRew,
string reason,
string disputerProofUri
);
event DoerReplied(uint256 indexed subId, string reply);
event NftDecided(uint256 indexed subId, Verdict decision, bool instant);
event NoNftDecision(uint256 indexed subId);
/// @dev No `reason`: appeal is a button.
event Appealed(
uint256 indexed subId, address indexed appellant, uint256 bondImd, uint256 bondRew, uint256 prepaid
);
event AppealReplied(uint256 indexed subId, address indexed by, string reply);
event SwarmAsked(uint256 indexed subId, bytes32 indexed requestId, uint8 kind, uint256 paid, bytes32 questionHash);
event SwarmCalled(
uint256 indexed subId,
address indexed caller,
bool sidesDoer,
uint256 bondImd,
uint256 bondRew,
uint256 fee
);
event SwarmSilent(uint256 indexed subId, bytes32 indexed requestId, uint64 windowFrom);
event AppealVoided(uint256 indexed subId, uint256 price);
event SwarmAnswered(bytes32 indexed requestId, uint256 indexed subId, bool answer, uint64 answerTime, bool viaCallback);
event AttestationIgnored(bytes32 indexed requestId, uint8 reason);
event SubmissionFinal(uint256 indexed subId, uint256 indexed taskId, Outcome outcome);
event DisputerClaimed(uint256 indexed subId, address indexed disputer, uint256 imd, uint256 rew);
event VoterRewardClaimed(uint256 indexed subId, address indexed payTo, uint256 votes, uint256 imd, uint256 rew, uint256 fee);
event VoidSubmissionClaimed(uint256 indexed subId, address indexed doer, uint256 imd, uint256 rew);
event Credited(address indexed token, address indexed account, uint256 amount);
event Paid(address indexed token, address indexed account, uint256 amount);
event TreasurySwept(address indexed token, address indexed treasury, uint256 amount);
/// @dev `amount` of `token` left for burning: $YOLO to the BuybackBurner (its burnYolo sends it to 0x…dEaD), any
/// other token (ETH, USDC, IMD) straight to the buyback wallet, to the BuybackBurner only if that send fails.
event Burned(address indexed token, uint256 amount);
event SubmissionSettled(
uint256 indexed subId,
bool nftRight,
uint256 penaltyImd,
uint256 toVotersImd,
uint256 toTreasuryImd,
uint256 penaltyRew,
uint256 toVotersRew,
uint256 toTreasuryRew
);
event ParamsCached(uint32 indexed version);
// ====================================================================== errors
error Paused();
error BadCurrency();
error BadAmount();
error BadDeadline();
error BadText();
/// @dev A text resupplied to build the swarm question does not hash to what was stored at creation/dispute:
/// wrong text, wrong order, or tampered calldata.
error RulesMismatch();
error BadTitle();
error BadCategory();
error BadProofType();
error BadCover();
/// @dev proofUri does not have the form its task's proof type requires (TextLib.checkProof).
error BadProof(uint8 proofType);
/// @dev Evidence: a note breaking the text rule or longer than MAX_NOTE_BYTES, or a screenshotUrl that is not a
/// bare `https://` link within MAX_SCREENSHOT_URL_BYTES (TextLib.checkScreenshotUrl).
error BadEvidence();
/// @dev A screenshot link (or video link, same Evidence.screenshotUrl) is mandatory for the
/// proof types the swarm cannot open itself (x_post, x_reply — both PROOF_X_POST — and video).
error EvidenceRequired();
/// @dev A proof link or screenshot link that is not `https://` on a host of the allowlist, or longer than
/// MAX_LINK_BYTES (TextLib.checkHost).
error HostNotAllowed();
error RewardTooSmall();
error NotEnoughEth();
error TaskNotOpen();
error DeadlinePassed();
error WrongPhase();
error WindowClosed();
error AlreadyDisputed();
/// @dev The doer of a submission cannot dispute it.
error DoerCannotDispute();
/// @dev The sender neither owns `tokenId` nor is a delegate.xyz delegate of its owner.
error NotTokenHolder(uint256 tokenId);
/// @dev `tokenId` already voted in this dispute, or appears twice in the list.
error TokenVoted(uint256 tokenId);
/// @dev A vote with no NFT ids.
error NoTokens();
/// @dev A vote with a side other than 1/2 or no payTo.
error BadVote();
/// @dev The wallet already voted the other side on this submission: the side cannot change.
error AlreadyVoted();
error RewardChanged();
error CostAboveMax();
error ImdShort();
error NotOpponent();
error AlreadyReplied();
error SwarmUnavailable();
error ActionNotSold();
error UnknownRequest();
error NothingToClaim();
error NotFinal();
error InsufficientGas();
error SwapDisabled();
error SwapExpired();
error SwapShort();
error TransferFailed();
/// @dev withdraw/withdrawTo to the zero address: a plain ETH `call` to address(0) would otherwise
/// succeed and burn the money with no way back.
error WithdrawToZero();
/// @dev A desk function called by someone other than the vault or the desk it serves.
error NotAuthorized();
/// @dev The vault has no route for this selector.
error UnknownFunction();
/// @dev A desk can be wired only once, by the vault, in the transaction that deployed it.
error WiringClosed();
error WrongWiring();
src/desks/Desk.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ParamsCore} from "../VaultParams.sol";
import {ParamsRegistry} from "../ParamsRegistry.sol";
import {IIntake} from "../interfaces/IIntake.sol";
import {TextRules} from "../helpers/TextRules.sol";
import {IVault} from "./DeskApi.sol";
import "../VaultTypes.sol";
/// @title Desk
/// @notice Common base of the two desks that hold the judging state of the vault (CaseDesk, DisputeDesk).
///
/// Wiring. The desks are deployed first, the vault last with their addresses; the vault's constructor calls
/// `wire` on each desk. `wire` works once and only inside the deployment transaction: the desk's constructor
/// raises a transient flag (EIP-1153), which disappears when that transaction ends. The launch deploys every
/// contract in one transaction, so nobody else can wire a desk first, and nobody can rewire it later.
///
/// Calls. Users call the vault; the vault forwards the call here and appends 52 bytes: the original sender
/// (20) and msg.value (32), the ETH itself stays in the vault. Functions marked `routed` accept only the
/// vault and read the user from `_sender()`. The other non-view functions accept only the vault or the named
/// sibling. The desks hold no money and make no transfer: every amount moves through the vault (IVault),
/// which also keeps the tasks.
abstract contract Desk {
/// @dev transient slot: 1 from the constructor until the end of the deployment transaction
bytes32 private constant WIRING_SLOT = keccak256("imd.taskvault.desk.wiring");
uint256 internal constant SUFFIX = 52;
address public immutable registry;
IERC20 public immutable imd;
IERC20 public immutable usdc;
TextRules internal immutable textRules;
address public vault;
address internal caseDesk;
address internal disputeDesk;
constructor(address registry_, address imd_, address usdc_, address textRules_) {
registry = registry_;
imd = IERC20(imd_);
usdc = IERC20(usdc_);
textRules = TextRules(textRules_);
bytes32 slot = WIRING_SLOT;
assembly ("memory-safe") {
tstore(slot, 1)
}
}
/// @notice True for the CaseDesk, false for the DisputeDesk: which slot of the vault this desk belongs in.
function isCaseDesk() public pure virtual returns (bool);
/// @notice Called once by the vault's constructor. Checks that the vault and this desk agree on the environment.
function wire(address registry_, address imd_, address usdc_, address caseDesk_, address disputeDesk_) external {
bytes32 slot = WIRING_SLOT;
uint256 open;
assembly ("memory-safe") {
open := tload(slot)
tstore(slot, 0)
}
if (open == 0 || vault != address(0)) revert WiringClosed();
if (registry_ != registry || imd_ != address(imd) || usdc_ != address(usdc)) revert WrongWiring();
if (caseDesk_ == address(0) || disputeDesk_ == address(0)) revert WrongWiring();
// the vault must put this desk in its own slot: swapped desks would deploy and then revert every
// submission
if ((isCaseDesk() ? caseDesk_ : disputeDesk_) != address(this)) revert WrongWiring();
vault = msg.sender;
caseDesk = caseDesk_;
disputeDesk = disputeDesk_;
}
modifier routed() {
if (msg.sender != vault) revert NotAuthorized();
_;
}
modifier only(address caller) {
if (msg.sender != caller) revert NotAuthorized();
_;
}
/// @dev The user who called the vault (valid in `routed` functions only).
function _sender() internal pure returns (address a) {
assembly ("memory-safe") {
a := shr(96, calldataload(sub(calldatasize(), 52)))
}
}
/// @dev The msg.value the user sent to the vault (valid in `routed` functions only).
function _value() internal pure returns (uint256 v) {
assembly ("memory-safe") {
v := calldataload(sub(calldatasize(), 32))
}
}
function _bank() internal view returns (IVault) {
return IVault(vault);
}
/// @dev The parameter snapshot of `version` (never changes once activated).
function _params(uint32 version) internal view returns (ParamsCore memory) {
return ParamsRegistry(registry).core(version);
}
/// @dev Live swarm price that never reverts (0 = not available now).
function _swarmPrice(ParamsCore memory p) internal view returns (uint256) {
try IIntake(p.intake).priceOf(p.swarmAction, address(imd)) returns (uint256 price) {
return price;
} catch {
return 0;
}
}
/// @dev Percent part of a bond (no escalation, always the same
/// bps, never above `amount` itself). No oracle: `amount` (the author's own reward) is already in the
/// task's currency.
function _pctBond(uint256 amount, uint16 bps) internal pure returns (uint256 b) {
if (amount == 0) return 0;
b = amount * bps / BPS;
if (b > amount) b = amount;
}
/// @dev The doer bond of a submission: 0.5 IMD fixed + 3% of the author's own reward `base` (no top-ups of
/// others, no $YOLO add-on), always the same regardless of rejected submissions or the
/// queue.
function _doerBond(uint256 base, ParamsCore memory p) internal pure returns (Bond memory b) {
b.imd = p.bondFixedImd;
b.rew = _pctBond(base, p.doerBondBps);
}
/// @dev The dispute/appeal bond of a submission: the fixed IMD part plus 1% of the author's own reward `base`
/// (no top-ups of others, no $YOLO add-on).
function _disputeBond(uint256 base, ParamsCore memory p) internal pure returns (Bond memory b) {
b.imd = p.bondFixedImd;
b.rew = _pctBond(base, p.disputeBondBps);
}
/// @dev Every user string sent to the swarm: TextLib.validText with the version's length limit.
function _checkText(string calldata str, ParamsCore memory p) internal view {
if (!textRules.validText(str, p.maxTextBytes)) revert BadText();
}
}
src/desks/DeskApi.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "../VaultTypes.sol";
/// @dev The internal API between TaskVault and its desks. Nothing here is callable by users: every function checks
/// that its caller is the vault or the one desk it serves (see each desk). Users reach the desks only through
/// the vault, which appends the original sender and msg.value to the forwarded calldata.
/// @notice What a task tells the case desk at submission time (TaskVault.submitTerms).
struct SubmitTerms {
TaskStatus status;
uint64 deadline;
uint32 version; // parameter version of the task
address currency;
uint8 proofType;
bool busy; // a submission is active: a new one is queued
uint256 pot;
uint256 base; // the author's own share of the pot: the base of the bonds' "rew" part
uint256 addon; // $YOLO add-on of the task (the vault's YoloSweetener): no bond, in the stake bonus base with the pot
}
/// @notice The fixed fields of a submission the other desks read (CaseDesk.subCore).
struct SubCore {
uint64 taskId;
address doer;
Phase phase;
Outcome outcome;
Verdict nftDecision;
uint64 windowEnd;
uint64 voteEnd;
uint32 version; // parameter version of its task
address currency; // reward currency of its task
uint256 reward; // R, fixed at submission (task currency)
uint256 base; // the author's own share of R at submission: the base of the dispute/appeal bond's "rew" part
uint256 addon; // $YOLO add-on, fixed at submission (a voter pool of its own on acceptance)
}
/// @notice A submission at settlement (CaseDesk -> DisputeDesk.settle).
struct Facts {
uint64 taskId;
uint32 version;
address currency;
address doer;
Verdict nftDecision;
uint256 reward;
Bond bond;
uint64 since; // the submission's time: the lock behind the stake bonus must still run at the payout
uint16 stakeBps; // the doer stake bonus fixed at submission (0..400 bps of R)
bool staked; // the doer had a stake at submission: the staked split applies even if stakeBps floors to 0
}
/// @notice NFT vote totals of a submission.
struct Tally {
uint256 accept;
uint256 reject;
uint256 walletsAccept;
uint256 walletsReject;
}
/// @notice The fixed fields of the current swarm caller of a submission (an `Appeal` without its texts).
struct AppealCore {
address appellant;
bool sidesDoer;
uint256 funds;
}
/// @notice A swarm question the vault pays for (IVault.ask): the Intake, its action and price, and the panel the
/// answer must come from (the parameters of the submission's task).
struct AskTerms {
uint64 subId;
uint8 kind;
uint16 minPanelSize;
uint16 minQuorum;
address intake;
bytes32 action;
bytes32 questionHash;
uint256 price;
}
/// @notice The vault as the desks see it: the bank (every amount moves here) and the tasks.
interface IVault {
function collectImd(address from, uint256 msgValue, uint256 needed, address adapter, ImdPay calldata payIn)
external
returns (uint256 ethNeeded);
/// @notice Books `amount` of `currency` from `from` for a bond's "rew" or "add" part (ETH from msg.value, IMD by
/// plain transferFrom, any other token by transferFrom): no swap, no oracle.
function collectBondPart(address from, uint256 msgValue, address currency, uint256 amount)
external
returns (uint256 ethNeeded);
function settleValue(address payer, uint256 msgValue, uint256 ethNeeded) external;
function credit(address token, address account, uint256 amount) external;
function pay(address token, address to, uint256 amount) external;
function addTreasury(address token, uint256 amount) external;
function burn(address token, uint256 amount) external;
function ask(AskTerms calldata t, bytes calldata body) external returns (bool ok, uint256 spent, bytes32 requestId);
function requests(bytes32 requestId) external view returns (SwarmRequest memory);
function advance(uint256 taskId) external;
function isContributor(uint256 taskId, address who) external view returns (bool);
function submitTerms(uint256 taskId, address doer) external view returns (SubmitTerms memory);
function potOf(uint256 taskId) external view returns (uint256);
function place(uint256 taskId, uint256 subId, bool queued) external;
function closeSubmission(uint256 taskId, Outcome o, uint256 reward) external returns (uint256 next);
function statusOf(uint256 taskId) external view returns (TaskStatus);
function sweetener() external view returns (address);
}
/// @notice The doer stake (YoloLockHub): a lock's power at a moment (strictly before it), and the
/// power a submission made at `since` keeps at the payout (0 once that lock ended or was withdrawn).
interface IDoerStake {
function powerAt(address who, uint256 t) external view returns (uint256);
function stakePower(address who, uint64 since) external view returns (uint256);
}
interface ICaseDesk {
function step(uint256 subId) external returns (bool moved);
function stepDeadline(uint256 subId) external view returns (uint256);
function subCore(uint256 subId) external view returns (SubCore memory);
function advanced(uint256 subId) external returns (SubCore memory);
function startVote(uint256 subId, uint32 voteWindow) external;
function markAppealed(uint256 subId) external;
function askEscalation(uint256 subId, uint256 price, RuleTexts calldata rt) external returns (bool ok, uint256 spent);
function askAppeal(uint256 subId, uint256 funds, RuleTexts calldata rt) external;
function unwind(uint256 subId) external;
function tryInstantDecision(uint256 subId, Tally calldata v) external;
function voteState(uint256 subId) external view returns (Phase phase, uint64 voteEnd, uint32 version);
function doerBondImd(uint256 subId) external view returns (uint256);
}
interface IDisputeDesk {
function tally(uint256 subId) external view returns (Tally memory);
function appealCore(uint256 subId) external view returns (AppealCore memory);
function appealAsked(uint256 subId, uint256 spent) external;
function dropCaller(uint256 subId) external;
function settle(uint256 subId, Outcome o, Facts calldata f) external;
}
src/helpers/SwarmQuestion.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {Submission, Task, RuleTexts, RulesMismatch} from "../VaultTypes.sol";
/// @title SwarmQuestion
/// @notice Builds the Intake JSON body (action oracle.request(at)oracle-1, docs "Ask the oracle") on-chain, so no
/// party can smuggle its own question. The task's rule texts and the dispute's reason/proof link are not
/// read from storage: they come in as `RuleTexts`, resupplied by
/// whoever is asking the swarm now, and are checked against Task.rulesHash / DisputerInfo.reasonHash
/// before they ever reach this builder (`SwarmQuestionBuilder.buildFor`):
/// {"v":1,"question":"<prefix>TASK: definitions task, task_proof and task_no | PROOF: .. | PROOF TYPE: x_post
/// | DOER: 0x.. | CASE: t/s/n",
/// "definitions":{<template definitions>,"task":"..","task_proof":"..","task_no":"..",
/// "claim_1":"..","claim_1_proof":"..",...,"doer_note":"..",
/// "doer_shot":"<https:// link, allowlisted host>"},
/// <bodyFields: chainId, window, answerType "bool", evidence, panelSize, quorum, validForSeconds, ...>,
/// "consumer":{"chainId":<chain>,"verifyingContract":"<vault>"}}
/// The question stays short (Intake limit 2000 chars); the task's three rule texts (TaskRules: TASK, PROOF,
/// NO) and the party texts go to `definitions` (values <= 512)
/// and the template must tell the panel they are untrusted claims. All strings were checked at input to
/// contain no quote, backslash or control characters, so they are embedded verbatim.
/// `questionHash` returned here is keccak256(question): the real derivation used by the IMD plane is
/// UNVERIFIED. It is only recorded (SwarmAsked, SwarmRequest): the callback path does not use it.
library SwarmQuestion {
// kind 1 is reserved
uint8 internal constant KIND_ESCALATION = 2; // = SWARM_KIND_ESCALATION
uint8 internal constant KIND_APPEAL = 3; // = SWARM_KIND_APPEAL
/// @dev Where the question points the panel for the task: its rules are the definitions task (TASK), task_proof
/// (WINDOW, WHO, PROOF, SOURCE) and task_no (NO if). Counted in ParamsBounds.QUESTION_FIXED.
bytes internal constant TASK_REF = "TASK: definitions task, task_proof and task_no";
struct Input {
bytes prefix;
bytes definitionFields; // template definitions: compact JSON members, may be empty
bytes bodyFields;
string task; // TaskRules.task: definition "task"
string taskProof; // TaskRules.proof: definition "task_proof"
string taskNo; // TaskRules.noIf: definition "task_no"
string proofUri;
string proofType; // x_post | video | onchain_tx | link
string screenshotUrl; // Evidence.screenshotUrl: empty = none
string doerNote;
address doer;
uint256 taskId;
uint256 subId;
uint256 nonce;
uint8 kind;
string[] claims; // dispute reasons, in filing order
string[] claimProofs; // parallel to claims: the disputer's own proof link
uint256 chainId;
address consumer;
}
function build(Input memory q) internal pure returns (bytes memory body, bytes32 questionHash) {
bytes memory question = bytes.concat(
q.prefix,
TASK_REF,
" | PROOF: ",
bytes(q.proofUri),
" | PROOF TYPE: ",
bytes(q.proofType),
" | DOER: ",
bytes(Strings.toHexString(q.doer)),
" | CASE: ",
bytes(Strings.toString(q.taskId)),
"/",
bytes(Strings.toString(q.subId)),
"/",
bytes(Strings.toString(q.nonce))
);
questionHash = keccak256(question);
bytes memory defs = q.definitionFields;
// the task's rules, one definition each (each 1..maxTextBytes <= 512, the Intake limit of a definition value)
defs = _member(defs, "task", bytes(q.task));
defs = _member(defs, "task_proof", bytes(q.taskProof));
defs = _member(defs, "task_no", bytes(q.taskNo));
for (uint256 i; i < q.claims.length; ++i) {
bytes memory idx = bytes(Strings.toString(i + 1));
defs = _member(defs, bytes.concat("claim_", idx), bytes(q.claims[i]));
// the disputer's own proof link, one definition per claim (parallel to
// claim_N), not merged into the reason text.
defs = _member(defs, bytes.concat("claim_", idx, "_proof"), bytes(q.claimProofs[i]));
}
// the doer's "why honest" text, attached to the proof at submission (no separate
// "doer answers the dispute" step)
defs = _member(defs, "doer_note", bytes(q.doerNote));
defs = _member(defs, "doer_shot", bytes(q.screenshotUrl));
// no "appeal" definition: an appeal/call of the swarm carries no text.
body = bytes.concat('{"v":1,"question":"', question, '"');
if (defs.length != 0) body = bytes.concat(body, ',"definitions":{', defs, "}");
body = bytes.concat(
body,
",",
q.bodyFields,
',"consumer":{"chainId":',
bytes(Strings.toString(q.chainId)),
',"verifyingContract":"',
bytes(Strings.toHexString(q.consumer)),
'"}}'
);
}
/// @dev Name of a proof type in the question (the same words the site and the templates use).
function proofTypeName(uint8 proofType) internal pure returns (string memory) {
if (proofType == 0) return "x_post";
if (proofType == 1) return "video";
if (proofType == 2) return "onchain_tx";
return "link";
}
/// @dev Appends `"key":"value"` to a list of JSON members; empty values are skipped.
function _member(bytes memory list, bytes memory key, bytes memory value) private pure returns (bytes memory) {
if (value.length == 0) return list;
bytes memory m = bytes.concat('"', key, '":"', value, '"');
return list.length == 0 ? m : bytes.concat(list, ",", m);
}
}
/// @title SwarmQuestionBuilder
/// @notice Stateless helper of the CaseDesk: assembles the question of a submission from what the vault's desks
/// store (their public views) and builds the Intake body. Read-only; the vault pays and sends it.
contract SwarmQuestionBuilder {
/// @param maxClaims how many dispute reasons go into the question (the task's parameter version)
/// @param rt the task rule texts and the filed dispute's reason/proof link,
/// resupplied by whoever is asking the swarm now (DisputeDesk.callSwarm, CaseDesk.askAppealSwarm) -
/// storage holds only their hashes (Task.rulesHash, DisputerInfo.reasonHash).
function buildFor(address vault, uint256 subId, uint8 kind, uint256 maxClaims, RuleTexts calldata rt)
external
view
returns (bytes memory body, bytes32 questionHash)
{
IQuestionSources v = IQuestionSources(vault);
Submission memory s = IQuestionSources(v.caseDesk()).getSubmission(subId);
Task memory t = v.getTask(s.taskId);
if (keccak256(abi.encode(rt.task, rt.taskProof, rt.taskNo)) != t.rulesHash) revert RulesMismatch();
// slither-disable-next-line uninitialized-local
SwarmQuestion.Input memory q;
(q.prefix, q.definitionFields, q.bodyFields) = IQuestionSources(v.registry()).template(t.paramsVersion);
q.task = rt.task;
q.taskProof = rt.taskProof;
q.taskNo = rt.taskNo;
q.proofType = SwarmQuestion.proofTypeName(t.proofType);
q.proofUri = s.proofUri;
q.screenshotUrl = s.screenshotUrl;
q.doerNote = s.doerNote;
q.doer = s.doer;
q.taskId = s.taskId;
q.subId = subId;
q.nonce = uint256(s.asks) + 1; // unique per question of this submission
q.kind = kind;
// at most one dispute reason (one dispute, one disputer). No "appeal" text.
(q.claims, q.claimProofs) =
IQuestionSources(v.disputeDesk()).questionPart(subId, maxClaims, rt.disputeReason, rt.disputerProofUri);
q.chainId = block.chainid;
q.consumer = vault;
return SwarmQuestion.build(q);
}
}
/// @dev The views the builder reads: the vault's tasks and desk addresses, the desks' records, the registry's template.
interface IQuestionSources {
function registry() external view returns (address);
function caseDesk() external view returns (address);
function disputeDesk() external view returns (address);
function getSubmission(uint256 subId) external view returns (Submission memory);
function getTask(uint256 taskId) external view returns (Task memory);
function template(uint32 version) external view returns (bytes memory, bytes memory, bytes memory);
function questionPart(uint256 subId, uint256 maxClaims, string calldata reason, string calldata disputerProofUri)
external
view
returns (string[] memory claims, string[] memory claimProofs);
}
src/helpers/TextRules.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "../VaultTypes.sol";
/// @title TextLib
/// @notice The text rules of every user string the vault stores or sends to the swarm (pure, inlined into TextRules).
library TextLib {
/// @dev Every user string is embedded verbatim into the swarm JSON body: 1..maxLen bytes of printable ASCII
/// 0x20..0x7e only (English only — no Cyrillic, CJK, emoji or any other byte >= 0x80),
/// no quote, backslash or DEL. Malformed text could make the Intake refuse the body, and a refusal counts
/// as silence. Used for the condition, proofs, reasons, replies, the title and the doer note.
/// Reads calldata directly and does no overflow checks: every index is below `len`, which calldata bounds.
function validText(string calldata str, uint256 maxLen) internal pure returns (bool) {
uint256 len = bytes(str).length;
if (len == 0 || len > maxLen) return false;
uint256 at;
assembly ("memory-safe") {
at := str.offset
}
unchecked {
uint256 i;
while (i < len) {
if (i + 32 <= len) {
uint256 w;
assembly ("memory-safe") {
w := calldataload(add(at, i))
}
if (w & HIGH_BITS == 0) {
// 32 ASCII bytes at once
if (_hasBadAscii(w)) return false;
i += 32;
continue;
}
return false; // some byte of this word is >= 0x80: not plain ASCII
}
uint256 c = _byteAt(at, i);
if (c >= 0x80 || c < 0x20 || c == 0x22 || c == 0x5c || c == 0x7f) return false;
++i;
}
}
return true;
}
uint256 private constant ONES = 0x0101010101010101010101010101010101010101010101010101010101010101;
uint256 private constant HIGH_BITS = ONES * 0x80;
/// @dev Whether a word of 32 ASCII bytes holds a control character, quote, backslash or DEL. Exact (Bit Twiddling
/// Hacks "hasless" and "haszero", valid for bytes below 0x80): `(x - ONES * n) & ~x & HIGH_BITS` is nonzero
/// iff some byte of x is below n.
function _hasBadAscii(uint256 w) private pure returns (bool) {
unchecked {
uint256 x22 = w ^ (ONES * 0x22);
uint256 x5c = w ^ (ONES * 0x5c);
uint256 x7f = w ^ (ONES * 0x7f);
uint256 found =
((w - ONES * 0x20) & ~w) | ((x22 - ONES) & ~x22) | ((x5c - ONES) & ~x5c) | ((x7f - ONES) & ~x7f);
return found & HIGH_BITS != 0;
}
}
function _byteAt(uint256 at, uint256 i) private pure returns (uint256 c) {
assembly ("memory-safe") {
c := byte(0, calldataload(add(at, i)))
}
}
/// @dev Cover link: empty (category cover) or `ipfs://…` / `https://…` with something after the scheme, at most
/// MAX_COVER_BYTES of link characters (`_linkTail`; it ends up in an `<img src>`, the site still treats it
/// as untrusted).
function checkCover(string calldata cover) internal pure {
bytes calldata b = bytes(cover);
uint256 len = b.length;
if (len == 0) return;
if (len > MAX_COVER_BYTES) revert BadCover();
// slither-disable-next-line uninitialized-local
uint256 scheme;
if (_startsWith(b, 0, "ipfs://")) scheme = 7;
else if (_startsWith(b, 0, "https://")) scheme = 8;
else revert BadCover();
if (len == scheme || !_linkTail(b, scheme)) revert BadCover();
}
/// @dev Evidence.screenshotUrl: empty (none) or a link on a host of the allowlist (`checkHost`, HostNotAllowed
/// otherwise), then link characters (no space, no quote/backslash/angle bracket), at most
/// MAX_SCREENSHOT_URL_BYTES (BadEvidence otherwise).
function checkScreenshotUrl(string calldata url) internal pure {
bytes calldata b = bytes(url);
uint256 len = b.length;
if (len == 0) return;
checkHost(b);
if (len > MAX_SCREENSHOT_URL_BYTES) revert BadEvidence();
if (len == 8 || !_linkTail(b, 8)) revert BadEvidence();
}
/// @dev A submission's proofUri in the form its task's proof type requires (the length and printable-ASCII rule is
/// `checkText`, checked before). Every link proof is first held to the host allowlist (`checkHost`,
/// HostNotAllowed), then to its form (BadProof):
/// x_post https://[www.|mobile.](x.com|twitter.com)/<user 1-15 [A-Za-z0-9_]>/status/<1-19 digits>
/// [then ? or / and link characters]
/// video https://[www.|m.](youtube.com|youtu.be)/<path>, or an x_post link (a video posted on X)
/// onchain_tx 0x + 64 hex digits (a transaction hash on Ethereum mainnet)
/// link https://<allowlisted host>[/?#]<link characters>
function checkProof(string calldata proof, uint8 proofType) internal pure {
bytes calldata b = bytes(proof);
bool ok;
if (proofType == PROOF_ONCHAIN_TX) {
ok = _isTxHash(b);
} else {
checkHost(b);
if (proofType == PROOF_X_POST) ok = _isXPost(b);
else if (proofType == PROOF_VIDEO) ok = _isVideo(b) || _isXPost(b);
else ok = b.length > 8 && _linkTail(b, 8);
}
if (!ok) revert BadProof(proofType);
}
/// @dev Proof and screenshot links (nothing else can even be sent): `https://`, at most
/// MAX_LINK_BYTES, and a host of the allowlist below. The host runs from right after `https://` to the first
/// `/`, `?`, `#` or the end; one `www.`, `m.` or `mobile.` prefix is dropped; the rest must equal a listed
/// host byte for byte, so a port (colon), userinfo (at sign), a space, upper case or another domain around a
/// listed name never matches.
function checkHost(bytes calldata b) internal pure {
uint256 len = b.length;
if (len > MAX_LINK_BYTES || !_startsWith(b, 0, "https://")) revert HostNotAllowed();
uint256 at = 8;
if (_startsWith(b, at, "www.")) at += 4;
else if (_startsWith(b, at, "mobile.")) at += 7;
else if (_startsWith(b, at, "m.")) at += 2;
uint256 end = at;
while (end < len) {
bytes1 c = b[end];
if (c == "/" || c == "?" || c == "#") break;
++end;
}
if (!_listed(keccak256(b[at:end]))) revert HostNotAllowed();
}
function _listed(bytes32 h) private pure returns (bool) {
// HOSTS-BEGIN
return h == keccak256("x.com") || h == keccak256("twitter.com") || h == keccak256("pbs.twimg.com")
|| h == keccak256("youtube.com") || h == keccak256("youtu.be") || h == keccak256("tiktok.com")
|| h == keccak256("instagram.com") || h == keccak256("drive.google.com")
|| h == keccak256("lh3.googleusercontent.com") || h == keccak256("photos.google.com")
|| h == keccak256("imgur.com") || h == keccak256("i.imgur.com") || h == keccak256("t.me")
|| h == keccak256("ibb.co") || h == keccak256("i.ibb.co") || h == keccak256("reddit.com")
|| h == keccak256("i.redd.it") || h == keccak256("dropbox.com") || h == keccak256("arweave.net")
|| h == keccak256("etherscan.io") || h == keccak256("sepolia.etherscan.io") || h == keccak256("github.com")
|| h == keccak256("kick.com") || h == keccak256("twitch.tv") || h == keccak256("clips.twitch.tv");
// HOSTS-END
}
/// @dev Link characters from `from` to the end: printable ASCII without space, quotes, backslash or angle
/// brackets (the swarm JSON, an href and an <img src> stay well-formed).
function _linkTail(bytes calldata b, uint256 from) private pure returns (bool) {
for (uint256 i = from; i < b.length; ++i) {
uint8 c = uint8(b[i]);
if (c <= 0x20 || c >= 0x7f || c == 0x22 || c == 0x27 || c == 0x3c || c == 0x3e || c == 0x5c) return false;
}
return true;
}
function _startsWith(bytes calldata b, uint256 at, bytes memory prefix) private pure returns (bool) {
if (b.length < at + prefix.length) return false;
for (uint256 i; i < prefix.length; ++i) {
if (b[at + i] != prefix[i]) return false;
}
return true;
}
/// @dev `https://` + host + `/`: index right after the slash, 0 when the host is not in the list.
/// The host may start with `www.` (and `m.` / `mobile.` where those exist).
function _afterHost(bytes calldata b, bytes[] memory hosts) private pure returns (uint256) {
if (!_startsWith(b, 0, "https://")) return 0;
uint256 at = 8;
if (_startsWith(b, at, "www.")) at += 4;
else if (_startsWith(b, at, "mobile.")) at += 7;
else if (_startsWith(b, at, "m.")) at += 2;
for (uint256 h; h < hosts.length; ++h) {
if (_startsWith(b, at, hosts[h]) && _startsWith(b, at + hosts[h].length, "/")) {
return at + hosts[h].length + 1;
}
}
return 0;
}
function _isXPost(bytes calldata b) private pure returns (bool) {
bytes[] memory hosts = new bytes[](2);
hosts[0] = "x.com";
hosts[1] = "twitter.com";
uint256 i = _afterHost(b, hosts);
if (i == 0) return false;
uint256 start = i;
while (i < b.length && i - start < 16 && _isHandleChar(uint8(b[i]))) ++i;
if (i == start || i - start > 15 || !_startsWith(b, i, "/status/")) return false;
i += 8;
start = i;
while (i < b.length && uint8(b[i]) >= 0x30 && uint8(b[i]) <= 0x39) ++i;
if (i == start || i - start > 19) return false;
if (i == b.length) return true;
return (b[i] == "?" || b[i] == "/") && _linkTail(b, i);
}
function _isVideo(bytes calldata b) private pure returns (bool) {
bytes[] memory hosts = new bytes[](2);
hosts[0] = "youtube.com";
hosts[1] = "youtu.be";
uint256 i = _afterHost(b, hosts);
return i != 0 && i < b.length && _linkTail(b, i);
}
function _isTxHash(bytes calldata b) private pure returns (bool) {
if (b.length != 66 || b[0] != "0" || b[1] != "x") return false;
for (uint256 i = 2; i < 66; ++i) {
uint8 c = uint8(b[i]);
if (!((c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x66) || (c >= 0x41 && c <= 0x46))) return false;
}
return true;
}
function _isHandleChar(uint8 c) private pure returns (bool) {
return (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) || c == 0x5f;
}
}
/// @title TextRules
/// @notice Stateless helper: the desks check user strings here (STATICCALL) instead of carrying the code themselves
/// (code size limit). Reverts carry the vault's own errors (BadCover, BadProof, BadEvidence, HostNotAllowed).
contract TextRules {
function validText(string calldata str, uint256 maxLen) external pure returns (bool) {
return TextLib.validText(str, maxLen);
}
function checkCover(string calldata cover) external pure {
TextLib.checkCover(cover);
}
function checkProof(string calldata proof, uint8 proofType) external pure {
TextLib.checkProof(proof, proofType);
}
function checkScreenshotUrl(string calldata url) external pure {
TextLib.checkScreenshotUrl(url);
}
}
src/interfaces/IIntake.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice IMD Intake (swarm oracle payment entry point), Ethereum mainnet: version 2
/// 0xa43e6f75ee006411f79ac1c84120606c2330de82 (the launch's; it keeps every function, event and getter of
/// version 1), version 1
/// 0x1397434cd35e8a9c8ac312a61d3a285eb31dea56 still served (source verified on Sourcify/Blockscout, selectors
/// checked against the bytecode). Only the version 1 functions are used here. `action` is the right-padded ASCII bytes32 of
/// "oracle.request(at)oracle-1". `request` is payable but must get msg.value == 0 for ERC-20 payment.
/// `request` pulls `amount` of `asset` from msg.sender (transferFrom) and forwards it to the
/// Intake payee; the control plane reads the `Requested` event, runs the panel, and the Intake
/// writer later calls `complete`, which (status 0 only) calls
/// `callback.target` with `callback.selector ++ abi.encode(requestId, attestation, signature)`
/// and a fixed gas budget (200,000 at the time of writing), inside a try.
interface IIntake {
struct Callback {
address target;
bytes4 selector;
}
function request(bytes32 action, bytes calldata body, Callback calldata callback, address asset, uint256 amount)
external
returns (bytes32 requestId);
/// @notice Live price of `action` paid in `asset`. The Intake price may differ at call time.
function priceOf(bytes32 action, address asset) external view returns (uint256);
/// @notice Stored request; `completed` turns true when the writer called `complete` (any status).
function requests(bytes32 requestId)
external
view
returns (address payer, address callbackTarget, bytes4 callbackSelector, bool completed);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"/tmp/imd-attest-Qwl6km/repo/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"/tmp/imd-attest-Qwl6km/repo/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"/tmp/imd-attest-Qwl6km/repo/lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"/tmp/imd-attest-Qwl6km/repo/lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"/tmp/imd-attest-Qwl6km/repo/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"/tmp/imd-attest-Qwl6km/repo/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"/tmp/imd-attest-Qwl6km/repo/lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
":@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
":@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
":hardhat/=lib/v4-core/node_modules/hardhat/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":solmate/=lib/v4-core/lib/solmate/",
":v4-core/=lib/v4-core/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.