Repository navigation
Expand file tree
/
Copy pathDefifaDeployer.sol
More file actions
1070 lines (934 loc) · 53.1 KB
/
Copy pathDefifaDeployer.sol
File metadata and controls
1070 lines (934 loc) · 53.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {IJB721TokenUriResolver} from "@bananapus/721-hook-v6/src/interfaces/IJB721TokenUriResolver.sol";
import {
JB721TiersRulesetMetadata,
JB721TiersRulesetMetadataResolver
} from "@bananapus/721-hook-v6/src/libraries/JB721TiersRulesetMetadataResolver.sol";
import {JB721TierConfig} from "@bananapus/721-hook-v6/src/structs/JB721TierConfig.sol";
import {JB721TierConfigFlags} from "@bananapus/721-hook-v6/src/structs/JB721TierConfigFlags.sol";
import {IJBAddressRegistry} from "@bananapus/address-registry-v6/src/interfaces/IJBAddressRegistry.sol";
import {IJBController, JBRulesetConfig, JBTerminalConfig} from "@bananapus/core-v6/src/interfaces/IJBController.sol";
import {IJBDirectory} from "@bananapus/core-v6/src/interfaces/IJBDirectory.sol";
import {IJBMultiTerminal} from "@bananapus/core-v6/src/interfaces/IJBMultiTerminal.sol";
import {IJBPayerTracker} from "@bananapus/core-v6/src/interfaces/IJBPayerTracker.sol";
import {IJBProjects} from "@bananapus/core-v6/src/interfaces/IJBProjects.sol";
import {IJBRulesetApprovalHook} from "@bananapus/core-v6/src/interfaces/IJBRulesetApprovalHook.sol";
import {IJBRulesets} from "@bananapus/core-v6/src/interfaces/IJBRulesets.sol";
import {IJBSplitHook} from "@bananapus/core-v6/src/interfaces/IJBSplitHook.sol";
import {IJBTerminal} from "@bananapus/core-v6/src/interfaces/IJBTerminal.sol";
import {JBConstants} from "@bananapus/core-v6/src/libraries/JBConstants.sol";
import {JBPayerTrackerLib} from "@bananapus/core-v6/src/libraries/JBPayerTrackerLib.sol";
import {JBAccountingContext} from "@bananapus/core-v6/src/structs/JBAccountingContext.sol";
import {JBCurrencyAmount} from "@bananapus/core-v6/src/structs/JBCurrencyAmount.sol";
import {JBFundAccessLimitGroup} from "@bananapus/core-v6/src/structs/JBFundAccessLimitGroup.sol";
import {JBRuleset} from "@bananapus/core-v6/src/structs/JBRuleset.sol";
import {JBRulesetMetadata} from "@bananapus/core-v6/src/structs/JBRulesetMetadata.sol";
import {JBSplit} from "@bananapus/core-v6/src/structs/JBSplit.sol";
import {JBSplitGroup} from "@bananapus/core-v6/src/structs/JBSplitGroup.sol";
import {ERC2771Context} from "@openzeppelin/contracts/metatx/ERC2771Context.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {mulDiv} from "@prb/math/src/Common.sol";
import {IJB721TiersHookStore} from "@bananapus/721-hook-v6/src/interfaces/IJB721TiersHookStore.sol";
import {DefifaHook} from "./DefifaHook.sol";
import {DefifaGamePhase} from "./enums/DefifaGamePhase.sol";
import {IDefifaDeployer} from "./interfaces/IDefifaDeployer.sol";
import {IDefifaGamePhaseReporter} from "./interfaces/IDefifaGamePhaseReporter.sol";
import {IDefifaGamePotReporter} from "./interfaces/IDefifaGamePotReporter.sol";
import {IDefifaGovernor} from "./interfaces/IDefifaGovernor.sol";
import {IDefifaHook} from "./interfaces/IDefifaHook.sol";
import {IDefifaReferee} from "./interfaces/IDefifaReferee.sol";
import {DefifaLaunchProjectData} from "./structs/DefifaLaunchProjectData.sol";
import {DefifaOpsData} from "./structs/DefifaOpsData.sol";
import {DefifaTierParams} from "./structs/DefifaTierParams.sol";
/// @notice Deploys and manages Defifa games — prediction-market-style contests built on Juicebox. Each game has
/// tiers representing outcomes (teams, players, events). Players mint tier NFTs during the mint phase, then after
/// the event concludes, a scorecard assigns cash-out weights to each tier. The treasury is distributed proportionally
/// to winning NFT holders. Games progress through phases: COUNTDOWN → MINT → REFUND → SCORING → COMPLETE (or
/// NO_CONTEST if minimum participation isn't met or scorecard ratification times out).
contract DefifaDeployer is
ERC2771Context,
IDefifaDeployer,
IDefifaGamePhaseReporter,
IDefifaGamePotReporter,
IERC721Receiver,
IJBPayerTracker
{
using Strings for uint256;
using SafeERC20 for IERC20;
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
/// @notice Thrown when fulfilling a game's commitments before its cash-out weights have been set.
error DefifaDeployer_CantFulfillYet(uint256 gameId);
/// @notice Thrown when launching a game with non-sequential phase timestamps, no mint duration, more than 128
/// tiers, no scorecard timeout, a scorecard timeout no longer than the timelock, or no referee. Each guard keeps a
/// launched game able to finish: phases in order, a mint window, tier tables that fit, a refund path, a timelock
/// that ends before the timeout, and someone to submit the result.
error DefifaDeployer_InvalidGameConfiguration(
uint256 start, uint256 mintPeriodDuration, uint256 refundPeriodDuration, uint256 tierCount
);
/// @notice Thrown when launching an ERC-20 game with a zero base currency.
error DefifaDeployer_InvalidCurrency(address token, uint256 currency);
/// @notice Thrown when triggering no-contest for a game that is not in its NO_CONTEST phase.
error DefifaDeployer_NotNoContest(uint256 gameId, DefifaGamePhase phase);
/// @notice Thrown when triggering no-contest for a game where it has already been triggered.
error DefifaDeployer_NoContestAlreadyTriggered(uint256 gameId);
/// @notice Thrown when the configured fee splits sum to more than 100%.
error DefifaDeployer_SplitsDontAddUp(uint256 totalPercent, uint256 maxPercent);
//*********************************************************************//
// ------------------------- public constants ------------------------ //
//*********************************************************************//
/// @notice The divisor that describes the protocol fee that should be taken.
/// @dev This is equal to 100 divided by the fee percent (e.g. 40 = 2.5% fee).
uint256 public constant override BASE_PROTOCOL_FEE_DIVISOR = 40;
/// @notice The divisor that describes the Defifa fee that should be taken.
/// @dev This is equal to 100 divided by the fee percent (e.g. 20 = 5% fee).
uint256 public constant override DEFIFA_FEE_DIVISOR = 20;
//*********************************************************************//
// --------------- public immutable stored properties ---------------- //
//*********************************************************************//
/// @notice The project ID that will receive protocol fees as commitments are fulfilled.
uint256 public immutable override BASE_PROTOCOL_PROJECT_ID;
/// @notice The controller with which new projects should be deployed.
IJBController public immutable override CONTROLLER;
/// @notice The project ID that receives Defifa game fees as commitments are fulfilled.
uint256 public immutable override DEFIFA_PROJECT_ID;
/// @notice The directory of terminals and controllers for each project.
IJBDirectory public immutable override DIRECTORY;
/// @notice The governance contract that ratifies scorecards for each game.
IDefifaGovernor public immutable override GOVERNOR;
/// @notice The original code for the Defifa hook to base subsequent instances on.
address public immutable override HOOK_CODE_ORIGIN;
/// @notice The 721 tiers hook store used by all games.
IJB721TiersHookStore public immutable override HOOK_STORE;
/// @notice The contract which mints ERC-721s that represent project ownership and transfers.
IJBProjects public immutable override PROJECTS;
/// @notice The Juicebox 721 tiers hook registry used to register deployed games.
IJBAddressRegistry public immutable override REGISTRY;
/// @notice The contract storing and managing project rulesets.
IJBRulesets public immutable override RULESETS;
/// @notice The default Defifa token URI resolver.
IJB721TokenUriResolver public immutable override TOKEN_URI_RESOLVER;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/// @notice The amount of commitments a game has fulfilled.
/// @custom:param gameId The ID of the game to check.
mapping(uint256 => uint256) public override fulfilledCommitmentsOf;
/// @notice Whether commitments have been fulfilled for a game.
/// @custom:param gameId The ID of the game to check.
mapping(uint256 => bool) public commitmentsFulfilledFor;
/// @notice Whether the no-contest refund ruleset has been triggered for a game.
/// @dev Once triggered, the game stays in NO_CONTEST and refunds are enabled.
/// @custom:param gameId The ID of the game to check.
mapping(uint256 => bool) public noContestTriggeredFor;
//*********************************************************************//
// ------------------- public transient properties ------------------- //
//*********************************************************************//
/// @notice The account that paid the creation fee for the game currently being launched.
/// @dev This contract owns the games it launches, so it advertises the resolved fee payer (the `launchGameWith`
/// ERC-2771 caller, or that caller's upstream payer when the caller is itself an `IJBPayerTracker`) while
/// `JBProjects.createFor` runs, letting a `pay`-routing fee receiver credit the true payer instead of this
/// deployer. Cleared back to `address(0)` once the call returns.
address public transient override originalPayer;
//*********************************************************************//
// -------------------- internal stored properties ------------------- //
//*********************************************************************//
/// @notice The game's ops.
/// @custom:param gameId The ID of the game whose ops are stored.
mapping(uint256 => DefifaOpsData) internal _opsOf;
/// @notice The total absolute split percent for each game (out of SPLITS_TOTAL_PERCENT).
/// @custom:param gameId The ID of the game whose total absolute split percent is stored.
mapping(uint256 => uint256) internal _commitmentPercentOf;
/// @notice This contract's nonce for deterministic hook deployment and registry entries.
/// @dev Initialized at 1 because the hook implementation is deployed before the first game clone.
uint256 internal _nonce;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/// @notice The current pot the game is played with.
/// @param gameId The ID of the game for which the pot applies.
/// @param includeCommitments A flag indicating if the portion of the pot committed to fulfill preprogrammed
/// obligations should be included.
/// @return The game's pot amount, as a fixed point number.
/// @return The token address the game's pot is measured in.
/// @return The number of decimals included in the amount.
function currentGamePotOf(
uint256 gameId,
bool includeCommitments
)
external
view
returns (uint256, address, uint256)
{
// Get a reference to the token being used by the project.
address token = _opsOf[gameId].token;
// Get a reference to the terminal via the directory.
IJBTerminal terminal = DIRECTORY.primaryTerminalOf({projectId: gameId, token: token});
// Get the accounting context for the project.
JBAccountingContext memory context = terminal.accountingContextForTokenOf({projectId: gameId, token: token});
// Get the current balance from the terminal's store.
uint256 pot = IJBMultiTerminal(address(terminal))
.STORE()
.balanceOf({terminal: address(terminal), projectId: gameId, token: token});
// Add any fulfilled commitments.
if (includeCommitments) pot += fulfilledCommitmentsOf[gameId];
return (pot, token, context.decimals);
}
/// @notice Whether or not the next phase still needs queuing.
/// @param gameId The ID of the game to get the queue status of.
/// @return Whether or not the next phase still needs queuing.
function nextPhaseNeedsQueueing(uint256 gameId) external view override returns (bool) {
// Get the game's current funding cycle along with its metadata.
JBRuleset memory currentRuleset = RULESETS.currentOf(gameId);
// Get the game's queued funding cycle along with its metadata.
(JBRuleset memory queuedRuleset,) = RULESETS.latestQueuedOf(gameId);
// If the configurations are the same and the game hasn't ended, queueing is still needed.
return currentRuleset.duration != 0 && currentRuleset.id == queuedRuleset.id;
}
/// @notice The safety mechanism parameters of a game.
/// @param gameId The ID of the game to get the safety params of.
/// @return minParticipation The minimum cumulative NFT mint cost for the game to proceed to scoring.
/// @return scorecardTimeout The maximum time after scoring begins for a scorecard to be ratified.
function safetyParamsOf(uint256 gameId)
external
view
override
returns (uint256 minParticipation, uint32 scorecardTimeout)
{
DefifaOpsData memory ops = _opsOf[gameId];
return (ops.minParticipation, ops.scorecardTimeout);
}
/// @notice Get the countdown, minting, and refund deadline timestamps for a game.
/// @param gameId The ID of the game for which the game times apply.
/// @return The game's start time, as a unix timestamp.
/// @return The game's minting period duration, in seconds.
/// @return The game's refund period duration, in seconds.
function timesFor(uint256 gameId) external view override returns (uint48, uint24, uint24) {
DefifaOpsData memory ops = _opsOf[gameId];
return (ops.start, ops.mintPeriodDuration, ops.refundPeriodDuration);
}
/// @notice Get the ERC-20 token address associated with a given game.
/// @param gameId The ID of the game to get the token of.
/// @return The game's token.
function tokenOf(uint256 gameId) external view override returns (address) {
return _opsOf[gameId].token;
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
/// @notice Returns the number of the game phase.
/// @dev The game phase corresponds to the game's current funding cycle number.
/// @dev NO_CONTEST is returned if the minimum participation threshold is not met, or if the scorecard timeout has
/// elapsed without ratification.
/// @param gameId The ID of the game to get the phase number of.
/// @return The game phase.
function currentGamePhaseOf(uint256 gameId) public view override returns (DefifaGamePhase) {
// Get the game's current funding cycle along with its metadata.
(JBRuleset memory currentRuleset, JBRulesetMetadata memory metadata) = CONTROLLER.currentRulesetOf(gameId);
// Cache the cycle number to avoid repeated memory reads.
uint256 cycleNumber = currentRuleset.cycleNumber;
// Return early for the first three phases based on cycle number.
if (cycleNumber == 0) return DefifaGamePhase.COUNTDOWN;
if (cycleNumber == 1) return DefifaGamePhase.MINT;
if (cycleNumber == 2 && _opsOf[gameId].refundPeriodDuration != 0) {
return DefifaGamePhase.REFUND;
}
// Check if the scorecard has been ratified (game is COMPLETE).
// This takes priority over all NO_CONTEST checks — a ratified scorecard is final.
if (IDefifaHook(metadata.dataHook).cashOutWeightIsSet()) return DefifaGamePhase.COMPLETE;
// If no-contest has already been triggered, stay in NO_CONTEST.
if (noContestTriggeredFor[gameId]) return DefifaGamePhase.NO_CONTEST;
// Get the game's ops data for the safety mechanism checks. Cache to avoid repeated SLOAD.
DefifaOpsData memory ops = _opsOf[gameId];
// Check minimum participation threshold using cumulative NFT mint cost from the hook.
// Terminal balance is NOT used because `addToBalanceOf` can inflate it without minting NFTs.
// `totalMintCost` tracks only actual paid mint value and is decremented on refunds/burns.
if (ops.minParticipation > 0) {
if (IDefifaHook(metadata.dataHook).totalMintCost() < ops.minParticipation) {
return DefifaGamePhase.NO_CONTEST;
}
}
// Check scorecard ratification timeout: if enough time has passed without a ratified scorecard, the game is
// NO_CONTEST.
// Game phase timing is timestamp-based by design.
// forge-lint: disable-next-line(block-timestamp)
if (ops.scorecardTimeout > 0 && block.timestamp > currentRuleset.start + ops.scorecardTimeout) {
return DefifaGamePhase.NO_CONTEST;
}
return DefifaGamePhase.SCORING;
}
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/// @param hookCodeOrigin The code of the Defifa hook.
/// @param tokenUriResolver The standard default token URI resolver.
/// @param governor The Defifa governor.
/// @param controller The controller to use to launch the game from.
/// @param registry The contract storing references to the deployer of each hook.
/// @param defifaProjectId The ID of the project that should take the fee from the games.
/// @param baseProtocolProjectId The ID of the protocol project that will receive fees from fulfilling commitments.
/// @param hookStore The store used by Defifa hooks.
/// @param trustedForwarder The trusted forwarder for the ERC2771Context.
constructor(
address hookCodeOrigin,
IJB721TokenUriResolver tokenUriResolver,
IDefifaGovernor governor,
IJBController controller,
IJBAddressRegistry registry,
uint256 defifaProjectId,
uint256 baseProtocolProjectId,
IJB721TiersHookStore hookStore,
address trustedForwarder
)
ERC2771Context(trustedForwarder)
{
HOOK_CODE_ORIGIN = hookCodeOrigin;
TOKEN_URI_RESOLVER = tokenUriResolver;
GOVERNOR = governor;
CONTROLLER = controller;
DIRECTORY = controller.DIRECTORY();
PROJECTS = controller.PROJECTS();
RULESETS = controller.RULESETS();
REGISTRY = registry;
DEFIFA_PROJECT_ID = defifaProjectId;
BASE_PROTOCOL_PROJECT_ID = baseProtocolProjectId;
HOOK_STORE = hookStore;
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice Fulfill split amounts between all splits for a game.
/// @param gameId The ID of the game to fulfill splits for.
function fulfillCommitmentsOf(uint256 gameId) external virtual override {
// Make sure commitments haven't already been fulfilled.
if (commitmentsFulfilledFor[gameId]) return;
commitmentsFulfilledFor[gameId] = true;
// Get the game's current funding cycle along with its metadata.
(, JBRulesetMetadata memory metadata) = CONTROLLER.currentRulesetOf(gameId);
// Make sure the game's commitments can be fulfilled.
if (!IDefifaHook(metadata.dataHook).cashOutWeightIsSet()) {
revert DefifaDeployer_CantFulfillYet({gameId: gameId});
}
// Get the game token and the terminal.
address token = _opsOf[gameId].token;
IJBMultiTerminal terminal =
IJBMultiTerminal(address(DIRECTORY.primaryTerminalOf({projectId: gameId, token: token})));
// Get the current pot and store it. This also prevents re-entrance since the check above will return early.
uint256 pot = terminal.STORE().balanceOf({terminal: address(terminal), projectId: gameId, token: token});
// If the pot is empty, queue the final ruleset without attempting payouts.
if (pot == 0) {
_queueFinalRuleset({gameId: gameId, metadata: metadata});
emit FulfilledCommitments({gameId: gameId, pot: 0, caller: _msgSender()});
return;
}
// Compute the fee amount based on the total absolute split percent stored at game creation.
uint256 feeAmount =
mulDiv({x: pot, y: _commitmentPercentOf[gameId], denominator: JBConstants.SPLITS_TOTAL_PERCENT});
// Store the actual fee amount for accurate currentGamePotOf reporting.
fulfilledCommitmentsOf[gameId] = feeAmount;
// Send only the fee portion as payouts. The remaining balance stays as surplus for cash-outs.
// Use the ruleset's baseCurrency — this matches the currency under which payout limits were stored
// at launch time, regardless of whether the token is native ETH or an ERC-20. Wrapped in try-catch so
// the final ruleset is always queued even if payout fails.
try terminal.sendPayoutsOf({
projectId: gameId, token: token, amount: feeAmount, currency: metadata.baseCurrency, minTokensPaidOut: 0
}) {}
catch (bytes memory reason) {
// Payout failed — fee stays in pot. Reset to 0 so currentGamePotOf
// doesn't double-count the fee.
fulfilledCommitmentsOf[gameId] = 0;
emit CommitmentPayoutFailed({gameId: gameId, amount: feeAmount, reason: reason, caller: _msgSender()});
}
// Queue the final ruleset and emit.
_queueFinalRuleset({gameId: gameId, metadata: metadata});
emit FulfilledCommitments({gameId: gameId, pot: pot, caller: _msgSender()});
}
/// @notice Launches a new game owned by this contract with a DefifaHook attached.
/// @param launchProjectData Data necessary to fulfill the transaction to launch a game.
/// @return gameId The ID of the newly configured game.
/// @dev Forwards `msg.value` to `JBProjects.createFor` to cover any configured project creation fee.
function launchGameWith(DefifaLaunchProjectData memory launchProjectData)
external
payable
override
returns (uint256 gameId)
{
// Game launch timing is timestamp-based by design.
uint256 currentTimestamp = block.timestamp;
// If no explicit game start is provided, start after the configured mint and refund windows.
if (launchProjectData.start == 0) {
uint256 start =
currentTimestamp + launchProjectData.mintPeriodDuration + launchProjectData.refundPeriodDuration;
if (start > type(uint48).max) {
revert DefifaDeployer_InvalidGameConfiguration({
start: start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
// Casting to uint48 is safe because `start` was bounded above.
// forge-lint: disable-next-line(unsafe-typecast)
launchProjectData.start = uint48(start);
}
// If callers provide a future start with no mint duration, derive a mint window that begins now and ends
// before the refund window. This preserves the requested start while keeping minting immediately available.
else if (
launchProjectData.mintPeriodDuration == 0
&& launchProjectData.start > currentTimestamp + launchProjectData.refundPeriodDuration
) {
launchProjectData.mintPeriodDuration =
uint24(launchProjectData.start - (currentTimestamp + launchProjectData.refundPeriodDuration));
}
// Make sure the provided gameplay timestamps are sequential and that there is a mint duration.
if (
launchProjectData.mintPeriodDuration == 0
|| launchProjectData.start
< currentTimestamp + launchProjectData.refundPeriodDuration + launchProjectData.mintPeriodDuration
) {
revert DefifaDeployer_InvalidGameConfiguration({
start: launchProjectData.start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
// The hook and governor hardcode uint256[128] tier-weight tables, so reject games with more than 128 tiers.
if (launchProjectData.tiers.length > 128) {
revert DefifaDeployer_InvalidGameConfiguration({
start: launchProjectData.start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
// Every game needs a timeout so scoring can resolve to NO_CONTEST if no scorecard is ratified.
if (launchProjectData.scorecardTimeout == 0) {
revert DefifaDeployer_InvalidGameConfiguration({
start: launchProjectData.start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
// Every game needs a referee to submit its scorecard.
if (launchProjectData.referee == address(0)) {
revert DefifaDeployer_InvalidGameConfiguration({
start: launchProjectData.start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
// Reject ERC-20 games with a zero currency. A zero baseCurrency would cause payout limit lookups
// in fulfillCommitmentsOf to silently fail, skipping all commitment payouts.
if (launchProjectData.token.token != JBConstants.NATIVE_TOKEN && launchProjectData.token.currency == 0) {
revert DefifaDeployer_InvalidCurrency({
token: launchProjectData.token.token, currency: launchProjectData.token.currency
});
}
// The timeout must outlast the timelock, or the game would enter NO_CONTEST before any scorecard could be
// ratified. A referee's own windows are its creator's responsibility.
if (launchProjectData.scorecardTimeout <= launchProjectData.timelockDuration) {
revert DefifaDeployer_InvalidGameConfiguration({
start: launchProjectData.start,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
tierCount: launchProjectData.tiers.length
});
}
address caller = _msgSender();
// Expose the resolved fee payer so a `pay`-routing fee receiver credits the true payer, not this deployer.
// Cleared immediately after.
originalPayer = JBPayerTrackerLib.resolve(caller);
// Reserve the game ID up front so permissionless project creations cannot invalidate hook deployment.
gameId = PROJECTS.createFor{value: msg.value}(address(this));
originalPayer = address(0);
// Store the timestamps that define the game phases.
_opsOf[gameId] = DefifaOpsData({
token: launchProjectData.token.token,
mintPeriodDuration: launchProjectData.mintPeriodDuration,
refundPeriodDuration: launchProjectData.refundPeriodDuration,
start: launchProjectData.start,
minParticipation: launchProjectData.minParticipation,
scorecardTimeout: launchProjectData.scorecardTimeout
});
// Keep track of the number of tiers.
uint256 numberOfTiers = launchProjectData.tiers.length;
// Create the standard tiers struct that will be populated from the defifa tiers.
JB721TierConfig[] memory hookTiers = new JB721TierConfig[](launchProjectData.tiers.length);
// Group all the tier names together.
string[] memory tierNames = new string[](launchProjectData.tiers.length);
// Keep a reference to the tier being iterated on.
DefifaTierParams memory defifaTier;
// Create the hook tiers from the Defifa tiers.
for (uint256 i; i < numberOfTiers;) {
defifaTier = launchProjectData.tiers[i];
// Set the tier. All tiers use the same price so that price-based voting power is equal.
hookTiers[i] = JB721TierConfig({
price: launchProjectData.tierPrice,
initialSupply: 999_999_999, // Uncapped minting — max value allowed by the 721 store.
votingUnits: 0,
reserveFrequency: defifaTier.reservedRate,
reserveBeneficiary: defifaTier.reservedTokenBeneficiary,
encodedIpfsUri: defifaTier.encodedIpfsUri,
category: 0,
discountPercent: 0,
flags: JB721TierConfigFlags({
allowOwnerMint: false,
useReserveBeneficiaryAsDefault: defifaTier.shouldUseReservedTokenBeneficiaryAsDefault,
transfersPausable: false,
useVotingUnits: false,
cantBeRemoved: true,
cantIncreaseDiscountPercent: true,
cantBuyWithCredits: false
}),
splitPercent: 0,
splits: new JBSplit[](0)
});
// Set the name.
tierNames[i] = defifaTier.name;
unchecked {
++i;
}
}
// Increment the nonce for this deployment.
uint256 currentNonce = ++_nonce;
// Clone deterministically using caller and nonce to prevent front-running.
// Clones.clone() creates the proxy before initialize() is called, allowing an
// attacker to front-run initialization and DOS the game deployment. Using
// cloneDeterministic with the ERC-2771 caller in the salt prevents this since a different
// caller produces a different address.
DefifaHook hook = DefifaHook(
Clones.cloneDeterministic({
implementation: HOOK_CODE_ORIGIN, salt: keccak256(abi.encodePacked(caller, currentNonce))
})
);
// Use the default uri resolver if provided, else use the hardcoded generic default.
IJB721TokenUriResolver uriResolver = launchProjectData.defaultTokenUriResolver
!= IJB721TokenUriResolver(address(0))
? launchProjectData.defaultTokenUriResolver
: TOKEN_URI_RESOLVER;
hook.initialize({
_gameId: gameId,
_name: launchProjectData.name,
_symbol: string.concat("DEFIFA #", gameId.toString()),
_rulesets: RULESETS,
_baseUri: launchProjectData.baseUri,
_tokenUriResolver: uriResolver,
_contractUri: launchProjectData.contractUri,
_tiers: hookTiers,
_currency: launchProjectData.token.currency,
_store: HOOK_STORE,
_gamePhaseReporter: this,
_gamePotReporter: this,
_defaultAttestationDelegate: launchProjectData.defaultAttestationDelegate,
_tierNames: tierNames
});
// Launch the Juicebox rulesets for the reserved project.
_launchGame({launchProjectData: launchProjectData, gameId: gameId, dataHook: address(hook)});
// Name the game's referee in the governor.
GOVERNOR.initializeGame({
gameId: gameId, referee: launchProjectData.referee, timelockDuration: launchProjectData.timelockDuration
});
// Give a contract referee its settings for this game.
if (launchProjectData.refereeData.length != 0) {
IDefifaReferee(launchProjectData.referee).initializeGameFor({
gameId: gameId, data: launchProjectData.refereeData
});
}
// Transfer ownership to the specified owner.
hook.transferOwnership(address(GOVERNOR));
// Register the actual CREATE2 clone address using the same salt and minimal-proxy init code
// that produced the deployed hook.
REGISTRY.registerAddress({
deployer: address(this),
salt: keccak256(abi.encodePacked(caller, currentNonce)),
bytecode: _cloneCreationCodeFor(address(HOOK_CODE_ORIGIN))
});
emit LaunchGame({gameId: gameId, hook: hook, governor: GOVERNOR, tokenUriResolver: uriResolver, caller: caller});
}
/// @notice Allows this contract to receive 721s.
function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
/// @notice Triggers the no-contest refund mechanism for a game.
/// @dev Anyone can call this once the game is in the NO_CONTEST phase. This queues a new ruleset without
/// payout limits, making the surplus equal to the balance so users can cash out at their mint price.
/// @dev Analogous to fulfillCommitmentsOf for COMPLETE — must be called before NO_CONTEST cash-outs work.
/// @param gameId The ID of the game to trigger no-contest for.
function triggerNoContestFor(uint256 gameId) external override {
// Make sure the game is currently in NO_CONTEST phase.
DefifaGamePhase phase = currentGamePhaseOf(gameId);
if (phase != DefifaGamePhase.NO_CONTEST) {
revert DefifaDeployer_NotNoContest({gameId: gameId, phase: phase});
}
// Make sure no-contest hasn't already been triggered.
if (noContestTriggeredFor[gameId]) revert DefifaDeployer_NoContestAlreadyTriggered({gameId: gameId});
// Mark as triggered.
// Note: the queued ruleset does not take effect until the current ruleset's cycle ends (or immediately
// if duration is 0). During this gap, the game reports NO_CONTEST but the on-chain ruleset still has
// payout limits, so cash-out reclaim values may differ from the full-refund expectation. Callers
// should verify the active ruleset before cashing out.
noContestTriggeredFor[gameId] = true;
// Get the game's current ruleset metadata for the data hook address.
(, JBRulesetMetadata memory metadata) = CONTROLLER.currentRulesetOf(gameId);
// Queue a new ruleset without payout limits so surplus = balance, enabling refunds.
JBRulesetConfig[] memory rulesetConfigs = new JBRulesetConfig[](1);
rulesetConfigs[0] = JBRulesetConfig({
mustStartAtOrAfter: 0,
duration: 0,
weight: 0,
weightCutPercent: 0,
approvalHook: IJBRulesetApprovalHook(address(0)),
metadata: JBRulesetMetadata({
reservedPercent: 0,
cashOutTaxRate: 0,
baseCurrency: metadata.baseCurrency,
pausePay: true,
pauseCreditTransfers: false,
allowOwnerMinting: false,
allowSetCustomToken: false,
allowTerminalMigration: false,
allowSetTerminals: false,
allowSetController: false,
allowAddAccountingContext: false,
allowAddPriceFeed: false,
ownerMustSendPayouts: true,
holdFees: false,
scopeCashOutsToLocalBalances: true,
useDataHookForPay: true,
useDataHookForCashOut: true,
dataHook: metadata.dataHook,
metadata: uint16(
JB721TiersRulesetMetadataResolver.pack721TiersRulesetMetadata(
JB721TiersRulesetMetadata({pauseTransfers: false, pauseMintPendingReserves: false})
)
)
}),
splitGroups: new JBSplitGroup[](0),
fundAccessLimitGroups: new JBFundAccessLimitGroup[](0)
});
// Queue the no-contest refund ruleset.
CONTROLLER.queueRulesetsOf({
projectId: gameId, rulesetConfigurations: rulesetConfigs, memo: "Defifa game: no contest."
});
emit QueuedNoContest({gameId: gameId, caller: _msgSender()});
}
//*********************************************************************//
// ------------------------ internal functions ----------------------- //
//*********************************************************************//
function _buildSplits(
uint256 gameId,
address dataHook,
address token,
JBSplit[] memory initialSplits
)
internal
returns (JBSplitGroup[] memory)
{
uint256 numberOfUserSplits = initialSplits.length;
// Compute absolute percents for protocol fees.
uint256 nanaAbsolutePercent = JBConstants.SPLITS_TOTAL_PERCENT / BASE_PROTOCOL_FEE_DIVISOR;
uint256 defifaAbsolutePercent = JBConstants.SPLITS_TOTAL_PERCENT / DEFIFA_FEE_DIVISOR;
// Sum all absolute percents.
uint256 totalAbsolutePercent = nanaAbsolutePercent + defifaAbsolutePercent;
for (uint256 i; i < numberOfUserSplits;) {
totalAbsolutePercent += initialSplits[i].percent;
unchecked {
++i;
}
}
// Validate that total fee splits don't exceed 100%.
if (totalAbsolutePercent > JBConstants.SPLITS_TOTAL_PERCENT) {
revert DefifaDeployer_SplitsDontAddUp({
totalPercent: totalAbsolutePercent, maxPercent: JBConstants.SPLITS_TOTAL_PERCENT
});
}
// Store the total absolute percent for use in fulfillCommitmentsOf.
_commitmentPercentOf[gameId] = totalAbsolutePercent;
// Build the splits array: user splits + Defifa + NANA (NANA last to absorb rounding).
uint256 splitCount = numberOfUserSplits + 2;
JBSplit[] memory splits = new JBSplit[](splitCount);
// Normalize user splits and copy them over.
uint256 normalizedTotal;
for (uint256 i; i < numberOfUserSplits;) {
splits[i] = initialSplits[i];
splits[i].percent = uint32(
mulDiv({
x: initialSplits[i].percent, y: JBConstants.SPLITS_TOTAL_PERCENT, denominator: totalAbsolutePercent
})
);
normalizedTotal += splits[i].percent;
unchecked {
++i;
}
}
// Add Defifa fee split (normalized).
uint256 defifaNormalized =
mulDiv({x: defifaAbsolutePercent, y: JBConstants.SPLITS_TOTAL_PERCENT, denominator: totalAbsolutePercent});
splits[numberOfUserSplits] = JBSplit({
preferAddToBalance: false,
// forge-lint: disable-next-line(unsafe-typecast)
percent: uint32(defifaNormalized),
// forge-lint: disable-next-line(unsafe-typecast)
projectId: uint64(DEFIFA_PROJECT_ID),
beneficiary: payable(address(dataHook)),
lockedUntil: 0,
hook: IJBSplitHook(address(0))
});
normalizedTotal += defifaNormalized;
// Add NANA protocol fee split last — absorbs rounding remainder from normalization.
// Because mulDiv rounds down, the sum of normalized percents can be slightly less than SPLITS_TOTAL_PERCENT.
// The NANA split receives the difference, so its effective percent may be a few basis points above its
// proportional share. This is economically negligible (< 1 bps at typical split counts).
// Beneficiary is the data hook so the hook receives NANA tokens for distribution during cash-outs.
splits[splitCount - 1] = JBSplit({
preferAddToBalance: false,
// forge-lint: disable-next-line(unsafe-typecast)
percent: uint32(JBConstants.SPLITS_TOTAL_PERCENT - normalizedTotal),
// forge-lint: disable-next-line(unsafe-typecast)
projectId: uint64(BASE_PROTOCOL_PROJECT_ID),
beneficiary: payable(address(dataHook)),
lockedUntil: 0,
hook: IJBSplitHook(address(0))
});
// Build the grouped split for the payment of the game token.
JBSplitGroup[] memory groupedSplits = new JBSplitGroup[](1);
groupedSplits[0] = JBSplitGroup({groupId: uint256(uint160(token)), splits: splits});
return groupedSplits;
}
/// @notice Launch the Juicebox project rulesets that define a Defifa game's lifecycle.
/// @dev The project ID is reserved before the hook clone is initialized, so this function launches rulesets for
/// that existing project instead of creating a new one. It also forwards `projectUri` to the controller so the
/// project metadata is set atomically with the first rulesets.
/// @param launchProjectData The normalized launch data for the game.
/// @param gameId The reserved Juicebox project ID for the game.
/// @param dataHook The initialized Defifa hook clone used by every ruleset.
function _launchGame(DefifaLaunchProjectData memory launchProjectData, uint256 gameId, address dataHook) internal {
// Accept exactly the token/accounting context the game was configured to use.
JBAccountingContext[] memory accountingContexts = new JBAccountingContext[](1);
accountingContexts[0] = launchProjectData.token;
// Build the terminal configuration for the Defifa project.
JBTerminalConfig[] memory terminalConfigurations = new JBTerminalConfig[](1);
terminalConfigurations[0] =
JBTerminalConfig({terminal: launchProjectData.terminal, accountingContextsToAccept: accountingContexts});
// Build the rulesets that this Defifa game will go through. Games always have MINT and SCORING phases; the
// REFUND phase is omitted entirely when its duration is zero so the scoring ruleset can follow minting.
bool hasRefundPhase = launchProjectData.refundPeriodDuration != 0;
JBRulesetConfig[] memory rulesetConfigs = new JBRulesetConfig[](hasRefundPhase ? 3 : 2);
// MINT cycle: payments are accepted, cash-outs are enabled, and pending reserved tokens are paused so the
// scoring/final phases decide how reserved tokens are distributed.
rulesetConfigs[0] = JBRulesetConfig({
mustStartAtOrAfter: launchProjectData.start - launchProjectData.mintPeriodDuration
- launchProjectData.refundPeriodDuration,
duration: launchProjectData.mintPeriodDuration,
weight: 0,
weightCutPercent: 0,
approvalHook: IJBRulesetApprovalHook(address(0)),
metadata: JBRulesetMetadata({
reservedPercent: 0,
cashOutTaxRate: 0,
baseCurrency: launchProjectData.token.currency,
pausePay: false,
pauseCreditTransfers: false,
allowOwnerMinting: false,
allowSetCustomToken: false,
allowTerminalMigration: false,
allowSetTerminals: false,
allowSetController: false,
allowAddAccountingContext: false,
allowAddPriceFeed: false,
ownerMustSendPayouts: false,
holdFees: false,
scopeCashOutsToLocalBalances: true,
useDataHookForPay: true,
useDataHookForCashOut: true,
dataHook: dataHook,
metadata: uint16(
JB721TiersRulesetMetadataResolver.pack721TiersRulesetMetadata(
JB721TiersRulesetMetadata({
pauseTransfers: false,
// Reserved tokens can't be minted during this funding cycle.
pauseMintPendingReserves: true
})
)
)
}),
splitGroups: new JBSplitGroup[](0),
fundAccessLimitGroups: new JBFundAccessLimitGroup[](0)
});
uint256 cycleNumber = 1;
if (hasRefundPhase) {
// REFUND cycle: payments are paused while cash-outs remain available at pre-scoring terms.
rulesetConfigs[cycleNumber++] = JBRulesetConfig({
mustStartAtOrAfter: launchProjectData.start - launchProjectData.refundPeriodDuration,
duration: launchProjectData.refundPeriodDuration,
weight: 0,
weightCutPercent: 0,
approvalHook: IJBRulesetApprovalHook(address(0)),
metadata: JBRulesetMetadata({
reservedPercent: 0,
cashOutTaxRate: 0,
baseCurrency: launchProjectData.token.currency,
// Refund phase does not allow new payments.
pausePay: true,
pauseCreditTransfers: false,
allowOwnerMinting: false,
allowSetCustomToken: false,
allowTerminalMigration: false,
allowSetTerminals: false,
allowSetController: false,
allowAddAccountingContext: false,
allowAddPriceFeed: false,
ownerMustSendPayouts: false,
holdFees: false,
scopeCashOutsToLocalBalances: true,
useDataHookForPay: true,
useDataHookForCashOut: true,
dataHook: dataHook,
metadata: uint16(
JB721TiersRulesetMetadataResolver.pack721TiersRulesetMetadata(
JB721TiersRulesetMetadata({
pauseTransfers: false,
// Reserved tokens can't be minted during this funding cycle.
pauseMintPendingReserves: true
})
)
)
}),
splitGroups: new JBSplitGroup[](0),
fundAccessLimitGroups: new JBFundAccessLimitGroup[](0)
});
}
// The scoring ruleset can send the whole pot as payouts. `fulfillCommitmentsOf` only sends the commitment
// portion and leaves the rest as surplus for the final cash-out ruleset.
JBCurrencyAmount[] memory payoutAmounts = new JBCurrencyAmount[](1);
payoutAmounts[0] = JBCurrencyAmount({
// We allow a payout of the full amount, this will then mostly be added back to the balance of the project.
amount: type(uint224).max,
currency: launchProjectData.token.currency
});
JBFundAccessLimitGroup[] memory fundAccessConstraints = new JBFundAccessLimitGroup[](1);
fundAccessConstraints[0] = JBFundAccessLimitGroup({
terminal: address(launchProjectData.terminal),
token: launchProjectData.token.token,
payoutLimits: payoutAmounts,
surplusAllowances: new JBCurrencyAmount[](0)
});
// SCORING cycle: payments pause, the game owner must send payouts, and the Defifa hook determines the final
// cash-out weights once a scorecard is ratified.
rulesetConfigs[cycleNumber++] = JBRulesetConfig({
mustStartAtOrAfter: launchProjectData.start,
duration: 0,
weight: 0,
weightCutPercent: 0,
approvalHook: IJBRulesetApprovalHook(address(0)),
metadata: JBRulesetMetadata({
reservedPercent: 0,
cashOutTaxRate: 0,
baseCurrency: launchProjectData.token.currency,
pausePay: true,
pauseCreditTransfers: false,
allowOwnerMinting: false,
allowSetCustomToken: false,
allowTerminalMigration: false,
allowSetTerminals: false,
allowSetController: false,
allowAddAccountingContext: false,
allowAddPriceFeed: false,
// Set this to true so only the deployer can fulfill the commitments.
ownerMustSendPayouts: true,
holdFees: false,
scopeCashOutsToLocalBalances: true,
useDataHookForPay: true,
useDataHookForCashOut: true,
dataHook: dataHook,
metadata: uint16(
JB721TiersRulesetMetadataResolver.pack721TiersRulesetMetadata(
JB721TiersRulesetMetadata({pauseTransfers: false, pauseMintPendingReserves: false})
)
)
}),
splitGroups: _buildSplits({
gameId: gameId,
dataHook: dataHook,
token: launchProjectData.token.token,
initialSplits: launchProjectData.splits
}),
fundAccessLimitGroups: fundAccessConstraints
});
// Launch the rulesets for the reserved project and set the project URI in the same controller call.