-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathSuperfluid.sol
More file actions
1227 lines (1108 loc) · 45.1 KB
/
Superfluid.sol
File metadata and controls
1227 lines (1108 loc) · 45.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: AGPLv3
pragma solidity ^0.8.23;
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { UUPSProxiable } from "../upgradability/UUPSProxiable.sol";
import { UUPSProxy } from "../upgradability/UUPSProxy.sol";
import {
ISuperfluid,
ISuperfluidGovernance,
ISuperAgreement,
ISuperApp,
SuperAppDefinitions,
ContextDefinitions,
BatchOperation,
SuperfluidGovernanceConfigs,
ISuperfluidToken,
ISuperToken,
ISuperTokenFactory
} from "../interfaces/superfluid/ISuperfluid.sol";
import { GeneralDistributionAgreementV1 } from "../agreements/gdav1/GeneralDistributionAgreementV1.sol";
import { SuperfluidUpgradeableBeacon } from "../upgradability/SuperfluidUpgradeableBeacon.sol";
import { CallUtils } from "../libs/CallUtils.sol";
import { CallbackUtils } from "../libs/CallbackUtils.sol";
import { BaseRelayRecipient } from "../libs/BaseRelayRecipient.sol";
import { SimpleForwarder } from "../utils/SimpleForwarder.sol";
import { ERC2771Forwarder } from "../utils/ERC2771Forwarder.sol";
import { ACL } from "../utils/ACL.sol";
/**
* @dev The Superfluid host implementation.
*
* NOTE:
* - Please read ISuperfluid for implementation notes.
* - For some deeper technical notes, please visit protocol-monorepo wiki area.
*
* @author Superfluid
*/
contract Superfluid is
UUPSProxiable,
ISuperfluid,
BaseRelayRecipient
{
using SafeCast for uint256;
struct AppManifest {
uint256 configWord;
}
// solhint-disable-next-line var-name-mixedcase
bool immutable public NON_UPGRADABLE_DEPLOYMENT;
// solhint-disable-next-line var-name-mixedcase
bool immutable public APP_WHITE_LISTING_ENABLED;
uint64 immutable public CALLBACK_GAS_LIMIT;
// simple forwarder contract used to relay arbitrary calls for batch operations
SimpleForwarder immutable public SIMPLE_FORWARDER;
ERC2771Forwarder immutable internal _ERC2771_FORWARDER;
// ACL (for superapp registration)
ACL immutable internal _ACL;
/**
* @dev Maximum number of level of apps can be composed together
*
* NOTE:
* - TODO Composite app feature is currently disabled. Hence app cannot
* will not be able to call other app.
*/
// solhint-disable-next-line var-name-mixedcase
uint constant public MAX_APP_CALLBACK_LEVEL = 1;
uint32 constant public MAX_NUM_AGREEMENTS = 256;
bytes32 constant public ACL_SUPERAPP_REGISTRATION_ROLE = keccak256("ACL_SUPERAPP_REGISTRATION_ROLE");
/* WARNING: NEVER RE-ORDER VARIABLES! Always double-check that new
variables are added APPEND-ONLY. Re-ordering variables can
permanently BREAK the deployed proxy contract. */
/// @dev Governance contract
ISuperfluidGovernance internal _gov;
/// @dev Agreement list indexed by agreement index minus one
ISuperAgreement[] internal _agreementClasses;
/// @dev Mapping between agreement type to agreement index (starting from 1)
mapping (bytes32 => uint) internal _agreementClassIndices;
/// @dev Super token
ISuperTokenFactory internal _superTokenFactory;
/// @dev App manifests
mapping(ISuperApp => AppManifest) internal _appManifests;
/// @dev Composite app white-listing: source app => (target app => isAllowed)
mapping(ISuperApp => mapping(ISuperApp => bool)) internal _compositeApps;
/// @dev Ctx stamp of the current transaction, it should always be cleared to
/// zero before transaction finishes
bytes32 internal _ctxStamp;
/// @dev if app whitelisting is enabled, this is to make sure the keys are used only once
mapping(bytes32 => bool) internal _appKeysUsedDeprecated;
/// NOTE: Whenever modifying the storage layout here it is important to update the validateStorageLayout
/// function in its respective mock contract to ensure that it doesn't break anything or lead to unexpected
/// behaviors/layout when upgrading
constructor(
bool nonUpgradable,
bool appWhiteListingEnabled,
uint64 callbackGasLimit,
address simpleForwarderAddress,
address erc2771ForwarderAddress,
address aclAddress
) {
NON_UPGRADABLE_DEPLOYMENT = nonUpgradable;
APP_WHITE_LISTING_ENABLED = appWhiteListingEnabled;
CALLBACK_GAS_LIMIT = callbackGasLimit;
SIMPLE_FORWARDER = SimpleForwarder(simpleForwarderAddress);
_ERC2771_FORWARDER = ERC2771Forwarder(erc2771ForwarderAddress);
_ACL = ACL(aclAddress);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UUPSProxiable
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function initialize(
ISuperfluidGovernance gov
)
external
initializer // OpenZeppelin Initializable
{
_gov = gov;
}
function proxiableUUID() public pure override returns (bytes32) {
return keccak256("org.superfluid-finance.contracts.Superfluid.implementation");
}
function updateCode(address newAddress) external override onlyGovernance {
if (NON_UPGRADABLE_DEPLOYMENT) revert HOST_NON_UPGRADEABLE();
if (Superfluid(newAddress).NON_UPGRADABLE_DEPLOYMENT()) revert HOST_CANNOT_DOWNGRADE_TO_NON_UPGRADEABLE();
_updateCodeAddress(newAddress);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Time
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getNow() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Governance
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getGovernance() external view override returns (ISuperfluidGovernance) {
return _gov;
}
function replaceGovernance(ISuperfluidGovernance newGov) external override onlyGovernance {
emit GovernanceReplaced(_gov, newGov);
_gov = newGov;
}
/**************************************************************************
* Agreement Whitelisting
*************************************************************************/
function registerAgreementClass(ISuperAgreement agreementClassLogic) external onlyGovernance override {
bytes32 agreementType = agreementClassLogic.agreementType();
if (_agreementClassIndices[agreementType] != 0) {
revert HOST_AGREEMENT_ALREADY_REGISTERED();
}
if (_agreementClasses.length >= MAX_NUM_AGREEMENTS) revert HOST_MAX_256_AGREEMENTS();
ISuperAgreement agreementClass;
if (!NON_UPGRADABLE_DEPLOYMENT) {
// initialize the proxy
UUPSProxy proxy = new UUPSProxy();
proxy.initializeProxy(address(agreementClassLogic));
agreementClass = ISuperAgreement(address(proxy));
} else {
agreementClass = ISuperAgreement(address(agreementClassLogic));
}
// register the agreement proxy
_agreementClasses.push((agreementClass));
_agreementClassIndices[agreementType] = _agreementClasses.length;
emit AgreementClassRegistered(agreementType, address(agreementClassLogic));
}
function updateAgreementClass(ISuperAgreement agreementClassLogic) external onlyGovernance override {
if (NON_UPGRADABLE_DEPLOYMENT) revert HOST_NON_UPGRADEABLE();
bytes32 agreementType = agreementClassLogic.agreementType();
uint idx = _agreementClassIndices[agreementType];
if (idx == 0) {
revert HOST_AGREEMENT_IS_NOT_REGISTERED();
}
UUPSProxiable proxiable = UUPSProxiable(address(_agreementClasses[idx - 1]));
proxiable.updateCode(address(agreementClassLogic));
emit AgreementClassUpdated(agreementType, address(agreementClassLogic));
}
function isAgreementTypeListed(bytes32 agreementType)
external view override
returns (bool yes)
{
uint idx = _agreementClassIndices[agreementType];
return idx != 0;
}
function isAgreementClassListed(ISuperAgreement agreementClass)
public view override
returns (bool yes)
{
bytes32 agreementType = agreementClass.agreementType();
uint idx = _agreementClassIndices[agreementType];
// it should also be the same agreement class proxy address
return idx != 0 && _agreementClasses[idx - 1] == agreementClass;
}
function getAgreementClass(bytes32 agreementType)
external view override
returns(ISuperAgreement agreementClass)
{
uint idx = _agreementClassIndices[agreementType];
if (idx == 0) {
revert HOST_AGREEMENT_IS_NOT_REGISTERED();
}
return ISuperAgreement(_agreementClasses[idx - 1]);
}
function mapAgreementClasses(uint256 bitmap)
external view override
returns (ISuperAgreement[] memory agreementClasses) {
uint i;
uint n;
// create memory output using the counted size
agreementClasses = new ISuperAgreement[](_agreementClasses.length);
// add to the output
n = 0;
for (i = 0; i < _agreementClasses.length; ++i) {
if ((bitmap & (1 << i)) > 0) {
agreementClasses[n++] = _agreementClasses[i];
}
}
// resize memory arrays
assembly { mstore(agreementClasses, n) }
}
function addToAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
external view override
returns (uint256 newBitmap)
{
uint idx = _agreementClassIndices[agreementType];
if (idx == 0) {
revert HOST_AGREEMENT_IS_NOT_REGISTERED();
}
return bitmap | (1 << (idx - 1));
}
function removeFromAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
external view override
returns (uint256 newBitmap)
{
uint idx = _agreementClassIndices[agreementType];
if (idx == 0) {
revert HOST_AGREEMENT_IS_NOT_REGISTERED();
}
return bitmap & ~(1 << (idx - 1));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Super Token Factory
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getSuperTokenFactory()
external view override
returns (ISuperTokenFactory factory)
{
return _superTokenFactory;
}
function getSuperTokenFactoryLogic()
external view override
returns (address logic)
{
assert(address(_superTokenFactory) != address(0));
if (NON_UPGRADABLE_DEPLOYMENT) return address(_superTokenFactory);
else return UUPSProxiable(address(_superTokenFactory)).getCodeAddress();
}
function updateSuperTokenFactory(ISuperTokenFactory newFactory)
external override
onlyGovernance
{
if (address(_superTokenFactory) == address(0)) {
if (!NON_UPGRADABLE_DEPLOYMENT) {
// initialize the proxy
UUPSProxy proxy = new UUPSProxy();
proxy.initializeProxy(address(newFactory));
_superTokenFactory = ISuperTokenFactory(address(proxy));
} else {
_superTokenFactory = newFactory;
}
_superTokenFactory.initialize();
} else {
if (NON_UPGRADABLE_DEPLOYMENT) revert HOST_NON_UPGRADEABLE();
UUPSProxiable(address(_superTokenFactory)).updateCode(address(newFactory));
}
emit SuperTokenFactoryUpdated(_superTokenFactory);
}
function updateSuperTokenLogic(ISuperToken token, address newLogicOverride)
external override
onlyGovernance
{
address newLogic = newLogicOverride != address(0) ?
newLogicOverride :
address(_superTokenFactory.getSuperTokenLogic());
// assuming it's uups proxiable
UUPSProxiable(address(token)).updateCode(newLogic);
emit SuperTokenLogicUpdated(token, newLogic);
}
function changeSuperTokenAdmin(ISuperToken token, address newAdmin) external onlyGovernance {
token.changeAdmin(newAdmin);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Superfluid Upgradeable Beacon
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @inheritdoc ISuperfluid
function updatePoolBeaconLogic(address newLogic) external override onlyGovernance {
GeneralDistributionAgreementV1 gda = GeneralDistributionAgreementV1(
address(
this.getAgreementClass(keccak256("org.superfluid-finance.agreements.GeneralDistributionAgreement.v1"))
)
);
SuperfluidUpgradeableBeacon beacon = SuperfluidUpgradeableBeacon(address(gda.superfluidPoolBeacon()));
beacon.upgradeTo(newLogic);
emit PoolBeaconLogicUpdated(address(beacon), newLogic);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// App Registry
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @inheritdoc ISuperfluid
function registerApp(uint256 configWord) external override {
if (APP_WHITE_LISTING_ENABLED) {
// for historical reasons, we internal use "k1" as default registration key
// solhint-disable-next-line avoid-tx-origin
_enforceAppRegistrationPermissioning("k1", tx.origin);
}
_registerApp(ISuperApp(msg.sender), configWord);
}
/// @inheritdoc ISuperfluid
function registerApp(ISuperApp app, uint256 configWord) external override {
// Cannot register an EOA as SuperApp
if ((address(app)).code.length == 0) revert HOST_MUST_BE_CONTRACT();
if (APP_WHITE_LISTING_ENABLED) {
_enforceAppRegistrationPermissioning("k1", msg.sender);
}
_registerApp(app, configWord);
}
/// @custom:deprecated
function registerAppWithKey(uint256 configWord, string calldata registrationKey)
external override
{
if (APP_WHITE_LISTING_ENABLED) {
// solhint-disable-next-line avoid-tx-origin
_enforceAppRegistrationPermissioning(registrationKey, tx.origin);
}
_registerApp(ISuperApp(msg.sender), configWord);
}
// Checks if the deployer account has permission to register SuperApps, reverts if not.
// New method: lookup in the ACL contract.
// Legacy/fallback method: lookup in the governance contract.
function _enforceAppRegistrationPermissioning(string memory registrationKey, address deployer) internal view {
// new method: check if the deployer is granted permission in the ACL
if (_ACL.hasRole(ACL_SUPERAPP_REGISTRATION_ROLE, deployer)) {
return;
}
// legacy/fallback method: check if permission is given by gov
bytes32 configKey = SuperfluidGovernanceConfigs.getAppRegistrationConfigKey(
// solhint-disable-next-line avoid-tx-origin
deployer,
registrationKey
);
// check if the key is valid and not expired
if (
_gov.getConfigAsUint256(
this,
ISuperfluidToken(address(0)),
configKey
// solhint-disable-next-line not-rely-on-time
) < block.timestamp)
{
revert HOST_NO_APP_REGISTRATION_PERMISSION();
}
}
/// @custom:deprecated
function registerAppByFactory(ISuperApp app, uint256 configWord) external override {
// Cannot register an EOA as SuperApp
if ((address(app)).code.length == 0) revert HOST_MUST_BE_CONTRACT();
if (APP_WHITE_LISTING_ENABLED) {
// enforce permissiniong with legacy gov config key for app factory
bytes32 configKey = SuperfluidGovernanceConfigs.getAppFactoryConfigKey(msg.sender);
bool isAuthorizedAppFactory = _gov.getConfigAsUint256(this, ISuperfluidToken(address(0)), configKey) == 1;
if (!isAuthorizedAppFactory) revert HOST_NO_APP_REGISTRATION_PERMISSION();
// We do not enforce any assumptions about what a "factory" is. It is whatever gov decided to.
}
_registerApp(app, configWord);
}
function _registerApp(ISuperApp app, uint256 configWord) private {
// validate configWord
if (
!SuperAppDefinitions.isConfigWordClean(configWord) ||
SuperAppDefinitions.getAppCallbackLevel(configWord) == 0 ||
(configWord & SuperAppDefinitions.APP_JAIL_BIT) != 0
) {
revert HOST_INVALID_CONFIG_WORD();
}
if (_appManifests[ISuperApp(app)].configWord != 0) revert HOST_SUPER_APP_ALREADY_REGISTERED();
_appManifests[ISuperApp(app)] = AppManifest(configWord);
emit AppRegistered(app);
}
function isApp(ISuperApp app) public view override returns(bool) {
return _appManifests[app].configWord > 0;
}
function getAppCallbackLevel(ISuperApp appAddr) public override view returns(uint8) {
return SuperAppDefinitions.getAppCallbackLevel(_appManifests[appAddr].configWord);
}
function getAppManifest(
ISuperApp app
)
external view override
returns (
bool isSuperApp,
bool isJailed,
uint256 noopMask
)
{
AppManifest memory manifest = _appManifests[app];
isSuperApp = (manifest.configWord > 0);
if (isSuperApp) {
isJailed = SuperAppDefinitions.isAppJailed(manifest.configWord);
noopMask = manifest.configWord & SuperAppDefinitions.AGREEMENT_CALLBACK_NOOP_BITMASKS;
}
}
function isAppJailed(
ISuperApp app
)
external view override
returns(bool)
{
return SuperAppDefinitions.isAppJailed(_appManifests[app].configWord);
}
function allowCompositeApp(
ISuperApp targetApp
)
external override
{
ISuperApp sourceApp = ISuperApp(msg.sender);
if (!isApp(sourceApp)) revert HOST_SENDER_IS_NOT_SUPER_APP();
if (!isApp(targetApp)) revert HOST_RECEIVER_IS_NOT_SUPER_APP();
if (getAppCallbackLevel(sourceApp) <= getAppCallbackLevel(targetApp)) {
revert HOST_SOURCE_APP_NEEDS_HIGHER_APP_LEVEL();
}
_compositeApps[sourceApp][targetApp] = true;
}
function isCompositeAppAllowed(
ISuperApp app,
ISuperApp targetApp
)
external view override
returns (bool)
{
return _compositeApps[app][targetApp];
}
/**************************************************************************
* Agreement Framework
*************************************************************************/
function callAppBeforeCallback(
ISuperApp app,
bytes calldata callData,
bool isTermination,
bytes calldata ctx
)
external override
onlyAgreement
assertValidCtx(ctx)
returns(bytes memory cbdata)
{
(bool success, bytes memory returnedData) = _callCallback(app, true, isTermination, callData, ctx);
if (success) {
if (CallUtils.isValidAbiEncodedBytes(returnedData)) {
cbdata = abi.decode(returnedData, (bytes));
} else {
if (!isTermination) {
revert APP_RULE(SuperAppDefinitions.APP_RULE_CTX_IS_MALFORMATED);
} else {
_jailApp(app, SuperAppDefinitions.APP_RULE_CTX_IS_MALFORMATED);
}
}
}
}
function callAppAfterCallback(
ISuperApp app,
bytes calldata callData,
bool isTermination,
bytes calldata ctx
)
external override
onlyAgreement
assertValidCtx(ctx)
returns(bytes memory newCtx)
{
(bool success, bytes memory returnedData) = _callCallback(app, false, isTermination, callData, ctx);
if (success) {
// the non static callback should not return empty ctx
if (CallUtils.isValidAbiEncodedBytes(returnedData)) {
newCtx = abi.decode(returnedData, (bytes));
if (!_isCtxValid(newCtx)) {
if (!isTermination) {
revert APP_RULE(SuperAppDefinitions.APP_RULE_CTX_IS_READONLY);
} else {
newCtx = ctx;
_jailApp(app, SuperAppDefinitions.APP_RULE_CTX_IS_READONLY);
}
}
} else {
if (!isTermination) {
revert APP_RULE(SuperAppDefinitions.APP_RULE_CTX_IS_MALFORMATED);
} else {
newCtx = ctx;
_jailApp(app, SuperAppDefinitions.APP_RULE_CTX_IS_MALFORMATED);
}
}
} else {
newCtx = ctx;
}
}
function appCallbackPush(
bytes calldata ctx,
ISuperApp app,
uint256 appCreditGranted,
int256 appCreditUsed,
ISuperfluidToken appCreditToken
)
external override
onlyAgreement
assertValidCtx(ctx)
returns (bytes memory appCtx)
{
Context memory context = decodeCtx(ctx);
// NOTE: we use 1 as a magic number here as we want to do this check once we are in a callback
// we use 1 instead of MAX_APP_CALLBACK_LEVEL because 1 captures what we are trying to enforce
if (isApp(ISuperApp(context.msgSender)) && context.appCallbackLevel >= 1) {
if (!_compositeApps[ISuperApp(context.msgSender)][app]) {
revert APP_RULE(SuperAppDefinitions.APP_RULE_COMPOSITE_APP_IS_NOT_WHITELISTED);
}
}
context.appCallbackLevel++;
context.callType = ContextDefinitions.CALL_INFO_CALL_TYPE_APP_CALLBACK;
context.appCreditGranted = appCreditGranted;
context.appCreditUsed = appCreditUsed;
context.appAddress = address(app);
context.appCreditToken = appCreditToken;
appCtx = _updateContext(context);
}
function appCallbackPop(
bytes calldata ctx,
int256 appCreditUsedDelta
)
external override
onlyAgreement
returns (bytes memory newCtx)
{
Context memory context = decodeCtx(ctx);
context.appCreditUsed += appCreditUsedDelta;
newCtx = _updateContext(context);
}
function ctxUseCredit(
bytes calldata ctx,
int256 appCreditUsedMore
)
external override
onlyAgreement
assertValidCtx(ctx)
returns (bytes memory newCtx)
{
Context memory context = decodeCtx(ctx);
context.appCreditUsed += appCreditUsedMore;
newCtx = _updateContext(context);
}
function jailApp(
bytes calldata ctx,
ISuperApp app,
uint256 reason
)
external override
onlyAgreement
assertValidCtx(ctx)
returns (bytes memory newCtx)
{
_jailApp(app, reason);
return ctx;
}
/**************************************************************************
* Contextless Call Proxies
*************************************************************************/
function _callAgreement(
address msgSender,
ISuperAgreement agreementClass,
bytes memory callData,
bytes memory userData
)
internal
cleanCtx
isAgreement(agreementClass)
returns(bytes memory returnedData)
{
// beware of the endianness
bytes4 agreementSelector = CallUtils.parseSelector(callData);
//Build context data
bytes memory ctx = _updateContext(Context({
appCallbackLevel: 0,
callType: ContextDefinitions.CALL_INFO_CALL_TYPE_AGREEMENT,
timestamp: getNow(),
msgSender: msgSender,
agreementSelector: agreementSelector,
userData: userData,
appCreditGranted: 0,
appCreditWantedDeprecated: 0,
appCreditUsed: 0,
appAddress: address(0),
appCreditToken: ISuperfluidToken(address(0))
}));
bool success;
(success, returnedData) = _callExternalWithReplacedCtx(address(agreementClass), callData, 0, ctx);
if (!success) {
CallUtils.revertFromReturnedData(returnedData);
}
// clear the stamp
_ctxStamp = 0;
}
function callAgreement(
ISuperAgreement agreementClass,
bytes memory callData,
bytes memory userData
)
external override
returns(bytes memory returnedData)
{
return _callAgreement(msg.sender, agreementClass, callData, userData);
}
function _callAppAction(
address msgSender,
ISuperApp app,
uint256 value,
bytes memory callData
)
internal
cleanCtx
isAppActive(app)
isValidAppAction(callData)
returns(bytes memory returnedData)
{
// Build context data
bytes memory ctx = _updateContext(Context({
appCallbackLevel: 0,
callType: ContextDefinitions.CALL_INFO_CALL_TYPE_APP_ACTION,
timestamp: getNow(),
msgSender: msgSender,
agreementSelector: 0,
userData: "",
appCreditGranted: 0,
appCreditWantedDeprecated: 0,
appCreditUsed: 0,
appAddress: address(app),
appCreditToken: ISuperfluidToken(address(0))
}));
bool success;
(success, returnedData) = _callExternalWithReplacedCtx(address(app), callData, value, ctx);
if (success) {
ctx = abi.decode(returnedData, (bytes));
if (!_isCtxValid(ctx)) revert APP_RULE(SuperAppDefinitions.APP_RULE_CTX_IS_READONLY);
} else {
CallUtils.revertFromReturnedData(returnedData);
}
// clear the stamp
_ctxStamp = 0;
}
function callAppAction(
ISuperApp app,
bytes memory callData
)
external override // NOTE: modifiers are called in _callAppAction
returns(bytes memory returnedData)
{
return _callAppAction(msg.sender, app, 0, callData);
}
/**************************************************************************
* Contextual Call Proxies
*************************************************************************/
function callAgreementWithContext(
ISuperAgreement agreementClass,
bytes calldata callData,
bytes calldata userData,
bytes calldata ctx
)
external override
requireValidCtx(ctx)
isAgreement(agreementClass)
returns (bytes memory newCtx, bytes memory returnedData)
{
Context memory context = decodeCtx(ctx);
if (context.appAddress != msg.sender) revert HOST_CALL_AGREEMENT_WITH_CTX_FROM_WRONG_ADDRESS();
address oldSender = context.msgSender;
context.msgSender = msg.sender;
//context.agreementSelector =;
context.userData = userData;
newCtx = _updateContext(context);
bool success;
(success, returnedData) = _callExternalWithReplacedCtx(address(agreementClass), callData, 0, newCtx);
if (success) {
(newCtx) = abi.decode(returnedData, (bytes));
assert(_isCtxValid(newCtx));
// back to old msg.sender
context = decodeCtx(newCtx);
context.msgSender = oldSender;
newCtx = _updateContext(context);
} else {
CallUtils.revertFromReturnedData(returnedData);
}
}
function callAppActionWithContext(
ISuperApp app,
bytes calldata callData,
bytes calldata ctx
)
external override
requireValidCtx(ctx)
isAppActive(app)
isValidAppAction(callData)
returns(bytes memory newCtx)
{
Context memory context = decodeCtx(ctx);
if (context.appAddress != msg.sender) revert HOST_CALL_APP_ACTION_WITH_CTX_FROM_WRONG_ADDRESS();
address oldSender = context.msgSender;
context.msgSender = msg.sender;
newCtx = _updateContext(context);
(bool success, bytes memory returnedData) = _callExternalWithReplacedCtx(address(app), callData, 0, newCtx);
if (success) {
(newCtx) = abi.decode(returnedData, (bytes));
if (!_isCtxValid(newCtx)) revert APP_RULE(SuperAppDefinitions.APP_RULE_CTX_IS_READONLY);
// back to old msg.sender
context = decodeCtx(newCtx);
context.msgSender = oldSender;
newCtx = _updateContext(context);
} else {
CallUtils.revertFromReturnedData(returnedData);
}
}
function decodeCtx(bytes memory ctx)
public pure override
returns (Context memory context)
{
return _decodeCtx(ctx);
}
function isCtxValid(bytes calldata ctx)
external view override
returns (bool)
{
return _isCtxValid(ctx);
}
/**************************************************************************
* Batch call
**************************************************************************/
function _batchCall(
address payable msgSender,
Operation[] calldata operations
)
internal
{
for (uint256 i = 0; i < operations.length; ++i) {
uint32 operationType = operations[i].operationType;
if (operationType == BatchOperation.OPERATION_TYPE_ERC20_APPROVE) {
(address spender, uint256 amount) =
abi.decode(operations[i].data, (address, uint256));
ISuperToken(operations[i].target).operationApprove(
msgSender,
spender,
amount);
} else if (operationType == BatchOperation.OPERATION_TYPE_ERC20_TRANSFER_FROM) {
(address sender, address receiver, uint256 amount) =
abi.decode(operations[i].data, (address, address, uint256));
ISuperToken(operations[i].target).operationTransferFrom(
msgSender,
sender,
receiver,
amount);
} else if (operationType == BatchOperation.OPERATION_TYPE_ERC777_SEND) {
(address recipient, uint256 amount, bytes memory userData) =
abi.decode(operations[i].data, (address, uint256, bytes));
ISuperToken(operations[i].target).operationSend(
msgSender,
recipient,
amount,
userData);
} else if (operationType == BatchOperation.OPERATION_TYPE_ERC20_INCREASE_ALLOWANCE) {
(address spender, uint256 addedValue) =
abi.decode(operations[i].data, (address, uint256));
ISuperToken(operations[i].target).operationIncreaseAllowance(
msgSender,
spender,
addedValue);
} else if (operationType == BatchOperation.OPERATION_TYPE_ERC20_DECREASE_ALLOWANCE) {
(address spender, uint256 subtractedValue) =
abi.decode(operations[i].data, (address, uint256));
ISuperToken(operations[i].target).operationDecreaseAllowance(
msgSender,
spender,
subtractedValue);
} else if (operationType == BatchOperation.OPERATION_TYPE_SUPERTOKEN_UPGRADE) {
ISuperToken(operations[i].target).operationUpgrade(
msgSender,
abi.decode(operations[i].data, (uint256))); // amount
} else if (operationType == BatchOperation.OPERATION_TYPE_SUPERTOKEN_DOWNGRADE) {
ISuperToken(operations[i].target).operationDowngrade(
msgSender,
abi.decode(operations[i].data, (uint256))); // amount
} else if (operationType == BatchOperation.OPERATION_TYPE_SUPERTOKEN_UPGRADE_TO) {
(address to, uint256 amount) = abi.decode(operations[i].data, (address, uint256));
ISuperToken(operations[i].target).operationUpgradeTo(
msgSender,
to,
amount);
} else if (operationType == BatchOperation.OPERATION_TYPE_SUPERTOKEN_DOWNGRADE_TO) {
(address to, uint256 amount) = abi.decode(operations[i].data, (address, uint256));
ISuperToken(operations[i].target).operationDowngradeTo(
msgSender,
to,
amount);
} else if (operationType == BatchOperation.OPERATION_TYPE_SUPERFLUID_CALL_AGREEMENT) {
(bytes memory callData, bytes memory userData) = abi.decode(operations[i].data, (bytes, bytes));
_callAgreement(
msgSender,
ISuperAgreement(operations[i].target),
callData,
userData);
}
// The following operations for call proxies allow forwarding of native tokens.
// we use `address(this).balance` instead of `msg.value`, because the latter ist not
// updated after forwarding to the first operation, while `balance` is.
// The initial balance is equal to `msg.value` because there's no other path
// for the contract to receive native tokens.
else if (operationType == BatchOperation.OPERATION_TYPE_SUPERFLUID_CALL_APP_ACTION) {
_callAppAction(
msgSender,
ISuperApp(operations[i].target),
address(this).balance,
operations[i].data);
} else if (operationType == BatchOperation.OPERATION_TYPE_SIMPLE_FORWARD_CALL) {
(bool success, bytes memory returnData) =
SIMPLE_FORWARDER.forwardCall{value: address(this).balance}(
operations[i].target,
operations[i].data);
if (!success) {
CallUtils.revertFromReturnedData(returnData);
}
} else if (operationType == BatchOperation.OPERATION_TYPE_ERC2771_FORWARD_CALL) {
(bool success, bytes memory returnData) =
_ERC2771_FORWARDER.forward2771Call{value: address(this).balance}(
operations[i].target,
msgSender,
operations[i].data);
if (!success) {
CallUtils.revertFromReturnedData(returnData);
}
} else {
revert HOST_UNKNOWN_BATCH_CALL_OPERATION_TYPE();
}
}
if (address(this).balance != 0) {
// return any native tokens left to the sender.
msgSender.transfer(address(this).balance);
}
}
/// @dev ISuperfluid.batchCall implementation
function batchCall(
Operation[] calldata operations
)
external override payable
{
_batchCall(payable(msg.sender), operations);
}
/// @dev ISuperfluid.forwardBatchCall implementation
function forwardBatchCall(Operation[] calldata operations)
external override payable
{
_batchCall(_getTransactionSigner(), operations);
}
/// @dev BaseRelayRecipient.isTrustedForwarder implementation
function isTrustedForwarder(address forwarder)
public view override
returns(bool)
{
return _gov.getConfigAsUint256(
this,
ISuperfluidToken(address(0)),
SuperfluidGovernanceConfigs.getTrustedForwarderConfigKey(forwarder)
) != 0;
}
/// @dev IRelayRecipient.versionRecipient implementation
function versionRecipient()
external override pure
returns (string memory)
{
return "v1";
}
function getERC2771Forwarder() external view override returns(address) {
return address(_ERC2771_FORWARDER);
}
function getACL() external view override returns(address) {
return address(_ACL);
}
/**************************************************************************
* Internal
**************************************************************************/
function _jailApp(ISuperApp app, uint256 reason)
internal
{
if ((_appManifests[app].configWord & SuperAppDefinitions.APP_JAIL_BIT) == 0) {
_appManifests[app].configWord |= SuperAppDefinitions.APP_JAIL_BIT;
emit Jail(app, reason);
}
}
function _updateContext(Context memory context)
private
returns (bytes memory ctx)
{
if (context.appCallbackLevel > MAX_APP_CALLBACK_LEVEL) {
revert APP_RULE(SuperAppDefinitions.APP_RULE_MAX_APP_LEVEL_REACHED);
}