@inco/lightning 0.1.20

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 (50) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +69 -0
  3. package/dumps/incoLightning_0_1_23__547622051.dump.json +1 -0
  4. package/dumps/incoLightning_0_1_23__547622051.env +15 -0
  5. package/dumps/incoLightning_0_1_23__830342853.dump.json +1 -0
  6. package/dumps/incoLightning_0_1_23__830342853.env +15 -0
  7. package/dumps/incoLightning_0_1_24__266705097.dump.json +1 -0
  8. package/dumps/incoLightning_0_1_24__266705097.env +15 -0
  9. package/dumps/incoLightning_0_1_25__986372984.dump.json +1 -0
  10. package/dumps/incoLightning_0_1_25__986372984.env +15 -0
  11. package/foundry.toml +20 -0
  12. package/package.json +27 -0
  13. package/remappings.txt +4 -0
  14. package/src/DeployUtils.sol +109 -0
  15. package/src/IncoLightning.sol +45 -0
  16. package/src/Lib.sol +389 -0
  17. package/src/Lib.template.sol +464 -0
  18. package/src/Types.sol +74 -0
  19. package/src/libs/incoLightning_0_1_22__761766708.sol +389 -0
  20. package/src/libs/incoLightning_0_1_23__547622051.sol +389 -0
  21. package/src/libs/incoLightning_0_1_23__830342853.sol +389 -0
  22. package/src/libs/incoLightning_0_1_24__266705097.sol +389 -0
  23. package/src/libs/incoLightning_0_1_25__986372984.sol +389 -0
  24. package/src/lightning-parts/AccessControl/BaseAccessControlList.sol +105 -0
  25. package/src/lightning-parts/AccessControl/test/TestBaseAccessControl.t.sol +12 -0
  26. package/src/lightning-parts/DecryptionHandler.sol +164 -0
  27. package/src/lightning-parts/EncryptedInput.sol +61 -0
  28. package/src/lightning-parts/EncryptedOperations.sol +610 -0
  29. package/src/lightning-parts/TrivialEncryption.sol +43 -0
  30. package/src/lightning-parts/primitives/EventCounter.sol +32 -0
  31. package/src/lightning-parts/primitives/HandleGeneration.sol +107 -0
  32. package/src/lightning-parts/primitives/HandleMetadata.sol +38 -0
  33. package/src/lightning-parts/primitives/SignatureVerifier.sol +47 -0
  34. package/src/lightning-parts/test/HandleMetadata.t.sol +87 -0
  35. package/src/pasted-dependencies/CreateX.sol +1293 -0
  36. package/src/pasted-dependencies/ICreateX.sol +187 -0
  37. package/src/test/AddTwo.sol +48 -0
  38. package/src/test/FakeIncoInfra/FakeComputeServer.sol +137 -0
  39. package/src/test/FakeIncoInfra/FakeIncoInfraBase.sol +77 -0
  40. package/src/test/FakeIncoInfra/KVStore.sol +35 -0
  41. package/src/test/FakeIncoInfra/MockOpHandler.sol +140 -0
  42. package/src/test/FakeIncoInfra/getOpForSelector.sol +71 -0
  43. package/src/test/IncoTest.sol +48 -0
  44. package/src/test/TestAddTwo.t.sol +31 -0
  45. package/src/test/TestDeploy.t.sol +39 -0
  46. package/src/test/TestExtractDataOfEventTooLarge.t.sol +43 -0
  47. package/src/test/TestFakeInfra.t.sol +301 -0
  48. package/src/test/TestVersion.t.sol +36 -0
  49. package/src/version/IncoLightningConfig.sol +13 -0
  50. package/src/version/Version.sol +76 -0
