@ballkidz/defifa 0.0.17 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,237 +1,91 @@
1
1
  # Defifa
2
2
 
3
- On-chain prediction games built on Juicebox. Players mint NFT game pieces representing teams or outcomes, a governor-based scorecard system determines payouts, and winners burn their NFTs to claim proportional shares of the pot.
3
+ Defifa is an on-chain prediction game system built on Juicebox. Players mint NFT game pieces, scorecards determine how the pot is distributed, and winners cash out by burning the NFTs that backed their position.
4
4
 
5
- Each game is a Juicebox project with phased rulesets that move through Countdown, Mint, Refund, Scoring, and Complete. The game's pot is the project's surplus. Anyone can launch a game by calling the deployer.
5
+ Architecture: [ARCHITECTURE.md](./ARCHITECTURE.md)
6
6
 
7
- ## How It Works
7
+ ## Overview
8
8
 
9
- ### Minting
9
+ Each Defifa game is a Juicebox project with a staged lifecycle:
10
10
 
11
- During the Mint phase, players pay the project's terminal to mint ERC-721 game pieces. Each tier represents a team or outcome -- all tiers share the same price. Minting delegates attestation power to the beneficiary (or a specified delegate), which is used later during scorecard governance.
11
+ - countdown before minting opens
12
+ - mint phase where players buy outcome NFTs
13
+ - optional refund window
14
+ - scoring phase where holders attest to scorecards
15
+ - completion or no-contest settlement
12
16
 
13
- ### Refunds
17
+ The project's surplus is the prize pot. Once a scorecard reaches quorum and survives its grace period, the hook updates cash-out weights so players can redeem winning pieces for their share.
14
18
 
15
- If an optional Refund phase is configured, players can burn their NFTs after minting closes to reclaim the full mint price. This gives players an exit window before the game locks in.
19
+ Use this repo when you want a full game system with lifecycle, governance, and settlement. Do not treat it as a generic tournament payout primitive; its assumptions are Defifa-specific.
16
20
 
17
- ### Scoring
21
+ If the issue is basic NFT issuance, project accounting, or generic governance plumbing, start in the underlying protocol repos first. Defifa is where the game-specific lifecycle and settlement assumptions get introduced.
18
22
 
19
- Once the game starts, anyone can submit a **scorecard** -- a proposed distribution of the pot across tiers. Scorecards are attested to by NFT holders, weighted by their tier-delegated voting power. Each tier contributes equal attestation power regardless of supply (capped at `MAX_ATTESTATION_POWER_TIER`), so a tier with 1 NFT has the same governance weight as a tier with 100 NFTs.
23
+ ## Key Contracts
20
24
 
21
- Once a scorecard reaches 50% quorum and its grace period elapses, it can be ratified. Ratification sets the cash-out weights on the hook and fulfills fee commitments (Defifa fee + protocol fee + user splits).
25
+ | Contract | Role |
26
+ | --- | --- |
27
+ | `DefifaDeployer` | Launches games, clones hooks, initializes governance, and fulfills post-game fee commitments. |
28
+ | `DefifaHook` | ERC-721 game piece hook that tracks tiers, delegation, and cash-out weights for settlement. |
29
+ | `DefifaGovernor` | Scorecard governance surface that accepts submissions, attestations, and ratification. |
30
+ | `DefifaTokenUriResolver` | On-chain metadata renderer for game cards. |
31
+ | `DefifaProjectOwner` | Ownership helper for the Defifa fee project. |
22
32
 
23
- ### Cash Outs
33
+ ## Mental Model
24
34
 
25
- After ratification, the game enters the Complete phase. Players burn their NFTs via the terminal's `cashOutTokensOf` to claim their proportional share of the remaining pot. Each NFT's share is its tier's scorecard weight divided by the tier's minted supply. Players also receive a proportional share of any fee tokens ($DEFIFA / $NANA) that accumulated from the game's fee payments.
35
+ Defifa is easiest to read as three layers:
26
36
 
27
- ### Safety Mechanisms
37
+ 1. launch and lifecycle packaging in `DefifaDeployer`
38
+ 2. player position and settlement state in `DefifaHook`
39
+ 3. scorecard selection in `DefifaGovernor`
28
40
 
29
- Two configurable safety mechanisms prevent games from getting stuck:
41
+ Most system-level issues come from how those layers interact, not from one layer in isolation.
30
42
 
