-
Notifications
You must be signed in to change notification settings - Fork 10
/
JBPayoutRedemptionPaymentTerminal3_1.sol
1488 lines (1291 loc) · 63.8 KB
/
JBPayoutRedemptionPaymentTerminal3_1.sol
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.16;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {ERC165Checker} from '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol';
import {PRBMath} from '@paulrberg/contracts/math/PRBMath.sol';
import {IJBAllowanceTerminal3_1} from './../interfaces/IJBAllowanceTerminal3_1.sol';
import {IJBController} from './../interfaces/IJBController.sol';
import {IJBDirectory} from './../interfaces/IJBDirectory.sol';
import {IJBFeeGauge} from './../interfaces/IJBFeeGauge.sol';
import {IJBPayoutRedemptionPaymentTerminal3_1} from './../interfaces/IJBPayoutRedemptionPaymentTerminal3_1.sol';
import {IJBSplitAllocator} from './../interfaces/IJBSplitAllocator.sol';
import {IJBOperatable} from './../interfaces/IJBOperatable.sol';
import {IJBOperatorStore} from './../interfaces/IJBOperatorStore.sol';
import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
import {IJBPayoutTerminal3_1} from './../interfaces/IJBPayoutTerminal3_1.sol';
import {IJBPrices} from './../interfaces/IJBPrices.sol';
import {IJBProjects} from './../interfaces/IJBProjects.sol';
import {IJBRedemptionTerminal} from './../interfaces/IJBRedemptionTerminal.sol';
import {IJBSingleTokenPaymentTerminalStore} from './../interfaces/IJBSingleTokenPaymentTerminalStore.sol';
import {IJBSplitsStore} from './../interfaces/IJBSplitsStore.sol';
import {JBConstants} from './../libraries/JBConstants.sol';
import {JBCurrencies} from './../libraries/JBCurrencies.sol';
import {JBFixedPointNumber} from './../libraries/JBFixedPointNumber.sol';
import {JBFundingCycleMetadataResolver} from './../libraries/JBFundingCycleMetadataResolver.sol';
import {JBOperations} from './../libraries/JBOperations.sol';
import {JBTokens} from './../libraries/JBTokens.sol';
import {JBDidPayData} from './../structs/JBDidPayData.sol';
import {JBDidRedeemData} from './../structs/JBDidRedeemData.sol';
import {JBFee} from './../structs/JBFee.sol';
import {JBFundingCycle} from './../structs/JBFundingCycle.sol';
import {JBPayDelegateAllocation} from './../structs/JBPayDelegateAllocation.sol';
import {JBTokenAmount} from './../structs/JBTokenAmount.sol';
import {JBRedemptionDelegateAllocation} from './../structs/JBRedemptionDelegateAllocation.sol';
import {JBSplit} from './../structs/JBSplit.sol';
import {JBSplitAllocationData} from './../structs/JBSplitAllocationData.sol';
import {JBOperatable} from './JBOperatable.sol';
import {JBSingleTokenPaymentTerminal} from './JBSingleTokenPaymentTerminal.sol';
/// @notice Generic terminal managing all inflows and outflows of funds into the protocol ecosystem.
abstract contract JBPayoutRedemptionPaymentTerminal3_1 is
JBSingleTokenPaymentTerminal,
JBOperatable,
Ownable,
IJBPayoutRedemptionPaymentTerminal3_1
{
// A library that parses the packed funding cycle metadata into a friendlier format.
using JBFundingCycleMetadataResolver for JBFundingCycle;
//*********************************************************************//
// --------------------------- custom errors ------------------------- //
//*********************************************************************//
error FEE_TOO_HIGH();
error INADEQUATE_DISTRIBUTION_AMOUNT();
error INADEQUATE_RECLAIM_AMOUNT();
error INADEQUATE_TOKEN_COUNT();
error NO_MSG_VALUE_ALLOWED();
error PAY_TO_ZERO_ADDRESS();
error PROJECT_TERMINAL_MISMATCH();
error REDEEM_TO_ZERO_ADDRESS();
error TERMINAL_IN_SPLIT_ZERO_ADDRESS();
error TERMINAL_TOKENS_INCOMPATIBLE();
//*********************************************************************//
// ---------------------------- modifiers ---------------------------- //
//*********************************************************************//
/// @notice A modifier that verifies this terminal is a terminal of provided project ID.
modifier isTerminalOf(uint256 _projectId) {
if (!directory.isTerminalOf(_projectId, this)) revert PROJECT_TERMINAL_MISMATCH();
_;
}
//*********************************************************************//
// --------------------- internal stored constants ------------------- //
//*********************************************************************//
/// @notice Maximum fee that can be set for a funding cycle configuration.
/// @dev Out of MAX_FEE (50_000_000 / 1_000_000_000).
uint256 internal constant _FEE_CAP = 50_000_000;
/// @notice The fee beneficiary project ID is 1, as it should be the first project launched during the deployment process.
uint256 internal constant _FEE_BENEFICIARY_PROJECT_ID = 1;
//*********************************************************************//
// --------------------- internal stored properties ------------------ //
//*********************************************************************//
/// @notice Fees that are being held to be processed later.
/// @custom:param _projectId The ID of the project for which fees are being held.
mapping(uint256 => JBFee[]) internal _heldFeesOf;
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/// @notice Mints ERC-721's that represent project ownership and transfers.
IJBProjects public immutable override projects;
/// @notice The directory of terminals and controllers for projects.
IJBDirectory public immutable override directory;
/// @notice The contract that stores splits for each project.
IJBSplitsStore public immutable override splitsStore;
/// @notice The contract that exposes price feeds.
IJBPrices public immutable override prices;
/// @notice The contract that stores and manages the terminal's data.
address public immutable override store;
/// @notice The currency to base token issuance on.
/// @dev If this differs from `currency`, there must be a price feed available to convert `currency` to `baseWeightCurrency`.
uint256 public immutable override baseWeightCurrency;
/// @notice The group that payout splits coming from this terminal are identified by.
uint256 public immutable override payoutSplitsGroup;
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/// @notice The platform fee percent.
/// @dev Out of MAX_FEE (25_000_000 / 1_000_000_000)
uint256 public override fee = 25_000_000; // 2.5%
/// @notice The data source that returns a discount to apply to a project's fee.
address public override feeGauge;
/// @notice Addresses that can be paid towards from this terminal without incurring a fee.
/// @dev Only addresses that are considered to be contained within the ecosystem can be feeless. Funds sent outside the ecosystem may incur fees despite being stored as feeless.
/// @custom:param _address The address that can be paid toward.
mapping(address => bool) public override isFeelessAddress;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/// @notice Gets the current overflowed amount in this terminal for a specified project, in terms of ETH.
/// @dev The current overflow is represented as a fixed point number with 18 decimals.
/// @param _projectId The ID of the project to get overflow for.
/// @return The current amount of ETH overflow that project has in this terminal, as a fixed point number with 18 decimals.
function currentEthOverflowOf(
uint256 _projectId
) external view virtual override returns (uint256) {
// Get this terminal's current overflow.
uint256 _overflow = IJBSingleTokenPaymentTerminalStore(store).currentOverflowOf(
this,
_projectId
);
// Adjust the decimals of the fixed point number if needed to have 18 decimals.
uint256 _adjustedOverflow = (decimals == 18)
? _overflow
: JBFixedPointNumber.adjustDecimals(_overflow, decimals, 18);
// Return the amount converted to ETH.
return
(currency == JBCurrencies.ETH)
? _adjustedOverflow
: PRBMath.mulDiv(
_adjustedOverflow,
10 ** decimals,
prices.priceFor(currency, JBCurrencies.ETH, decimals)
);
}
/// @notice The fees that are currently being held to be processed later for each project.
/// @param _projectId The ID of the project for which fees are being held.
/// @return An array of fees that are being held.
function heldFeesOf(uint256 _projectId) external view override returns (JBFee[] memory) {
return _heldFeesOf[_projectId];
}
//*********************************************************************//
// -------------------------- public views --------------------------- //
//*********************************************************************//
/// @notice Indicates if this contract adheres to the specified interface.
/// @dev See {IERC165-supportsInterface}.
/// @param _interfaceId The ID of the interface to check for adherance to.
/// @return A flag indicating if the provided interface ID is supported.
function supportsInterface(
bytes4 _interfaceId
) public view virtual override(JBSingleTokenPaymentTerminal, IERC165) returns (bool) {
return
_interfaceId == type(IJBPayoutRedemptionPaymentTerminal3_1).interfaceId ||
_interfaceId == type(IJBPayoutTerminal3_1).interfaceId ||
_interfaceId == type(IJBAllowanceTerminal3_1).interfaceId ||
_interfaceId == type(IJBRedemptionTerminal).interfaceId ||
_interfaceId == type(IJBOperatable).interfaceId ||
super.supportsInterface(_interfaceId);
}
//*********************************************************************//
// -------------------------- internal views ------------------------- //
//*********************************************************************//
/// @notice Checks the balance of tokens in this contract.
/// @return The contract's balance.
function _balance() internal view virtual returns (uint256);
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/// @param _decimals The number of decimals the token fixed point amounts are expected to have.
/// @param _currency The currency that this terminal's token adheres to for price feeds.
/// @param _baseWeightCurrency The currency to base token issuance on.
/// @param _payoutSplitsGroup The group that denotes payout splits from this terminal in the splits store.
/// @param _operatorStore A contract storing operator assignments.
/// @param _projects A contract which mints ERC-721's that represent project ownership and transfers.
/// @param _directory A contract storing directories of terminals and controllers for each project.
/// @param _splitsStore A contract that stores splits for each project.
/// @param _prices A contract that exposes price feeds.
/// @param _store A contract that stores the terminal's data.
/// @param _owner The address that will own this contract.
constructor(
// payable constructor save the gas used to check msg.value==0
address _token,
uint256 _decimals,
uint256 _currency,
uint256 _baseWeightCurrency,
uint256 _payoutSplitsGroup,
IJBOperatorStore _operatorStore,
IJBProjects _projects,
IJBDirectory _directory,
IJBSplitsStore _splitsStore,
IJBPrices _prices,
address _store,
address _owner
)
payable
JBSingleTokenPaymentTerminal(_token, _decimals, _currency)
JBOperatable(_operatorStore)
{
baseWeightCurrency = _baseWeightCurrency;
payoutSplitsGroup = _payoutSplitsGroup;
projects = _projects;
directory = _directory;
splitsStore = _splitsStore;
prices = _prices;
store = _store;
transferOwnership(_owner);
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/// @notice Contribute tokens to a project.
/// @param _projectId The ID of the project being paid.
/// @param _amount The amount of terminal tokens being received, as a fixed point number with the same amount of decimals as this terminal. If this terminal's token is ETH, this is ignored and msg.value is used in its place.
/// @param _token The token being paid. This terminal ignores this property since it only manages one token.
/// @param _beneficiary The address to mint tokens for and pass along to the funding cycle's data source and delegate.
/// @param _minReturnedTokens The minimum number of project tokens expected in return, as a fixed point number with the same amount of decimals as this terminal.
/// @param _preferClaimedTokens A flag indicating whether the request prefers to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract. Leaving them unclaimed saves gas.
/// @param _memo A memo to pass along to the emitted event, and passed along the the funding cycle's data source and delegate. A data source can alter the memo before emitting in the event and forwarding to the delegate.
/// @param _metadata Bytes to send along to the data source, delegate, and emitted event, if provided.
/// @return The number of tokens minted for the beneficiary, as a fixed point number with 18 decimals.
function pay(
uint256 _projectId,
uint256 _amount,
address _token,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string calldata _memo,
bytes calldata _metadata
) external payable virtual override isTerminalOf(_projectId) returns (uint256) {
_token; // Prevents unused var compiler and natspec complaints.
// ETH shouldn't be sent if this terminal's token isn't ETH.
if (token != JBTokens.ETH) {
if (msg.value > 0) revert NO_MSG_VALUE_ALLOWED();
// Get a reference to the balance before receiving tokens.
uint256 _balanceBefore = _balance();
// Transfer tokens to this terminal from the msg sender.
_transferFrom(msg.sender, payable(address(this)), _amount);
// The amount should reflect the change in balance.
_amount = _balance() - _balanceBefore;
}
// If this terminal's token is ETH, override _amount with msg.value.
else _amount = msg.value;
return
_pay(
_amount,
msg.sender,
_projectId,
_beneficiary,
_minReturnedTokens,
_preferClaimedTokens,
_memo,
_metadata
);
}
/// @notice Holders can redeem their tokens to claim the project's overflowed tokens, or to trigger rules determined by the project's current funding cycle's data source.
/// @dev Only a token holder or a designated operator can redeem its tokens.
/// @param _holder The account to redeem tokens for.
/// @param _projectId The ID of the project to which the tokens being redeemed belong.
/// @param _tokenCount The number of project tokens to redeem, as a fixed point number with 18 decimals.
/// @param _token The token being reclaimed. This terminal ignores this property since it only manages one token.
/// @param _minReturnedTokens The minimum amount of terminal tokens expected in return, as a fixed point number with the same amount of decimals as the terminal.
/// @param _beneficiary The address to send the terminal tokens to.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Bytes to send along to the data source, delegate, and emitted event, if provided.
/// @return reclaimAmount The amount of terminal tokens that the project tokens were redeemed for, as a fixed point number with 18 decimals.
function redeemTokensOf(
address _holder,
uint256 _projectId,
uint256 _tokenCount,
address _token,
uint256 _minReturnedTokens,
address payable _beneficiary,
string memory _memo,
bytes memory _metadata
)
external
virtual
override
requirePermission(_holder, _projectId, JBOperations.REDEEM)
returns (uint256 reclaimAmount)
{
_token; // Prevents unused var compiler and natspec complaints.
return
_redeemTokensOf(
_holder,
_projectId,
_tokenCount,
_minReturnedTokens,
_beneficiary,
_memo,
_metadata
);
}
/// @notice Distributes payouts for a project with the distribution limit of its current funding cycle.
/// @dev Payouts are sent to the preprogrammed splits. Any leftover is sent to the project's owner.
/// @dev Anyone can distribute payouts on a project's behalf. The project can preconfigure a wildcard split that is used to send funds to msg.sender. This can be used to incentivize calling this function.
/// @dev All funds distributed outside of this contract or any feeless terminals incure the protocol fee.
/// @param _projectId The ID of the project having its payouts distributed.
/// @param _amount The amount of terminal tokens to distribute, as a fixed point number with same number of decimals as this terminal.
/// @param _currency The expected currency of the amount being distributed. Must match the project's current funding cycle's distribution limit currency.
/// @param _token The token being distributed. This terminal ignores this property since it only manages one token.
/// @param _minReturnedTokens The minimum number of terminal tokens that the `_amount` should be valued at in terms of this terminal's currency, as a fixed point number with the same number of decimals as this terminal.
/// @param _metadata Bytes to send along to the emitted event, if provided.
/// @return netLeftoverDistributionAmount The amount that was sent to the project owner, as a fixed point number with the same amount of decimals as this terminal.
function distributePayoutsOf(
uint256 _projectId,
uint256 _amount,
uint256 _currency,
address _token,
uint256 _minReturnedTokens,
bytes calldata _metadata
) external virtual override returns (uint256 netLeftoverDistributionAmount) {
_token; // Prevents unused var compiler and natspec complaints.
return _distributePayoutsOf(_projectId, _amount, _currency, _minReturnedTokens, _metadata);
}
/// @notice Only a project's owner or a designated operator can use its allowance.
/// @dev Incurs the protocol fee.
/// @param _projectId The ID of the project to use the allowance of.
/// @param _amount The amount of terminal tokens to use from this project's current allowance, as a fixed point number with the same amount of decimals as this terminal.
/// @param _currency The expected currency of the amount being distributed. Must match the project's current funding cycle's overflow allowance currency.
/// @param _token The token being distributed. This terminal ignores this property since it only manages one token.
/// @param _minReturnedTokens The minimum number of tokens that the `_amount` should be valued at in terms of this terminal's currency, as a fixed point number with 18 decimals.
/// @param _beneficiary The address to send the funds to.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Bytes to send along to the emitted event, if provided.
/// @return netDistributedAmount The amount of tokens that was distributed to the beneficiary, as a fixed point number with the same amount of decimals as the terminal.
function useAllowanceOf(
uint256 _projectId,
uint256 _amount,
uint256 _currency,
address _token,
uint256 _minReturnedTokens,
address payable _beneficiary,
string memory _memo,
bytes calldata _metadata
)
external
virtual
override
requirePermission(projects.ownerOf(_projectId), _projectId, JBOperations.USE_ALLOWANCE)
returns (uint256 netDistributedAmount)
{
_token; // Prevents unused var compiler and natspec complaints.
return
_useAllowanceOf(
_projectId,
_amount,
_currency,
_minReturnedTokens,
_beneficiary,
_memo,
_metadata
);
}
/// @notice Allows a project owner to migrate its funds and operations to a new terminal that accepts the same token type.
/// @dev Only a project's owner or a designated operator can migrate it.
/// @param _projectId The ID of the project being migrated.
/// @param _to The terminal contract that will gain the project's funds.
/// @return balance The amount of funds that were migrated, as a fixed point number with the same amount of decimals as this terminal.
function migrate(
uint256 _projectId,
IJBPaymentTerminal _to
)
external
virtual
override
requirePermission(projects.ownerOf(_projectId), _projectId, JBOperations.MIGRATE_TERMINAL)
returns (uint256 balance)
{
// The terminal being migrated to must accept the same token as this terminal.
if (!_to.acceptsToken(token, _projectId)) revert TERMINAL_TOKENS_INCOMPATIBLE();
// Record the migration in the store.
balance = IJBSingleTokenPaymentTerminalStore(store).recordMigration(_projectId);
// Transfer the balance if needed.
if (balance > 0) {
// Trigger any inherited pre-transfer logic.
_beforeTransferTo(address(_to), balance);
// If this terminal's token is ETH, send it in msg.value.
uint256 _payableValue = token == JBTokens.ETH ? balance : 0;
// Withdraw the balance to transfer to the new terminal;
_to.addToBalanceOf{value: _payableValue}(_projectId, balance, token, '', bytes(''));
}
emit Migrate(_projectId, _to, balance, msg.sender);
}
/// @notice Receives funds belonging to the specified project.
/// @param _projectId The ID of the project to which the funds received belong.
/// @param _amount The amount of tokens to add, as a fixed point number with the same number of decimals as this terminal. If this is an ETH terminal, this is ignored and msg.value is used instead.
/// @param _token The token being paid. This terminal ignores this property since it only manages one currency.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Extra data to pass along to the emitted event.
function addToBalanceOf(
uint256 _projectId,
uint256 _amount,
address _token,
string calldata _memo,
bytes calldata _metadata
) external payable virtual override isTerminalOf(_projectId) {
// Do not refund held fees by default.
addToBalanceOf(_projectId, _amount, _token, false, _memo, _metadata);
}
/// @notice Process any fees that are being held for the project.
/// @dev Only a project owner, an operator, or the contract's owner can process held fees.
/// @param _projectId The ID of the project whos held fees should be processed.
function processFees(
uint256 _projectId
)
external
virtual
override
requirePermissionAllowingOverride(
projects.ownerOf(_projectId),
_projectId,
JBOperations.PROCESS_FEES,
msg.sender == owner()
)
{
// Get a reference to the project's held fees.
JBFee[] memory _heldFees = _heldFeesOf[_projectId];
// Delete the held fees.
delete _heldFeesOf[_projectId];
// Push array length in stack
uint256 _heldFeeLength = _heldFees.length;
// Process each fee.
for (uint256 _i; _i < _heldFeeLength; ) {
// Get the fee amount.
uint256 _amount = _feeAmount(
_heldFees[_i].amount,
_heldFees[_i].fee,
_heldFees[_i].feeDiscount
);
// Process the fee.
_processFee(_amount, _heldFees[_i].beneficiary, _projectId);
emit ProcessFee(_projectId, _amount, true, _heldFees[_i].beneficiary, msg.sender);
unchecked {
++_i;
}
}
}
/// @notice Allows the fee to be updated.
/// @dev Only the owner of this contract can change the fee.
/// @param _fee The new fee, out of MAX_FEE.
function setFee(uint256 _fee) external virtual override onlyOwner {
// The provided fee must be within the max.
if (_fee > _FEE_CAP) revert FEE_TOO_HIGH();
// Store the new fee.
fee = _fee;
emit SetFee(_fee, msg.sender);
}
/// @notice Allows the fee gauge to be updated.
/// @dev Only the owner of this contract can change the fee gauge.
/// @param _feeGauge The new fee gauge.
function setFeeGauge(address _feeGauge) external virtual override onlyOwner {
// Store the new fee gauge.
feeGauge = _feeGauge;
emit SetFeeGauge(_feeGauge, msg.sender);
}
/// @notice Sets whether projects operating on this terminal can pay towards the specified address without incurring a fee.
/// @param _address The address that can be paid towards while still bypassing fees.
/// @param _flag A flag indicating whether the terminal should be feeless or not.
function setFeelessAddress(address _address, bool _flag) external virtual override onlyOwner {
// Set the flag value.
isFeelessAddress[_address] = _flag;
emit SetFeelessAddress(_address, _flag, msg.sender);
}
//*********************************************************************//
// ----------------------- public transactions ----------------------- //
//*********************************************************************//
/// @notice Receives funds belonging to the specified project.
/// @param _amount The amount of tokens to add, as a fixed point number with the same number of decimals as this terminal. If this is an ETH terminal, this is ignored and msg.value is used instead.
/// @param _token The token being paid. This terminal ignores this property since it only manages one currency.
/// @param _shouldRefundHeldFees A flag indicating if held fees should be refunded based on the amount being added.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Extra data to pass along to the emitted event.
function addToBalanceOf(
uint256 _projectId,
uint256 _amount,
address _token,
bool _shouldRefundHeldFees,
string calldata _memo,
bytes calldata _metadata
) public payable virtual override isTerminalOf(_projectId) {
_token; // Prevents unused var compiler and natspec complaints.
// If this terminal's token isn't ETH, make sure no msg.value was sent, then transfer the tokens in from msg.sender.
if (token != JBTokens.ETH) {
// Amount must be greater than 0.
if (msg.value > 0) revert NO_MSG_VALUE_ALLOWED();
// Get a reference to the balance before receiving tokens.
uint256 _balanceBefore = _balance();
// Transfer tokens to this terminal from the msg sender.
_transferFrom(msg.sender, payable(address(this)), _amount);
// The amount should reflect the change in balance.
_amount = _balance() - _balanceBefore;
}
// If the terminal's token is ETH, override `_amount` with msg.value.
else _amount = msg.value;
// Add to balance.
_addToBalanceOf(_projectId, _amount, _shouldRefundHeldFees, _memo, _metadata);
}
//*********************************************************************//
// ---------------------- internal transactions ---------------------- //
//*********************************************************************//
/// @notice Transfers tokens.
/// @param _from The address from which the transfer should originate.
/// @param _to The address to which the transfer should go.
/// @param _amount The amount of the transfer, as a fixed point number with the same number of decimals as this terminal.
function _transferFrom(address _from, address payable _to, uint256 _amount) internal virtual {
_from; // Prevents unused var compiler and natspec complaints.
_to; // Prevents unused var compiler and natspec complaints.
_amount; // Prevents unused var compiler and natspec complaints.
}
/// @notice Logic to be triggered before transferring tokens from this terminal.
/// @param _to The address to which the transfer is going.
/// @param _amount The amount of the transfer, as a fixed point number with the same number of decimals as this terminal.
function _beforeTransferTo(address _to, uint256 _amount) internal virtual {
_to; // Prevents unused var compiler and natspec complaints.
_amount; // Prevents unused var compiler and natspec complaints.
}
/// @notice Logic to be triggered if a transfer should be undone
/// @param _to The address to which the transfer went.
/// @param _amount The amount of the transfer, as a fixed point number with the same number of decimals as this terminal.
function _cancelTransferTo(address _to, uint256 _amount) internal virtual {
_to; // Prevents unused var compiler and natspec complaints.
_amount; // Prevents unused var compiler and natspec complaints.
}
/// @notice Holders can redeem their tokens to claim the project's overflowed tokens, or to trigger rules determined by the project's current funding cycle's data source.
/// @dev Only a token holder or a designated operator can redeem its tokens.
/// @param _holder The account to redeem tokens for.
/// @param _projectId The ID of the project to which the tokens being redeemed belong.
/// @param _tokenCount The number of project tokens to redeem, as a fixed point number with 18 decimals.
/// @param _minReturnedTokens The minimum amount of terminal tokens expected in return, as a fixed point number with the same amount of decimals as the terminal.
/// @param _beneficiary The address to send the terminal tokens to.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Bytes to send along to the data source, delegate, and emitted event, if provided.
/// @return reclaimAmount The amount of terminal tokens that the project tokens were redeemed for, as a fixed point number with 18 decimals.
function _redeemTokensOf(
address _holder,
uint256 _projectId,
uint256 _tokenCount,
uint256 _minReturnedTokens,
address payable _beneficiary,
string memory _memo,
bytes memory _metadata
) internal returns (uint256 reclaimAmount) {
// Can't send reclaimed funds to the zero address.
if (_beneficiary == address(0)) revert REDEEM_TO_ZERO_ADDRESS();
// Define variables that will be needed outside the scoped section below.
// Keep a reference to the funding cycle during which the redemption is being made.
JBFundingCycle memory _fundingCycle;
// Scoped section prevents stack too deep. `_delegateAllocations` only used within scope.
{
JBRedemptionDelegateAllocation[] memory _delegateAllocations;
// Record the redemption.
(
_fundingCycle,
reclaimAmount,
_delegateAllocations,
_memo
) = IJBSingleTokenPaymentTerminalStore(store).recordRedemptionFor(
_holder,
_projectId,
_tokenCount,
_memo,
_metadata
);
// The amount being reclaimed must be at least as much as was expected.
if (reclaimAmount < _minReturnedTokens) revert INADEQUATE_RECLAIM_AMOUNT();
// Burn the project tokens.
if (_tokenCount > 0)
IJBController(directory.controllerOf(_projectId)).burnTokensOf(
_holder,
_projectId,
_tokenCount,
'',
false
);
// If delegate allocations were specified by the data source, fulfill them.
if (_delegateAllocations.length != 0) {
// Keep a reference to the token amount being forwarded to the delegate.
JBTokenAmount memory _forwardedAmount = JBTokenAmount(token, 0, decimals, currency);
JBDidRedeemData memory _data = JBDidRedeemData(
_holder,
_projectId,
_fundingCycle.configuration,
_tokenCount,
JBTokenAmount(token, reclaimAmount, decimals, currency),
_forwardedAmount,
_beneficiary,
_memo,
_metadata
);
uint256 _numDelegates = _delegateAllocations.length;
for (uint256 _i; _i < _numDelegates; ) {
// Get a reference to the delegate being iterated on.
JBRedemptionDelegateAllocation memory _delegateAllocation = _delegateAllocations[_i];
// Trigger any inherited pre-transfer logic.
_beforeTransferTo(address(_delegateAllocation.delegate), _delegateAllocation.amount);
// Keep track of the msg.value to use in the delegate call
uint256 _payableValue;
// If this terminal's token is ETH, send it in msg.value.
if (token == JBTokens.ETH) _payableValue = _delegateAllocation.amount;
// Pass the correct token forwardedAmount to the delegate
_data.forwardedAmount.value = _delegateAllocation.amount;
_delegateAllocation.delegate.didRedeem{value: _payableValue}(_data);
emit DelegateDidRedeem(
_delegateAllocation.delegate,
_data,
_delegateAllocation.amount,
msg.sender
);
unchecked {
++_i;
}
}
}
}
// Send the reclaimed funds to the beneficiary.
if (reclaimAmount > 0) _transferFrom(address(this), _beneficiary, reclaimAmount);
emit RedeemTokens(
_fundingCycle.configuration,
_fundingCycle.number,
_projectId,
_holder,
_beneficiary,
_tokenCount,
reclaimAmount,
_memo,
_metadata,
msg.sender
);
}
/// @notice Distributes payouts for a project with the distribution limit of its current funding cycle.
/// @dev Payouts are sent to the preprogrammed splits. Any leftover is sent to the project's owner.
/// @dev Anyone can distribute payouts on a project's behalf. The project can preconfigure a wildcard split that is used to send funds to msg.sender. This can be used to incentivize calling this function.
/// @dev All funds distributed outside of this contract or any feeless terminals incure the protocol fee.
/// @param _projectId The ID of the project having its payouts distributed.
/// @param _amount The amount of terminal tokens to distribute, as a fixed point number with same number of decimals as this terminal.
/// @param _currency The expected currency of the amount being distributed. Must match the project's current funding cycle's distribution limit currency.
/// @param _minReturnedTokens The minimum number of terminal tokens that the `_amount` should be valued at in terms of this terminal's currency, as a fixed point number with the same number of decimals as this terminal.
/// @param _metadata Bytes to send along to the emitted event, if provided.
/// @return netLeftoverDistributionAmount The amount that was sent to the project owner, as a fixed point number with the same amount of decimals as this terminal.
function _distributePayoutsOf(
uint256 _projectId,
uint256 _amount,
uint256 _currency,
uint256 _minReturnedTokens,
bytes calldata _metadata
) internal returns (uint256 netLeftoverDistributionAmount) {
// Record the distribution.
(
JBFundingCycle memory _fundingCycle,
uint256 _distributedAmount
) = IJBSingleTokenPaymentTerminalStore(store).recordDistributionFor(
_projectId,
_amount,
_currency
);
// The amount being distributed must be at least as much as was expected.
if (_distributedAmount < _minReturnedTokens) revert INADEQUATE_DISTRIBUTION_AMOUNT();
// Get a reference to the project owner, which will receive tokens from paying the platform fee
// and receive any extra distributable funds not allocated to payout splits.
address payable _projectOwner = payable(projects.ownerOf(_projectId));
// Define variables that will be needed outside the scoped section below.
// Keep a reference to the fee amount that was paid.
uint256 _fee;
// Scoped section prevents stack too deep. `_feeDiscount`, `_feeEligibleDistributionAmount`, and `_leftoverDistributionAmount` only used within scope.
{
// Get the amount of discount that should be applied to any fees taken.
// If the fee is zero, set the discount to 100% for convenience.
uint256 _feeDiscount = fee == 0
? JBConstants.MAX_FEE_DISCOUNT
: _currentFeeDiscount(_projectId);
// The amount distributed that is eligible for incurring fees.
uint256 _feeEligibleDistributionAmount;
// The amount leftover after distributing to the splits.
uint256 _leftoverDistributionAmount;
// Payout to splits and get a reference to the leftover transfer amount after all splits have been paid.
// Also get a reference to the amount that was distributed to splits from which fees should be taken.
(_leftoverDistributionAmount, _feeEligibleDistributionAmount) = _distributeToPayoutSplitsOf(
_projectId,
_fundingCycle.configuration,
payoutSplitsGroup,
_distributedAmount,
_feeDiscount
);
if (_feeDiscount != JBConstants.MAX_FEE_DISCOUNT) {
// Leftover distribution amount is also eligible for a fee since the funds are going out of the ecosystem to _beneficiary.
unchecked {
_feeEligibleDistributionAmount += _leftoverDistributionAmount;
}
}
// Take the fee.
_fee = _feeEligibleDistributionAmount != 0
? _takeFeeFrom(
_projectId,
_fundingCycle,
_feeEligibleDistributionAmount,
_projectOwner,
_feeDiscount
)
: 0;
// Transfer any remaining balance to the project owner and update returned leftover accordingly.
if (_leftoverDistributionAmount != 0) {
// Subtract the fee from the net leftover amount.
netLeftoverDistributionAmount =
_leftoverDistributionAmount -
_feeAmount(_leftoverDistributionAmount, fee, _feeDiscount);
// Transfer the amount to the project owner.
_transferFrom(address(this), _projectOwner, netLeftoverDistributionAmount);
}
}
emit DistributePayouts(
_fundingCycle.configuration,
_fundingCycle.number,
_projectId,
_projectOwner,
_amount,
_distributedAmount,
_fee,
netLeftoverDistributionAmount,
_metadata,
msg.sender
);
}
/// @notice Allows a project to send funds from its overflow up to the preconfigured allowance.
/// @dev Only a project's owner or a designated operator can use its allowance.
/// @dev Incurs the protocol fee.
/// @param _projectId The ID of the project to use the allowance of.
/// @param _amount The amount of terminal tokens to use from this project's current allowance, as a fixed point number with the same amount of decimals as this terminal.
/// @param _currency The expected currency of the amount being distributed. Must match the project's current funding cycle's overflow allowance currency.
/// @param _minReturnedTokens The minimum number of tokens that the `_amount` should be valued at in terms of this terminal's currency, as a fixed point number with 18 decimals.
/// @param _beneficiary The address to send the funds to.
/// @param _memo A memo to pass along to the emitted event.
/// @param _metadata Bytes to send along to the emitted event, if provided.
/// @return netDistributedAmount The amount of tokens that was distributed to the beneficiary, as a fixed point number with the same amount of decimals as the terminal.
function _useAllowanceOf(
uint256 _projectId,
uint256 _amount,
uint256 _currency,
uint256 _minReturnedTokens,
address payable _beneficiary,
string memory _memo,
bytes calldata _metadata
) internal returns (uint256 netDistributedAmount) {
// Record the use of the allowance.
(
JBFundingCycle memory _fundingCycle,
uint256 _distributedAmount
) = IJBSingleTokenPaymentTerminalStore(store).recordUsedAllowanceOf(
_projectId,
_amount,
_currency
);
// The amount being withdrawn must be at least as much as was expected.
if (_distributedAmount < _minReturnedTokens) revert INADEQUATE_DISTRIBUTION_AMOUNT();
// Scoped section prevents stack too deep. `_fee`, `_projectOwner`, `_feeDiscount`, and `_netAmount` only used within scope.
{
// Keep a reference to the fee amount that was paid.
uint256 _fee;
// Get a reference to the project owner, which will receive tokens from paying the platform fee.
address _projectOwner = projects.ownerOf(_projectId);
// Get the amount of discount that should be applied to any fees taken.
// If the fee is zero or if the fee is being used by an address that doesn't incur fees, set the discount to 100% for convenience.
uint256 _feeDiscount = fee == 0 || isFeelessAddress[msg.sender]
? JBConstants.MAX_FEE_DISCOUNT
: _currentFeeDiscount(_projectId);
// Take a fee from the `_distributedAmount`, if needed.
_fee = _feeDiscount == JBConstants.MAX_FEE_DISCOUNT
? 0
: _takeFeeFrom(_projectId, _fundingCycle, _distributedAmount, _projectOwner, _feeDiscount);
unchecked {
// The net amount is the withdrawn amount without the fee.
netDistributedAmount = _distributedAmount - _fee;
}
// Transfer any remaining balance to the beneficiary.
if (netDistributedAmount > 0)
_transferFrom(address(this), _beneficiary, netDistributedAmount);
}
emit UseAllowance(
_fundingCycle.configuration,
_fundingCycle.number,
_projectId,
_beneficiary,
_amount,
_distributedAmount,
netDistributedAmount,
_memo,
_metadata,
msg.sender
);
}
/// @notice Pays out splits for a project's funding cycle configuration.
/// @param _projectId The ID of the project for which payout splits are being distributed.
/// @param _domain The domain of the splits to distribute the payout between.
/// @param _group The group of the splits to distribute the payout between.
/// @param _amount The total amount being distributed, as a fixed point number with the same number of decimals as this terminal.
/// @param _feeDiscount The amount of discount to apply to the fee, out of the MAX_FEE.
/// @return leftoverAmount If the leftover amount if the splits don't add up to 100%.
/// @return feeEligibleDistributionAmount The total amount of distributions that are eligible to have fees taken from.
function _distributeToPayoutSplitsOf(
uint256 _projectId,
uint256 _domain,
uint256 _group,
uint256 _amount,
uint256 _feeDiscount
) internal returns (uint256 leftoverAmount, uint256 feeEligibleDistributionAmount) {
// Set the leftover amount to the initial amount.
leftoverAmount = _amount;
// The total percentage available to split
uint256 leftoverPercentage = JBConstants.SPLITS_TOTAL_PERCENT;
// Get a reference to the project's payout splits.
JBSplit[] memory _splits = splitsStore.splitsOf(_projectId, _domain, _group);
// Transfer between all splits.
for (uint256 _i; _i < _splits.length; ) {
// Get a reference to the split being iterated on.
JBSplit memory _split = _splits[_i];
// The amount to send towards the split.
uint256 _payoutAmount = _split.percent == leftoverPercentage
? leftoverAmount
: PRBMath.mulDiv(_amount, _split.percent, JBConstants.SPLITS_TOTAL_PERCENT);
// Decrement the leftover percentage.
leftoverPercentage -= _split.percent;
// The payout amount substracting any applicable incurred fees.
uint256 _netPayoutAmount = _distributeToPayoutSplit(
_split,
_projectId,
_group,
_payoutAmount,
_feeDiscount
);
// If the split allocator is set as feeless, this distribution is not eligible for a fee.
if (_netPayoutAmount != 0 && _netPayoutAmount != _payoutAmount)
feeEligibleDistributionAmount += _payoutAmount;
if (_payoutAmount > 0) {
// Subtract from the amount to be sent to the beneficiary.
unchecked {
leftoverAmount = leftoverAmount - _payoutAmount;
}
}
emit DistributeToPayoutSplit(
_projectId,
_domain,
_group,
_split,
_payoutAmount,
_netPayoutAmount,
msg.sender
);
unchecked {
++_i;
}
}
}
/// @notice Pays out a split for a project's funding cycle configuration.
/// @param _split The split to distribute payouts to.
/// @param _amount The total amount being distributed to the split, as a fixed point number with the same number of decimals as this terminal.
/// @param _feeDiscount The amount of discount to apply to the fee, out of the MAX_FEE.
/// @return netPayoutAmount The amount sent to the split after subtracting fees.
function _distributeToPayoutSplit(
JBSplit memory _split,
uint256 _projectId,
uint256 _group,
uint256 _amount,
uint256 _feeDiscount