-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRunesCardV1_flat.sol
More file actions
773 lines (646 loc) · 28.7 KB
/
RunesCardV1_flat.sol
File metadata and controls
773 lines (646 loc) · 28.7 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
// Sources flattened with hardhat v2.26.3 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/introspection/IERC165.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/interfaces/IERC165.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// File @openzeppelin/contracts/interfaces/IERC20.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
// File @openzeppelin/contracts/interfaces/IERC1363.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
// File @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol@v5.4.0
// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
// File contracts/RunesCardV1.sol
// Original license: SPDX_License_Identifier: MIT
pragma solidity ^0.8.22;
contract RunesCardV1 {
using SafeERC20 for IERC20;
struct Card {
uint64 id;
address creator;
address token;
uint256 amount;
bytes32 redeemCodeHash;
string description;
string link;
uint16 cardType;
bool isRedeemed;
uint64 createdAt;
uint64 redeemedAt;
address redeemedBy;
}
// Events
event CardCreated(
uint64 indexed id,
address indexed creator,
address indexed token,
uint256 amount,
uint64 timestamp
);
event CardRedeemed(
uint64 indexed id,
address indexed redeemer,
uint256 amount,
uint64 timestamp
);
event ProtocolFeeChanged(uint256 oldFee, uint256 newFee);
event FeesWithdrawn(
address indexed token,
uint256 amount,
address indexed recipient,
uint64 timestamp
);
event TokenWhitelisted(address indexed token);
event TokenRemovedFromWhitelist(address indexed token);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Paused(address indexed account);
event Unpaused(address indexed account);
// State variables
uint8 public version;
uint256 public protocolFee; // in basis points (e.g., 100 = 1%)
uint64 public cardCounter;
address public owner;
bool public paused;
mapping(uint64 => Card) public cards;
mapping(address => uint64[]) private userCards;
mapping(address => uint64[]) private redeemedCards;
mapping(address => uint256) public totalFeesCollected;
mapping(address => bool) public whitelistedTokens;
// Custom errors
error AmountMustBeGreaterThanZero();
error InvalidTokenAddress();
error InvalidRedeemCode();
error InvalidDescription();
error InvalidLink();
error InvalidCardType();
error InvalidCardId();
error CardAlreadyRedeemed();
error PageSizeMustBeGreaterThanZero();
error PageSizeTooLarge();
error InvalidRecipientAddress();
error InsufficientBalance();
error TokenTransferFailed();
error OnlyOwner();
error ContractPaused();
error InvalidOwnerAddress();
error TokenNotWhitelisted();
// Modifiers
modifier onlyOwner() {
if (msg.sender != owner) revert OnlyOwner();
_;
}
modifier whenNotPaused() {
if (paused) revert ContractPaused();
_;
}
modifier onlyWhitelistedToken(address token) {
if (!whitelistedTokens[token]) revert TokenNotWhitelisted();
_;
}
constructor(address _owner, uint256 _initialFee) {
require(_owner != address(0), "Owner cannot be zero");
owner = _owner;
version = 1;
cardCounter = 0;
protocolFee = _initialFee;
paused = false;
}
function whitelistToken(address token) external onlyOwner {
if (token == address(0)) revert InvalidTokenAddress();
whitelistedTokens[token] = true;
emit TokenWhitelisted(token);
}
function removeTokenFromWhitelist(address token) external onlyOwner {
if (token == address(0)) revert InvalidTokenAddress();
whitelistedTokens[token] = false;
emit TokenRemovedFromWhitelist(token);
}
function createCard(
address token,
uint256 amount,
bytes32 redeemCodeHash,
string calldata description,
string calldata link,
uint16 cardType
) external whenNotPaused onlyWhitelistedToken(token) {
if (amount == 0) revert AmountMustBeGreaterThanZero();
if (redeemCodeHash == bytes32(0)) revert InvalidRedeemCode();
if (bytes(description).length == 0) revert InvalidDescription();
if (bytes(link).length == 0) revert InvalidLink();
if (cardType == 0) revert InvalidCardType();
cardCounter++;
uint64 newId = cardCounter;
// Transfer tokens from creator to contract
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
Card memory newCard = Card({
id: newId,
creator: msg.sender,
token: token,
amount: amount,
redeemCodeHash: redeemCodeHash,
description: description,
link: link,
cardType: cardType,
isRedeemed: false,
createdAt: uint64(block.timestamp),
redeemedAt: 0,
redeemedBy: address(0)
});
cards[newId] = newCard;
userCards[msg.sender].push(newId);
emit CardCreated(newId, msg.sender, token, amount, uint64(block.timestamp));
}
function redeemCard(string calldata redeemCode, uint64 id) external whenNotPaused {
if (id == 0 || id > cardCounter) revert InvalidCardId();
Card storage card = cards[id];
if (card.isRedeemed) revert CardAlreadyRedeemed();
bytes32 computedHash = keccak256(abi.encodePacked(redeemCode));
if (computedHash != card.redeemCodeHash) revert InvalidRedeemCode();
uint256 feeAmount = (card.amount * protocolFee) / 10000;
uint256 redeemAmount = card.amount - feeAmount;
// Transfer redeem amount to redeemer
IERC20(card.token).safeTransfer(msg.sender, redeemAmount);
// Transfer fee to owner if fee > 0
if (feeAmount > 0) {
IERC20(card.token).safeTransfer(owner, feeAmount);
totalFeesCollected[card.token] += feeAmount;
}
card.isRedeemed = true;
card.redeemedBy = msg.sender;
card.redeemedAt = uint64(block.timestamp);
redeemedCards[msg.sender].push(id);
emit CardRedeemed(id, msg.sender, redeemAmount, uint64(block.timestamp));
}
function getCardBalance(uint64 id) external view returns (uint256) {
Card memory card = cards[id];
return card.isRedeemed ? 0 : card.amount;
}
function getCardById(uint64 id) external view returns (Card memory) {
if (id == 0 || id > cardCounter) revert InvalidCardId();
return cards[id];
}
function getUsersCards(address user) external view returns (Card[] memory) {
uint256 count = userCards[user].length;
Card[] memory userCardList = new Card[](count);
for (uint256 i = 0; i < count; i++) {
userCardList[i] = cards[userCards[user][i]];
}
return userCardList;
}
function getUsersCardsPaginated(
uint64 page,
uint64 pageSize,
address user
) external view returns (Card[] memory, uint64) {
if (pageSize == 0) revert PageSizeMustBeGreaterThanZero();
if (pageSize > 50) revert PageSizeTooLarge();
uint256 totalCount = userCards[user].length;
uint256 startIndex = uint256(page) * uint256(pageSize);
if (startIndex >= totalCount) {
return (new Card[](0), uint64(totalCount));
}
uint256 endIndex = startIndex + pageSize;
if (endIndex > totalCount) {
endIndex = totalCount;
}
uint256 resultSize = endIndex - startIndex;
Card[] memory paginatedCards = new Card[](resultSize);
for (uint256 i = 0; i < resultSize; i++) {
paginatedCards[i] = cards[userCards[user][startIndex + i]];
}
return (paginatedCards, uint64(totalCount));
}
function getUsersRedeemedCardsPaginated(
uint64 page,
uint64 pageSize,
address user
) external view returns (Card[] memory, uint64) {
if (pageSize == 0) revert PageSizeMustBeGreaterThanZero();
if (pageSize > 50) revert PageSizeTooLarge();
uint256 totalCount = redeemedCards[user].length;
uint256 startIndex = uint256(page) * uint256(pageSize);
if (startIndex >= totalCount) {
return (new Card[](0), uint64(totalCount));
}
uint256 endIndex = startIndex + pageSize;
if (endIndex > totalCount) {
endIndex = totalCount;
}
uint256 resultSize = endIndex - startIndex;
Card[] memory paginatedCards = new Card[](resultSize);
for (uint256 i = 0; i < resultSize; i++) {
paginatedCards[i] = cards[redeemedCards[user][startIndex + i]];
}
return (paginatedCards, uint64(totalCount));
}
function getUserRedeemedCardCount(address user) external view returns (uint64) {
return uint64(redeemedCards[user].length);
}
function getUserCardCount(address user) external view returns (uint64) {
return uint64(userCards[user].length);
}
function setProtocolFee(uint256 newFee) external onlyOwner {
uint256 oldFee = protocolFee;
protocolFee = newFee;
emit ProtocolFeeChanged(oldFee, newFee);
}
function withdrawFees(
address token,
uint256 amount,
address recipient
) external onlyOwner {
if (token == address(0)) revert InvalidTokenAddress();
if (recipient == address(0)) revert InvalidRecipientAddress();
if (amount == 0) revert AmountMustBeGreaterThanZero();
uint256 contractBalance = IERC20(token).balanceOf(address(this));
if (contractBalance < amount) revert InsufficientBalance();
IERC20(token).safeTransfer(recipient, amount);
emit FeesWithdrawn(token, amount, recipient, uint64(block.timestamp));
}
function getContractTokenBalance(address token) external view returns (uint256) {
if (token == address(0)) revert InvalidTokenAddress();
return IERC20(token).balanceOf(address(this));
}
function getTotalFeesCollected(address token) external view returns (uint256) {
return totalFeesCollected[token];
}
function isTokenWhitelisted(address token) external view returns (bool) {
return whitelistedTokens[token];
}
function pause() external onlyOwner {
paused = true;
emit Paused(msg.sender);
}
function unpause() external onlyOwner {
paused = false;
emit Unpaused(msg.sender);
}
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner == address(0)) revert InvalidOwnerAddress();
address previousOwner = owner;
owner = newOwner;
emit OwnershipTransferred(previousOwner, newOwner);
}
}