-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAccounting.sol
More file actions
1177 lines (1053 loc) · 43.2 KB
/
Copy pathAccounting.sol
File metadata and controls
1177 lines (1053 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {EVMSignerAndVerifier} from "./EVMSignerAndVerifier.sol";
import {EIP712SignatureVerifier} from "./EIP712SignatureVerifier.sol";
import {
ChainType,
FundLock,
HistoryEntry,
HistoryKind,
TokenInfo,
TokenType,
UnsupportedTokenType,
UserInfo
} from "./Types.sol";
import {IAccountingSiweAuth} from "./interfaces/IAccountingSiweAuth.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {UPUPSUpgradeable} from "./lib/UPUPSUpgradeable.sol";
/**
* @title Accounting
* @notice Cross-chain accounting module for managing user balances and fund operations.
*
* Deposits verified off-chain by ROFL TEE, credited via onlyROFL. Per-user deposit
* addresses derived on-chain from contract's secretKey. Fund locking, P2P transfers,
* and automated withdrawals via EIP-712 signatures.
*/
contract Accounting is EIP712SignatureVerifier, EVMSignerAndVerifier, OwnableUpgradeable, UPUPSUpgradeable {
/// @notice Contract version, bumped on each upgrade for tracking/verification.
uint64 public constant VERSION = 1;
/// @dev Maximum entries returned by `getHistory` in a single call.
uint256 private constant MAX_HISTORY_PAGE_SIZE = 100;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IAccountingSiweAuth public immutable siweAuth;
/// @dev internal (not private) so MockAccounting test helper can set balances directly.
mapping(address user => mapping(bytes32 tokenId => uint256 balance))
internal balances;
mapping(bytes32 tokenId => TokenInfo tokenInfo) public tokens;
mapping(bytes32 depositId => bool processed) public processedDeposits;
mapping(address user => UserInfo) private userInfo;
WithdrawalRequest[] public withdrawals;
uint256 private nextLockId;
/// @dev Array of all registered token IDs for enumeration
bytes32[] private registeredTokenIds;
/// @dev requestId = keccak256(abi.encode(beneficiary, tokenId, version)).
/// Deterministic key ⇒ one pending slot per (beneficiary, token, version).
/// Re-requesting overwrites; no explicit cancel needed.
mapping(bytes32 requestId => EmergencyWithdrawRequest) public emergencyWithdrawRequests;
mapping(address user => HistoryEntry[] entries) private history;
struct EmergencyWithdrawRequest {
address toAddress;
uint256 blockNumber; // 0 ⇒ slot empty
}
error EmergencyWithdrawTooSoon();
error EmergencyWithdrawNotFound();
event EmergencyWithdrawRequested(bytes32 indexed requestId, bytes32 indexed tokenId);
event EmergencyWithdrawExecuted(bytes32 indexed requestId);
event Deposit(
bytes32 indexed tokenId,
uint256 amount,
bytes32 depositId
);
event Withdrawal(
address indexed userAddress,
bytes32 indexed tokenId,
uint256 amount,
uint256 chainId
);
event WithdrawalResolved(
uint256 indexed index,
address indexed userAddress,
bytes32 indexed tokenId,
address toAddress,
uint256 amount,
uint256 chainId
);
event TokenRegistered(bytes32 indexed tokenId, TokenType tokenType);
error InsufficientBalance();
error TooManyActiveLocks();
error InvalidLockId();
error LockNotExpired();
error InsufficientLockedAmount();
error AddressMismatch();
error InvalidExpiry();
error InvalidAmount();
error WithdrawalTooSoon();
error Unauthorized();
error DepositAlreadyProcessed();
error InvalidSiweAuth();
struct WithdrawalRequest {
address userAddress;
address toAddress;
uint256 amount;
uint256 blockNumber;
bytes32 tokenId;
bool resolved;
bytes txIdentifier; // nonce, utxo identifier, or similar
}
/// @custom:oz-upgrades-unsafe-allow constructor
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
constructor(address siweAuthAddress) {
_disableInitializers();
if (siweAuthAddress == address(0)) revert InvalidSiweAuth();
siweAuth = IAccountingSiweAuth(siweAuthAddress);
}
/**
* @notice Internal initializer for the Accounting contract.
* @param _roflAppID The ROFL app identifier
* @param _owner Address that will own this contract
*/
function __Accounting_init(bytes21 _roflAppID, address _owner) internal onlyInitializing {
__EIP712SignatureVerifier_init();
__EVMSignerAndVerifier_init(_roflAppID);
__Ownable_init(_owner);
nextLockId = 1;
}
/**
* @notice Initializes the Accounting contract.
* @dev Replaces the constructor for upgradeable contracts.
* @param _roflAppID The ROFL app identifier (stable across redeployments)
* @param _owner Address that will own this contract
*/
function initialize(bytes21 _roflAppID, address _owner) external virtual initializer {
__Accounting_init(_roflAppID, _owner);
}
/**
* @notice Authorizes the upgrade proposal.
* @dev Required by UPUPSUpgradeable. Only the contract owner can propose the upgrade.
*/
function _authorizeProposeUpgrade() internal override onlyOwner {}
/**
* @notice Authorizes an upgrade to a new implementation.
* @dev Required by UUPSUpgradeable. Only the contract owner can upgrade.
* @param newImplementation Address of the new implementation contract
*/
function _authorizeUpgrade(address newImplementation) internal override onlyOwner acceptProposedUpgrade(newImplementation) {}
/// @dev Ownership renunciation is disabled to prevent bricking the proxy.
function renounceOwnership() public pure override {
revert();
}
function _authSender(bytes memory token) internal view returns (address) {
if (token.length != 0) {
return siweAuth.authSender(token);
}
return msg.sender;
}
function _appendHistory(
address user,
HistoryKind kind,
bytes memory payload
) internal {
history[user].push(
HistoryEntry({
kind: kind,
timestamp: uint64(block.timestamp),
payload: payload
})
);
}
/**
* @dev Appends a single history entry for `user` packing the token, amount,
* and counterparty.
* @param user The account whose history is appended.
* @param kind The history entry kind.
* @param tokenId The token involved in the operation.
* @param amount The operation amount.
* @param counterparty The other party to the operation.
*/
function _appendUserCounterpartyHistory(
address user,
HistoryKind kind,
bytes32 tokenId,
uint256 amount,
address counterparty
) internal {
_appendHistory(
user,
kind,
abi.encodePacked(tokenId, amount, counterparty)
);
}
/**
* @notice Get the deposit address for an authenticated user.
* @param chainType The chain family (see ChainType enum)
* @param version Key derivation index
* @param siweToken Opaque SIWE auth token from /auth/login
* @return depositAddr The deposit address for the authenticated user
*/
function getDepositAddress(
ChainType chainType,
uint256 version,
bytes calldata siweToken
) external view returns (address depositAddr) {
address beneficiary = _authSender(siweToken);
(depositAddr, ) = _deriveDepositKeypair(beneficiary, chainType, version);
}
/**
* @notice Credit a deposit to a beneficiary. ROFL-only.
* @param beneficiary The address to credit
* @param tokenId The token identifier
* @param amount The deposit amount (verified off-chain by TEE)
* @param depositId Unique deposit identifier: keccak256(chainId, txHash, tokenId, depositIndex)
*/
function creditDeposit(
address beneficiary,
bytes32 tokenId,
uint256 amount,
bytes32 depositId
) external onlyROFL {
if (beneficiary == address(0)) revert AddressMismatch();
if (processedDeposits[depositId]) revert DepositAlreadyProcessed();
if (amount == 0) revert InvalidAmount();
if (tokens[tokenId].data.length == 0) revert UnsupportedTokenType();
processedDeposits[depositId] = true;
balances[beneficiary][tokenId] += amount;
_appendHistory(
beneficiary,
HistoryKind.Deposit,
abi.encodePacked(tokenId, amount, depositId)
);
emit Deposit(tokenId, amount, depositId);
}
// ─── Emergency Withdraw ───────────────────────────────────────────
/**
* @notice Deterministic key for an emergency withdrawal slot.
* @param beneficiary The user who owns the deposit address
* @param tokenId The token identifier
* @param version Key derivation index
* @return The request ID for the emergency withdrawal slot
*/
function emergencyWithdrawKey(
address beneficiary,
bytes32 tokenId,
uint256 version
) public pure returns (bytes32) {
return keccak256(abi.encode(beneficiary, tokenId, version));
}
/**
* @notice Request emergency withdrawal of unswept funds from deposit address.
* @dev Requires 1-block delay before execution (same as normal withdrawal).
* No signature needed — msg.sender is the beneficiary and controls all
* parameters directly (unlike normal withdrawals where ROFL submits on
* the user's behalf).
* One slot per (beneficiary, tokenId, version) — a second request
* overwrites the first (which subsumes "cancel": re-request with any
* new params to reset the timer/destination).
* chainId and chainType are not parameters: they are derived from the
* tokenId at execute time, so a caller cannot request a withdrawal for
* one token and have it signed on a different chain.
* @param tokenId The token identifier
* @param toAddress Destination address for the emergency withdrawal
* @param version Key derivation index for the deposit keypair
* @return requestId Deterministic key for the emergency withdrawal slot
*/
function requestEmergencyWithdraw(
bytes32 tokenId,
address toAddress,
uint256 version
) external returns (bytes32 requestId) {
if (toAddress == address(0)) revert AddressMismatch();
if (tokens[tokenId].data.length == 0) revert UnsupportedTokenType();
requestId = emergencyWithdrawKey(msg.sender, tokenId, version);
emergencyWithdrawRequests[requestId] = EmergencyWithdrawRequest({
toAddress: toAddress,
blockNumber: block.number
});
emit EmergencyWithdrawRequested(requestId, tokenId);
}
/**
* @notice Execute an emergency withdrawal after 1-block delay.
* @dev Contract derives deposit keypair, signs a transfer tx, returns raw signed tx bytes.
* Caller broadcasts the signed tx on the source chain.
* Caller supplies nonce/amount/gasPrice — the contract has no knowledge of source-chain
* state when ROFL is down.
* No msg.sender check: toAddress is fixed at request time, so any caller
* can only send funds to the beneficiary's chosen destination. Safe to
* call multiple times — source-chain nonce is the double-spend guard.
* @param beneficiary The user who owns the deposit address
* @param tokenId The token identifier (determines chainId and token type)
* @param version Key derivation index for the deposit keypair
* @param sourceChainNonce Current nonce of the deposit address on the source chain
* @param amount Amount to transfer out of the deposit address
* @param gasPrice Gas price (wei) to embed in the signed source-chain transaction
* @return signedTx Raw signed transaction ready to broadcast on the source chain
*/
function executeEmergencyWithdraw(
address beneficiary,
bytes32 tokenId,
uint256 version,
uint64 sourceChainNonce,
uint256 amount,
uint256 gasPrice
) public returns (bytes memory signedTx) {
bytes32 requestId = emergencyWithdrawKey(beneficiary, tokenId, version);
EmergencyWithdrawRequest memory req = emergencyWithdrawRequests[requestId];
if (req.blockNumber == 0) revert EmergencyWithdrawNotFound();
if (block.number - req.blockNumber < 1) revert EmergencyWithdrawTooSoon();
TokenInfo memory tInfo = tokens[tokenId];
// Dispatch on tokenType; the else-revert is the single exhaustiveness guard.
// When a non-EVM TokenType is added, add a branch here with its ChainType.
if (tInfo.tokenType == TokenType.NativeEVM) {
uint256 chainId = EVMSignerAndVerifier.decodeEVMNativeTokenData(tInfo.data);
signedTx = generateDepositAddressTransfer(
beneficiary,
ChainType.EVM,
version,
chainId,
req.toAddress,
amount,
sourceChainNonce,
gasPrice
);
} else if (tInfo.tokenType == TokenType.ERC20) {
(uint256 chainId, address tokenAddress) = EVMSignerAndVerifier
.decodeEVMErc20TokenData(tInfo.data);
signedTx = generateDepositAddressERC20Transfer(
beneficiary,
ChainType.EVM,
version,
chainId,
req.toAddress,
tokenAddress,
amount,
sourceChainNonce,
gasPrice
);
} else {
revert UnsupportedTokenType();
}
emit EmergencyWithdrawExecuted(requestId);
}
// ─── Locks ────────────────────────────────────────────────────────
/**
* @notice Creates a lock on user funds for exclusive access by a designated service.
*
* This function allows users to lock a portion of their funds for use by a specific
* service. Locked funds are removed from the user's available balance but remain
* owned by the user until the lock expires or the service transfers them.
*
* The locking mechanism enables:
* - Escrow-like functionality for service interactions
* - Temporary delegation of fund access to trusted services
* - Time-bounded locks that automatically expire
* - Multiple concurrent locks per user (up to 10)
*
* Security features:
* - EIP-712 signature verification to authorize the lock
* - Expiry timestamp validation to ensure locks are created with future expiry
* - Balance verification before locking
* - Limited number of active locks per user (max 10)
*
* @dev The signature must be from the user whose funds are being locked.
* Locked funds are stored in the user's activeLocks array.
* The expiry must be a timestamp in the future (> block.timestamp).
*
* @param serviceAddress The address of the service that will have access to the locked funds
* @param tokenId The identifier of the token to lock
* @param amount The amount of tokens to lock
* @param expiry The timestamp when the lock expires and funds can be reclaimed (must be in future)
* @param nonce The nonce for replay protection (must match user's current createLockNonces)
* @param signature The EIP-712 signature from the user authorizing the lock
*/
function createLock(
address serviceAddress,
bytes32 tokenId,
uint256 amount,
uint256 expiry,
uint256 nonce,
bytes calldata signature
) public {
if (expiry <= block.timestamp) revert InvalidExpiry();
if (amount == 0) revert InvalidAmount();
address userAddress = EIP712SignatureVerifier.verifyLockSignature(
serviceAddress,
tokenId,
amount,
expiry,
nonce,
signature
);
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
if (locks.length >= 10) revert TooManyActiveLocks();
if (balances[userAddress][tokenId] < amount)
revert InsufficientBalance();
balances[userAddress][tokenId] -= amount;
uint256 lockId = nextLockId++;
locks.push(
FundLock({
lockId: lockId,
serviceId: serviceAddress,
tokenId: tokenId,
amount: amount,
expiry: expiry
})
);
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.CreateLock,
tokenId,
amount,
serviceAddress
);
}
function _findLockIndex(
FundLock[] storage locks,
uint256 lockId
) internal view returns (uint256) {
for (uint256 i = 0; i < locks.length; i++) {
if (locks[i].lockId == lockId) {
return i;
}
}
revert InvalidLockId();
}
function _scheduleWithdrawal(
address userAddress,
address toAddress,
bytes32 tokenId,
uint256 amount
) internal {
TokenInfo memory tInfo = tokens[tokenId];
bytes memory txIdentifier;
uint256 chainId;
if (tInfo.tokenType == TokenType.NativeEVM) {
chainId = EVMSignerAndVerifier.decodeEVMNativeTokenData(tInfo.data);
if (gasPrices[chainId] == 0) revert GasPriceNotSet(chainId);
txIdentifier = abi.encode(getEVMNonceAndIncrement(chainId));
} else if (tInfo.tokenType == TokenType.ERC20) {
(chainId, ) = EVMSignerAndVerifier.decodeEVMErc20TokenData(
tInfo.data
);
if (gasPrices[chainId] == 0) revert GasPriceNotSet(chainId);
txIdentifier = abi.encode(getEVMNonceAndIncrement(chainId));
} else {
revert UnsupportedTokenType();
}
withdrawals.push(
WithdrawalRequest({
userAddress: userAddress,
toAddress: toAddress,
amount: amount,
blockNumber: block.number,
tokenId: tokenId,
txIdentifier: txIdentifier,
resolved: false
})
);
emit Withdrawal(userAddress, tokenId, amount, chainId);
}
/**
* @notice Modifies an existing lock by increasing the locked amount and/or extending expiry.
* @dev Expiry can only be extended (newExpiry >= current expiry). Amount increases are
* drawn from the user's available balance. Authorized via EIP-712 user signature.
* @param lockId The unique identifier of the lock to modify
* @param amount Additional amount to add to the lock (0 to only extend expiry)
* @param newExpiry The new expiry timestamp for the lock
* @param nonce The nonce for replay protection (must match user's current modifyLockNonces)
* @param signature The EIP-712 signature from the user authorizing the modification
*/
function modifyLock(
uint256 lockId,
uint256 amount,
uint256 newExpiry,
uint256 nonce,
bytes calldata signature
) public {
address userAddress = EIP712SignatureVerifier.verifyModifyLockSignature(
lockId,
amount,
newExpiry,
nonce,
signature
);
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
uint256 lockIndex = _findLockIndex(locks, lockId);
FundLock storage lock = locks[lockIndex];
if (newExpiry < lock.expiry) revert InvalidExpiry();
if (amount == 0 && newExpiry == lock.expiry) revert InvalidAmount();
if (amount > 0) {
if (balances[userAddress][lock.tokenId] < amount)
revert InsufficientBalance();
balances[userAddress][lock.tokenId] -= amount;
lock.amount += amount;
}
lock.expiry = newExpiry;
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.ModifyLock,
lock.tokenId,
amount,
lock.serviceId
);
}
/**
* @notice Unlocks a single expired fund lock and returns funds to the user's available balance.
*
* This function allows users to reclaim funds from an expired lock. Once a lock's
* expiry timestamp has passed, the original user can call this function to
* unlock the funds and restore them to their available balance.
*
* The unlocking process:
* 1. Validates the lock index exists
* 2. Checks that the lock has expired (block.timestamp >= expiry)
* 3. Returns any remaining locked amount to the user's balance
* 4. Removes the lock from the user's active locks array
*
* Security features:
* - Time-based expiry validation to prevent premature unlocking
* - Index bounds checking to prevent invalid access
* - Efficient lock removal using swap-and-pop pattern
*
* @dev Uses swap-and-pop to remove locks efficiently from the array.
* The lock order may change after removal due to the swap operation.
* Anyone can call this function for any user if the lock has expired.
* The purpose of this function is to allow users to reclaim funds if
* a service goes down or becomes unresponsive.
*
* @param userAddress The address of the user whose lock should be unlocked
* @param lockId The unique identifier of the lock to unlock
*/
function unlockSingleLock(address userAddress, uint256 lockId) public {
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
uint256 lockIndex = _findLockIndex(locks, lockId);
FundLock memory lock = locks[lockIndex];
if (lock.amount != 0) {
if (block.timestamp < lock.expiry) revert LockNotExpired();
balances[userAddress][lock.tokenId] += lock.amount;
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.UnlockLock,
lock.tokenId,
lock.amount,
lock.serviceId
);
}
locks[lockIndex] = locks[locks.length - 1];
locks.pop();
}
/**
* @notice Unlocks all expired fund locks for a user and returns funds to available balance.
*
* This function iterates through all of a user's active locks and unlocks any that
* have expired. This is a convenience function to avoid calling unlockSingleLock
* multiple times when a user has several expired locks.
*
* @dev Iterates backwards to handle swap-and-pop without skipping elements.
* Anyone can call this function for any user.
*
* @param userAddress The address of the user whose expired locks should be unlocked
* @return unlockedCount The number of locks that were successfully unlocked
*/
function unlockAllExpiredLocks(
address userAddress
) external returns (uint256 unlockedCount) {
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
unlockedCount = 0;
uint256 i = locks.length;
while (i > 0) {
i--;
FundLock memory lock = locks[i];
if (block.timestamp >= lock.expiry && lock.amount > 0) {
balances[userAddress][lock.tokenId] += lock.amount;
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.UnlockLock,
lock.tokenId,
lock.amount,
lock.serviceId
);
locks[i] = locks[locks.length - 1];
locks.pop();
unlockedCount++;
}
}
return unlockedCount;
}
/**
* @notice Transfers locked funds under service authorization.
*
* This function allows a service to transfer funds that were previously locked
* to them by a user. Unlike regular transfers, this requires authorization from
* the service (not the original user) since the funds are under the service's
* temporary control.
*
* The transfer process:
* 1. Validates the lock index and retrieves the lock details
* 2. Verifies the service's EIP-712 signature authorizing the transfer
* 3. Checks that the lock has sufficient funds for the transfer
* 4. Reduces the locked amount and credits the recipient
* 5. Removes the lock if all funds are transferred
*
* Security features:
* - Service signature verification (not user signature)
* - Lock amount validation before transfer
* - Automatic lock cleanup when empty
* - Signature replay protection via EIP712SignatureVerifier
*
* @dev The signature must be from the service address associated with the lock.
* If the lock amount reaches zero, the lock is automatically removed.
* The lock array may be reordered due to swap-and-pop removal. The service is
* a user (managed the same way as regular users) and any user can act as a service.
*
* @param userAddress The address of the user who originally locked the funds
* @param toAddress The address receiving the transferred locked funds
* @param lockId The unique identifier of the lock to transfer from
* @param amount The amount of locked tokens to transfer
* @param nonce The nonce for replay protection (must match service's current transferLockedNonces)
* @param signature The EIP-712 signature from the service authorizing the transfer
*/
function transferFromLock(
address userAddress,
address toAddress,
uint256 lockId,
uint256 amount,
uint256 nonce,
bytes calldata signature
) public {
if (amount == 0) revert InvalidAmount();
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
uint256 lockIndex = _findLockIndex(locks, lockId);
FundLock storage lock = locks[lockIndex];
EIP712SignatureVerifier.verifyTransferLockedSignature(
lock.serviceId,
userAddress,
toAddress,
lockId,
amount,
nonce,
signature
);
if (lock.amount < amount) revert InsufficientLockedAmount();
lock.amount -= amount;
balances[toAddress][lock.tokenId] += amount;
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.TransferFromLockOut,
lock.tokenId,
amount,
toAddress
);
if (toAddress != address(0) && toAddress != userAddress) {
_appendUserCounterpartyHistory(
toAddress,
HistoryKind.TransferFromLockIn,
lock.tokenId,
amount,
userAddress
);
}
if (lock.amount == 0) {
locks[lockIndex] = locks[locks.length - 1];
locks.pop();
}
}
/**
* @notice Withdraws locked funds to an external on-chain address via scheduled withdrawal.
* @dev Service-authorized counterpart to `transferFromLock`: instead of crediting an
* internal balance, this schedules a cross-chain withdrawal signed by ROFL.
* Signature must come from the lock's serviceId. If `lock.amount` hits zero the
* slot is removed via swap-and-pop.
* @param userAddress The user who originally created the lock
* @param toAddress The external destination address on the token's source chain
* @param lockId The unique identifier of the lock to withdraw from
* @param amount The amount of locked tokens to withdraw
* @param nonce The nonce for replay protection (must match service's current withdrawFromLock nonce)
* @param signature The EIP-712 signature from the service authorizing the withdrawal
*/
function withdrawFromLock(
address userAddress,
address toAddress,
uint256 lockId,
uint256 amount,
uint256 nonce,
bytes calldata signature
) public {
if (amount == 0) revert InvalidAmount();
if (toAddress == address(0)) revert AddressMismatch();
UserInfo storage uInfo = userInfo[userAddress];
FundLock[] storage locks = uInfo.activeLocks;
uint256 lockIndex = _findLockIndex(locks, lockId);
FundLock storage lock = locks[lockIndex];
EIP712SignatureVerifier.verifyWithdrawFromLockSignature(
lock.serviceId,
userAddress,
toAddress,
lockId,
amount,
nonce,
signature
);
if (lock.amount < amount) revert InsufficientLockedAmount();
lock.amount -= amount;
bytes32 tokenId = lock.tokenId;
if (lock.amount == 0) {
locks[lockIndex] = locks[locks.length - 1];
locks.pop();
}
_scheduleWithdrawal(userAddress, toAddress, tokenId, amount);
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.Withdraw,
tokenId,
amount,
toAddress
);
}
/**
* @notice Transfers funds between users within the accounting system.
*
* This function enables peer-to-peer transfers of tokens between users
* without requiring on-chain transactions on the original token's blockchain.
* The transfer happens entirely within the accounting system's ledger.
*
* The transfer process:
* 1. Verifies the user's EIP-712 signature authorizing the transfer
* 2. Checks that the sender has sufficient balance
* 3. Debits the amount from sender's balance
* 4. Credits the amount to recipient's balance
*
* Security features:
* - EIP-712 signature verification to authorize the transfer
* - Balance verification before debiting
*
* @dev The signature must be from the sender.
* This is an internal transfer that doesn't generate blockchain transactions.
*
* @param toAddress The address of the user receiving the funds
* @param tokenId The identifier of the token being transferred
* @param amount The amount of tokens to transfer
* @param nonce The nonce for replay protection (must match user's current transfer nonce)
* @param signature The EIP-712 signature from the sender authorizing the transfer
*/
function transferBalance(
address toAddress,
bytes32 tokenId,
uint256 amount,
uint256 nonce,
bytes calldata signature
) public {
if (amount == 0) revert InvalidAmount();
address userAddress = EIP712SignatureVerifier.verifyTransferSignature(
toAddress,
tokenId,
amount,
nonce,
signature
);
if (balances[userAddress][tokenId] < amount)
revert InsufficientBalance();
balances[userAddress][tokenId] -= amount;
balances[toAddress][tokenId] += amount;
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.TransferBalanceOut,
tokenId,
amount,
toAddress
);
if (toAddress != address(0) && toAddress != userAddress) {
_appendUserCounterpartyHistory(
toAddress,
HistoryKind.TransferBalanceIn,
tokenId,
amount,
userAddress
);
}
}
/**
* @notice Initiates withdrawal by scheduling it for future resolution.
*
* This function processes user withdrawal requests by:
* 1. Verifying the user's authorization via EIP-712 signature
* 2. Debiting the requested amount from the user's account
* 3. Scheduling the withdrawal for resolution in a future block
*
* Security features:
* - EIP-712 signature verification to authorize withdrawal
* - Balance verification before debiting
* - Nonce setting when scheduling transactions
*
* @param tokenId The identifier of the token to withdraw
* @param amount The amount of tokens to withdraw
* @param nonce The user's current withdrawal nonce for replay protection
* @param signature The EIP-712 signature from the user authorizing the withdrawal
*/
function requestWithdrawal(
bytes32 tokenId,
uint256 amount,
uint256 nonce,
bytes calldata signature
) public {
if (amount == 0) revert InvalidAmount();
address userAddress = EIP712SignatureVerifier.verifyWithdrawSignature(
tokenId,
amount,
nonce,
signature
);
if (balances[userAddress][tokenId] < amount)
revert InsufficientBalance();
balances[userAddress][tokenId] -= amount;
_scheduleWithdrawal(userAddress, userAddress, tokenId, amount);
_appendUserCounterpartyHistory(
userAddress,
HistoryKind.Withdraw,
tokenId,
amount,
userAddress
);
}
/**
* @notice Resolves a withdrawal by generating a signed transaction for the destination chain.
*
* This function is idempotent - it can be called multiple times for the same withdrawal.
* On first call, it marks the withdrawal as resolved and emits an event. On subsequent
* calls, it skips the state change but still returns the signed transaction. This allows:
* - Retrying broadcast if the previous attempt failed
* - Anyone to get the signed_tx and broadcast if the original resolver didn't
* - Prevention of griefing where someone resolves but never broadcasts
*
* The function processes withdrawal requests by:
* 1. Ensuring a minimum block delay has passed to prevent simulation attacks
* 2. Generating a signed transaction to transfer tokens to the user on the destination chain
* 3. Marking as resolved (only on first call)
*
* Security features:
* - Token-type specific transaction generation
* - Simulation-attack protection by enforcing a minimum block delay before resolution
*
* @dev The returned transaction must be broadcast externally to complete withdrawal.
* Replay protection is handled via nonces assigned at request time.
*
* @param index The index of the withdrawal request to resolve
* @return signedTx The raw signed transaction ready for broadcast
*/
function resolveWithdrawal(
uint256 index
) public returns (bytes memory signedTx) {
WithdrawalRequest storage withdrawalRequest = withdrawals[index];
if (block.number - withdrawalRequest.blockNumber < 1) {
revert WithdrawalTooSoon();
}
address userAddress = withdrawalRequest.userAddress;
address toAddress = withdrawalRequest.toAddress;
bytes32 tokenId = withdrawalRequest.tokenId;
uint256 amount = withdrawalRequest.amount;
TokenInfo memory tInfo = tokens[tokenId];
uint256 chainId;
if (tInfo.tokenType == TokenType.NativeEVM) {
chainId = EVMSignerAndVerifier.decodeEVMNativeTokenData(tInfo.data);
uint64 nonce = abi.decode(withdrawalRequest.txIdentifier, (uint64));
signedTx = EVMSignerAndVerifier.generateNativeTransfer(
chainId,
toAddress,
amount,
nonce
);
} else if (tInfo.tokenType == TokenType.ERC20) {
address tokenAddress;
(chainId, tokenAddress) = EVMSignerAndVerifier
.decodeEVMErc20TokenData(tInfo.data);
uint64 nonce = abi.decode(withdrawalRequest.txIdentifier, (uint64));
signedTx = EVMSignerAndVerifier.generateERC20Transfer(
chainId,
toAddress,
tokenAddress,
amount,
nonce
);
} else {
revert UnsupportedTokenType();
}
// Only mark resolved and emit event if not already resolved
if (!withdrawalRequest.resolved) {
withdrawalRequest.resolved = true;
emit WithdrawalResolved(
index,
userAddress,
tokenId,
toAddress,
amount,
chainId
);
}
return signedTx;
}
/**
* @notice Computes a unique identifier for a token based on its type and metadata.
*
* This function generates a deterministic token ID by hashing the token's type
* and chain-specific data. The same token configuration will always produce