-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathIntentSource.sol
700 lines (615 loc) · 23.3 KB
/
IntentSource.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
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IIntentSource} from "./interfaces/IIntentSource.sol";
import {BaseProver} from "./prover/BaseProver.sol";
import {Intent, Route, Reward, Call} from "./types/Intent.sol";
import {Semver} from "./libs/Semver.sol";
import {Vault} from "./Vault.sol";
/**
* @title IntentSource
* @notice Source chain contract for the Eco Protocol's intent system
* @dev Used to create intents and withdraw associated rewards. Works in conjunction with
* an inbox contract on the destination chain. Verifies intent fulfillment through
* a prover contract on the source chain
* @dev This contract should not hold any funds or hold any roles for other contracts.
*/
contract IntentSource is IIntentSource, Semver {
using SafeERC20 for IERC20;
mapping(bytes32 intentHash => VaultStorage) public vaults;
constructor() {}
/**
* @notice Retrieves reward status for a given intent hash
* @param intentHash Hash of the intent to query
* @return status Current status of the intent
*/
function getRewardStatus(
bytes32 intentHash
) external view returns (RewardStatus status) {
return RewardStatus(vaults[intentHash].state.status);
}
/**
* @notice Retrieves vault state for a given intent hash
* @param intentHash Hash of the intent to query
* @return VaultState struct containing vault information
*/
function getVaultState(
bytes32 intentHash
) external view returns (VaultState memory) {
return vaults[intentHash].state;
}
/**
* @notice Retrieves the permitContact address funding an intent
*/
function getPermitContract(
bytes32 intentHash
) external view returns (address) {
return vaults[intentHash].permitContract;
}
/**
* @notice Calculates the hash of an intent and its components
* @param intent The intent to hash
* @return intentHash Combined hash of route and reward
* @return routeHash Hash of the route component
* @return rewardHash Hash of the reward component
*/
function getIntentHash(
Intent calldata intent
)
public
pure
returns (bytes32 intentHash, bytes32 routeHash, bytes32 rewardHash)
{
routeHash = keccak256(abi.encode(intent.route));
rewardHash = keccak256(abi.encode(intent.reward));
intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
}
/**
* @notice Calculates the deterministic address of the intent vault
* @param intent Intent to calculate vault address for
* @return Address of the intent vault
*/
function intentVaultAddress(
Intent calldata intent
) external view returns (address) {
(bytes32 intentHash, bytes32 routeHash, ) = getIntentHash(intent);
return _getIntentVaultAddress(intentHash, routeHash, intent.reward);
}
/**
* @notice Creates an intent without funding
* @param intent The complete intent struct to be published
* @return intentHash Hash of the created intent
*/
function publish(
Intent calldata intent
) external returns (bytes32 intentHash) {
(intentHash, , ) = getIntentHash(intent);
VaultState memory state = vaults[intentHash].state;
_validateAndPublishIntent(intent, intentHash, state);
}
/**
* @notice Creates and funds an intent in a single transaction
* @param intent The complete intent struct to be published and funded
* @return intentHash Hash of the created and funded intent
*/
function publishAndFund(
Intent calldata intent,
bool allowPartial
) external payable returns (bytes32 intentHash) {
bytes32 routeHash;
(intentHash, routeHash, ) = getIntentHash(intent);
VaultState memory state = vaults[intentHash].state;
_validateInitialFundingState(state, intentHash);
_validateSourceChain(intent.route.source, intentHash);
_validateAndPublishIntent(intent, intentHash, state);
address vault = _getIntentVaultAddress(
intentHash,
routeHash,
intent.reward
);
_fundIntent(intentHash, intent.reward, vault, msg.sender, allowPartial);
_returnExcessEth(intentHash, address(this).balance);
}
/**
* @notice Funds an existing intent
* @param routeHash Hash of the route component
* @param reward Reward structure containing distribution details
* @return intentHash Hash of the funded intent
*/
function fund(
bytes32 routeHash,
Reward calldata reward,
bool allowPartial
) external payable returns (bytes32 intentHash) {
bytes32 rewardHash = keccak256(abi.encode(reward));
intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
VaultState memory state = vaults[intentHash].state;
_validateInitialFundingState(state, intentHash);
address vault = _getIntentVaultAddress(intentHash, routeHash, reward);
_fundIntent(intentHash, reward, vault, msg.sender, allowPartial);
_returnExcessEth(intentHash, address(this).balance);
}
/**
* @notice Funds an intent for a user with permit/allowance
* @param routeHash Hash of the route component
* @param reward Reward structure containing distribution details
* @param funder Address to fund the intent from
* @param permitContact Address of the permitContact instance
* @param allowPartial Whether to allow partial funding
* @return intentHash Hash of the funded intent
*/
function fundFor(
bytes32 routeHash,
Reward calldata reward,
address funder,
address permitContact,
bool allowPartial
) external returns (bytes32 intentHash) {
bytes32 rewardHash = keccak256(abi.encode(reward));
intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
VaultState memory state = vaults[intentHash].state;
address vault = _getIntentVaultAddress(intentHash, routeHash, reward);
_fundIntentFor(
state,
reward,
intentHash,
routeHash,
vault,
funder,
permitContact,
allowPartial
);
}
/**
* @notice Creates and funds an intent using permit/allowance
* @param intent The complete intent struct
* @param funder Address to fund the intent from
* @param permitContact Address of the permitContact instance
* @param allowPartial Whether to allow partial funding
* @return intentHash Hash of the created and funded intent
*/
function publishAndFundFor(
Intent calldata intent,
address funder,
address permitContact,
bool allowPartial
) external returns (bytes32 intentHash) {
bytes32 routeHash;
(intentHash, routeHash, ) = getIntentHash(intent);
VaultState memory state = vaults[intentHash].state;
_validateAndPublishIntent(intent, intentHash, state);
_validateSourceChain(intent.route.source, intentHash);
address vault = _getIntentVaultAddress(
intentHash,
routeHash,
intent.reward
);
_fundIntentFor(
state,
intent.reward,
intentHash,
routeHash,
vault,
funder,
permitContact,
allowPartial
);
}
/**
* @notice Checks if an intent is completely funded
* @param intent Intent to validate
* @return True if intent is completely funded, false otherwise
*/
function isIntentFunded(
Intent calldata intent
) external view returns (bool) {
if (intent.route.source != block.chainid) return false;
(bytes32 intentHash, bytes32 routeHash, ) = getIntentHash(intent);
address vault = _getIntentVaultAddress(
intentHash,
routeHash,
intent.reward
);
return _isRewardFunded(intent.reward, vault);
}
/**
* @notice Withdraws rewards associated with an intent to its claimant
* @param routeHash Hash of the intent's route
* @param reward Reward structure of the intent
*/
function withdrawRewards(bytes32 routeHash, Reward calldata reward) public {
bytes32 rewardHash = keccak256(abi.encode(reward));
bytes32 intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
address claimant = BaseProver(reward.prover).provenIntents(intentHash);
VaultState memory state = vaults[intentHash].state;
// Claim the rewards if the intent has not been claimed
if (
claimant != address(0) &&
state.status != uint8(RewardStatus.Claimed) &&
state.status != uint8(RewardStatus.Refunded)
) {
state.status = uint8(RewardStatus.Claimed);
state.mode = uint8(VaultMode.Claim);
state.allowPartialFunding = 0;
state.usePermit = 0;
state.target = claimant;
vaults[intentHash].state = state;
emit Withdrawal(intentHash, claimant);
new Vault{salt: routeHash}(intentHash, reward);
return;
}
if (claimant == address(0)) {
revert UnauthorizedWithdrawal(intentHash);
} else {
revert RewardsAlreadyWithdrawn(intentHash);
}
}
/**
* @notice Batch withdraws multiple intents
* @param routeHashes Array of route hashes for the intents
* @param rewards Array of reward structures for the intents
*/
function batchWithdraw(
bytes32[] calldata routeHashes,
Reward[] calldata rewards
) external {
uint256 length = routeHashes.length;
if (length != rewards.length) {
revert ArrayLengthMismatch();
}
for (uint256 i = 0; i < length; ++i) {
withdrawRewards(routeHashes[i], rewards[i]);
}
}
/**
* @notice Refunds rewards to the intent creator
* @param routeHash Hash of the intent's route
* @param reward Reward structure of the intent
*/
function refund(bytes32 routeHash, Reward calldata reward) external {
bytes32 rewardHash = keccak256(abi.encode(reward));
bytes32 intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
VaultState memory state = vaults[intentHash].state;
if (
state.status != uint8(RewardStatus.Claimed) &&
state.status != uint8(RewardStatus.Refunded)
) {
address claimant = BaseProver(reward.prover).provenIntents(
intentHash
);
// Check if the intent has been proven to prevent unauthorized refunds
if (claimant != address(0)) {
revert IntentNotClaimed(intentHash);
}
// Revert if intent has not expired
if (block.timestamp <= reward.deadline) {
revert IntentNotExpired(intentHash);
}
}
if (state.status != uint8(RewardStatus.Claimed)) {
state.status = uint8(RewardStatus.Refunded);
}
state.mode = uint8(VaultMode.Refund);
state.allowPartialFunding = 0;
state.usePermit = 0;
state.target = address(0);
vaults[intentHash].state = state;
emit Refund(intentHash, reward.creator);
new Vault{salt: routeHash}(intentHash, reward);
}
/**
* @notice Recover tokens that were sent to the intent vault by mistake
* @dev Must not be among the intent's rewards
* @param routeHash Hash of the intent's route
* @param reward Reward structure of the intent
* @param token Token address for handling incorrect vault transfers
*/
function recoverToken(
bytes32 routeHash,
Reward calldata reward,
address token
) external {
if (token == address(0)) {
revert InvalidRefundToken();
}
bytes32 rewardHash = keccak256(abi.encode(reward));
bytes32 intentHash = keccak256(abi.encodePacked(routeHash, rewardHash));
VaultState memory state = vaults[intentHash].state;
// selfdestruct() will refund all native tokens to the creator
// we can't refund native intents before the claim/refund happens
// because deploying and destructing the vault will refund the native reward prematurely
if (
state.status != uint8(RewardStatus.Claimed) &&
state.status != uint8(RewardStatus.Refunded) &&
reward.nativeValue > 0
) {
revert IntentNotClaimed(intentHash);
}
// Check if the token is part of the reward
for (uint256 i = 0; i < reward.tokens.length; ++i) {
if (reward.tokens[i].token == token) {
revert InvalidRefundToken();
}
}
state.mode = uint8(VaultMode.RecoverToken);
state.allowPartialFunding = 0;
state.usePermit = 0;
state.target = token;
vaults[intentHash].state = state;
emit Refund(intentHash, reward.creator);
new Vault{salt: routeHash}(intentHash, reward);
}
/**
* @notice Validates that an intent's vault holds sufficient rewards
* @dev Checks both native token and ERC20 token balances
* @param reward Reward to validate
* @param vault Address of the intent's vault
* @return True if vault has sufficient funds, false otherwise
*/
function _isRewardFunded(
Reward calldata reward,
address vault
) internal view returns (bool) {
uint256 rewardsLength = reward.tokens.length;
if (vault.balance < reward.nativeValue) return false;
for (uint256 i = 0; i < rewardsLength; ++i) {
address token = reward.tokens[i].token;
uint256 amount = reward.tokens[i].amount;
uint256 balance = IERC20(token).balanceOf(vault);
if (balance < amount) return false;
}
return true;
}
/**
* @notice Calculates the deterministic address of an intent vault using CREATE2
* @dev Follows EIP-1014 for address calculation
* @param intentHash Hash of the full intent
* @param routeHash Hash of the route component
* @param reward Reward structure
* @return The calculated vault address
*/
function _getIntentVaultAddress(
bytes32 intentHash,
bytes32 routeHash,
Reward calldata reward
) internal view returns (address) {
/* Convert a hash which is bytes32 to an address which is 20-byte long
according to https://docs.soliditylang.org/en/v0.8.9/control-structures.html?highlight=create2#salted-contract-creations-create2 */
return
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
address(this),
routeHash,
keccak256(
abi.encodePacked(
type(Vault).creationCode,
abi.encode(intentHash, reward)
)
)
)
)
)
)
);
}
/**
* @notice Validates and publishes a new intent
* @param intent The intent to validate and publish
* @param intentHash Hash of the intent
* @param state Current vault state
*/
function _validateAndPublishIntent(
Intent calldata intent,
bytes32 intentHash,
VaultState memory state
) internal {
if (
state.status == uint8(RewardStatus.Claimed) ||
state.status == uint8(RewardStatus.Refunded)
) {
revert IntentAlreadyExists(intentHash);
}
emit IntentCreated(
intentHash,
intent.route.salt,
intent.route.source,
intent.route.destination,
intent.route.inbox,
intent.route.tokens,
intent.route.calls,
intent.reward.creator,
intent.reward.prover,
intent.reward.deadline,
intent.reward.nativeValue,
intent.reward.tokens
);
}
/**
* @notice Disabling fundFor for native intents
* @dev Deploying vault in Fund mode might cause a loss of native reward
* @param reward Reward structure to validate
* @param vault Address of the intent vault
* @param intentHash Hash of the intent
*/
function _disableNativeReward(
Reward calldata reward,
address vault,
bytes32 intentHash
) internal view {
// selfdestruct() will refund all native tokens to the creator
// we can't use Fund mode for intents with native value
// because deploying and destructing the vault will refund the native reward prematurely
if (reward.nativeValue > 0 && vault.balance > 0) {
revert CannotFundForWithNativeReward(intentHash);
}
}
/**
* @notice Validates the initial funding state
* @param state Current vault state
* @param intentHash Hash of the intent
*/
function _validateInitialFundingState(
VaultState memory state,
bytes32 intentHash
) internal pure {
if (state.status != uint8(RewardStatus.Initial)) {
revert IntentAlreadyFunded(intentHash);
}
}
/**
* @notice Validates the funding state for partial funding
* @param state Current vault state
* @param intentHash Hash of the intent
*/
function _validateFundingState(
VaultState memory state,
bytes32 intentHash
) internal pure {
if (
state.status != uint8(RewardStatus.Initial) &&
state.status != uint8(RewardStatus.PartiallyFunded)
) {
revert IntentAlreadyFunded(intentHash);
}
}
/**
* @notice Handles the funding of an intent
* @param intentHash Hash of the intent
* @param reward Reward structure to fund
* @param vault Address of the intent vault
* @param funder Address providing the funds
*/
function _fundIntent(
bytes32 intentHash,
Reward calldata reward,
address vault,
address funder,
bool allowPartial
) internal {
if (reward.nativeValue > 0) {
if (msg.value < reward.nativeValue) {
revert InsufficientNativeReward(intentHash);
}
payable(vault).transfer(reward.nativeValue);
}
uint256 rewardsLength = reward.tokens.length;
bool partiallyFunded;
// Iterate through each token in the reward structure
for (uint256 i; i < rewardsLength; ++i) {
// Get token address and required amount for current reward
address token = reward.tokens[i].token;
uint256 amount = reward.tokens[i].amount;
uint256 vaultBalance = IERC20(token).balanceOf(vault);
// Only proceed if vault needs more tokens and we have permission to transfer them
if (vaultBalance < amount) {
// Calculate how many more tokens the vault needs to be fully funded
uint256 remainingAmount = amount - vaultBalance;
// Check how many tokens this contract is allowed to transfer from funding source
uint256 allowance = IERC20(token).allowance(
funder,
address(this)
);
uint256 funderBalance = IERC20(token).balanceOf(funder);
allowance = allowance < funderBalance
? allowance
: funderBalance;
uint256 transferAmount;
// Calculate transfer amount as minimum of what's needed and what's allowed
if (allowance >= remainingAmount) {
transferAmount = remainingAmount;
} else if (allowPartial) {
transferAmount = allowance;
partiallyFunded = true;
} else {
revert InsufficientTokenAllowance(
token,
funder,
remainingAmount
);
}
if (transferAmount > 0) {
// Transfer tokens from funding source to vault using safe transfer
IERC20(token).safeTransferFrom(
funder,
vault,
transferAmount
);
}
}
}
if (partiallyFunded) {
emit IntentPartiallyFunded(intentHash, funder);
} else {
emit IntentFunded(intentHash, funder);
}
}
function _fundIntentFor(
VaultState memory state,
Reward calldata reward,
bytes32 intentHash,
bytes32 routeHash,
address vault,
address funder,
address permitContact,
bool allowPartial
) internal {
_disableNativeReward(reward, vault, intentHash);
_validateFundingState(state, intentHash);
if (state.status == uint8(RewardStatus.Initial)) {
state.status = allowPartial
? uint8(RewardStatus.PartiallyFunded)
: uint8(RewardStatus.Funded);
}
state.mode = uint8(VaultMode.Fund);
state.allowPartialFunding = allowPartial ? 1 : 0;
state.usePermit = permitContact != address(0) ? 1 : 0;
state.target = funder;
if (permitContact != address(0)) {
vaults[intentHash].permitContract = permitContact;
}
vaults[intentHash].state = state;
new Vault{salt: routeHash}(intentHash, reward);
if (state.status == uint8(RewardStatus.Funded)) {
emit IntentFunded(intentHash, funder);
} else if (
state.status == uint8(RewardStatus.PartiallyFunded) &&
_isRewardFunded(reward, vault)
) {
state.status = uint8(RewardStatus.Funded);
vaults[intentHash].state = state;
emit IntentFunded(intentHash, funder);
} else {
emit IntentPartiallyFunded(intentHash, funder);
}
}
/**
* @notice Validates that the intent is being published on correct chain
* @param sourceChain Chain ID specified in the intent
* @param intentHash Hash of the intent
*/
function _validateSourceChain(
uint256 sourceChain,
bytes32 intentHash
) internal view {
if (sourceChain != block.chainid) {
revert WrongSourceChain(intentHash);
}
}
/**
* @notice Returns excess ETH to the sender
* @param intentHash Hash of the intent
* @param amount Amount of ETH to return
*/
function _returnExcessEth(bytes32 intentHash, uint256 amount) internal {
if (amount > 0) {
(bool success, ) = payable(msg.sender).call{value: amount}("");
if (!success) revert NativeRewardTransferFailed(intentHash);
}
}
}