@zoralabs/coins 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/.turbo/turbo-build.log +76 -0
  2. package/CHANGELOG.md +14 -0
  3. package/LICENSE +21 -0
  4. package/abis/Address.json +29 -0
  5. package/abis/BaseTest.json +691 -0
  6. package/abis/Clones.json +7 -0
  7. package/abis/Coin.json +1693 -0
  8. package/abis/CoinConstants.json +93 -0
  9. package/abis/CoinTest.json +998 -0
  10. package/abis/ContextUpgradeable.json +25 -0
  11. package/abis/ContractVersionBase.json +15 -0
  12. package/abis/Deploy.json +29 -0
  13. package/abis/ECDSA.json +29 -0
  14. package/abis/EIP712.json +67 -0
  15. package/abis/EIP712Upgradeable.json +74 -0
  16. package/abis/ERC1967Proxy.json +67 -0
  17. package/abis/ERC1967Utils.json +85 -0
  18. package/abis/ERC20PermitUpgradeable.json +527 -0
  19. package/abis/ERC20Upgradeable.json +333 -0
  20. package/abis/FactoryTest.json +845 -0
  21. package/abis/IBeacon.json +15 -0
  22. package/abis/ICoin.json +541 -0
  23. package/abis/ICoinComments.json +53 -0
  24. package/abis/IERC1155Errors.json +104 -0
  25. package/abis/IERC165.json +21 -0
  26. package/abis/IERC1822Proxiable.json +15 -0
  27. package/abis/IERC20.json +221 -0
  28. package/abis/IERC20Errors.json +88 -0
  29. package/abis/IERC20Metadata.json +224 -0
  30. package/abis/IERC20Permit.json +77 -0
  31. package/abis/IERC5267.json +51 -0
  32. package/abis/IERC721.json +287 -0
  33. package/abis/IERC721Enumerable.json +343 -0
  34. package/abis/IERC721Errors.json +105 -0
  35. package/abis/IERC721Metadata.json +332 -0
  36. package/abis/IERC721Receiver.json +36 -0
  37. package/abis/IERC721TokenReceiver.json +36 -0
  38. package/abis/IERC7572.json +21 -0
  39. package/abis/IMulticall3.json +440 -0
  40. package/abis/INonfungiblePositionManager.json +366 -0
  41. package/abis/IProtocolRewards.json +348 -0
  42. package/abis/ISwapRouter.json +137 -0
  43. package/abis/IUniswapV3Pool.json +148 -0
  44. package/abis/IUniswapV3SwapCallback.json +25 -0
  45. package/abis/IVersionedContract.json +15 -0
  46. package/abis/IWETH.json +118 -0
  47. package/abis/IZoraFactory.json +138 -0
  48. package/abis/Initializable.json +25 -0
  49. package/abis/Math.json +7 -0
  50. package/abis/MockERC20.json +322 -0
  51. package/abis/MockERC721.json +350 -0
  52. package/abis/MultiOwnable.json +171 -0
  53. package/abis/MultiOwnableTest.json +796 -0
  54. package/abis/NoncesUpgradeable.json +60 -0
  55. package/abis/OwnableUpgradeable.json +99 -0
  56. package/abis/ProtocolRewards.json +494 -0
  57. package/abis/Proxy.json +6 -0
  58. package/abis/ReentrancyGuardUpgradeable.json +30 -0
  59. package/abis/SafeERC20.json +34 -0
  60. package/abis/Script.json +15 -0
  61. package/abis/ShortStrings.json +18 -0
  62. package/abis/StdAssertions.json +379 -0
  63. package/abis/StdInvariant.json +180 -0
  64. package/abis/Strings.json +18 -0
  65. package/abis/Test.json +570 -0
  66. package/abis/UUPSUpgradeable.json +130 -0
  67. package/abis/Vm.json +8627 -0
  68. package/abis/VmSafe.json +7297 -0
  69. package/abis/ZoraFactory.json +67 -0
  70. package/abis/ZoraFactoryImpl.json +422 -0
  71. package/abis/stdError.json +119 -0
  72. package/abis/stdStorageSafe.json +52 -0
  73. package/addresses/1.json +4 -0
  74. package/addresses/8453.json +9 -0
  75. package/addresses/84532.json +9 -0
  76. package/dist/index.cjs +1236 -0
  77. package/dist/index.cjs.map +1 -0
  78. package/dist/index.d.ts +2 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +1208 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/wagmiGenerated.d.ts +1645 -0
  83. package/dist/wagmiGenerated.d.ts.map +1 -0
  84. package/foundry.toml +9 -0
  85. package/package/index.ts +1 -0
  86. package/package/wagmiGenerated.ts +1211 -0
  87. package/package.json +48 -0
  88. package/remappings.txt +4 -0
  89. package/script/Deploy.s.sol +14 -0
  90. package/slither.config.json +6 -0
  91. package/src/Coin.sol +579 -0
  92. package/src/ZoraFactoryImpl.sol +142 -0
  93. package/src/interfaces/ICoin.sol +194 -0
  94. package/src/interfaces/ICoinComments.sol +8 -0
  95. package/src/interfaces/IERC7572.sol +12 -0
  96. package/src/interfaces/INonfungiblePositionManager.sol +104 -0
  97. package/src/interfaces/IProtocolRewards.sol +12 -0
  98. package/src/interfaces/ISwapRouter.sol +38 -0
  99. package/src/interfaces/IUniswapV3Pool.sol +43 -0
  100. package/src/interfaces/IUniswapV3SwapCallback.sol +17 -0
  101. package/src/interfaces/IWETH.sol +16 -0
  102. package/src/interfaces/IZoraFactory.sol +56 -0
  103. package/src/proxy/ZoraFactory.sol +26 -0
  104. package/src/utils/CoinConstants.sol +67 -0
  105. package/src/utils/MultiOwnable.sol +126 -0
  106. package/src/utils/TickMath.sol +210 -0
  107. package/src/version/ContractVersionBase.sol +14 -0
  108. package/test/Coin.t.sol +443 -0
  109. package/test/Factory.t.sol +298 -0
  110. package/test/MultiOwnable.t.sol +156 -0
  111. package/test/utils/BaseTest.sol +178 -0
  112. package/test/utils/ProtocolRewards.sol +1499 -0
  113. package/tsconfig.build.json +10 -0
  114. package/tsconfig.json +9 -0
  115. package/tsup.config.ts +11 -0
  116. package/wagmi.config.ts +16 -0
