-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoRepMarket.sol
More file actions
525 lines (454 loc) · 20 KB
/
PoRepMarket.sol
File metadata and controls
525 lines (454 loc) · 20 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
// SPDX-License-Identifier: MIT
// solhint-disable var-name-mixedcase
pragma solidity =0.8.30;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {CommonTypes} from "filecoin-solidity/v0.8/types/CommonTypes.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ISPRegistry} from "./interfaces/ISPRegistry.sol";
import {ValidatorFactory} from "./ValidatorFactory.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {SLITypes} from "./types/SLITypes.sol";
import {PoRepTypes} from "./types/PoRepTypes.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @title PoRepMarket contract
* @dev PoRepMarket contract is a contract that allows users to create and manage deal proposals for PoRep deals
* @notice PoRepMarket contract
*/
contract PoRepMarket is Initializable, AccessControlUpgradeable, UUPSUpgradeable {
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice role to manage contract upgrades
*/
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/**
* @notice Maximum Filecoin storage deal duration: 1278 days (~3.5 years),
* per FIP-0052 (NV21 actor policy update).
* References:
* https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0052.md
* https://github.com/filecoin-project/core-devs/blob/master/Network%20Upgrades/v21.md
*/
uint32 public constant MAX_DEAL_DURATION_DAYS = 1278;
/// @custom:storage-location erc7201:porepmarket.storage.DealProposalsStorage
struct DealProposalsStorage {
mapping(uint256 dealId => PoRepTypes.DealProposal) _dealProposals;
EnumerableSet.UintSet _dealIdsReadyForPayment;
ISPRegistry _SPRegistryContract;
ValidatorFactory _validatorFactoryContract;
address _clientSmartContract;
uint256 _dealIdCounter;
}
// keccak256(abi.encode(uint256(keccak256("porepmarket.storage.DealProposalsStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant DEAL_PROPOSALS_STORAGE_LOCATION =
0xea093611145db18b250f1cd58e07fc50de512902beb662a10f8e6d1dd55f6700;
// solhint-disable-next-line use-natspec
function _getDealProposalsStorage() private pure returns (DealProposalsStorage storage $) {
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := DEAL_PROPOSALS_STORAGE_LOCATION
}
}
/**
* @notice function to allow acess to storage
* @return DealProposalsStorage storage struct
*/
function s() private pure returns (DealProposalsStorage storage) {
return _getDealProposalsStorage();
}
/**
* @notice DealProposalCreated event
* @param dealId The id of the deal proposal
* @param client The address of the client
* @param provider The address of the provider
* @param requirements The SLI thresholds for the deal
* @param manifestLocation The location of the manifest for the deal
* @param totalDealSize The total size of the deal in bytes
*/
event DealProposalCreated(
uint256 indexed dealId,
address indexed client,
CommonTypes.FilActorId indexed provider,
SLITypes.SLIThresholds requirements,
string manifestLocation,
uint256 totalDealSize
);
/**
* @notice DealAccepted event
* @param dealId The id of the deal proposal
* @param owner The address of the owner
* @param provider The address of the provider
*/
event DealAccepted(uint256 indexed dealId, address indexed owner, CommonTypes.FilActorId indexed provider);
/**
* @notice ValidatorUpdated event
* @dev ValidatorUpdated event is emitted when a validator is updated
* @param dealId The id of the deal proposal
* @param validator The address of the validator
*/
event ValidatorUpdated(uint256 indexed dealId, address indexed validator);
/**
* @notice RailIdUpdated event
* @dev RailIdUpdated event is emitted when a rail id is updated
* @param dealId The id of the deal proposal
* @param railId The id of the rail
*/
event RailIdUpdated(uint256 indexed dealId, uint256 indexed railId);
/**
* @notice DealCompleted event
* @param dealId The id of the deal proposal
* @param client The address of the client
* @param provider The address of the provider
*/
event DealCompleted(uint256 indexed dealId, address indexed client, CommonTypes.FilActorId indexed provider);
/**
* @notice DealTerminated event
* @dev DealTerminated event is emitted when a deal is terminated
* @param dealId The id of the deal proposal
* @param terminator The address that terminated the deal
* @param endEpoch The Filecoin epoch at which the deal was terminated
*/
event DealTerminated(uint256 indexed dealId, address indexed terminator, uint256 indexed endEpoch);
/**
* @notice DealRejected event
* @param dealId The id of the deal proposal
* @param rejector The address of the rejector
*/
event DealRejected(uint256 indexed dealId, address indexed rejector);
/**
* @notice ManifestLocationUpdated event
* @dev ManifestLocationUpdated event is emitted when a manifest location is updated
* @param dealId The id of the deal proposal
* @param oldManifestLocation The old manifest location
* @param newManifestLocation The new manifest location
*/
event ManifestLocationUpdated(uint256 indexed dealId, string oldManifestLocation, string newManifestLocation);
/**
* @notice ClientSmartContractUpdated event
* @dev ClientSmartContractUpdated event is emitted when the client smart contract is updated
* @param clientSmartContract The address of the client smart contract
*/
event ClientSmartContractUpdated(address indexed clientSmartContract);
error NotTheRegisteredValidator(uint256 dealId, address validator);
error NotTheDealValidator(uint256 dealId, address validator);
error NotTheClientSmartContract(uint256 dealId, address clientSmartContract);
error NotTheControllingAddress(uint256 dealId, address msgSender, CommonTypes.FilActorId provider);
error DealNotInExpectedState(uint256 dealId, PoRepTypes.DealState currentState, PoRepTypes.DealState expectedState);
error CallerIsNotValidator(uint256 dealId, address caller);
error DealDoesNotExist();
error NotTheClientOrStorageProvider(uint256 dealId, address rejector);
error NoProviderFoundForDeal();
error ValidatorAlreadySet(uint256 dealId);
error InvalidRetrievabilityBps(uint16 value);
error InvalidIndexingPct(uint8 value);
error InvalidRailId();
error RailIdAlreadySet();
error UnauthorisedCaller(uint256 dealId, address caller, address expectedCaller);
error EmptyManifestLocation();
error TooLongManifestLocation();
error InvalidClientSmartContractAddress();
error InvalidDealDuration();
/**
* @notice Constructor
*/
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the contract
* @param _admin The address of the admin
* @param _validatorFactory The address of the validator registry
* @param _spRegistry The address of the SP registry
*/
function initialize(address _admin, address _validatorFactory, address _spRegistry) public initializer {
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(UPGRADER_ROLE, _admin);
DealProposalsStorage storage $ = s();
$._validatorFactoryContract = ValidatorFactory(_validatorFactory);
$._SPRegistryContract = ISPRegistry(_spRegistry);
}
/**
* @notice Sets the client smart contract
* @dev Sets the client smart contract
* @param _clientSmartContract The address of the client smart contract
*/
function setClientSmartContract(address _clientSmartContract) public onlyRole(DEFAULT_ADMIN_ROLE) {
if (_clientSmartContract == address(0)) revert InvalidClientSmartContractAddress();
DealProposalsStorage storage $ = _getDealProposalsStorage();
$._clientSmartContract = _clientSmartContract;
emit ClientSmartContractUpdated(_clientSmartContract);
}
/**
* @notice Proposes a deal
* @param requirements The SLI thresholds for the deal
* @param terms The commercial terms for the deal
* @param manifestLocation The location of the manifest for the deal
*/
function proposeDeal(
SLITypes.SLIThresholds calldata requirements,
SLITypes.DealTerms calldata terms,
string calldata manifestLocation
) external {
_ensureCorrectManifestLocation(manifestLocation);
_ensureCorrectRequirements(requirements);
_ensureCorrectTerms(terms);
DealProposalsStorage storage $ = s();
(CommonTypes.FilActorId provider, bool autoApprove) =
$._SPRegistryContract.getProviderForDeal(requirements, terms);
if (CommonTypes.FilActorId.unwrap(provider) == 0) {
revert NoProviderFoundForDeal();
}
uint256 dealId = ++$._dealIdCounter;
PoRepTypes.DealState initialState = autoApprove ? PoRepTypes.DealState.Accepted : PoRepTypes.DealState.Proposed;
$._dealProposals[dealId] = PoRepTypes.DealProposal({
dealId: dealId,
client: msg.sender,
provider: provider,
requirements: requirements,
terms: terms,
validator: address(0),
state: initialState,
railId: 0,
manifestLocation: manifestLocation
});
emit DealProposalCreated(dealId, msg.sender, provider, requirements, manifestLocation, terms.dealSizeBytes);
if (autoApprove) {
emit DealAccepted(dealId, msg.sender, provider);
}
}
/**
* @notice Updates the validator and rail id for a deal proposal
* @param dealId The id of the deal proposal
*/
function updateValidator(uint256 dealId) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Accepted);
if (dp.validator != address(0)) {
revert ValidatorAlreadySet(dealId);
}
if (!$._validatorFactoryContract.isValidatorContract(msg.sender)) {
revert NotTheRegisteredValidator(dealId, msg.sender);
}
dp.validator = msg.sender;
emit ValidatorUpdated(dealId, msg.sender);
}
/**
* @notice Updates the rail id for a deal proposal
* @dev Updates the rail id for a deal proposal
* @param dealId The id of the deal proposal
* @param railId The id of the rail
*/
function updateRailId(uint256 dealId, uint256 railId) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Accepted);
if (dp.railId != 0) {
revert RailIdAlreadySet();
}
if (railId == 0) {
revert InvalidRailId();
}
if (dp.validator != msg.sender) {
revert NotTheDealValidator(dealId, msg.sender);
}
dp.railId = railId;
emit RailIdUpdated(dealId, railId);
}
/**
* @notice Gets a deal proposal
* @param dealId The id of the deal proposal
* @return DealProposal The deal proposal
*/
function getDealProposal(uint256 dealId) external view returns (PoRepTypes.DealProposal memory) {
DealProposalsStorage storage $ = s();
return $._dealProposals[dealId];
}
/**
* @notice Accepts a deal
* @param dealId The id of the deal proposal
*/
function acceptDeal(uint256 dealId) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Proposed);
if (!$._SPRegistryContract.isAuthorizedForProvider(msg.sender, dp.provider)) {
revert NotTheControllingAddress(dealId, msg.sender, dp.provider);
}
dp.state = PoRepTypes.DealState.Accepted;
emit DealAccepted(dealId, msg.sender, dp.provider);
}
/**
* @notice Completes a deal
* @param dealId The id of the deal proposal
*/
function completeDeal(uint256 dealId) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Accepted);
if (msg.sender != $._clientSmartContract) revert NotTheClientSmartContract(dealId, msg.sender);
dp.state = PoRepTypes.DealState.Completed;
$._dealIdsReadyForPayment.add(dealId);
// TODO: actualSizeBytes should come from Client contract's allocation tracking
// For now, use estimated size (no tolerance delta)
$._SPRegistryContract.commitCapacity(dp.provider, dp.terms.dealSizeBytes, dp.terms.dealSizeBytes);
emit DealCompleted(dealId, msg.sender, dp.provider);
}
/**
* @notice Terminate a deal
* @dev Terminates a deal by setting the deal state to terminated
* @param dealId The id of the deal proposal
* @param terminator The address that terminated the deal
* @param endEpoch The Filecoin epoch at which the deal was terminated
*/
function terminateDeal(uint256 dealId, address terminator, uint256 endEpoch) external {
DealProposalsStorage storage $ = _getDealProposalsStorage();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Completed);
if (msg.sender != dp.validator || dp.validator == address(0)) {
revert CallerIsNotValidator(dealId, msg.sender);
}
$._SPRegistryContract.releaseCapacity(dp.provider, dp.terms.dealSizeBytes);
$._dealIdsReadyForPayment.remove(dealId);
dp.state = PoRepTypes.DealState.Terminated;
emit DealTerminated(dealId, terminator, endEpoch);
}
/**
* @notice Rejects a deal
* @param dealId The id of the deal proposal
*/
function rejectDeal(uint256 dealId) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dp = $._dealProposals[dealId];
_ensureDealExists(dp);
_ensureDealCorrectState(dp, PoRepTypes.DealState.Proposed);
if (msg.sender != dp.client && !$._SPRegistryContract.isAuthorizedForProvider(msg.sender, dp.provider)) {
revert NotTheClientOrStorageProvider(dealId, msg.sender);
}
dp.state = PoRepTypes.DealState.Rejected;
$._SPRegistryContract.releasePendingCapacity(dp.provider, dp.terms.dealSizeBytes);
emit DealRejected(dealId, msg.sender);
}
/**
* @notice Gets all completed deals
* @return completedDeals Array of completed deal proposals
*/
function getCompletedDeals() external view returns (PoRepTypes.DealProposal[] memory completedDeals) {
DealProposalsStorage storage $ = s();
uint256[] memory completedDealsIds = $._dealIdsReadyForPayment.values();
completedDeals = new PoRepTypes.DealProposal[](completedDealsIds.length);
uint256 dealCounter = 0;
for (uint256 i = 0; i < completedDealsIds.length; i++) {
PoRepTypes.DealProposal memory dp = $._dealProposals[completedDealsIds[i]];
if (dp.state == PoRepTypes.DealState.Completed) {
completedDeals[dealCounter] = dp;
dealCounter++;
}
}
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
mstore(completedDeals, dealCounter)
}
}
/**
* @notice Retrieves the manifest location URL for a specific deal proposal
* @param dealId The unique identifier of the deal proposal
* @return manifestLocation The manifest location URL for a specific deal proposal
*/
function getManifestLocation(uint256 dealId) external view returns (string memory manifestLocation) {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dealProposal = $._dealProposals[dealId];
_ensureDealExists(dealProposal);
return dealProposal.manifestLocation;
}
/**
* @notice Updates the manifest location for a specific deal proposal
* @param dealId The unique identifier of the deal proposal
* @param newManifestLocation The new manifest location URL to be updated for the deal proposal
*/
function updateManifestLocation(uint256 dealId, string calldata newManifestLocation) external {
DealProposalsStorage storage $ = s();
PoRepTypes.DealProposal storage dealProposal = $._dealProposals[dealId];
_ensureDealExists(dealProposal);
if (msg.sender != dealProposal.client) {
revert UnauthorisedCaller(dealId, msg.sender, dealProposal.client);
}
if (bytes(newManifestLocation).length == 0) {
revert EmptyManifestLocation();
}
if (bytes(newManifestLocation).length > 2048) {
revert TooLongManifestLocation();
}
string memory oldManifestLocation = dealProposal.manifestLocation;
dealProposal.manifestLocation = newManifestLocation;
emit ManifestLocationUpdated(dealId, oldManifestLocation, newManifestLocation);
}
/**
* @notice Ensures a deal exists
* @param dealProposal The id of the deal proposal
*/
function _ensureDealExists(PoRepTypes.DealProposal memory dealProposal) internal pure {
if (dealProposal.dealId == 0) revert DealDoesNotExist();
}
/**
* @notice Ensures a deal is in the correct state
* @param dp The deal proposal
* @param expectedState The expected state
*/
function _ensureDealCorrectState(PoRepTypes.DealProposal memory dp, PoRepTypes.DealState expectedState)
internal
pure
{
if (dp.state != expectedState) revert DealNotInExpectedState(dp.dealId, dp.state, expectedState);
}
/**
* @notice Ensures the requirements are correct
* @param requirements The SLI thresholds for the deal
*/
function _ensureCorrectRequirements(SLITypes.SLIThresholds calldata requirements) internal pure {
if (requirements.retrievabilityBps > 10_000) {
revert InvalidRetrievabilityBps(requirements.retrievabilityBps);
}
if (requirements.indexingPct > 100) {
revert InvalidIndexingPct(requirements.indexingPct);
}
}
/**
* @notice Ensures the terms are correct
* @param terms The terms for the deal
*/
function _ensureCorrectTerms(SLITypes.DealTerms calldata terms) internal pure {
if (terms.durationDays == 0) {
revert InvalidDealDuration();
}
if (terms.durationDays > MAX_DEAL_DURATION_DAYS) {
revert InvalidDealDuration();
}
if (terms.durationDays % 30 != 0) {
revert InvalidDealDuration();
}
}
/**
* @notice Ensures the manifest location is correct
* @param manifestLocation The manifest location for the deal
*/
function _ensureCorrectManifestLocation(string calldata manifestLocation) internal pure {
if (bytes(manifestLocation).length == 0) {
revert EmptyManifestLocation();
}
if (bytes(manifestLocation).length > 2048) {
revert TooLongManifestLocation();
}
}
// solhint-disable no-empty-blocks
/**
* @notice Authorizes an upgrade
* @param newImplementation The address of the new implementation
*/
function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE) {}
}