31
- - **Minimum participation** (`minParticipation`) -- if the pot never reaches a threshold, the game enters No Contest and all players can refund at mint price.
32
- - **Scorecard timeout** (`scorecardTimeout`) -- if no scorecard is ratified within a time limit after scoring begins, the game enters No Contest.
33
-
34
- ## Architecture
35
-
36
- ```
37
- DefifaDeployer ──── launches ────► Juicebox Project (phased rulesets)
38
- │ │
39
- ├── clones ──► DefifaHook (ERC-721 game pieces, cash-out weights)
40
- │ │
41
- │ └── uses ──► JB721TiersHookStore (tier storage)
42
-
43
- └── initializes ──► DefifaGovernor (scorecard governance)
44
-
45
- └── owns ──► DefifaHook (sets weights on ratification)
46
- ```
43
+ ## Install
47
44
 
48
- ### Contracts
49
-
50
- | Contract | Description |
51
- |----------|-------------|
52
- | `DefifaDeployer` | Game factory. Clones the hook, launches a Juicebox project with phased rulesets (Mint → Refund → Scoring), initializes the governor, and manages post-game commitment fulfillment (fee payouts). Also serves as the game phase and pot reporter. |
53
- | `DefifaHook` | ERC-721 game piece hook (extends `JB721Hook`). Manages tier-based cash-out weights, per-tier attestation delegation with checkpointed voting power (`Checkpoints.Trace208`), and custom cash-out logic that distributes the pot proportionally based on the ratified scorecard. Deployed as minimal proxy clones. |
54
- | `DefifaGovernor` | Scorecard governance. Accepts scorecard submissions (tier weight proposals), collects attestations weighted by tier-delegated voting power, and ratifies scorecards that reach 50% quorum. Executes the winning scorecard on the hook via low-level call. |
55
- | `DefifaHookLib` | Library with pure/view helpers: scorecard validation, cash-out weight calculation, fee token distribution, attestation unit aggregation. Extracted to stay within EIP-170 contract size limits. |
56
- | `DefifaTokenUriResolver` | On-chain SVG token URI resolver. Renders dynamic game cards showing phase, pot size, rarity, team name, and current value using embedded Capsules typeface. |
57
- | `DefifaProjectOwner` | Receives the Defifa fee project's ownership NFT and permanently grants the deployer `SET_SPLIT_GROUPS` permission. |
58
-
59
- ### Game Lifecycle
60
-
61
- | Phase | Ruleset Cycle | What Happens |
62
- |-------|---------------|--------------|
63
- | `COUNTDOWN` | 0 | Project launched, minting not yet open. |
64
- | `MINT` | 1 | Players pay to mint NFT game pieces. Cash outs return full mint price (refund). Delegation can be set. |
65
- | `REFUND` | 2 (optional) | Minting closed, refunds still allowed at face value. Delegation can still change. |
66
- | `SCORING` | 3+ | Game started. Scorecards submitted, attested to, and ratified via governor. Delegation frozen. |
67
- | `COMPLETE` | -- | Scorecard ratified. Commitments fulfilled. Players burn NFTs to claim pot share + fee tokens. |
68
- | `NO_CONTEST` | -- | Safety mechanism triggered. All players can refund at mint price. |
69
-
70
- ### Game Lifecycle Flow
71
-
72
- ```mermaid
73
- sequenceDiagram
74
- participant Deployer as Game Creator
75
- participant DD as DefifaDeployer
76
- participant JB as Juicebox Project
77
- participant Hook as DefifaHook
78
- participant Gov as DefifaGovernor
79
- participant Player as Players
80
-
81
- Note over DD,JB: DEPLOY
82
- Deployer->>DD: launchGameFor(config)
83
- DD->>Hook: clone & initialize (tiers, token URI)
84
- DD->>JB: launchProjectFor (phased rulesets)
85
- DD->>Gov: initialize (hook, quorum, grace period)
86
-
87
- Note over JB,Player: COUNTDOWN
88
- JB-->>Player: project live, minting not yet open
89
-
90
- Note over JB,Player: MINT
91
- Player->>JB: pay (mint price)
92
- JB->>Hook: afterPayRecordedWith (mint NFT)
93
- Hook-->>Player: ERC-721 game piece
94
- Player->>Hook: setTierDelegatesTo (delegate attestation power)
95
-
96
- Note over JB,Player: REFUND (optional)
97
- Player->>JB: cashOutTokensOf (burn NFT)
98
- JB->>Hook: afterCashOutRecordedWith (full refund)
99
- Hook-->>Player: mint price returned
100
-
101
- Note over Gov,Player: SCORING
102
- Player->>Gov: submitScorecard (tier weights)
103
- Player->>Gov: castVote (attest to scorecard)
104
- Note over Gov: quorum reached + grace period elapsed
105
- Player->>Gov: ratifyScorecard
106
- Gov->>Hook: setCashOutWeights (winning scorecard)
107
- Gov->>DD: fulfillCommitments (pay fees + splits)
108
-
109
- Note over JB,Player: COMPLETE
110
- Player->>JB: cashOutTokensOf (burn NFT)
111
- JB->>Hook: afterCashOutRecordedWith (pot share)
112
- Hook-->>Player: proportional pot share + fee tokens
45
+ ```bash
46
+ npm install @ballkidz/defifa
113
47
  ```
114
48
 
115
- ### Fee Structure
116
-
117
- | Fee | Rate | Recipient |
118
- |-----|------|-----------|
119
- | Protocol fee | 2.5% (`BASE_PROTOCOL_FEE_DIVISOR = 40`) | Base protocol project |
120
- | Defifa fee | 5% (`DEFIFA_FEE_DIVISOR = 20`) | Defifa project |
121
- | User splits | Configurable | Custom split recipients |
122
-
123
- Fees are taken as payouts during commitment fulfillment. The remaining surplus is available for player cash outs. Fee payments generate $NANA and $DEFIFA tokens, which accumulate in the hook and are distributed proportionally to players when they cash out.
124
-
125
- ### Structs
126
-
127
- | Struct | Purpose |
128
- |--------|---------|
129
- | `DefifaLaunchProjectData` | Full game configuration: name, tiers, token, durations, splits, attestation params, safety params, terminal, store. |
130
- | `DefifaTierParams` | Per-tier config: name, reserved rate, beneficiary, encoded IPFS URI. Price is set uniformly via `tierPrice` on the launch data. |
131
- | `DefifaTierCashOutWeight` | Scorecard entry: tier ID and its cash-out weight. Weights must sum to `TOTAL_CASHOUT_WEIGHT` (1e18). |
132
- | `DefifaOpsData` | Packed game timing and safety params: token, start, mint duration, refund duration, min participation, scorecard timeout. |
133
- | `DefifaDelegation` | Delegation assignment: delegatee address and tier ID. |
134
-
135
- ### Enums
136
-
137
- | Enum | Values |
138
- |------|--------|
139
- | `DefifaGamePhase` | `COUNTDOWN`, `MINT`, `REFUND`, `SCORING`, `COMPLETE`, `NO_CONTEST` |
140
- | `DefifaScorecardState` | `PENDING`, `ACTIVE`, `DEFEATED`, `SUCCEEDED`, `RATIFIED` |
49
+ ## Development
141
50
 
142
- ## Risks
51
+ ```bash
52
+ npm install
53
+ forge build
54
+ forge test
55
+ ```
143
56
 
144
- - **Scorecard timeout gap.** The `scorecardTimeout` safety mechanism triggers No Contest only if no scorecard is ratified before the deadline. However, if `minParticipation` was already met (pot above threshold), the minimum-participation safety net does not apply. A game can get stuck in the `SCORING` phase indefinitely if valid scorecards are submitted but never reach quorum -- the timeout only fires when _no_ scorecard is ratified in time, so a perpetually-contested game with active but insufficient attestation has no automatic resolution path.
57
+ Useful scripts:
145
58
 
146
- - **Attestation power is per-tier, not per-NFT.** Each tier contributes equal governance weight (capped at `MAX_ATTESTATION_POWER_TIER`) regardless of how many NFTs were minted in that tier. A tier with 1 NFT holder has the same attestation power as a tier with 100 holders. This means a player who is the sole holder of a low-supply tier controls disproportionate voting power relative to their capital at risk, which could be exploited to steer scorecard outcomes.
59
+ - `npm run deploy:mainnets`
60
+ - `npm run deploy:testnets`
147
61
 
148
- - **Fee token accumulation depends on external terminals.** When commitments are fulfilled, fee payments to the Defifa and protocol projects generate $DEFIFA and $NANA tokens that accumulate in the hook for later distribution to players. If the receiving projects' terminals revert (e.g., paused, migrated, or misconfigured), the `fulfillCommitments` call will fail, blocking the game from entering the `COMPLETE` phase. Players would need to wait for the external terminal issue to be resolved before they can cash out.
62
+ ## Deployment Notes
149
63
 
150
- - **Ratified scorecards are permanent.** Once a scorecard is ratified by the governor and cash-out weights are set on the hook, those weights cannot be changed for that game. There is no mechanism to re-score or appeal. If a scorecard is ratified with incorrect weights (e.g., due to a rushed attestation or a governance attack during low participation), the payout distribution is locked in permanently.
64
+ Deployments are handled through Sphinx. The system composes Juicebox core, the 721 hook stack, and Defifa-specific governance and resolver contracts into a single game-launch surface.
151
65
 
152
66
  ## Repository Layout
153
67
 
154
- ```
155
- defifa-collection-deployer-v6/
156
- ├── src/
157
- │ ├── DefifaDeployer.sol -- Game factory, phase/pot reporter, commitment fulfillment
158
- │ ├── DefifaGovernor.sol -- Scorecard governance, attestation, ratification
159
- │ ├── DefifaHook.sol -- ERC-721 game pieces, cash-out weights, delegation
160
- │ ├── DefifaProjectOwner.sol -- Defifa fee project ownership holder
161
- │ ├── DefifaTokenUriResolver.sol -- On-chain SVG token URI renderer
162
- │ ├── enums/
163
- │ │ ├── DefifaGamePhase.sol -- COUNTDOWN, MINT, REFUND, SCORING, COMPLETE, NO_CONTEST
164
- │ │ └── DefifaScorecardState.sol -- PENDING, ACTIVE, DEFEATED, SUCCEEDED, RATIFIED
165
- │ ├── interfaces/
166
- │ │ ├── IDefifaDeployer.sol
167
- │ │ ├── IDefifaGamePhaseReporter.sol
168
- │ │ ├── IDefifaGamePotReporter.sol
169
- │ │ ├── IDefifaGovernor.sol
170
- │ │ ├── IDefifaHook.sol
171
- │ │ └── IDefifaTokenUriResolver.sol
172
- │ ├── libraries/
173
- │ │ ├── DefifaFontImporter.sol -- Capsules typeface loader for SVG rendering
174
- │ │ └── DefifaHookLib.sol -- Scorecard validation, cash-out math, fee distribution
175
- │ └── structs/
176
- │ ├── DefifaAttestations.sol
177
- │ ├── DefifaDelegation.sol
178
- │ ├── DefifaLaunchProjectData.sol
179
- │ ├── DefifaOpsData.sol
180
- │ ├── DefifaScorecard.sol
181
- │ ├── DefifaTierCashOutWeight.sol
182
- │ └── DefifaTierParams.sol
183
- ├── test/
184
- │ ├── DefifaAdversarialQuorum.t.sol
185
- │ ├── DefifaAuditLowGuards.t.sol
186
- │ ├── DefifaFeeAccounting.t.sol
187
- │ ├── DefifaGovernor.t.sol
188
- │ ├── DefifaHookRegressions.t.sol
189
- │ ├── DefifaMintCostInvariant.t.sol
190
- │ ├── DefifaNoContest.t.sol
191
- │ ├── DefifaSecurity.t.sol
192
- │ ├── DefifaUSDC.t.sol
193
- │ ├── Fork.t.sol
194
- │ ├── SVG.t.sol
195
- │ ├── TestAuditGaps.sol
196
- │ ├── TestQALastMile.t.sol
197
- │ ├── deployScript.t.sol
198
- │ └── regression/
199
- │ ├── AttestationDelegateBeneficiary.t.sol
200
- │ ├── FulfillmentBlocksRatification.t.sol
201
- │ └── GracePeriodBypass.t.sol
202
- ├── script/
203
- │ ├── Deploy.s.sol -- Deployment script
204
- │ └── helpers/
205
- │ └── DefifaDeploymentLib.sol -- Deployment helper library
206
- ├── lib/ -- Git submodule dependencies
207
- │ ├── base64/
208
- │ ├── capsules/
209
- │ ├── forge-std/
210
- │ └── typeface/
211
- └── docs/
212
- └── plans/ -- Design documents
68
+ ```text
69
+ src/
70
+ DefifaDeployer.sol
71
+ DefifaGovernor.sol
72
+ DefifaHook.sol
73
+ DefifaProjectOwner.sol
74
+ DefifaTokenUriResolver.sol
75
+ enums/
76
+ interfaces/
77
+ libraries/
78
+ structs/
79
+ test/
80
+ lifecycle, fee, governance, invariant, fork, audit, and regression coverage
81
+ script/
82
+ Deploy.s.sol
83
+ helpers/
213
84
  ```