@@ -0,0 +1,1499 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity ^0.8.0;
3
+
4
+ /// @dev For testing purposes only
5
+
6
+ // packages/protocol-rewards/_imagine/Enjoy.sol
7
+
8
+ /*
9
+
10
+ ░░░░░░░░░░░░░░
11
+ ░░▒▒░░░░░░░░░░░░░░░░░░░░
12
+ ░░▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░
13
+ ░░▒▒▒▒░░░░░░░░░░░░░░ ░░░░░░░░
14
+ ░▓▓▒▒▒▒░░░░░░░░░░░░ ░░░░░░░
15
+ ░▓▓▓▒▒▒▒░░░░░░░░░░░░ ░░░░░░░░
16
+ ░▓▓▓▒▒▒▒░░░░░░░░░░░░░░ ░░░░░░░░░░
17
+ ░▓▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░
18
+ ░▓▓▓▓▓▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░
19
+ ░▓▓▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░
20
+ ░░▓▓▓▓▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░
21
+ ░░▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░░░░░░▒▒▒▒▒░░
22
+ ░░▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░
23
+ ░░▓▓▓▓▓▓▓▓▓▓▓▓▒▒░░░
24
+
25
+ OURS TRULY,
26
+
27
+ */
28
+
29
+ interface Enjoy {}
30
+
31
+ // packages/protocol-rewards/src/interfaces/IProtocolRewards.sol
32
+
33
+ /// @title IProtocolRewards
34
+ /// @notice The interface for deposits & withdrawals for Protocol Rewards
35
+ interface IProtocolRewards {
36
+ /// @notice Rewards Deposit Event
37
+ /// @param creator Creator for NFT rewards
38
+ /// @param createReferral Creator referral
39
+ /// @param mintReferral Mint referral user
40
+ /// @param firstMinter First minter reward recipient
41
+ /// @param zora ZORA recipient
42
+ /// @param from The caller of the deposit
43
+ /// @param creatorReward Creator reward amount
44
+ /// @param createReferralReward Creator referral reward
45
+ /// @param mintReferralReward Mint referral amount
46
+ /// @param firstMinterReward First minter reward amount
47
+ /// @param zoraReward ZORA amount
48
+ event RewardsDeposit(
49
+ address indexed creator,
50
+ address indexed createReferral,
51
+ address indexed mintReferral,
52
+ address firstMinter,
53
+ address zora,
54
+ address from,
55
+ uint256 creatorReward,
56
+ uint256 createReferralReward,
57
+ uint256 mintReferralReward,
58
+ uint256 firstMinterReward,
59
+ uint256 zoraReward
60
+ );
61
+
62
+ /// @notice Deposit Event
63
+ /// @param from From user
64
+ /// @param to To user (within contract)
65
+ /// @param reason Optional bytes4 reason for indexing
66
+ /// @param amount Amount of deposit
67
+ /// @param comment Optional user comment
68
+ event Deposit(address indexed from, address indexed to, bytes4 indexed reason, uint256 amount, string comment);
69
+
70
+ /// @notice Withdraw Event
71
+ /// @param from From user
72
+ /// @param to To user (within contract)
73
+ /// @param amount Amount of deposit
74
+ event Withdraw(address indexed from, address indexed to, uint256 amount);
75
+
76
+ /// @notice Cannot send to address zero
77
+ error ADDRESS_ZERO();
78
+
79
+ /// @notice Function argument array length mismatch
80
+ error ARRAY_LENGTH_MISMATCH();
81
+
82
+ /// @notice Invalid deposit
83
+ error INVALID_DEPOSIT();
84
+
85
+ /// @notice Invalid signature for deposit
86
+ error INVALID_SIGNATURE();
87
+
88
+ /// @notice Invalid withdraw
89
+ error INVALID_WITHDRAW();
90
+
91
+ /// @notice Signature for withdraw is too old and has expired
92
+ error SIGNATURE_DEADLINE_EXPIRED();
93
+
94
+ /// @notice Low-level ETH transfer has failed
95
+ error TRANSFER_FAILED();
96
+
97
+ /// @notice Generic function to deposit ETH for a recipient, with an optional comment
98
+ /// @param to Address to deposit to
99
+ /// @param to Reason system reason for deposit (used for indexing)
100
+ /// @param comment Optional comment as reason for deposit
101
+ function deposit(address to, bytes4 why, string calldata comment) external payable;
102
+
103
+ /// @notice Generic function to deposit ETH for multiple recipients, with an optional comment
104
+ /// @param recipients recipients to send the amount to, array aligns with amounts
105
+ /// @param amounts amounts to send to each recipient, array aligns with recipients
106
+ /// @param reasons optional bytes4 hash for indexing
107
+ /// @param comment Optional comment to include with mint
108
+ function depositBatch(address[] calldata recipients, uint256[] calldata amounts, bytes4[] calldata reasons, string calldata comment) external payable;
109
+
110
+ /// @notice Used by Zora ERC-721 & ERC-1155 contracts to deposit protocol rewards
111
+ /// @param creator Creator for NFT rewards
112
+ /// @param creatorReward Creator reward amount
113
+ /// @param createReferral Creator referral
114
+ /// @param createReferralReward Creator referral reward
115
+ /// @param mintReferral Mint referral user
116
+ /// @param mintReferralReward Mint referral amount
117
+ /// @param firstMinter First minter reward
118
+ /// @param firstMinterReward First minter reward amount
119
+ /// @param zora ZORA recipient
120
+ /// @param zoraReward ZORA amount
121
+ function depositRewards(
122
+ address creator,
123
+ uint256 creatorReward,
124
+ address createReferral,
125
+ uint256 createReferralReward,
126
+ address mintReferral,
127
+ uint256 mintReferralReward,
128
+ address firstMinter,
129
+ uint256 firstMinterReward,
130
+ address zora,
131
+ uint256 zoraReward
132
+ ) external payable;
133
+
134
+ /// @notice Withdraw protocol rewards
135
+ /// @param to Withdraws from msg.sender to this address
136
+ /// @param amount amount to withdraw
137
+ function withdraw(address to, uint256 amount) external;
138
+
139
+ /// @notice Execute a withdraw of protocol rewards via signature
140
+ /// @param from Withdraw from this address
141
+ /// @param to Withdraw to this address
142
+ /// @param amount Amount to withdraw
143
+ /// @param deadline Deadline for the signature to be valid
144
+ /// @param v V component of signature
145
+ /// @param r R component of signature
146
+ /// @param s S component of signature
147
+ function withdrawWithSig(address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
148
+ }
149
+
150
+ // packages/protocol-rewards/src/lib/IERC5267.sol
151
+
152
+ // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
153
+
154
+ interface IERC5267 {
155
+ /**
156
+ * @dev MAY be emitted to signal that the domain could have changed.
157
+ */
158
+ event EIP712DomainChanged();
159
+
160
+ /**
161
+ * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
162
+ * signature.
163
+ */
164
+ function eip712Domain()
165
+ external
166
+ view
167
+ returns (
168
+ bytes1 fields,
169
+ string memory name,
170
+ string memory version,
171
+ uint256 chainId,
172
+ address verifyingContract,
173
+ bytes32 salt,
174
+ uint256[] memory extensions
175
+ );
176
+ }
177
+
178
+ // packages/protocol-rewards/src/lib/Math.sol
179
+
180
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
181
+
182
+ /**
183
+ * @dev Standard math utilities missing in the Solidity language.
184
+ */
185
+ library Math {
186
+ enum Rounding {
187
+ Down, // Toward negative infinity
188
+ Up, // Toward infinity
189
+ Zero // Toward zero
190
+ }
191
+
192
+ /**
193
+ * @dev Returns the largest of two numbers.
194
+ */
195
+ function max(uint256 a, uint256 b) internal pure returns (uint256) {
196
+ return a > b ? a : b;
197
+ }
198
+
199
+ /**
200
+ * @dev Returns the smallest of two numbers.
201
+ */
202
+ function min(uint256 a, uint256 b) internal pure returns (uint256) {
203
+ return a < b ? a : b;
204
+ }
205
+
206
+ /**
207
+ * @dev Returns the average of two numbers. The result is rounded towards
208
+ * zero.
209
+ */
210
+ function average(uint256 a, uint256 b) internal pure returns (uint256) {
211
+ // (a + b) / 2 can overflow.
212
+ return (a & b) + (a ^ b) / 2;
213
+ }
214
+
215
+ /**
216
+ * @dev Returns the ceiling of the division of two numbers.
217
+ *
218
+ * This differs from standard division with `/` in that it rounds up instead
219
+ * of rounding down.
220
+ */
221
+ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
222
+ // (a + b - 1) / b can overflow on addition, so we distribute.
223
+ return a == 0 ? 0 : (a - 1) / b + 1;
224
+ }
225
+
226
+ /**
227
+ * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
228
+ * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
229
+ * with further edits by Uniswap Labs also under MIT license.
230
+ */
231
+ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
232
+ unchecked {
233
+ // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
234
+ // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
235
+ // variables such that product = prod1 * 2^256 + prod0.
236
+ uint256 prod0; // Least significant 256 bits of the product
237
+ uint256 prod1; // Most significant 256 bits of the product
238
+ assembly {
239
+ let mm := mulmod(x, y, not(0))
240
+ prod0 := mul(x, y)
241
+ prod1 := sub(sub(mm, prod0), lt(mm, prod0))
242
+ }
243
+
244
+ // Handle non-overflow cases, 256 by 256 division.
245
+ if (prod1 == 0) {
246
+ // Solidity will revert if denominator == 0, unlike the div opcode on its own.
247
+ // The surrounding unchecked block does not change this fact.
248
+ // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
249
+ return prod0 / denominator;
250
+ }
251
+
252
+ // Make sure the result is less than 2^256. Also prevents denominator == 0.
253
+ require(denominator > prod1, "Math: mulDiv overflow");
254
+
255
+ ///////////////////////////////////////////////
256
+ // 512 by 256 division.
257
+ ///////////////////////////////////////////////
258
+
259
+ // Make division exact by subtracting the remainder from [prod1 prod0].
260
+ uint256 remainder;
261
+ assembly {
262
+ // Compute remainder using mulmod.
263
+ remainder := mulmod(x, y, denominator)
264
+
265
+ // Subtract 256 bit number from 512 bit number.
266
+ prod1 := sub(prod1, gt(remainder, prod0))
267
+ prod0 := sub(prod0, remainder)
268
+ }
269
+
270
+ // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
271
+ // See https://cs.stackexchange.com/q/138556/92363.
272
+
273
+ // Does not overflow because the denominator cannot be zero at this stage in the function.
274
+ uint256 twos = denominator & (~denominator + 1);
275
+ assembly {
276
+ // Divide denominator by twos.
277
+ denominator := div(denominator, twos)
278
+
279
+ // Divide [prod1 prod0] by twos.
280
+ prod0 := div(prod0, twos)
281
+
282
+ // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
283
+ twos := add(div(sub(0, twos), twos), 1)
284
+ }
285
+
286
+ // Shift in bits from prod1 into prod0.
287
+ prod0 |= prod1 * twos;
288
+
289
+ // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
290
+ // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
291
+ // four bits. That is, denominator * inv = 1 mod 2^4.
292
+ uint256 inverse = (3 * denominator) ^ 2;
293
+
294
+ // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
295
+ // in modular arithmetic, doubling the correct bits in each step.
296
+ inverse *= 2 - denominator * inverse; // inverse mod 2^8
297
+ inverse *= 2 - denominator * inverse; // inverse mod 2^16
298
+ inverse *= 2 - denominator * inverse; // inverse mod 2^32
299
+ inverse *= 2 - denominator * inverse; // inverse mod 2^64
300
+ inverse *= 2 - denominator * inverse; // inverse mod 2^128
301
+ inverse *= 2 - denominator * inverse; // inverse mod 2^256
302
+
303
+ // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
304
+ // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
305
+ // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
306
+ // is no longer required.
307
+ result = prod0 * inverse;
308
+ return result;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
314
+ */
315
+ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
316
+ uint256 result = mulDiv(x, y, denominator);
317
+ if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
318
+ result += 1;
319
+ }
320
+ return result;
321
+ }
322
+
323
+ /**
324
+ * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
325
+ *
326
+ * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
327
+ */
328
+ function sqrt(uint256 a) internal pure returns (uint256) {
329
+ if (a == 0) {
330
+ return 0;
331
+ }
332
+
333
+ // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
334
+ //
335
+ // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
336
+ // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
337
+ //
338
+ // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
339
+ // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
340
+ // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
341
+ //
342
+ // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
343
+ uint256 result = 1 << (log2(a) >> 1);
344
+
345
+ // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
346
+ // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
347
+ // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
348
+ // into the expected uint128 result.
349
+ unchecked {
350
+ result = (result + a / result) >> 1;
351
+ result = (result + a / result) >> 1;
352
+ result = (result + a / result) >> 1;
353
+ result = (result + a / result) >> 1;
354
+ result = (result + a / result) >> 1;
355
+ result = (result + a / result) >> 1;
356
+ result = (result + a / result) >> 1;
357
+ return min(result, a / result);
358
+ }
359
+ }
360
+
361
+ /**
362
+ * @notice Calculates sqrt(a), following the selected rounding direction.
363
+ */
364
+ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
365
+ unchecked {
366
+ uint256 result = sqrt(a);
367
+ return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
368
+ }
369
+ }
370
+
371
+ /**
372
+ * @dev Return the log in base 2, rounded down, of a positive value.
373
+ * Returns 0 if given 0.
374
+ */
375
+ function log2(uint256 value) internal pure returns (uint256) {
376
+ uint256 result = 0;
377
+ unchecked {
378
+ if (value >> 128 > 0) {
379
+ value >>= 128;
380
+ result += 128;
381
+ }
382
+ if (value >> 64 > 0) {
383
+ value >>= 64;
384
+ result += 64;
385
+ }
386
+ if (value >> 32 > 0) {
387
+ value >>= 32;
388
+ result += 32;
389
+ }
390
+ if (value >> 16 > 0) {
391
+ value >>= 16;
392
+ result += 16;
393
+ }
394
+ if (value >> 8 > 0) {
395
+ value >>= 8;
396
+ result += 8;
397
+ }
398
+ if (value >> 4 > 0) {
399
+ value >>= 4;
400
+ result += 4;
401
+ }
402
+ if (value >> 2 > 0) {
403
+ value >>= 2;
404
+ result += 2;
405
+ }
406
+ if (value >> 1 > 0) {
407
+ result += 1;
408
+ }
409
+ }
410
+ return result;
411
+ }
412
+
413
+ /**
414
+ * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
415
+ * Returns 0 if given 0.
416
+ */
417
+ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
418
+ unchecked {
419
+ uint256 result = log2(value);
420
+ return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
421
+ }
422
+ }
423
+
424
+ /**
425
+ * @dev Return the log in base 10, rounded down, of a positive value.
426
+ * Returns 0 if given 0.
427
+ */
428
+ function log10(uint256 value) internal pure returns (uint256) {
429
+ uint256 result = 0;
430
+ unchecked {
431
+ if (value >= 10 ** 64) {
432
+ value /= 10 ** 64;
433
+ result += 64;
434
+ }
435
+ if (value >= 10 ** 32) {
436
+ value /= 10 ** 32;
437
+ result += 32;
438
+ }
439
+ if (value >= 10 ** 16) {
440
+ value /= 10 ** 16;
441
+ result += 16;
442
+ }
443
+ if (value >= 10 ** 8) {
444
+ value /= 10 ** 8;
445
+ result += 8;
446
+ }
447
+ if (value >= 10 ** 4) {
448
+ value /= 10 ** 4;
449
+ result += 4;
450
+ }
451
+ if (value >= 10 ** 2) {
452
+ value /= 10 ** 2;
453
+ result += 2;
454
+ }
455
+ if (value >= 10 ** 1) {
456
+ result += 1;
457
+ }
458
+ }
459
+ return result;
460
+ }
461
+
462
+ /**
463
+ * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
464
+ * Returns 0 if given 0.
465
+ */
466
+ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
467
+ unchecked {
468
+ uint256 result = log10(value);
469
+ return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
470
+ }
471
+ }
472
+
473
+ /**
474
+ * @dev Return the log in base 256, rounded down, of a positive value.
475
+ * Returns 0 if given 0.
476
+ *
477
+ * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
478
+ */
479
+ function log256(uint256 value) internal pure returns (uint256) {
480
+ uint256 result = 0;
481
+ unchecked {
482
+ if (value >> 128 > 0) {
483
+ value >>= 128;
484
+ result += 16;
485
+ }
486
+ if (value >> 64 > 0) {
487
+ value >>= 64;
488
+ result += 8;
489
+ }
490
+ if (value >> 32 > 0) {
491
+ value >>= 32;
492
+ result += 4;
493
+ }
494
+ if (value >> 16 > 0) {
495
+ value >>= 16;
496
+ result += 2;
497
+ }
498
+ if (value >> 8 > 0) {
499
+ result += 1;
500
+ }
501
+ }
502
+ return result;
503
+ }
504
+
505
+ /**
506
+ * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
507
+ * Returns 0 if given 0.
508
+ */
509
+ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
510
+ unchecked {
511
+ uint256 result = log256(value);
512
+ return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
513
+ }
514
+ }
515
+ }
516
+
517
+ // packages/protocol-rewards/src/lib/SignedMath.sol
518
+
519
+ // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
520
+
521
+ /**
522
+ * @dev Standard signed math utilities missing in the Solidity language.
523
+ */
524
+ library SignedMath {
525
+ /**
526
+ * @dev Returns the largest of two signed numbers.
527
+ */
528
+ function max(int256 a, int256 b) internal pure returns (int256) {
529
+ return a > b ? a : b;
530
+ }
531
+
532
+ /**
533
+ * @dev Returns the smallest of two signed numbers.
534
+ */
535
+ function min(int256 a, int256 b) internal pure returns (int256) {
536
+ return a < b ? a : b;
537
+ }
538
+
539
+ /**
540
+ * @dev Returns the average of two signed numbers without overflow.
541
+ * The result is rounded towards zero.
542
+ */
543
+ function average(int256 a, int256 b) internal pure returns (int256) {
544
+ // Formula from the book "Hacker's Delight"
545
+ int256 x = (a & b) + ((a ^ b) >> 1);
546
+ return x + (int256(uint256(x) >> 255) & (a ^ b));
547
+ }
548
+
549
+ /**
550
+ * @dev Returns the absolute unsigned value of a signed value.
551
+ */
552
+ function abs(int256 n) internal pure returns (uint256) {
553
+ unchecked {
554
+ // must be unchecked in order to support `n = type(int256).min`
555
+ return uint256(n >= 0 ? n : -n);
556
+ }
557
+ }
558
+ }
559
+
560
+ // packages/protocol-rewards/src/lib/StorageSlot.sol
561
+
562
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
563
+ // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
564
+
565
+ /**
566
+ * @dev Library for reading and writing primitive types to specific storage slots.
567
+ *
568
+ * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
569
+ * This library helps with reading and writing to such slots without the need for inline assembly.
570
+ *
571
+ * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
572
+ *
573
+ * Example usage to set ERC1967 implementation slot:
574
+ * ```solidity
575
+ * contract ERC1967 {
576
+ * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
577
+ *
578
+ * function _getImplementation() internal view returns (address) {
579
+ * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
580
+ * }
581
+ *
582
+ * function _setImplementation(address newImplementation) internal {
583
+ * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
584
+ * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
585
+ * }
586
+ * }
587
+ * ```
588
+ *
589
+ * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
590
+ * _Available since v4.9 for `string`, `bytes`._
591
+ */
592
+ library StorageSlot {
593
+ struct AddressSlot {
594
+ address value;
595
+ }
596
+
597
+ struct BooleanSlot {
598
+ bool value;
599
+ }
600
+
601
+ struct Bytes32Slot {
602
+ bytes32 value;
603
+ }
604
+
605
+ struct Uint256Slot {
606
+ uint256 value;
607
+ }
608
+
609
+ struct StringSlot {
610
+ string value;
611
+ }
612
+
613
+ struct BytesSlot {
614
+ bytes value;
615
+ }
616
+
617
+ /**
618
+ * @dev Returns an `AddressSlot` with member `value` located at `slot`.
619
+ */
620
+ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
621
+ /// @solidity memory-safe-assembly
622
+ assembly {
623
+ r.slot := slot
624
+ }
625
+ }
626
+
627
+ /**
628
+ * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
629
+ */
630
+ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
631
+ /// @solidity memory-safe-assembly
632
+ assembly {
633
+ r.slot := slot
634
+ }
635
+ }
636
+
637
+ /**
638
+ * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
639
+ */
640
+ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
641
+ /// @solidity memory-safe-assembly
642
+ assembly {
643
+ r.slot := slot
644
+ }
645
+ }
646
+
647
+ /**
648
+ * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
649
+ */
650
+ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
651
+ /// @solidity memory-safe-assembly
652
+ assembly {
653
+ r.slot := slot
654
+ }
655
+ }
656
+
657
+ /**
658
+ * @dev Returns an `StringSlot` with member `value` located at `slot`.
659
+ */
660
+ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
661
+ /// @solidity memory-safe-assembly
662
+ assembly {
663
+ r.slot := slot
664
+ }
665
+ }
666
+
667
+ /**
668
+ * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
669
+ */
670
+ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
671
+ /// @solidity memory-safe-assembly
672
+ assembly {
673
+ r.slot := store.slot
674
+ }
675
+ }
676
+
677
+ /**
678
+ * @dev Returns an `BytesSlot` with member `value` located at `slot`.
679
+ */
680
+ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
681
+ /// @solidity memory-safe-assembly
682
+ assembly {
683
+ r.slot := slot
684
+ }
685
+ }
686
+
687
+ /**
688
+ * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
689
+ */
690
+ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
691
+ /// @solidity memory-safe-assembly
692
+ assembly {
693
+ r.slot := store.slot
694
+ }
695
+ }
696
+ }
697
+
698
+ // packages/protocol-rewards/src/lib/ShortStrings.sol
699
+
700
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
701
+
702
+ // | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
703
+ // | length | 0x BB |
704
+ type ShortString is bytes32;
705
+
706
+ /**
707
+ * @dev This library provides functions to convert short memory strings
708
+ * into a `ShortString` type that can be used as an immutable variable.
709
+ *
710
+ * Strings of arbitrary length can be optimized using this library if
711
+ * they are short enough (up to 31 bytes) by packing them with their
712
+ * length (1 byte) in a single EVM word (32 bytes). Additionally, a
713
+ * fallback mechanism can be used for every other case.
714
+ *
715
+ * Usage example:
716
+ *
717
+ * ```solidity
718
+ * contract Named {
719
+ * using ShortStrings for *;
720
+ *
721
+ * ShortString private immutable _name;
722
+ * string private _nameFallback;
723
+ *
724
+ * constructor(string memory contractName) {
725
+ * _name = contractName.toShortStringWithFallback(_nameFallback);
726
+ * }
727
+ *
728
+ * function name() external view returns (string memory) {
729
+ * return _name.toStringWithFallback(_nameFallback);
730
+ * }
731
+ * }
732
+ * ```
733
+ */
734
+ library ShortStrings {
735
+ // Used as an identifier for strings longer than 31 bytes.
736
+ bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
737
+
738
+ error StringTooLong(string str);
739
+ error InvalidShortString();
740
+
741
+ /**
742
+ * @dev Encode a string of at most 31 chars into a `ShortString`.
743
+ *
744
+ * This will trigger a `StringTooLong` error is the input string is too long.
745
+ */
746
+ function toShortString(string memory str) internal pure returns (ShortString) {
747
+ bytes memory bstr = bytes(str);
748
+ if (bstr.length > 31) {
749
+ revert StringTooLong(str);
750
+ }
751
+ return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
752
+ }
753
+
754
+ /**
755
+ * @dev Decode a `ShortString` back to a "normal" string.
756
+ */
757
+ function toString(ShortString sstr) internal pure returns (string memory) {
758
+ uint256 len = byteLength(sstr);
759
+ // using `new string(len)` would work locally but is not memory safe.
760
+ string memory str = new string(32);
761
+ /// @solidity memory-safe-assembly
762
+ assembly {
763
+ mstore(str, len)
764
+ mstore(add(str, 0x20), sstr)
765
+ }
766
+ return str;
767
+ }
768
+
769
+ /**
770
+ * @dev Return the length of a `ShortString`.
771
+ */
772
+ function byteLength(ShortString sstr) internal pure returns (uint256) {
773
+ uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
774
+ if (result > 31) {
775
+ revert InvalidShortString();
776
+ }
777
+ return result;
778
+ }
779
+
780
+ /**
781
+ * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
782
+ */
783
+ function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
784
+ if (bytes(value).length < 32) {
785
+ return toShortString(value);
786
+ } else {
787
+ StorageSlot.getStringSlot(store).value = value;
788
+ return ShortString.wrap(_FALLBACK_SENTINEL);
789
+ }
790
+ }
791
+
792
+ /**
793
+ * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
794
+ */
795
+ function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
796
+ if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
797
+ return toString(value);
798
+ } else {
799
+ return store;
800
+ }
801
+ }
802
+
803
+ /**
804
+ * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
805
+ *
806
+ * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
807
+ * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
808
+ */
809
+ function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
810
+ if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
811
+ return byteLength(value);
812
+ } else {
813
+ return bytes(store).length;
814
+ }
815
+ }
816
+ }
817
+
818
+ // packages/protocol-rewards/src/lib/Strings.sol
819
+
820
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
821
+
822
+ /**
823
+ * @dev String operations.
824
+ */
825
+ library Strings {
826
+ bytes16 private constant _SYMBOLS = "0123456789abcdef";
827
+ uint8 private constant _ADDRESS_LENGTH = 20;
828
+
829
+ /**
830
+ * @dev Converts a `uint256` to its ASCII `string` decimal representation.
831
+ */
832
+ function toString(uint256 value) internal pure returns (string memory) {
833
+ unchecked {
834
+ uint256 length = Math.log10(value) + 1;
835
+ string memory buffer = new string(length);
836
+ uint256 ptr;
837
+ /// @solidity memory-safe-assembly
838
+ assembly {
839
+ ptr := add(buffer, add(32, length))
840
+ }
841
+ while (true) {
842
+ ptr--;
843
+ /// @solidity memory-safe-assembly
844
+ assembly {
845
+ mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
846
+ }
847
+ value /= 10;
848
+ if (value == 0) break;
849
+ }
850
+ return buffer;
851
+ }
852
+ }
853
+
854
+ /**
855
+ * @dev Converts a `int256` to its ASCII `string` decimal representation.
856
+ */
857
+ function toString(int256 value) internal pure returns (string memory) {
858
+ return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
859
+ }
860
+
861
+ /**
862
+ * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
863
+ */
864
+ function toHexString(uint256 value) internal pure returns (string memory) {
865
+ unchecked {
866
+ return toHexString(value, Math.log256(value) + 1);
867
+ }
868
+ }
869
+
870
+ /**
871
+ * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
872
+ */
873
+ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
874
+ bytes memory buffer = new bytes(2 * length + 2);
875
+ buffer[0] = "0";
876
+ buffer[1] = "x";
877
+ for (uint256 i = 2 * length + 1; i > 1; --i) {
878
+ buffer[i] = _SYMBOLS[value & 0xf];
879
+ value >>= 4;
880
+ }
881
+ require(value == 0, "Strings: hex length insufficient");
882
+ return string(buffer);
883
+ }
884
+
885
+ /**
886
+ * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
887
+ */
888
+ function toHexString(address addr) internal pure returns (string memory) {
889
+ return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
890
+ }
891
+
892
+ /**
893
+ * @dev Returns true if the two strings are equal.
894
+ */
895
+ function equal(string memory a, string memory b) internal pure returns (bool) {
896
+ return keccak256(bytes(a)) == keccak256(bytes(b));
897
+ }
898
+ }
899
+
900
+ // packages/protocol-rewards/src/lib/ECDSA.sol
901
+
902
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
903
+
904
+ /**
905
+ * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
906
+ *
907
+ * These functions can be used to verify that a message was signed by the holder
908
+ * of the private keys of a given address.
909
+ */
910
+ library ECDSA {
911
+ enum RecoverError {
912
+ NoError,
913
+ InvalidSignature,
914
+ InvalidSignatureLength,
915
+ InvalidSignatureS,
916
+ InvalidSignatureV // Deprecated in v4.8
917
+ }
918
+
919
+ function _throwError(RecoverError error) private pure {
920
+ if (error == RecoverError.NoError) {
921
+ return; // no error: do nothing
922
+ } else if (error == RecoverError.InvalidSignature) {
923
+ revert("ECDSA: invalid signature");
924
+ } else if (error == RecoverError.InvalidSignatureLength) {
925
+ revert("ECDSA: invalid signature length");
926
+ } else if (error == RecoverError.InvalidSignatureS) {
927
+ revert("ECDSA: invalid signature 's' value");
928
+ }
929
+ }
930
+
931
+ /**
932
+ * @dev Returns the address that signed a hashed message (`hash`) with
933
+ * `signature` or error string. This address can then be used for verification purposes.
934
+ *
935
+ * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
936
+ * this function rejects them by requiring the `s` value to be in the lower
937
+ * half order, and the `v` value to be either 27 or 28.
938
+ *
939
+ * IMPORTANT: `hash` _must_ be the result of a hash operation for the
940
+ * verification to be secure: it is possible to craft signatures that
941
+ * recover to arbitrary addresses for non-hashed data. A safe way to ensure
942
+ * this is by receiving a hash of the original message (which may otherwise
943
+ * be too long), and then calling {toEthSignedMessageHash} on it.
944
+ *
945
+ * Documentation for signature generation:
946
+ * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
947
+ * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
948
+ *
949
+ * _Available since v4.3._
950
+ */
951
+ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
952
+ if (signature.length == 65) {
953
+ bytes32 r;
954
+ bytes32 s;
955
+ uint8 v;
956
+ // ecrecover takes the signature parameters, and the only way to get them
957
+ // currently is to use assembly.
958
+ /// @solidity memory-safe-assembly
959
+ assembly {
960
+ r := mload(add(signature, 0x20))
961
+ s := mload(add(signature, 0x40))
962
+ v := byte(0, mload(add(signature, 0x60)))
963
+ }
964
+ return tryRecover(hash, v, r, s);
965
+ } else {
966
+ return (address(0), RecoverError.InvalidSignatureLength);
967
+ }
968
+ }
969
+
970
+ /**
971
+ * @dev Returns the address that signed a hashed message (`hash`) with
972
+ * `signature`. This address can then be used for verification purposes.
973
+ *
974
+ * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
975
+ * this function rejects them by requiring the `s` value to be in the lower
976
+ * half order, and the `v` value to be either 27 or 28.
977
+ *
978
+ * IMPORTANT: `hash` _must_ be the result of a hash operation for the
979
+ * verification to be secure: it is possible to craft signatures that
980
+ * recover to arbitrary addresses for non-hashed data. A safe way to ensure
981
+ * this is by receiving a hash of the original message (which may otherwise
982
+ * be too long), and then calling {toEthSignedMessageHash} on it.
983
+ */
984
+ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
985
+ (address recovered, RecoverError error) = tryRecover(hash, signature);
986
+ _throwError(error);
987
+ return recovered;
988
+ }
989
+
990
+ /**
991
+ * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
992
+ *
993
+ * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
994
+ *
995
+ * _Available since v4.3._
996
+ */
997
+ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
998
+ bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
999
+ uint8 v = uint8((uint256(vs) >> 255) + 27);
1000
+ return tryRecover(hash, v, r, s);
1001
+ }
1002
+
1003
+ /**
1004
+ * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
1005
+ *
1006
+ * _Available since v4.2._
1007
+ */
1008
+ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
1009
+ (address recovered, RecoverError error) = tryRecover(hash, r, vs);
1010
+ _throwError(error);
1011
+ return recovered;
1012
+ }
1013
+
1014
+ /**
1015
+ * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
1016
+ * `r` and `s` signature fields separately.
1017
+ *
1018
+ * _Available since v4.3._
1019
+ */
1020
+ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
1021
+ // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
1022
+ // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
1023
+ // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
1024
+ // signatures from current libraries generate a unique signature with an s-value in the lower half order.
1025
+ //
1026
+ // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
1027
+ // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
1028
+ // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
1029
+ // these malleable signatures as well.
1030
+ if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
1031
+ return (address(0), RecoverError.InvalidSignatureS);
1032
+ }
1033
+
1034
+ // If the signature is valid (and not malleable), return the signer address
1035
+ address signer = ecrecover(hash, v, r, s);
1036
+ if (signer == address(0)) {
1037
+ return (address(0), RecoverError.InvalidSignature);
1038
+ }
1039
+
1040
+ return (signer, RecoverError.NoError);
1041
+ }
1042
+
1043
+ /**
1044
+ * @dev Overload of {ECDSA-recover} that receives the `v`,
1045
+ * `r` and `s` signature fields separately.
1046
+ */
1047
+ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
1048
+ (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
1049
+ _throwError(error);
1050
+ return recovered;
1051
+ }
1052
+
1053
+ /**
1054
+ * @dev Returns an Ethereum Signed Message, created from a `hash`. This
1055
+ * produces hash corresponding to the one signed with the
1056
+ * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
1057
+ * JSON-RPC method as part of EIP-191.
1058
+ *
1059
+ * See {recover}.
1060
+ */
1061
+ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
1062
+ // 32 is the length in bytes of hash,
1063
+ // enforced by the type signature above
1064
+ /// @solidity memory-safe-assembly
1065
+ assembly {
1066
+ mstore(0x00, "\x19Ethereum Signed Message:\n32")
1067
+ mstore(0x1c, hash)
1068
+ message := keccak256(0x00, 0x3c)
1069
+ }
1070
+ }
1071
+
1072
+ /**
1073
+ * @dev Returns an Ethereum Signed Message, created from `s`. This
1074
+ * produces hash corresponding to the one signed with the
1075
+ * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
1076
+ * JSON-RPC method as part of EIP-191.
1077
+ *
1078
+ * See {recover}.
1079
+ */
1080
+ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
1081
+ return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
1082
+ }
1083
+
1084
+ /**
1085
+ * @dev Returns an Ethereum Signed Typed Data, created from a
1086
+ * `domainSeparator` and a `structHash`. This produces hash corresponding
1087
+ * to the one signed with the
1088
+ * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
1089
+ * JSON-RPC method as part of EIP-712.
1090
+ *
1091
+ * See {recover}.
1092
+ */
1093
+ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
1094
+ /// @solidity memory-safe-assembly
1095
+ assembly {
1096
+ let ptr := mload(0x40)
1097
+ mstore(ptr, "\x19\x01")
1098
+ mstore(add(ptr, 0x02), domainSeparator)
1099
+ mstore(add(ptr, 0x22), structHash)
1100
+ data := keccak256(ptr, 0x42)
1101
+ }
1102
+ }
1103
+
1104
+ /**
1105
+ * @dev Returns an Ethereum Signed Data with intended validator, created from a
1106
+ * `validator` and `data` according to the version 0 of EIP-191.
1107
+ *
1108
+ * See {recover}.
1109
+ */
1110
+ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
1111
+ return keccak256(abi.encodePacked("\x19\x00", validator, data));
1112
+ }
1113
+ }
1114
+
1115
+ // packages/protocol-rewards/src/lib/EIP712.sol
1116
+
1117
+ // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
1118
+
1119
+ /**
1120
+ * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
1121
+ *
1122
+ * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
1123
+ * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
1124
+ * they need in their contracts using a combination of `abi.encode` and `keccak256`.
1125
+ *
1126
+ * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
1127
+ * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
1128
+ * ({_hashTypedDataV4}).
1129
+ *
1130
+ * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
1131
+ * the chain id to protect against replay attacks on an eventual fork of the chain.
1132
+ *
1133
+ * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
1134
+ * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
1135
+ *
1136
+ * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
1137
+ * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
1138
+ * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
1139
+ *
1140
+ * _Available since v3.4._
1141
+ *
1142
+ * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
1143
+ */
1144
+ abstract contract EIP712 is IERC5267 {
1145
+ using ShortStrings for *;
1146
+
1147
+ bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
1148
+
1149
+ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
1150
+ // invalidate the cached domain separator if the chain id changes.
1151
+ bytes32 private immutable _cachedDomainSeparator;
1152
+ uint256 private immutable _cachedChainId;
1153
+ address private immutable _cachedThis;
1154
+
1155
+ bytes32 private immutable _hashedName;
1156
+ bytes32 private immutable _hashedVersion;
1157
+
1158
+ ShortString private immutable _name;
1159
+ ShortString private immutable _version;
1160
+ string private _nameFallback;
1161
+ string private _versionFallback;
1162
+
1163
+ /**
1164
+ * @dev Initializes the domain separator and parameter caches.
1165
+ *
1166
+ * The meaning of `name` and `version` is specified in
1167
+ * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
1168
+ *
1169
+ * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
1170
+ * - `version`: the current major version of the signing domain.
1171
+ *
1172
+ * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
1173
+ * contract upgrade].
1174
+ */
1175
+ constructor(string memory name, string memory version) {
1176
+ _name = name.toShortStringWithFallback(_nameFallback);
1177
+ _version = version.toShortStringWithFallback(_versionFallback);
1178
+ _hashedName = keccak256(bytes(name));
1179
+ _hashedVersion = keccak256(bytes(version));
1180
+
1181
+ _cachedChainId = block.chainid;
1182
+ _cachedDomainSeparator = _buildDomainSeparator();
1183
+ _cachedThis = address(this);
1184
+ }
1185
+
1186
+ /**
1187
+ * @dev Returns the domain separator for the current chain.
1188
+ */
1189
+ function _domainSeparatorV4() internal view returns (bytes32) {
1190
+ if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
1191
+ return _cachedDomainSeparator;
1192
+ } else {
1193
+ return _buildDomainSeparator();
1194
+ }
1195
+ }
1196
+
1197
+ function _buildDomainSeparator() private view returns (bytes32) {
1198
+ return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
1199
+ }
1200
+
1201
+ /**
1202
+ * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
1203
+ * function returns the hash of the fully encoded EIP712 message for this domain.
1204
+ *
1205
+ * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
1206
+ *
1207
+ * ```solidity
1208
+ * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
1209
+ * keccak256("Mail(address to,string contents)"),
1210
+ * mailTo,
1211
+ * keccak256(bytes(mailContents))
1212
+ * )));
1213
+ * address signer = ECDSA.recover(digest, signature);
1214
+ * ```
1215
+ */
1216
+ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
1217
+ return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
1218
+ }
1219
+
1220
+ /**
1221
+ * @dev See {EIP-5267}.
1222
+ *
1223
+ * _Available since v4.9._
1224
+ */
1225
+ function eip712Domain()
1226
+ public
1227
+ view
1228
+ virtual
1229
+ override
1230
+ returns (
1231
+ bytes1 fields,
1232
+ string memory name,
1233
+ string memory version,
1234
+ uint256 chainId,
1235
+ address verifyingContract,
1236
+ bytes32 salt,
1237
+ uint256[] memory extensions
1238
+ )
1239
+ {
1240
+ return (
1241
+ hex"0f", // 01111
1242
+ _name.toStringWithFallback(_nameFallback),
1243
+ _version.toStringWithFallback(_versionFallback),
1244
+ block.chainid,
1245
+ address(this),
1246
+ bytes32(0),
1247
+ new uint256[](0)
1248
+ );
1249
+ }
1250
+ }
1251
+
1252
+ // packages/protocol-rewards/src/ProtocolRewards.sol
1253
+
1254
+ /// @title ProtocolRewards
1255
+ /// @notice Manager of deposits & withdrawals for protocol rewards
1256
+ contract ProtocolRewards is Enjoy, IProtocolRewards, EIP712 {
1257
+ /// @notice The EIP-712 typehash for gasless withdraws
1258
+ bytes32 public constant WITHDRAW_TYPEHASH = keccak256("Withdraw(address from,address to,uint256 amount,uint256 nonce,uint256 deadline)");
1259
+
1260
+ /// @notice An account's balance
1261
+ mapping(address => uint256) public balanceOf;
1262
+
1263
+ /// @notice An account's nonce for gasless withdraws
1264
+ mapping(address => uint256) public nonces;
1265
+
1266
+ constructor() payable EIP712("ProtocolRewards", "1") {}
1267
+
1268
+ /// @notice The total amount of ETH held in the contract
1269
+ function totalSupply() external view returns (uint256) {
1270
+ return address(this).balance;
1271
+ }
1272
+
1273
+ /// @notice Generic function to deposit ETH for a recipient, with an optional comment
1274
+ /// @param to Address to deposit to
1275
+ /// @param to Reason system reason for deposit (used for indexing)
1276
+ /// @param comment Optional comment as reason for deposit
1277
+ function deposit(address to, bytes4 reason, string calldata comment) external payable {
1278
+ if (to == address(0)) {
1279
+ revert ADDRESS_ZERO();
1280
+ }
1281
+
1282
+ balanceOf[to] += msg.value;
1283
+
1284
+ emit Deposit(msg.sender, to, reason, msg.value, comment);
1285
+ }
1286
+
1287
+ /// @notice Generic function to deposit ETH for multiple recipients, with an optional comment
1288
+ /// @param recipients recipients to send the amount to, array aligns with amounts
1289
+ /// @param amounts amounts to send to each recipient, array aligns with recipients
1290
+ /// @param reasons optional bytes4 hash for indexing
1291
+ /// @param comment Optional comment to include with mint
1292
+ function depositBatch(address[] calldata recipients, uint256[] calldata amounts, bytes4[] calldata reasons, string calldata comment) external payable {
1293
+ uint256 numRecipients = recipients.length;
1294
+
1295
+ if (numRecipients != amounts.length || numRecipients != reasons.length) {
1296
+ revert ARRAY_LENGTH_MISMATCH();
1297
+ }
1298
+
1299
+ uint256 expectedTotalValue;
1300
+
1301
+ for (uint256 i; i < numRecipients; ) {
1302
+ expectedTotalValue += amounts[i];
1303
+
1304
+ unchecked {
1305
+ ++i;
1306
+ }
1307
+ }
1308
+
1309
+ if (msg.value != expectedTotalValue) {
1310
+ revert INVALID_DEPOSIT();
1311
+ }
1312
+
1313
+ address currentRecipient;
1314
+ uint256 currentAmount;
1315
+
1316
+ for (uint256 i; i < numRecipients; ) {
1317
+ currentRecipient = recipients[i];
1318
+ currentAmount = amounts[i];
1319
+
1320
+ if (currentRecipient == address(0)) {
1321
+ revert ADDRESS_ZERO();
1322
+ }
1323
+
1324
+ balanceOf[currentRecipient] += currentAmount;
1325
+
1326
+ emit Deposit(msg.sender, currentRecipient, reasons[i], currentAmount, comment);
1327
+
1328
+ unchecked {
1329
+ ++i;
1330
+ }
1331
+ }
1332
+ }
1333
+
1334
+ /// @notice Used by Zora ERC-721 & ERC-1155 contracts to deposit protocol rewards
1335
+ /// @param creator Creator for NFT rewards
1336
+ /// @param creatorReward Creator reward amount
1337
+ /// @param createReferral Creator referral
1338
+ /// @param createReferralReward Creator referral reward
1339
+ /// @param mintReferral Mint referral user
1340
+ /// @param mintReferralReward Mint referral amount
1341
+ /// @param firstMinter First minter reward
1342
+ /// @param firstMinterReward First minter reward amount
1343
+ /// @param zora ZORA recipient
1344
+ /// @param zoraReward ZORA amount
1345
+ function depositRewards(
1346
+ address creator,
1347
+ uint256 creatorReward,
1348
+ address createReferral,
1349
+ uint256 createReferralReward,
1350
+ address mintReferral,
1351
+ uint256 mintReferralReward,
1352
+ address firstMinter,
1353
+ uint256 firstMinterReward,
1354
+ address zora,
1355
+ uint256 zoraReward
1356
+ ) external payable {
1357
+ if (msg.value != (creatorReward + createReferralReward + mintReferralReward + firstMinterReward + zoraReward)) {
1358
+ revert INVALID_DEPOSIT();
1359
+ }
1360
+
1361
+ unchecked {
1362
+ if (creator != address(0)) {
1363
+ balanceOf[creator] += creatorReward;
1364
+ }
1365
+ if (createReferral != address(0)) {
1366
+ balanceOf[createReferral] += createReferralReward;
1367
+ }
1368
+ if (mintReferral != address(0)) {
1369
+ balanceOf[mintReferral] += mintReferralReward;
1370
+ }
1371
+ if (firstMinter != address(0)) {
1372
+ balanceOf[firstMinter] += firstMinterReward;
1373
+ }
1374
+ if (zora != address(0)) {
1375
+ balanceOf[zora] += zoraReward;
1376
+ }
1377
+ }
1378
+
1379
+ emit RewardsDeposit(
1380
+ creator,
1381
+ createReferral,
1382
+ mintReferral,
1383
+ firstMinter,
1384
+ zora,
1385
+ msg.sender,
1386
+ creatorReward,
1387
+ createReferralReward,
1388
+ mintReferralReward,
1389
+ firstMinterReward,
1390
+ zoraReward
1391
+ );
1392
+ }
1393
+
1394
+ /// @notice Withdraw protocol rewards
1395
+ /// @param to Withdraws from msg.sender to this address
1396
+ /// @param amount Amount to withdraw (0 for total balance)
1397
+ function withdraw(address to, uint256 amount) external {
1398
+ if (to == address(0)) {
1399
+ revert ADDRESS_ZERO();
1400
+ }
1401
+
1402
+ address owner = msg.sender;
1403
+
1404
+ if (amount > balanceOf[owner]) {
1405
+ revert INVALID_WITHDRAW();
1406
+ }
1407
+
1408
+ if (amount == 0) {
1409
+ amount = balanceOf[owner];
1410
+ }
1411
+
1412
+ balanceOf[owner] -= amount;
1413
+
1414
+ emit Withdraw(owner, to, amount);
1415
+
1416
+ (bool success, ) = to.call{value: amount}("");
1417
+
1418
+ if (!success) {
1419
+ revert TRANSFER_FAILED();
1420
+ }
1421
+ }
1422
+
1423
+ /// @notice Withdraw rewards on behalf of an address
1424
+ /// @param to The address to withdraw for
1425
+ /// @param amount The amount to withdraw (0 for total balance)
1426
+ function withdrawFor(address to, uint256 amount) external {
1427
+ if (to == address(0)) {
1428
+ revert ADDRESS_ZERO();
1429
+ }
1430
+
1431
+ if (amount > balanceOf[to]) {
1432
+ revert INVALID_WITHDRAW();
1433
+ }
1434
+
1435
+ if (amount == 0) {
1436
+ amount = balanceOf[to];
1437
+ }
1438
+
1439
+ balanceOf[to] -= amount;
1440
+
1441
+ emit Withdraw(to, to, amount);
1442
+
1443
+ (bool success, ) = to.call{value: amount}("");
1444
+
1445
+ if (!success) {
1446
+ revert TRANSFER_FAILED();
1447
+ }
1448
+ }
1449
+
1450
+ /// @notice Execute a withdraw of protocol rewards via signature
1451
+ /// @param from Withdraw from this address
1452
+ /// @param to Withdraw to this address
1453
+ /// @param amount Amount to withdraw (0 for total balance)
1454
+ /// @param deadline Deadline for the signature to be valid
1455
+ /// @param v V component of signature
1456
+ /// @param r R component of signature
1457
+ /// @param s S component of signature
1458
+ function withdrawWithSig(address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
1459
+ if (block.timestamp > deadline) {
1460
+ revert SIGNATURE_DEADLINE_EXPIRED();
1461
+ }
1462
+
1463
+ bytes32 withdrawHash;
1464
+
1465
+ unchecked {
1466
+ withdrawHash = keccak256(abi.encode(WITHDRAW_TYPEHASH, from, to, amount, nonces[from]++, deadline));
1467
+ }
1468
+
1469
+ bytes32 digest = _hashTypedDataV4(withdrawHash);
1470
+
1471
+ address recoveredAddress = ecrecover(digest, v, r, s);
1472
+
1473
+ if (recoveredAddress == address(0) || recoveredAddress != from) {
1474
+ revert INVALID_SIGNATURE();
1475
+ }
1476
+
1477
+ if (to == address(0)) {
1478
+ revert ADDRESS_ZERO();
1479
+ }
1480
+
1481
+ if (amount > balanceOf[from]) {
1482
+ revert INVALID_WITHDRAW();
1483
+ }
1484
+
1485
+ if (amount == 0) {
1486
+ amount = balanceOf[from];
1487
+ }
1488
+
1489
+ balanceOf[from] -= amount;
1490
+
1491
+ emit Withdraw(from, to, amount);
1492
+
1493
+ (bool success, ) = to.call{value: amount}("");
1494
+
1495
+ if (!success) {
1496
+ revert TRANSFER_FAILED();
1497
+ }
1498
+ }
1499
+ }