@@ -0,0 +1,1293 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ pragma solidity ^0.8;
3
+
4
+ // inco note : pasted because importing createx using github forces a solc version we don't use
5
+
6
+ address constant createXAddress = 0xba5Ed099633D3B313e4D5F7bdc1305d3c28ba5Ed;
7
+ address constant createXDeployer = 0xeD456e05CaAb11d66C4c797dD6c1D6f9A7F352b5;
8
+
9
+ /**
10
+ * @title CreateX Factory Smart Contract
11
+ * @author pcaversaccio (https://web.archive.org/web/20230921103111/https://pcaversaccio.com/)
12
+ * @custom:coauthor Matt Solomon (https://web.archive.org/web/20230921103335/https://mattsolomon.dev/)
13
+ * @notice Factory smart contract to make easier and safer usage of the
14
+ * `CREATE` (https://web.archive.org/web/20230921103540/https://www.evm.codes/#f0?fork=shanghai) and `CREATE2`
15
+ * (https://web.archive.org/web/20230921103540/https://www.evm.codes/#f5?fork=shanghai) EVM opcodes as well as of
16
+ * `CREATE3`-based (https://web.archive.org/web/20230921103920/https://github.com/ethereum/EIPs/pull/3171) contract creations.
17
+ * @dev To simplify testing of non-public variables and functions, we use the `internal`
18
+ * function visibility specifier `internal` for all variables and functions, even though
19
+ * they could technically be `private` since we do not expect anyone to inherit from
20
+ * the `CreateX` contract.
21
+ * @custom:security-contact See https://web.archive.org/web/20230921105029/https://raw.githubusercontent.com/pcaversaccio/createx/main/SECURITY.md.
22
+ */
23
+ contract CreateX {
24
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
25
+ /* IMMUTABLES */
26
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
27
+
28
+ /**
29
+ * @dev Caches the contract address at construction, to be used for the custom errors.
30
+ */
31
+ address internal immutable _SELF = address(this);
32
+
33
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
34
+ /* TYPES */
35
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
36
+
37
+ /**
38
+ * @dev Struct for the `payable` amounts in a deploy-and-initialise call.
39
+ */
40
+ struct Values {
41
+ uint256 constructorAmount;
42
+ uint256 initCallAmount;
43
+ }
44
+
45
+ /**
46
+ * @dev Enum for the selection of a permissioned deploy protection.
47
+ */
48
+ enum SenderBytes {
49
+ MsgSender,
50
+ ZeroAddress,
51
+ Random
52
+ }
53
+
54
+ /**
55
+ * @dev Enum for the selection of a cross-chain redeploy protection.
56
+ */
57
+ enum RedeployProtectionFlag {
58
+ True,
59
+ False,
60
+ Unspecified
61
+ }
62
+
63
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
64
+ /* EVENTS */
65
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
66
+
67
+ /**
68
+ * @dev Event that is emitted when a contract is successfully created.
69
+ * @param newContract The address of the new contract.
70
+ * @param salt The 32-byte random value used to create the contract address.
71
+ */
72
+ event ContractCreation(address indexed newContract, bytes32 indexed salt);
73
+
74
+ /**
75
+ * @dev Event that is emitted when a contract is successfully created.
76
+ * @param newContract The address of the new contract.
77
+ */
78
+ event ContractCreation(address indexed newContract);
79
+
80
+ /**
81
+ * @dev Event that is emitted when a `CREATE3` proxy contract is successfully created.
82
+ * @param newContract The address of the new proxy contract.
83
+ * @param salt The 32-byte random value used to create the proxy address.
84
+ */
85
+ event Create3ProxyContractCreation(
86
+ address indexed newContract,
87
+ bytes32 indexed salt
88
+ );
89
+
90
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
91
+ /* CUSTOM ERRORS */
92
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
93
+
94
+ /**
95
+ * @dev Error that occurs when the contract creation failed.
96
+ * @param emitter The contract that emits the error.
97
+ */
98
+ error FailedContractCreation(address emitter);
99
+
100
+ /**
101
+ * @dev Error that occurs when the contract initialisation call failed.
102
+ * @param emitter The contract that emits the error.
103
+ * @param revertData The data returned by the failed initialisation call.
104
+ */
105
+ error FailedContractInitialisation(address emitter, bytes revertData);
106
+
107
+ /**
108
+ * @dev Error that occurs when the salt value is invalid.
109
+ * @param emitter The contract that emits the error.
110
+ */
111
+ error InvalidSalt(address emitter);
112
+
113
+ /**
114
+ * @dev Error that occurs when the nonce value is invalid.
115
+ * @param emitter The contract that emits the error.
116
+ */
117
+ error InvalidNonceValue(address emitter);
118
+
119
+ /**
120
+ * @dev Error that occurs when transferring ether has failed.
121
+ * @param emitter The contract that emits the error.
122
+ * @param revertData The data returned by the failed ether transfer.
123
+ */
124
+ error FailedEtherTransfer(address emitter, bytes revertData);
125
+
126
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
127
+ /* CREATE */
128
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
129
+
130
+ /**
131
+ * @dev Deploys a new contract via calling the `CREATE` opcode and using the creation
132
+ * bytecode `initCode` and `msg.value` as inputs. In order to save deployment costs,
133
+ * we do not sanity check the `initCode` length. Note that if `msg.value` is non-zero,
134
+ * `initCode` must have a `payable` constructor.
135
+ * @param initCode The creation bytecode.
136
+ * @return newContract The 20-byte address where the contract was deployed.
137
+ */
138
+ function deployCreate(
139
+ bytes memory initCode
140
+ ) public payable returns (address newContract) {
141
+ assembly ("memory-safe") {
142
+ newContract := create(
143
+ callvalue(),
144
+ add(initCode, 0x20),
145
+ mload(initCode)
146
+ )
147
+ }
148
+ _requireSuccessfulContractCreation({newContract: newContract});
149
+ emit ContractCreation({newContract: newContract});
150
+ }
151
+
152
+ /**
153
+ * @dev Deploys and initialises a new contract via calling the `CREATE` opcode and using the
154
+ * creation bytecode `initCode`, the initialisation code `data`, the struct for the `payable`
155
+ * amounts `values`, the refund address `refundAddress`, and `msg.value` as inputs. In order to
156
+ * save deployment costs, we do not sanity check the `initCode` length. Note that if `values.constructorAmount`
157
+ * is non-zero, `initCode` must have a `payable` constructor.
158
+ * @param initCode The creation bytecode.
159
+ * @param data The initialisation code that is passed to the deployed contract.
160
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
161
+ * @param refundAddress The 20-byte address where any excess ether is returned to.
162
+ * @return newContract The 20-byte address where the contract was deployed.
163
+ * @custom:security This function allows for reentrancy, however we refrain from adding
164
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
165
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
166
+ */
167
+ function deployCreateAndInit(
168
+ bytes memory initCode,
169
+ bytes memory data,
170
+ Values memory values,
171
+ address refundAddress
172
+ ) public payable returns (address newContract) {
173
+ assembly ("memory-safe") {
174
+ newContract := create(
175
+ mload(values),
176
+ add(initCode, 0x20),
177
+ mload(initCode)
178
+ )
179
+ }
180
+ _requireSuccessfulContractCreation({newContract: newContract});
181
+ emit ContractCreation({newContract: newContract});
182
+
183
+ (bool success, bytes memory returnData) = newContract.call{
184
+ value: values.initCallAmount
185
+ }(data);
186
+ if (!success) {
187
+ revert FailedContractInitialisation({
188
+ emitter: _SELF,
189
+ revertData: returnData
190
+ });
191
+ }
192
+
193
+ if (_SELF.balance != 0) {
194
+ // Any wei amount previously forced into this contract (e.g. by using the `SELFDESTRUCT`
195
+ // opcode) will be part of the refund transaction.
196
+ (success, returnData) = refundAddress.call{value: _SELF.balance}(
197
+ ""
198
+ );
199
+ if (!success) {
200
+ revert FailedEtherTransfer({
201
+ emitter: _SELF,
202
+ revertData: returnData
203
+ });
204
+ }
205
+ }
206
+ }
207
+
208
+ /**
209
+ * @dev Deploys and initialises a new contract via calling the `CREATE` opcode and using the
210
+ * creation bytecode `initCode`, the initialisation code `data`, the struct for the `payable`
211
+ * amounts `values`, and `msg.value` as inputs. In order to save deployment costs, we do not
212
+ * sanity check the `initCode` length. Note that if `values.constructorAmount` is non-zero,
213
+ * `initCode` must have a `payable` constructor, and any excess ether is returned to `msg.sender`.
214
+ * @param initCode The creation bytecode.
215
+ * @param data The initialisation code that is passed to the deployed contract.
216
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
217
+ * @return newContract The 20-byte address where the contract was deployed.
218
+ * @custom:security This function allows for reentrancy, however we refrain from adding
219
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
220
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
221
+ */
222
+ function deployCreateAndInit(
223
+ bytes memory initCode,
224
+ bytes memory data,
225
+ Values memory values
226
+ ) public payable returns (address newContract) {
227
+ newContract = deployCreateAndInit({
228
+ initCode: initCode,
229
+ data: data,
230
+ values: values,
231
+ refundAddress: msg.sender
232
+ });
233
+ }
234
+
235
+ /**
236
+ * @dev Deploys a new EIP-1167 minimal proxy contract using the `CREATE` opcode, and initialises
237
+ * the implementation contract using the implementation address `implementation`, the initialisation
238
+ * code `data`, and `msg.value` as inputs. Note that if `msg.value` is non-zero, the initialiser
239
+ * function called via `data` must be `payable`.
240
+ * @param implementation The 20-byte implementation contract address.
241
+ * @param data The initialisation code that is passed to the deployed proxy contract.
242
+ * @return proxy The 20-byte address where the clone was deployed.
243
+ * @custom:security This function allows for reentrancy, however we refrain from adding
244
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
245
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
246
+ */
247
+ function deployCreateClone(
248
+ address implementation,
249
+ bytes memory data
250
+ ) public payable returns (address proxy) {
251
+ bytes20 implementationInBytes = bytes20(implementation);
252
+ assembly ("memory-safe") {
253
+ let clone := mload(0x40)
254
+ mstore(
255
+ clone,
256
+ hex"3d_60_2d_80_60_0a_3d_39_81_f3_36_3d_3d_37_3d_3d_3d_36_3d_73_00_00_00_00_00_00_00_00_00_00_00_00"
257
+ )
258
+ mstore(add(clone, 0x14), implementationInBytes)
259
+ mstore(
260
+ add(clone, 0x28),
261
+ hex"5a_f4_3d_82_80_3e_90_3d_91_60_2b_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
262
+ )
263
+ proxy := create(0, clone, 0x37)
264
+ }
265
+ if (proxy == address(0)) {
266
+ revert FailedContractCreation({emitter: _SELF});
267
+ }
268
+ emit ContractCreation({newContract: proxy});
269
+
270
+ (bool success, bytes memory returnData) = proxy.call{value: msg.value}(
271
+ data
272
+ );
273
+ _requireSuccessfulContractInitialisation({
274
+ success: success,
275
+ returnData: returnData,
276
+ implementation: implementation
277
+ });
278
+ }
279
+
280
+ /**
281
+ * @dev Returns the address where a contract will be stored if deployed via `deployer` using
282
+ * the `CREATE` opcode. For the specification of the Recursive Length Prefix (RLP) encoding
283
+ * scheme, please refer to p. 19 of the Ethereum Yellow Paper (https://web.archive.org/web/20230921110603/https://ethereum.github.io/yellowpaper/paper.pdf)
284
+ * and the Ethereum Wiki (https://web.archive.org/web/20230921112807/https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/).
285
+ * For further insights also, see the following issue: https://web.archive.org/web/20230921112943/https://github.com/transmissions11/solmate/issues/207.
286
+ *
287
+ * Based on the EIP-161 (https://web.archive.org/web/20230921113207/https://raw.githubusercontent.com/ethereum/EIPs/master/EIPS/eip-161.md) specification,
288
+ * all contract accounts on the Ethereum mainnet are initiated with `nonce = 1`. Thus, the
289
+ * first contract address created by another contract is calculated with a non-zero nonce.
290
+ * @param deployer The 20-byte deployer address.
291
+ * @param nonce The next 32-byte nonce of the deployer address.
292
+ * @return computedAddress The 20-byte address where a contract will be stored.
293
+ */
294
+ function computeCreateAddress(
295
+ address deployer,
296
+ uint256 nonce
297
+ ) public view returns (address computedAddress) {
298
+ bytes memory data;
299
+ bytes1 len = bytes1(0x94);
300
+
301
+ // The theoretical allowed limit, based on EIP-2681, for an account nonce is 2**64-2:
302
+ // https://web.archive.org/web/20230921113252/https://eips.ethereum.org/EIPS/eip-2681.
303
+ if (nonce > type(uint64).max - 1) {
304
+ revert InvalidNonceValue({emitter: _SELF});
305
+ }
306
+
307
+ // The integer zero is treated as an empty byte string and therefore has only one length prefix,
308
+ // 0x80, which is calculated via 0x80 + 0.
309
+ if (nonce == 0x00) {
310
+ data = abi.encodePacked(bytes1(0xd6), len, deployer, bytes1(0x80));
311
+ }
312
+ // A one-byte integer in the [0x00, 0x7f] range uses its own value as a length prefix, there is no
313
+ // additional "0x80 + length" prefix that precedes it.
314
+ else if (nonce <= 0x7f) {
315
+ data = abi.encodePacked(bytes1(0xd6), len, deployer, uint8(nonce));
316
+ }
317
+ // In the case of `nonce > 0x7f` and `nonce <= type(uint8).max`, we have the following encoding scheme
318
+ // (the same calculation can be carried over for higher nonce bytes):
319
+ // 0xda = 0xc0 (short RLP prefix) + 0x1a (= the bytes length of: 0x94 + address + 0x84 + nonce, in hex),
320
+ // 0x94 = 0x80 + 0x14 (= the bytes length of an address, 20 bytes, in hex),
321
+ // 0x84 = 0x80 + 0x04 (= the bytes length of the nonce, 4 bytes, in hex).
322
+ else if (nonce <= type(uint8).max) {
323
+ data = abi.encodePacked(
324
+ bytes1(0xd7),
325
+ len,
326
+ deployer,
327
+ bytes1(0x81),
328
+ uint8(nonce)
329
+ );
330
+ } else if (nonce <= type(uint16).max) {
331
+ data = abi.encodePacked(
332
+ bytes1(0xd8),
333
+ len,
334
+ deployer,
335
+ bytes1(0x82),
336
+ uint16(nonce)
337
+ );
338
+ } else if (nonce <= type(uint24).max) {
339
+ data = abi.encodePacked(
340
+ bytes1(0xd9),
341
+ len,
342
+ deployer,
343
+ bytes1(0x83),
344
+ uint24(nonce)
345
+ );
346
+ } else if (nonce <= type(uint32).max) {
347
+ data = abi.encodePacked(
348
+ bytes1(0xda),
349
+ len,
350
+ deployer,
351
+ bytes1(0x84),
352
+ uint32(nonce)
353
+ );
354
+ } else if (nonce <= type(uint40).max) {
355
+ data = abi.encodePacked(
356
+ bytes1(0xdb),
357
+ len,
358
+ deployer,
359
+ bytes1(0x85),
360
+ uint40(nonce)
361
+ );
362
+ } else if (nonce <= type(uint48).max) {
363
+ data = abi.encodePacked(
364
+ bytes1(0xdc),
365
+ len,
366
+ deployer,
367
+ bytes1(0x86),
368
+ uint48(nonce)
369
+ );
370
+ } else if (nonce <= type(uint56).max) {
371
+ data = abi.encodePacked(
372
+ bytes1(0xdd),
373
+ len,
374
+ deployer,
375
+ bytes1(0x87),
376
+ uint56(nonce)
377
+ );
378
+ } else {
379
+ data = abi.encodePacked(
380
+ bytes1(0xde),
381
+ len,
382
+ deployer,
383
+ bytes1(0x88),
384
+ uint64(nonce)
385
+ );
386
+ }
387
+
388
+ computedAddress = address(uint160(uint256(keccak256(data))));
389
+ }
390
+
391
+ /**
392
+ * @dev Returns the address where a contract will be stored if deployed via this contract
393
+ * using the `CREATE` opcode. For the specification of the Recursive Length Prefix (RLP)
394
+ * encoding scheme, please refer to p. 19 of the Ethereum Yellow Paper (https://web.archive.org/web/20230921110603/https://ethereum.github.io/yellowpaper/paper.pdf)
395
+ * and the Ethereum Wiki (https://web.archive.org/web/20230921112807/https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/).
396
+ * For further insights also, see the following issue: https://web.archive.org/web/20230921112943/https://github.com/transmissions11/solmate/issues/207.
397
+ *
398
+ * Based on the EIP-161 (https://web.archive.org/web/20230921113207/https://raw.githubusercontent.com/ethereum/EIPs/master/EIPS/eip-161.md) specification,
399
+ * all contract accounts on the Ethereum mainnet are initiated with `nonce = 1`. Thus, the
400
+ * first contract address created by another contract is calculated with a non-zero nonce.
401
+ * @param nonce The next 32-byte nonce of this contract.
402
+ * @return computedAddress The 20-byte address where a contract will be stored.
403
+ */
404
+ function computeCreateAddress(
405
+ uint256 nonce
406
+ ) public view returns (address computedAddress) {
407
+ computedAddress = computeCreateAddress({deployer: _SELF, nonce: nonce});
408
+ }
409
+
410
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
411
+ /* CREATE2 */
412
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
413
+
414
+ /**
415
+ * @dev Deploys a new contract via calling the `CREATE2` opcode and using the salt value `salt`,
416
+ * the creation bytecode `initCode`, and `msg.value` as inputs. In order to save deployment costs,
417
+ * we do not sanity check the `initCode` length. Note that if `msg.value` is non-zero, `initCode`
418
+ * must have a `payable` constructor.
419
+ * @param salt The 32-byte random value used to create the contract address.
420
+ * @param initCode The creation bytecode.
421
+ * @return newContract The 20-byte address where the contract was deployed.
422
+ */
423
+ function deployCreate2(
424
+ bytes32 salt,
425
+ bytes memory initCode
426
+ ) public payable returns (address newContract) {
427
+ bytes32 guardedSalt = _guard({salt: salt});
428
+ assembly ("memory-safe") {
429
+ newContract := create2(
430
+ callvalue(),
431
+ add(initCode, 0x20),
432
+ mload(initCode),
433
+ guardedSalt
434
+ )
435
+ }
436
+ _requireSuccessfulContractCreation({newContract: newContract});
437
+ emit ContractCreation({newContract: newContract, salt: guardedSalt});
438
+ }
439
+
440
+ /**
441
+ * @dev Deploys a new contract via calling the `CREATE2` opcode and using the creation bytecode
442
+ * `initCode` and `msg.value` as inputs. The salt value is calculated pseudo-randomly using a
443
+ * diverse selection of block and transaction properties. This approach does not guarantee true
444
+ * randomness! In order to save deployment costs, we do not sanity check the `initCode` length.
445
+ * Note that if `msg.value` is non-zero, `initCode` must have a `payable` constructor.
446
+ * @param initCode The creation bytecode.
447
+ * @return newContract The 20-byte address where the contract was deployed.
448
+ */
449
+ function deployCreate2(
450
+ bytes memory initCode
451
+ ) public payable returns (address newContract) {
452
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
453
+ // `deployCreate2`.
454
+ newContract = deployCreate2({
455
+ salt: _generateSalt(),
456
+ initCode: initCode
457
+ });
458
+ }
459
+
460
+ /**
461
+ * @dev Deploys and initialises a new contract via calling the `CREATE2` opcode and using the
462
+ * salt value `salt`, the creation bytecode `initCode`, the initialisation code `data`, the struct
463
+ * for the `payable` amounts `values`, the refund address `refundAddress`, and `msg.value` as inputs.
464
+ * In order to save deployment costs, we do not sanity check the `initCode` length. Note that if
465
+ * `values.constructorAmount` is non-zero, `initCode` must have a `payable` constructor.
466
+ * @param salt The 32-byte random value used to create the contract address.
467
+ * @param initCode The creation bytecode.
468
+ * @param data The initialisation code that is passed to the deployed contract.
469
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
470
+ * @param refundAddress The 20-byte address where any excess ether is returned to.
471
+ * @return newContract The 20-byte address where the contract was deployed.
472
+ * @custom:security This function allows for reentrancy, however we refrain from adding
473
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
474
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
475
+ */
476
+ function deployCreate2AndInit(
477
+ bytes32 salt,
478
+ bytes memory initCode,
479
+ bytes memory data,
480
+ Values memory values,
481
+ address refundAddress
482
+ ) public payable returns (address newContract) {
483
+ bytes32 guardedSalt = _guard({salt: salt});
484
+ assembly ("memory-safe") {
485
+ newContract := create2(
486
+ mload(values),
487
+ add(initCode, 0x20),
488
+ mload(initCode),
489
+ guardedSalt
490
+ )
491
+ }
492
+ _requireSuccessfulContractCreation({newContract: newContract});
493
+ emit ContractCreation({newContract: newContract, salt: guardedSalt});
494
+
495
+ (bool success, bytes memory returnData) = newContract.call{
496
+ value: values.initCallAmount
497
+ }(data);
498
+ if (!success) {
499
+ revert FailedContractInitialisation({
500
+ emitter: _SELF,
501
+ revertData: returnData
502
+ });
503
+ }
504
+
505
+ if (_SELF.balance != 0) {
506
+ // Any wei amount previously forced into this contract (e.g. by using the `SELFDESTRUCT`
507
+ // opcode) will be part of the refund transaction.
508
+ (success, returnData) = refundAddress.call{value: _SELF.balance}(
509
+ ""
510
+ );
511
+ if (!success) {
512
+ revert FailedEtherTransfer({
513
+ emitter: _SELF,
514
+ revertData: returnData
515
+ });
516
+ }
517
+ }
518
+ }
519
+
520
+ /**
521
+ * @dev Deploys and initialises a new contract via calling the `CREATE2` opcode and using the
522
+ * salt value `salt`, creation bytecode `initCode`, the initialisation code `data`, the struct for
523
+ * the `payable` amounts `values`, and `msg.value` as inputs. In order to save deployment costs,
524
+ * we do not sanity check the `initCode` length. Note that if `values.constructorAmount` is non-zero,
525
+ * `initCode` must have a `payable` constructor, and any excess ether is returned to `msg.sender`.
526
+ * @param salt The 32-byte random value used to create the contract address.
527
+ * @param initCode The creation bytecode.
528
+ * @param data The initialisation code that is passed to the deployed contract.
529
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
530
+ * @return newContract The 20-byte address where the contract was deployed.
531
+ * @custom:security This function allows for reentrancy, however we refrain from adding
532
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
533
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
534
+ */
535
+ function deployCreate2AndInit(
536
+ bytes32 salt,
537
+ bytes memory initCode,
538
+ bytes memory data,
539
+ Values memory values
540
+ ) public payable returns (address newContract) {
541
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
542
+ // `deployCreate2AndInit`.
543
+ newContract = deployCreate2AndInit({
544
+ salt: salt,
545
+ initCode: initCode,
546
+ data: data,
547
+ values: values,
548
+ refundAddress: msg.sender
549
+ });
550
+ }
551
+
552
+ /**
553
+ * @dev Deploys and initialises a new contract via calling the `CREATE2` opcode and using the
554
+ * creation bytecode `initCode`, the initialisation code `data`, the struct for the `payable`
555
+ * amounts `values`, the refund address `refundAddress`, and `msg.value` as inputs. The salt value
556
+ * is calculated pseudo-randomly using a diverse selection of block and transaction properties.
557
+ * This approach does not guarantee true randomness! In order to save deployment costs, we do not
558
+ * sanity check the `initCode` length. Note that if `values.constructorAmount` is non-zero, `initCode`
559
+ * must have a `payable` constructor.
560
+ * @param initCode The creation bytecode.
561
+ * @param data The initialisation code that is passed to the deployed contract.
562
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
563
+ * @param refundAddress The 20-byte address where any excess ether is returned to.
564
+ * @return newContract The 20-byte address where the contract was deployed.
565
+ * @custom:security This function allows for reentrancy, however we refrain from adding
566
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
567
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
568
+ */
569
+ function deployCreate2AndInit(
570
+ bytes memory initCode,
571
+ bytes memory data,
572
+ Values memory values,
573
+ address refundAddress
574
+ ) public payable returns (address newContract) {
575
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
576
+ // `deployCreate2AndInit`.
577
+ newContract = deployCreate2AndInit({
578
+ salt: _generateSalt(),
579
+ initCode: initCode,
580
+ data: data,
581
+ values: values,
582
+ refundAddress: refundAddress
583
+ });
584
+ }
585
+
586
+ /**
587
+ * @dev Deploys and initialises a new contract via calling the `CREATE2` opcode and using the
588
+ * creation bytecode `initCode`, the initialisation code `data`, the struct for the `payable` amounts
589
+ * `values`, and `msg.value` as inputs. The salt value is calculated pseudo-randomly using a
590
+ * diverse selection of block and transaction properties. This approach does not guarantee true
591
+ * randomness! In order to save deployment costs, we do not sanity check the `initCode` length.
592
+ * Note that if `values.constructorAmount` is non-zero, `initCode` must have a `payable` constructor,
593
+ * and any excess ether is returned to `msg.sender`.
594
+ * @param initCode The creation bytecode.
595
+ * @param data The initialisation code that is passed to the deployed contract.
596
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
597
+ * @return newContract The 20-byte address where the contract was deployed.
598
+ * @custom:security This function allows for reentrancy, however we refrain from adding
599
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
600
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
601
+ */
602
+ function deployCreate2AndInit(
603
+ bytes memory initCode,
604
+ bytes memory data,
605
+ Values memory values
606
+ ) public payable returns (address newContract) {
607
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
608
+ // `deployCreate2AndInit`.
609
+ newContract = deployCreate2AndInit({
610
+ salt: _generateSalt(),
611
+ initCode: initCode,
612
+ data: data,
613
+ values: values,
614
+ refundAddress: msg.sender
615
+ });
616
+ }
617
+
618
+ /**
619
+ * @dev Deploys a new EIP-1167 minimal proxy contract using the `CREATE2` opcode and the salt
620
+ * value `salt`, and initialises the implementation contract using the implementation address
621
+ * `implementation`, the initialisation code `data`, and `msg.value` as inputs. Note that if
622
+ * `msg.value` is non-zero, the initialiser function called via `data` must be `payable`.
623
+ * @param salt The 32-byte random value used to create the proxy contract address.
624
+ * @param implementation The 20-byte implementation contract address.
625
+ * @param data The initialisation code that is passed to the deployed proxy contract.
626
+ * @return proxy The 20-byte address where the clone was deployed.
627
+ * @custom:security This function allows for reentrancy, however we refrain from adding
628
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
629
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
630
+ */
631
+ function deployCreate2Clone(
632
+ bytes32 salt,
633
+ address implementation,
634
+ bytes memory data
635
+ ) public payable returns (address proxy) {
636
+ bytes32 guardedSalt = _guard({salt: salt});
637
+ bytes20 implementationInBytes = bytes20(implementation);
638
+ assembly ("memory-safe") {
639
+ let clone := mload(0x40)
640
+ mstore(
641
+ clone,
642
+ hex"3d_60_2d_80_60_0a_3d_39_81_f3_36_3d_3d_37_3d_3d_3d_36_3d_73_00_00_00_00_00_00_00_00_00_00_00_00"
643
+ )
644
+ mstore(add(clone, 0x14), implementationInBytes)
645
+ mstore(
646
+ add(clone, 0x28),
647
+ hex"5a_f4_3d_82_80_3e_90_3d_91_60_2b_57_fd_5b_f3_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00_00"
648
+ )
649
+ proxy := create2(0, clone, 0x37, guardedSalt)
650
+ }
651
+ if (proxy == address(0)) {
652
+ revert FailedContractCreation({emitter: _SELF});
653
+ }
654
+ emit ContractCreation({newContract: proxy, salt: guardedSalt});
655
+
656
+ (bool success, bytes memory returnData) = proxy.call{value: msg.value}(
657
+ data
658
+ );
659
+ _requireSuccessfulContractInitialisation({
660
+ success: success,
661
+ returnData: returnData,
662
+ implementation: implementation
663
+ });
664
+ }
665
+
666
+ /**
667
+ * @dev Deploys a new EIP-1167 minimal proxy contract using the `CREATE2` opcode and the salt
668
+ * value `salt`, and initialises the implementation contract using the implementation address
669
+ * `implementation`, the initialisation code `data`, and `msg.value` as inputs. The salt value is
670
+ * calculated pseudo-randomly using a diverse selection of block and transaction properties. This
671
+ * approach does not guarantee true randomness! Note that if `msg.value` is non-zero, the initialiser
672
+ * function called via `data` must be `payable`.
673
+ * @param implementation The 20-byte implementation contract address.
674
+ * @param data The initialisation code that is passed to the deployed proxy contract.
675
+ * @return proxy The 20-byte address where the clone was deployed.
676
+ * @custom:security This function allows for reentrancy, however we refrain from adding
677
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
678
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
679
+ */
680
+ function deployCreate2Clone(
681
+ address implementation,
682
+ bytes memory data
683
+ ) public payable returns (address proxy) {
684
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
685
+ // `deployCreate2Clone`.
686
+ proxy = deployCreate2Clone({
687
+ salt: _generateSalt(),
688
+ implementation: implementation,
689
+ data: data
690
+ });
691
+ }
692
+
693
+ /**
694
+ * @dev Returns the address where a contract will be stored if deployed via `deployer` using
695
+ * the `CREATE2` opcode. Any change in the `initCodeHash` or `salt` values will result in a new
696
+ * destination address. This implementation is based on OpenZeppelin:
697
+ * https://web.archive.org/web/20230921113703/https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/181d518609a9f006fcb97af63e6952e603cf100e/contracts/utils/Create2.sol.
698
+ * @param salt The 32-byte random value used to create the contract address.
699
+ * @param initCodeHash The 32-byte bytecode digest of the contract creation bytecode.
700
+ * @param deployer The 20-byte deployer address.
701
+ * @return computedAddress The 20-byte address where a contract will be stored.
702
+ */
703
+ function computeCreate2Address(
704
+ bytes32 salt,
705
+ bytes32 initCodeHash,
706
+ address deployer
707
+ ) public pure returns (address computedAddress) {
708
+ assembly ("memory-safe") {
709
+ // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
710
+ // |----------------------|---------------------------------------------------------------------------|
711
+ // | initCodeHash | CCCCCCCCCCCCC...CC |
712
+ // | salt | BBBBBBBBBBBBB...BB |
713
+ // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
714
+ // | 0xFF | FF |
715
+ // |----------------------|---------------------------------------------------------------------------|
716
+ // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
717
+ // | keccak256(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
718
+ let ptr := mload(0x40)
719
+ mstore(add(ptr, 0x40), initCodeHash)
720
+ mstore(add(ptr, 0x20), salt)
721
+ mstore(ptr, deployer)
722
+ let start := add(ptr, 0x0b)
723
+ mstore8(start, 0xff)
724
+ computedAddress := keccak256(start, 85)
725
+ }
726
+ }
727
+
728
+ /**
729
+ * @dev Returns the address where a contract will be stored if deployed via this contract using
730
+ * the `CREATE2` opcode. Any change in the `initCodeHash` or `salt` values will result in a new
731
+ * destination address.
732
+ * @param salt The 32-byte random value used to create the contract address.
733
+ * @param initCodeHash The 32-byte bytecode digest of the contract creation bytecode.
734
+ * @return computedAddress The 20-byte address where a contract will be stored.
735
+ */
736
+ function computeCreate2Address(
737
+ bytes32 salt,
738
+ bytes32 initCodeHash
739
+ ) public view returns (address computedAddress) {
740
+ computedAddress = computeCreate2Address({
741
+ salt: salt,
742
+ initCodeHash: initCodeHash,
743
+ deployer: _SELF
744
+ });
745
+ }
746
+
747
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
748
+ /* CREATE3 */
749
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
750
+
751
+ /**
752
+ * @dev Deploys a new contract via employing the `CREATE3` pattern (i.e. without an initcode
753
+ * factor) and using the salt value `salt`, the creation bytecode `initCode`, and `msg.value`
754
+ * as inputs. In order to save deployment costs, we do not sanity check the `initCode` length.
755
+ * Note that if `msg.value` is non-zero, `initCode` must have a `payable` constructor. This
756
+ * implementation is based on Solmate:
757
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
758
+ * @param salt The 32-byte random value used to create the proxy contract address.
759
+ * @param initCode The creation bytecode.
760
+ * @return newContract The 20-byte address where the contract was deployed.
761
+ * @custom:security We strongly recommend implementing a permissioned deploy protection by setting
762
+ * the first 20 bytes equal to `msg.sender` in the `salt` to prevent maliciously intended frontrun
763
+ * proxy deployments on other chains.
764
+ */
765
+ function deployCreate3(
766
+ bytes32 salt,
767
+ bytes memory initCode
768
+ ) public payable returns (address newContract) {
769
+ bytes32 guardedSalt = _guard({salt: salt});
770
+ bytes
771
+ memory proxyChildBytecode = hex"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3";
772
+ address proxy;
773
+ assembly ("memory-safe") {
774
+ proxy := create2(
775
+ 0,
776
+ add(proxyChildBytecode, 32),
777
+ mload(proxyChildBytecode),
778
+ guardedSalt
779
+ )
780
+ }
781
+ if (proxy == address(0)) {
782
+ revert FailedContractCreation({emitter: _SELF});
783
+ }
784
+ emit Create3ProxyContractCreation({
785
+ newContract: proxy,
786
+ salt: guardedSalt
787
+ });
788
+
789
+ newContract = computeCreate3Address({salt: guardedSalt});
790
+ (bool success, ) = proxy.call{value: msg.value}(initCode);
791
+ _requireSuccessfulContractCreation({
792
+ success: success,
793
+ newContract: newContract
794
+ });
795
+ emit ContractCreation({newContract: newContract});
796
+ }
797
+
798
+ /**
799
+ * @dev Deploys a new contract via employing the `CREATE3` pattern (i.e. without an initcode
800
+ * factor) and using the salt value `salt`, the creation bytecode `initCode`, and `msg.value`
801
+ * as inputs. The salt value is calculated pseudo-randomly using a diverse selection of block
802
+ * and transaction properties. This approach does not guarantee true randomness! In order to save
803
+ * deployment costs, we do not sanity check the `initCode` length. Note that if `msg.value` is
804
+ * non-zero, `initCode` must have a `payable` constructor. This implementation is based on Solmate:
805
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
806
+ * @param initCode The creation bytecode.
807
+ * @return newContract The 20-byte address where the contract was deployed.
808
+ */
809
+ function deployCreate3(
810
+ bytes memory initCode
811
+ ) public payable returns (address newContract) {
812
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
813
+ // `deployCreate3`.
814
+ newContract = deployCreate3({
815
+ salt: _generateSalt(),
816
+ initCode: initCode
817
+ });
818
+ }
819
+
820
+ /**
821
+ * @dev Deploys and initialises a new contract via employing the `CREATE3` pattern (i.e. without
822
+ * an initcode factor) and using the salt value `salt`, the creation bytecode `initCode`, the
823
+ * initialisation code `data`, the struct for the `payable` amounts `values`, the refund address
824
+ * `refundAddress`, and `msg.value` as inputs. In order to save deployment costs, we do not sanity
825
+ * check the `initCode` length. Note that if `values.constructorAmount` is non-zero, `initCode` must
826
+ * have a `payable` constructor. This implementation is based on Solmate:
827
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
828
+ * @param salt The 32-byte random value used to create the proxy contract address.
829
+ * @param initCode The creation bytecode.
830
+ * @param data The initialisation code that is passed to the deployed contract.
831
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
832
+ * @param refundAddress The 20-byte address where any excess ether is returned to.
833
+ * @return newContract The 20-byte address where the contract was deployed.
834
+ * @custom:security This function allows for reentrancy, however we refrain from adding
835
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
836
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
837
+ * Furthermore, we strongly recommend implementing a permissioned deploy protection by setting
838
+ * the first 20 bytes equal to `msg.sender` in the `salt` to prevent maliciously intended frontrun
839
+ * proxy deployments on other chains.
840
+ */
841
+ function deployCreate3AndInit(
842
+ bytes32 salt,
843
+ bytes memory initCode,
844
+ bytes memory data,
845
+ Values memory values,
846
+ address refundAddress
847
+ ) public payable returns (address newContract) {
848
+ bytes32 guardedSalt = _guard({salt: salt});
849
+ bytes
850
+ memory proxyChildBytecode = hex"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3";
851
+ address proxy;
852
+ assembly ("memory-safe") {
853
+ proxy := create2(
854
+ 0,
855
+ add(proxyChildBytecode, 32),
856
+ mload(proxyChildBytecode),
857
+ guardedSalt
858
+ )
859
+ }
860
+ if (proxy == address(0)) {
861
+ revert FailedContractCreation({emitter: _SELF});
862
+ }
863
+ emit Create3ProxyContractCreation({
864
+ newContract: proxy,
865
+ salt: guardedSalt
866
+ });
867
+
868
+ newContract = computeCreate3Address({salt: guardedSalt});
869
+ (bool success, ) = proxy.call{value: values.constructorAmount}(
870
+ initCode
871
+ );
872
+ _requireSuccessfulContractCreation({
873
+ success: success,
874
+ newContract: newContract
875
+ });
876
+ emit ContractCreation({newContract: newContract});
877
+
878
+ bytes memory returnData;
879
+ (success, returnData) = newContract.call{value: values.initCallAmount}(
880
+ data
881
+ );
882
+ if (!success) {
883
+ revert FailedContractInitialisation({
884
+ emitter: _SELF,
885
+ revertData: returnData
886
+ });
887
+ }
888
+
889
+ if (_SELF.balance != 0) {
890
+ // Any wei amount previously forced into this contract (e.g. by using the `SELFDESTRUCT`
891
+ // opcode) will be part of the refund transaction.
892
+ (success, returnData) = refundAddress.call{value: _SELF.balance}(
893
+ ""
894
+ );
895
+ if (!success) {
896
+ revert FailedEtherTransfer({
897
+ emitter: _SELF,
898
+ revertData: returnData
899
+ });
900
+ }
901
+ }
902
+ }
903
+
904
+ /**
905
+ * @dev Deploys and initialises a new contract via employing the `CREATE3` pattern (i.e. without
906
+ * an initcode factor) and using the salt value `salt`, the creation bytecode `initCode`, the
907
+ * initialisation code `data`, the struct for the `payable` amounts `values`, and `msg.value` as
908
+ * inputs. In order to save deployment costs, we do not sanity check the `initCode` length. Note
909
+ * that if `values.constructorAmount` is non-zero, `initCode` must have a `payable` constructor,
910
+ * and any excess ether is returned to `msg.sender`. This implementation is based on Solmate:
911
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
912
+ * @param salt The 32-byte random value used to create the proxy contract address.
913
+ * @param initCode The creation bytecode.
914
+ * @param data The initialisation code that is passed to the deployed contract.
915
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
916
+ * @return newContract The 20-byte address where the contract was deployed.
917
+ * @custom:security This function allows for reentrancy, however we refrain from adding
918
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
919
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
920
+ * Furthermore, we strongly recommend implementing a permissioned deploy protection by setting
921
+ * the first 20 bytes equal to `msg.sender` in the `salt` to prevent maliciously intended frontrun
922
+ * proxy deployments on other chains.
923
+ */
924
+ function deployCreate3AndInit(
925
+ bytes32 salt,
926
+ bytes memory initCode,
927
+ bytes memory data,
928
+ Values memory values
929
+ ) public payable returns (address newContract) {
930
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
931
+ // `deployCreate3AndInit`.
932
+ newContract = deployCreate3AndInit({
933
+ salt: salt,
934
+ initCode: initCode,
935
+ data: data,
936
+ values: values,
937
+ refundAddress: msg.sender
938
+ });
939
+ }
940
+
941
+ /**
942
+ * @dev Deploys and initialises a new contract via employing the `CREATE3` pattern (i.e. without
943
+ * an initcode factor) and using the creation bytecode `initCode`, the initialisation code `data`,
944
+ * the struct for the `payable` amounts `values`, the refund address `refundAddress`, and `msg.value`
945
+ * as inputs. The salt value is calculated pseudo-randomly using a diverse selection of block and
946
+ * transaction properties. This approach does not guarantee true randomness! In order to save deployment
947
+ * costs, we do not sanity check the `initCode` length. Note that if `values.constructorAmount` is non-zero,
948
+ * `initCode` must have a `payable` constructor. This implementation is based on Solmate:
949
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
950
+ * @param initCode The creation bytecode.
951
+ * @param data The initialisation code that is passed to the deployed contract.
952
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
953
+ * @param refundAddress The 20-byte address where any excess ether is returned to.
954
+ * @return newContract The 20-byte address where the contract was deployed.
955
+ * @custom:security This function allows for reentrancy, however we refrain from adding
956
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
957
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
958
+ */
959
+ function deployCreate3AndInit(
960
+ bytes memory initCode,
961
+ bytes memory data,
962
+ Values memory values,
963
+ address refundAddress
964
+ ) public payable returns (address newContract) {
965
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
966
+ // `deployCreate3AndInit`.
967
+ newContract = deployCreate3AndInit({
968
+ salt: _generateSalt(),
969
+ initCode: initCode,
970
+ data: data,
971
+ values: values,
972
+ refundAddress: refundAddress
973
+ });
974
+ }
975
+
976
+ /**
977
+ * @dev Deploys and initialises a new contract via employing the `CREATE3` pattern (i.e. without
978
+ * an initcode factor) and using the creation bytecode `initCode`, the initialisation code `data`,
979
+ * the struct for the `payable` amounts `values`, `msg.value` as inputs. The salt value is calculated
980
+ * pseudo-randomly using a diverse selection of block and transaction properties. This approach does
981
+ * not guarantee true randomness! In order to save deployment costs, we do not sanity check the `initCode`
982
+ * length. Note that if `values.constructorAmount` is non-zero, `initCode` must have a `payable` constructor,
983
+ * and any excess ether is returned to `msg.sender`. This implementation is based on Solmate:
984
+ * https://web.archive.org/web/20230921113832/https://raw.githubusercontent.com/transmissions11/solmate/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/CREATE3.sol.
985
+ * @param initCode The creation bytecode.
986
+ * @param data The initialisation code that is passed to the deployed contract.
987
+ * @param values The specific `payable` amounts for the deployment and initialisation call.
988
+ * @return newContract The 20-byte address where the contract was deployed.
989
+ * @custom:security This function allows for reentrancy, however we refrain from adding
990
+ * a mutex lock to keep it as use-case agnostic as possible. Please ensure at the protocol
991
+ * level that potentially malicious reentrant calls do not affect your smart contract system.
992
+ */
993
+ function deployCreate3AndInit(
994
+ bytes memory initCode,
995
+ bytes memory data,
996
+ Values memory values
997
+ ) public payable returns (address newContract) {
998
+ // Note that the safeguarding function `_guard` is called as part of the overloaded function
999
+ // `deployCreate3AndInit`.
1000
+ newContract = deployCreate3AndInit({
1001
+ salt: _generateSalt(),
1002
+ initCode: initCode,
1003
+ data: data,
1004
+ values: values,
1005
+ refundAddress: msg.sender
1006
+ });
1007
+ }
1008
+
1009
+ /**
1010
+ * @dev Returns the address where a contract will be stored if deployed via `deployer` using
1011
+ * the `CREATE3` pattern (i.e. without an initcode factor). Any change in the `salt` value will
1012
+ * result in a new destination address. This implementation is based on Solady:
1013
+ * https://web.archive.org/web/20230921114120/https://raw.githubusercontent.com/Vectorized/solady/1c1ac4ad9c8558001e92d8d1a7722ef67bec75df/src/utils/CREATE3.sol.
1014
+ * @param salt The 32-byte random value used to create the proxy contract address.
1015
+ * @param deployer The 20-byte deployer address.
1016
+ * @return computedAddress The 20-byte address where a contract will be stored.
1017
+ */
1018
+ function computeCreate3Address(
1019
+ bytes32 salt,
1020
+ address deployer
1021
+ ) public pure returns (address computedAddress) {
1022
+ assembly ("memory-safe") {
1023
+ let ptr := mload(0x40)
1024
+ mstore(0x00, deployer)
1025
+ mstore8(0x0b, 0xff)
1026
+ mstore(0x20, salt)
1027
+ mstore(
1028
+ 0x40,
1029
+ hex"21_c3_5d_be_1b_34_4a_24_88_cf_33_21_d6_ce_54_2f_8e_9f_30_55_44_ff_09_e4_99_3a_62_31_9a_49_7c_1f"
1030
+ )
1031
+ mstore(0x14, keccak256(0x0b, 0x55))
1032
+ mstore(0x40, ptr)
1033
+ mstore(0x00, 0xd694)
1034
+ mstore8(0x34, 0x01)
1035
+ computedAddress := keccak256(0x1e, 0x17)
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * @dev Returns the address where a contract will be stored if deployed via this contract using
1041
+ * the `CREATE3` pattern (i.e. without an initcode factor). Any change in the `salt` value will
1042
+ * result in a new destination address. This implementation is based on Solady:
1043
+ * https://web.archive.org/web/20230921114120/https://raw.githubusercontent.com/Vectorized/solady/1c1ac4ad9c8558001e92d8d1a7722ef67bec75df/src/utils/CREATE3.sol.
1044
+ * @param salt The 32-byte random value used to create the proxy contract address.
1045
+ * @return computedAddress The 20-byte address where a contract will be stored.
1046
+ */
1047
+ function computeCreate3Address(
1048
+ bytes32 salt
1049
+ ) public view returns (address computedAddress) {
1050
+ computedAddress = computeCreate3Address({salt: salt, deployer: _SELF});
1051
+ }
1052
+
1053
+ /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
1054
+ /* HELPER FUNCTIONS */
1055
+ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
1056
+
1057
+ /**
1058
+ * @dev Implements different safeguarding mechanisms depending on the encoded values in the salt
1059
+ * (`||` stands for byte-wise concatenation):
1060
+ * => salt (32 bytes) = 0xbebebebebebebebebebebebebebebebebebebebe||ff||1212121212121212121212
1061
+ * - The first 20 bytes (i.e. `bebebebebebebebebebebebebebebebebebebebe`) may be used to
1062
+ * implement a permissioned deploy protection by setting them equal to `msg.sender`,
1063
+ * - The 21st byte (i.e. `ff`) may be used to implement a cross-chain redeploy protection by
1064
+ * setting it equal to `0x01`,
1065
+ * - The last random 11 bytes (i.e. `1212121212121212121212`) allow for 2**88 bits of entropy
1066
+ * for mining a salt.
1067
+ * @param salt The 32-byte random value used to create the contract address.
1068
+ * @return guardedSalt The guarded 32-byte random value used to create the contract address.
1069
+ */
1070
+ function _guard(bytes32 salt) internal view returns (bytes32 guardedSalt) {
1071
+ (
1072
+ SenderBytes senderBytes,
1073
+ RedeployProtectionFlag redeployProtectionFlag
1074
+ ) = _parseSalt({salt: salt});
1075
+
1076
+ if (
1077
+ senderBytes == SenderBytes.MsgSender &&
1078
+ redeployProtectionFlag == RedeployProtectionFlag.True
1079
+ ) {
1080
+ // Configures a permissioned deploy protection as well as a cross-chain redeploy protection.
1081
+ guardedSalt = keccak256(
1082
+ abi.encode(msg.sender, block.chainid, salt)
1083
+ );
1084
+ } else if (
1085
+ senderBytes == SenderBytes.MsgSender &&
1086
+ redeployProtectionFlag == RedeployProtectionFlag.False
1087
+ ) {
1088
+ // Configures solely a permissioned deploy protection.
1089
+ guardedSalt = _efficientHash({
1090
+ a: bytes32(uint256(uint160(msg.sender))),
1091
+ b: salt
1092
+ });
1093
+ } else if (senderBytes == SenderBytes.MsgSender) {
1094
+ // Reverts if the 21st byte is greater than `0x01` in order to enforce developer explicitness.
1095
+ revert InvalidSalt({emitter: _SELF});
1096
+ } else if (
1097
+ senderBytes == SenderBytes.ZeroAddress &&
1098
+ redeployProtectionFlag == RedeployProtectionFlag.True
1099
+ ) {
1100
+ // Configures solely a cross-chain redeploy protection. In order to prevent a pseudo-randomly
1101
+ // generated cross-chain redeploy protection, we enforce the zero address check for the first 20 bytes.
1102
+ guardedSalt = _efficientHash({a: bytes32(block.chainid), b: salt});
1103
+ } else if (
1104
+ senderBytes == SenderBytes.ZeroAddress &&
1105
+ redeployProtectionFlag == RedeployProtectionFlag.Unspecified
1106
+ ) {
1107
+ // Reverts if the 21st byte is greater than `0x01` in order to enforce developer explicitness.
1108
+ revert InvalidSalt({emitter: _SELF});
1109
+ } else {
1110
+ // For the non-pseudo-random cases, the salt value `salt` is hashed to prevent the safeguard mechanisms
1111
+ // from being bypassed. Otherwise, the salt value `salt` is not modified.
1112
+ guardedSalt = (salt != _generateSalt())
1113
+ ? keccak256(abi.encode(salt))
1114
+ : salt;
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * @dev Returns the enum for the selection of a permissioned deploy protection as well as a
1120
+ * cross-chain redeploy protection.
1121
+ * @param salt The 32-byte random value used to create the contract address.
1122
+ * @return senderBytes The 8-byte enum for the selection of a permissioned deploy protection.
1123
+ * @return redeployProtectionFlag The 8-byte enum for the selection of a cross-chain redeploy
1124
+ * protection.
1125
+ */
1126
+ function _parseSalt(
1127
+ bytes32 salt
1128
+ )
1129
+ internal
1130
+ view
1131
+ returns (
1132
+ SenderBytes senderBytes,
1133
+ RedeployProtectionFlag redeployProtectionFlag
1134
+ )
1135
+ {
1136
+ if (
1137
+ address(bytes20(salt)) == msg.sender && bytes1(salt[20]) == hex"01"
1138
+ ) {
1139
+ (senderBytes, redeployProtectionFlag) = (
1140
+ SenderBytes.MsgSender,
1141
+ RedeployProtectionFlag.True
1142
+ );
1143
+ } else if (
1144
+ address(bytes20(salt)) == msg.sender && bytes1(salt[20]) == hex"00"
1145
+ ) {
1146
+ (senderBytes, redeployProtectionFlag) = (
1147
+ SenderBytes.MsgSender,
1148
+ RedeployProtectionFlag.False
1149
+ );
1150
+ } else if (address(bytes20(salt)) == msg.sender) {
1151
+ (senderBytes, redeployProtectionFlag) = (
1152
+ SenderBytes.MsgSender,
1153
+ RedeployProtectionFlag.Unspecified
1154
+ );
1155
+ } else if (
1156
+ address(bytes20(salt)) == address(0) && bytes1(salt[20]) == hex"01"
1157
+ ) {
1158
+ (senderBytes, redeployProtectionFlag) = (
1159
+ SenderBytes.ZeroAddress,
1160
+ RedeployProtectionFlag.True
1161
+ );
1162
+ } else if (
1163
+ address(bytes20(salt)) == address(0) && bytes1(salt[20]) == hex"00"
1164
+ ) {
1165
+ (senderBytes, redeployProtectionFlag) = (
1166
+ SenderBytes.ZeroAddress,
1167
+ RedeployProtectionFlag.False
1168
+ );
1169
+ } else if (address(bytes20(salt)) == address(0)) {
1170
+ (senderBytes, redeployProtectionFlag) = (
1171
+ SenderBytes.ZeroAddress,
1172
+ RedeployProtectionFlag.Unspecified
1173
+ );
1174
+ } else if (bytes1(salt[20]) == hex"01") {
1175
+ (senderBytes, redeployProtectionFlag) = (
1176
+ SenderBytes.Random,
1177
+ RedeployProtectionFlag.True
1178
+ );
1179
+ } else if (bytes1(salt[20]) == hex"00") {
1180
+ (senderBytes, redeployProtectionFlag) = (
1181
+ SenderBytes.Random,
1182
+ RedeployProtectionFlag.False
1183
+ );
1184
+ } else {
1185
+ (senderBytes, redeployProtectionFlag) = (
1186
+ SenderBytes.Random,
1187
+ RedeployProtectionFlag.Unspecified
1188
+ );
1189
+ }
1190
+ }
1191
+
1192
+ /**
1193
+ * @dev Returns the `keccak256` hash of `a` and `b` after concatenation.
1194
+ * @param a The first 32-byte value to be concatenated and hashed.
1195
+ * @param b The second 32-byte value to be concatenated and hashed.
1196
+ * @return hash The 32-byte `keccak256` hash of `a` and `b`.
1197
+ */
1198
+ function _efficientHash(
1199
+ bytes32 a,
1200
+ bytes32 b
1201
+ ) internal pure returns (bytes32 hash) {
1202
+ assembly ("memory-safe") {
1203
+ mstore(0x00, a)
1204
+ mstore(0x20, b)
1205
+ hash := keccak256(0x00, 0x40)
1206
+ }
1207
+ }
1208
+
1209
+ /**
1210
+ * @dev Generates pseudo-randomly a salt value using a diverse selection of block and
1211
+ * transaction properties.
1212
+ * @return salt The 32-byte pseudo-random salt value.
1213
+ */
1214
+ function _generateSalt() internal view returns (bytes32 salt) {
1215
+ unchecked {
1216
+ salt = keccak256(
1217
+ abi.encode(
1218
+ // We don't use `block.number - 256` (the maximum value on the EVM) to accommodate
1219
+ // any chains that may try to reduce the amount of available historical block hashes.
1220
+ // We also don't subtract 1 to mitigate any risks arising from consecutive block
1221
+ // producers on a PoS chain. Therefore, we use `block.number - 32` as a reasonable
1222
+ // compromise, one we expect should work on most chains, which is 1 epoch on Ethereum
1223
+ // mainnet. Please note that if you use this function between the genesis block and block
1224
+ // number 31, the block property `blockhash` will return zero, but the returned salt value
1225
+ // `salt` will still have a non-zero value due to the hashing characteristic and the other
1226
+ // remaining properties.
1227
+ blockhash(block.number - 32),
1228
+ block.coinbase,
1229
+ block.number,
1230
+ block.timestamp,
1231
+ block.prevrandao,
1232
+ block.chainid,
1233
+ msg.sender
1234
+ )
1235
+ );
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * @dev Ensures that `newContract` is a non-zero byte contract.
1241
+ * @param success The Boolean success condition.
1242
+ * @param newContract The 20-byte address where the contract was deployed.
1243
+ */
1244
+ function _requireSuccessfulContractCreation(
1245
+ bool success,
1246
+ address newContract
1247
+ ) internal view {
1248
+ // Note that reverting if `newContract == address(0)` isn't strictly necessary here, as if
1249
+ // the deployment fails, `success == false` should already hold. However, since the `CreateX`
1250
+ // contract should be usable and safe on a wide range of chains, this check is cheap enough
1251
+ // that there is no harm in including it (security > gas optimisations). It can potentially
1252
+ // protect against unexpected chain behaviour or a hypothetical compiler bug that doesn't surface
1253
+ // the call success status properly.
1254
+ if (
1255
+ !success ||
1256
+ newContract == address(0) ||
1257
+ newContract.code.length == 0
1258
+ ) {
1259
+ revert FailedContractCreation({emitter: _SELF});
1260
+ }
1261
+ }
1262
+
1263
+ /**
1264
+ * @dev Ensures that `newContract` is a non-zero byte contract.
1265
+ * @param newContract The 20-byte address where the contract was deployed.
1266
+ */
1267
+ function _requireSuccessfulContractCreation(
1268
+ address newContract
1269
+ ) internal view {
1270
+ if (newContract == address(0) || newContract.code.length == 0) {
1271
+ revert FailedContractCreation({emitter: _SELF});
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * @dev Ensures that the contract initialisation call to `implementation` has been successful.
1277
+ * @param success The Boolean success condition.
1278
+ * @param returnData The return data from the contract initialisation call.
1279
+ * @param implementation The 20-byte address where the implementation was deployed.
1280
+ */
1281
+ function _requireSuccessfulContractInitialisation(
1282
+ bool success,
1283
+ bytes memory returnData,
1284
+ address implementation
1285
+ ) internal view {
1286
+ if (!success || implementation.code.length == 0) {
1287
+ revert FailedContractInitialisation({
1288
+ emitter: _SELF,
1289
+ revertData: returnData
1290
+ });
1291
+ }
1292
+ }
1293
+ }