Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "contracts/lib/forge-std"]
path = contracts/lib/forge-std
url = https://github.com/foundry-rs/forge-std.git
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ This repository is the public toolkit for builders:

The SDK never holds keys or sends transactions. It returns `{ to, data, value }` for the user's wallet to review and send.

## Reference modules

`QRafflePot` uses blockhash randomness. Block producers or sequencers can predict or influence the result, so keep pots small. VRF is planned for a future version. See [`contracts/README.md`](contracts/README.md) for module behavior and tests.

## Quick start

```js
Expand Down
20 changes: 18 additions & 2 deletions contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
| File | What it is |
|---|---|
| `src/QModuleBase.sol` | The base every marketplace module inherits, **unchanged**. Review checks its SHA-256 against `SHA256SUMS.txt`. |
| `src/QStakeModule.sol` | Reference module: holder staking, payouts streamed over a day. |
| `src/QRafflePot.sol` | Reference module: a raffle pot. |
| `src/QStakeModule.sol` | Reference module: holder staking with fixed-end 24–30-hour reward streams. |
| `src/QRafflePot.sol` | Reference module: a raffle pot with a 1% bounty for timely completed draws. |

Build with [Foundry](https://book.getfoundry.sh): `forge build` (settings in `foundry.toml`: solc 0.8.26, `via_ir`, optimizer 200
runs, `cancun`, `bytecode_hash = none`).
Expand All @@ -14,3 +14,19 @@ deterministic deployer `0x4e59b44847b379578588920ca78fbf26c0b4956c`, salt `kecca
`init = creationCode ++ abi.encode(token, quote, builder, builderBps)`.

Start with [`../docs/modules.md`](../docs/modules.md), then submit at <https://qhooks.com/market-submit.html>.

## Raffle randomness and expiry

`QRafflePot` uses a future blockhash, not VRF. Block producers or sequencers can predict or influence the result: keep pots small; VRF is planned for a future version. Anyone completing a timely draw earns 1% of each pot currency; the winner receives the remainder. If the draw hash expires after its 256-block window, the round closes without a winner and its pot carries to the next entered round. The expired round cannot be re-armed; entrants can still withdraw their deposits.

## Tests

From the repository root, initialize the pinned test dependency, then run the local mock-only regressions:

```sh
git submodule update --init --recursive
cd contracts
forge test
```