214
85
 
215
- ## Install
216
-
217
- ```bash
218
- npm install @ballkidz/defifa
219
- ```
220
-
221
- ## Develop
222
-
223
- Uses [npm](https://www.npmjs.com/) for package management and [Foundry](https://github.com/foundry-rs/foundry) for builds, tests, and deployments. Requires `via-ir = true` in foundry.toml.
224
-
225
- ```bash
226
- curl -L https://foundry.paradigm.xyz | sh
227
- npm install && forge install
228
- ```
86
+ ## Risks And Notes
229
87
 
230
- | Command | Description |
231
- |---------|-------------|
232
- | `forge build` | Compile contracts and write artifacts to `out`. |
233
- | `forge test` | Run the test suite (155 tests: unit, fuzz, invariant). |
234
- | `forge test -vvvv` | Run tests with full traces. |
235
- | `forge fmt` | Format Solidity files. |
236
- | `forge build --sizes` | Get contract sizes. |
237
- | `forge clean` | Remove build artifacts and cache. |
88
+ - scorecard governance quality depends on quorum, grace period, and participation assumptions set at launch
89
+ - optional refund windows and no-contest thresholds materially change game economics
90
+ - settlement is only as good as the ratified scorecard; bad governance configuration can still produce bad outcomes
91
+ - fee-accounting and pending-reserve edge cases are heavily tested because they are easy places for pot dilution or griefing
package/RISKS.md CHANGED
@@ -1,4 +1,21 @@
1
- # RISKS.md -- defifa-collection-deployer-v6
1
+ # Defifa Risk Register
2
+
3
+ This file focuses on the game-theoretic, governance, and settlement risks in Defifa's prediction-game flow: minting, attestation, scorecard ratification, and final cash out.
4
+
5
+ ## How to use this file
6
+
7
+ - Read `Priority risks` first; they identify the main ways a game can settle unfairly or get stuck.
8
+ - Use the detailed sections below to reason about governor power, live supply assumptions, and downstream hook dependencies.
9
+ - Treat `Accepted Behaviors` and `Invariants to Verify` as explicit boundaries for audit scope.
10
+
11
+ ## Priority risks
12
+
13
+ | Priority | Risk | Why it matters | Primary controls |
14
+ |----------|------|----------------|------------------|
15
+ | P0 | Scorecard capture at quorum | An actor that assembles 50%+ of attestation power can ratify an arbitrary scorecard and redirect the pot. | Tier-level attestation caps, grace period, and governance review of delegate concentration. |
16
+ | P1 | Shared 721 hook store blast radius | Defifa inherits the same shared `JB721TiersHookStore` surface as the general 721 hook ecosystem. A store bug hits every game. | Reuse of audited 721-hook invariants, store-focused testing, and ecosystem-level monitoring. |
17
+ | P1 | Supply and reserve accounting drift | Game fairness depends on attestation power, fee-token dilution, and cash-out weights tracking real mint/reserve state. | Explicit invariants on supply, reserve inclusion, and tier-weight arithmetic. |
18
+
2
19
 
3
20
  ## 1. Trust Assumptions
4
21
 
@@ -7,7 +24,7 @@
7
24
  - **DefifaProjectOwner Irrecoverability.** Once the Defifa project NFT is transferred to DefifaProjectOwner, it cannot be recovered. This is intentional but irreversible.
8
25
  - **External Dependencies.** Relies on JB721TiersHookStore, JBController, JBMultiTerminal, JBRulesets, and JBPrices. Bugs in any upstream contract affect all Defifa games.
9
26
  - **Default Attestation Delegate.** If set, the default attestation delegate receives delegated attestation power for all new minters who do not specify a delegate. This entity accumulates significant governance power.
10
- - **721 hook store shared with nana-721-hook-v6.** DefifaHook extends `JB721TiersHook`, sharing the same `JB721TiersHookStore`. All store-level risks from [nana-721-hook-v6 RISKS.md](../nana-721-hook-v6/RISKS.md) apply including the `totalCashOutWeight` tier iteration cost and the category sort order enforcement. Store bugs affect all Defifa games simultaneously.
27
+ - **721 hook store shared with nana-721-hook-v6.** `DefifaHook` uses the same `JB721TiersHookStore` dependency as the broader 721-hook ecosystem even though it has its own hook implementation. All store-level risks from [nana-721-hook-v6 RISKS.md](../nana-721-hook-v6/RISKS.md) still apply wherever Defifa relies on shared tier-store semantics. Store bugs affect all Defifa games simultaneously.
11
28
 
12
29
  ## 2. Economic Risks
13
30