`forge-std` is pinned to v1.9.7 (`77041d2ce690e692d6e03cc812b57d1ddaa4d505`). Tests cover raffle expiry/carry-over/bounties, fixed-end staking streams, dust-sync resistance, just-in-time staking and reward conservation. They require no RPC or wallet.
4 changes: 2 additions & 2 deletions contracts/SHA256SUMS.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
84dafd9d69d240737fb53cac28bae51780b0447082c817254cc32ae272fae9c6 QModuleBase.sol
8aae62f02836960875c854a3a131e16485c515c48853dff2f07923318a1edcf6 QStakeModule.sol
6e4bddf11b17941cbf93229ae383773b6e1eea5a69f18fc0fa475ec641d07657 QRafflePot.sol
2e57efaf294ebe28542a186eea75a4dd8e2f2e16f2d6d336999d790e053ba85e QStakeModule.sol
c8c1057a52d57574c09582312401114579da311fe83027097beb46645a81aa7f QRafflePot.sol
1 change: 1 addition & 0 deletions contracts/lib/forge-std
Submodule forge-std added at 77041d
51 changes: 40 additions & 11 deletions contracts/src/QRafflePot.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@ import {QModuleBase} from "./QModuleBase.sol";
/// pot. Holders enter a daily round by depositing the token; tickets are tokens x seconds left in the round, so
/// entering at the last minute buys almost nothing. After a round ends anyone draws it: the first call picks a draw
/// block a few blocks ahead, the next call after that block uses its hash to pick one winner, weighted by tickets,
/// who wins the whole pot in the token and the pair currency. Every depositor takes their tokens back once the round
/// has ended, winner or not. Rounds nobody entered are skipped; their income waits for the next draw.
/// Randomness comes from a future block hash: good enough for a small pot, but the chain's block producer could
/// influence it, so pots are not meant to be large. No owner.
/// who wins the pot (less a small bounty for whoever completes the draw) in the token and the pair currency. Every
/// depositor takes their tokens back once the round has ended, winner or not. Rounds nobody entered are skipped; their
/// income waits for the next draw.
/// A draw block's hash is only readable for 256 blocks. If nobody completes the draw in that window the round closes
/// with no winner and its pot carries over to the next entered round: an armed round is never re-armed, so a loser who
/// has already seen the losing hash cannot roll again. The bounty pays anyone to complete draws on time.
/// Randomness comes from a future block hash: good enough for a small pot, but the chain's block producer (on Arbitrum
/// Orbit chains, the sequencer) could predict or influence it, so pots are not meant to be large; use VRF for more.
/// No owner.
contract QRafflePot is QModuleBase {
uint256 public constant ROUND = 1 days;
uint256 public constant DRAW_DELAY = 2; // blocks between arming a draw and drawing it
/// @notice Share of the pot paid to whoever completes a draw, in basis points: 1%.
uint256 public constant DRAW_BOUNTY_BPS = 100;

uint256 public immutable start;

Expand Down Expand Up @@ -45,6 +52,9 @@ contract QRafflePot is QModuleBase {
event Withdrawn(uint256 indexed round, address indexed who, uint256 amount);
event Armed(uint256 indexed round, uint256 drawBlock);
event Drawn(uint256 indexed round, address indexed winner, uint256 tokenPrize, uint256 quotePrize);
event Bounty(uint256 indexed round, address indexed drawer, uint256 tokenAmount, uint256 quoteAmount);
/// @notice Nobody drew round `round` while its draw block's hash was readable: no winner, the pot carries over.
event Expired(uint256 indexed round);
event Claimed(address indexed who, uint256 tokenAmount, uint256 quoteAmount);

constructor(address token_, address quote_, address builder_, uint16 builderBps_)
Expand Down Expand Up @@ -96,36 +106,51 @@ contract QRafflePot is QModuleBase {
}

/// @notice Draws the next ended round with entries. The first call arms it (picks a draw block DRAW_DELAY
/// blocks ahead); a call after that block draws. If the draw block is too old for its hash, it re-arms.
/// blocks ahead); a call after that block draws, and the caller earns DRAW_BOUNTY_BPS of the pot. If the draw block
/// is too old for its hash, the round closes with no winner and its pot carries over; it is never re-armed.
/// Returns true when a winner was drawn.
function draw() external guarded returns (bool) {
require(drawIndex < entered.length, "QRaffle: nothing to draw");
uint256 r = entered[drawIndex];
require(r < currentRound(), "QRaffle: round open");
Round storage rd = rounds[r];
if (rd.drawBlock == 0 || (block.number > rd.drawBlock && blockhash(rd.drawBlock) == 0)) {
if (rd.drawBlock == 0) {
rd.drawBlock = uint64(block.number + DRAW_DELAY);
emit Armed(r, rd.drawBlock);
return false;
}
require(block.number > rd.drawBlock, "QRaffle: too early");
bytes32 h = blockhash(rd.drawBlock);
if (h == 0) {
rd.drawn = true; // winner stays address(0); deposits come back through withdraw as usual
drawIndex++;
emit Expired(r);
return false;
}
_syncAll();
uint256 seed = uint256(keccak256(abi.encode(blockhash(rd.drawBlock), r, address(this))));
uint256 seed = uint256(keccak256(abi.encode(h, r, address(this))));
address w = _pick(r, seed % rd.weight);
uint256 pt = pot[0];
uint256 pq = pot[1];
pot[0] = 0;
pot[1] = 0;
uint256 bt = pt * DRAW_BOUNTY_BPS / BPS;
uint256 bq = pq * DRAW_BOUNTY_BPS / BPS;
pt -= bt;
pq -= bq;
_won[w][0] += pt;
_won[w][1] += pq;
_prizesOwed[0] += pt;
_prizesOwed[1] += pq;
_won[msg.sender][0] += bt;
_won[msg.sender][1] += bq;
_prizesOwed[0] += pt + bt;
_prizesOwed[1] += pq + bq;
rd.drawn = true;
rd.winner = w;
rd.prizeToken = pt;
rd.prizeQuote = pq;
drawIndex++;
emit Drawn(r, w, pt, pq);
if (bt != 0 || bq != 0) emit Bounty(r, msg.sender, bt, bq);
return true;
}

Expand Down Expand Up @@ -153,11 +178,15 @@ contract QRafflePot is QModuleBase {
return (_won[who][0], _won[who][1]);
}

/// @notice The pot the next draw pays, counting income that has arrived but not been counted yet.
/// @notice The pot the next draw pays its winner (after the drawer's bounty), counting income that has arrived
/// but not been counted yet.
function nextPrize() external view returns (uint256 tokenAmount, uint256 quoteAmount) {
(uint256 t,) = _peek(0);
(uint256 q,) = _peek(1);
return (pot[0] + t - t * builderBps / BPS, pot[1] + q - q * builderBps / BPS);
tokenAmount = pot[0] + t - t * builderBps / BPS;
quoteAmount = pot[1] + q - q * builderBps / BPS;
tokenAmount -= tokenAmount * DRAW_BOUNTY_BPS / BPS;
quoteAmount -= quoteAmount * DRAW_BOUNTY_BPS / BPS;
}

/// @notice Entries in round `r`.
Expand Down
100 changes: 76 additions & 24 deletions contracts/src/QStakeModule.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,29 @@ import {QModuleBase} from "./QModuleBase.sol";
/// @title QStakeModule
/// @notice Holder staking as a marketplace module: QStakeVault's logic on QModuleBase. Stake the launch token, earn
/// what the launch pays this module (less its builder's share, if any) in the token and its pair currency, streamed
/// over DURATION so staking for one block around a payout earns almost nothing. Funds that stream while nobody is
/// staked are kept and streamed again once someone is. Staked tokens are never counted as income. No lockup, no owner.
/// The same function names and selectors as QStakeVault, so one Staking panel drives both.
/// over at least DURATION so staking for one block around a payout earns almost nothing. Funds that stream while
/// nobody is staked are kept and streamed again once someone is. Staked tokens are never counted as income. No lockup,
/// no owner. The same function names and selectors as QStakeVault, so one Staking panel drives both.
///
/// Streams: income is added to a tranche whose end is fixed on a clock grid (the end of the current EPOCH plus
/// DURATION, so every payout streams for between DURATION and DURATION + EPOCH). A later arrival in the same epoch only
/// raises that tranche's rate; it never moves the end of income that is already streaming, so a sync, or a dust
/// donation followed by a sync, cannot slow anyone's payout. A sync with no new income only moves the stream to now.
contract QStakeModule is QModuleBase {
uint256 public constant DURATION = 1 days;
/// @notice Width of the clock grid tranche ends sit on.
uint256 public constant EPOCH = 6 hours;
uint256 private constant SLOTS = DURATION / EPOCH + 1; // tranches that can be live at once
uint256 private constant E18 = 1e18;
uint256 private constant E36 = 1e36;

struct Stream {
struct Tranche {
uint256 rate; // reward per second, scaled by 1e18
uint64 finish;
}

struct Stream {
Tranche[SLOTS] tranches;
uint64 last;
uint256 acc; // reward per staked unit, scaled by 1e36
uint256 booked; // the module's share of income received so far and not yet paid out
Expand Down Expand Up @@ -88,10 +100,18 @@ contract QStakeModule is QModuleBase {
return (_earnedView(who, 0), _earnedView(who, 1));
}

/// @notice A currency's stream: reward per second (1e18-scaled), when it ends, and what it still holds.
/// @notice A currency's stream: reward per second now (1e18-scaled, all live tranches), when the last tranche
/// ends, and what it still holds.
function stream(uint256 i) external view returns (uint256 rate, uint64 finish, uint256 booked, uint256 idle) {
Stream storage s = _streams[i];
return (s.rate, s.finish, s.booked, s.idle);
for (uint256 k; k < SLOTS; ++k) {
Tranche storage t = s.tranches[k];
if (t.finish > block.timestamp) {
rate += t.rate;
if (t.finish > finish) finish = t.finish;
}
}
return (rate, finish, s.booked, s.idle);
}

function _reserved(uint256 i) internal view override returns (uint256) {
Expand All @@ -113,45 +133,77 @@ contract QStakeModule is QModuleBase {
}

/// Moves the stream to now, counts new income (the builder's cut comes off first), then streams it plus
/// anything that streamed while nobody was staked.
/// anything that streamed while nobody was staked. With no new income and nothing idle this only accrues.
function _sync(uint256 i) private {
Stream storage s = _streams[i];
_accrue(s);
_intake(i); // books and streams new income through _income
if (s.idle != 0) _start(i, 0);
uint256 idle = s.idle;
if (idle != 0) {
s.idle = 0;
_add(i, idle);
}
}

function _income(uint256 i, uint256 net) internal override {
_streams[i].booked += net;
_start(i, net);
_add(i, net);
}

function _start(uint256 i, uint256 incoming) private {
/// Adds `amount` to the tranche ending at the grid end for now. Other tranches, and what this tranche already
/// streams, keep their rate and end. Runs after `_accrue`, so a finished tranche has been fully counted.
function _add(uint256 i, uint256 amount) private {
if (amount == 0) return;
Stream storage s = _streams[i];
uint256 add = incoming + s.idle;
if (add == 0) return;
s.idle = 0;
uint256 left = block.timestamp < s.finish ? s.rate * (s.finish - block.timestamp) : 0;
s.rate = (left + add * E18) / DURATION;
s.finish = uint64(block.timestamp + DURATION);
s.last = uint64(block.timestamp);
emit Streamed(currency(i), add, s.rate, s.finish);
uint256 end = (block.timestamp / EPOCH + 1) * EPOCH + DURATION;
(Tranche storage t, bool live) = _tranche(s, end);
if (!live) {
t.rate = 0;
t.finish = uint64(end);
}
uint256 r = amount * E18 / (end - block.timestamp);
t.rate += r;
emit Streamed(currency(i), amount, r, uint64(end));
}

/// The tranche that ends at `end` (live = true), else a finished one to reuse. Only tranches opened in the last
/// SLOTS - 1 epochs can still be running and each epoch opens at most one, so a finished slot always exists.
function _tranche(Stream storage s, uint256 end) private view returns (Tranche storage t, bool live) {
uint256 freeK = SLOTS;
for (uint256 k; k < SLOTS; ++k) {
uint256 f = s.tranches[k].finish;
if (f == end) return (s.tranches[k], true);
if (freeK == SLOTS && f <= block.timestamp) freeK = k;
}
require(freeK < SLOTS, "QStake: tranches"); // unreachable
return (s.tranches[freeK], false);
}

/// Credits everything every tranche streamed since `last`. Each tranche runs at a constant rate until its own end.
function _accrue(Stream storage s) private {
uint256 t = block.timestamp < s.finish ? block.timestamp : s.finish;
if (t <= s.last) return;
uint256 amount = s.rate * (t - s.last);
uint256 last = s.last;
if (block.timestamp <= last) return;
uint256 amount = _streamed(s, last);
s.last = uint64(block.timestamp);
if (amount == 0) return;
if (totalStaked != 0) s.acc += amount * E18 / totalStaked;
else s.idle += amount / E18;
s.last = uint64(t);
}

/// What the tranches streamed between `from` and now (1e18-scaled).
function _streamed(Stream storage s, uint256 from) private view returns (uint256 amount) {
for (uint256 k; k < SLOTS; ++k) {
Tranche storage t = s.tranches[k];
uint256 f = t.finish;
if (f <= from) continue;
amount += t.rate * ((block.timestamp < f ? block.timestamp : f) - from);
}
}

function _earnedView(address who, uint256 i) private view returns (uint256) {
Stream storage s = _streams[i];
uint256 acc = s.acc;
uint256 t = block.timestamp < s.finish ? block.timestamp : s.finish;
if (t > s.last && totalStaked != 0) acc += s.rate * (t - s.last) * E18 / totalStaked;
if (block.timestamp > s.last && totalStaked != 0) acc += _streamed(s, s.last) * E18 / totalStaked;
return _owed[who][i] + staked[who] * (acc - _debt[who][i]) / E36;
}

Expand Down
Loading
Loading