Clones.sol 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0) (proxy/Clones.sol)
  3. pragma solidity ^0.8.20;
  4. import {Create2} from "../utils/Create2.sol";
  5. import {Errors} from "../utils/Errors.sol";
  6. /**
  7. * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
  8. * deploying minimal proxy contracts, also known as "clones".
  9. *
  10. * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
  11. * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
  12. *
  13. * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
  14. * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
  15. * deterministic method.
  16. */
  17. library Clones {
  18. error CloneArgumentsTooLong();
  19. /**
  20. * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
  21. *
  22. * This function uses the create opcode, which should never revert.
  23. *
  24. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  25. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  26. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  27. */
  28. function clone(address implementation) internal returns (address instance) {
  29. return clone(implementation, 0);
  30. }
  31. /**
  32. * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
  33. * to the new contract.
  34. *
  35. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  36. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  37. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  38. *
  39. * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
  40. * to always have enough balance for new deployments. Consider exposing this function under a payable method.
  41. */
  42. function clone(address implementation, uint256 value) internal returns (address instance) {
  43. if (address(this).balance < value) {
  44. revert Errors.InsufficientBalance(address(this).balance, value);
  45. }
  46. assembly ("memory-safe") {
  47. // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
  48. // of the `implementation` address with the bytecode before the address.
  49. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
  50. // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
  51. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
  52. instance := create(value, 0x09, 0x37)
  53. }
  54. if (instance == address(0)) {
  55. revert Errors.FailedDeployment();
  56. }
  57. }
  58. /**
  59. * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
  60. *
  61. * This function uses the create2 opcode and a `salt` to deterministically deploy
  62. * the clone. Using the same `implementation` and `salt` multiple times will revert, since
  63. * the clones cannot be deployed twice at the same address.
  64. *
  65. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  66. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  67. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  68. */
  69. function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
  70. return cloneDeterministic(implementation, salt, 0);
  71. }
  72. /**
  73. * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
  74. * a `value` parameter to send native currency to the new contract.
  75. *
  76. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  77. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  78. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  79. *
  80. * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
  81. * to always have enough balance for new deployments. Consider exposing this function under a payable method.
  82. */
  83. function cloneDeterministic(
  84. address implementation,
  85. bytes32 salt,
  86. uint256 value
  87. ) internal returns (address instance) {
  88. if (address(this).balance < value) {
  89. revert Errors.InsufficientBalance(address(this).balance, value);
  90. }
  91. assembly ("memory-safe") {
  92. // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
  93. // of the `implementation` address with the bytecode before the address.
  94. mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
  95. // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
  96. mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
  97. instance := create2(value, 0x09, 0x37, salt)
  98. }
  99. if (instance == address(0)) {
  100. revert Errors.FailedDeployment();
  101. }
  102. }
  103. /**
  104. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
  105. */
  106. function predictDeterministicAddress(
  107. address implementation,
  108. bytes32 salt,
  109. address deployer
  110. ) internal pure returns (address predicted) {
  111. assembly ("memory-safe") {
  112. let ptr := mload(0x40)
  113. mstore(add(ptr, 0x38), deployer)
  114. mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
  115. mstore(add(ptr, 0x14), implementation)
  116. mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
  117. mstore(add(ptr, 0x58), salt)
  118. mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
  119. predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
  120. }
  121. }
  122. /**
  123. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
  124. */
  125. function predictDeterministicAddress(
  126. address implementation,
  127. bytes32 salt
  128. ) internal view returns (address predicted) {
  129. return predictDeterministicAddress(implementation, salt, address(this));
  130. }
  131. /**
  132. * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
  133. * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
  134. * access the arguments within the implementation, use {fetchCloneArgs}.
  135. *
  136. * This function uses the create opcode, which should never revert.
  137. *
  138. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  139. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  140. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  141. */
  142. function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
  143. return cloneWithImmutableArgs(implementation, args, 0);
  144. }
  145. /**
  146. * @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
  147. * parameter to send native currency to the new contract.
  148. *
  149. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  150. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  151. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  152. *
  153. * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
  154. * to always have enough balance for new deployments. Consider exposing this function under a payable method.
  155. */
  156. function cloneWithImmutableArgs(
  157. address implementation,
  158. bytes memory args,
  159. uint256 value
  160. ) internal returns (address instance) {
  161. if (address(this).balance < value) {
  162. revert Errors.InsufficientBalance(address(this).balance, value);
  163. }
  164. bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
  165. assembly ("memory-safe") {
  166. instance := create(value, add(bytecode, 0x20), mload(bytecode))
  167. }
  168. if (instance == address(0)) {
  169. revert Errors.FailedDeployment();
  170. }
  171. }
  172. /**
  173. * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
  174. * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
  175. * access the arguments within the implementation, use {fetchCloneArgs}.
  176. *
  177. * This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
  178. * `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
  179. * at the same address.
  180. *
  181. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  182. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  183. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  184. */
  185. function cloneDeterministicWithImmutableArgs(
  186. address implementation,
  187. bytes memory args,
  188. bytes32 salt
  189. ) internal returns (address instance) {
  190. return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
  191. }
  192. /**
  193. * @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
  194. * but with a `value` parameter to send native currency to the new contract.
  195. *
  196. * WARNING: This function does not check if `implementation` has code. A clone that points to an address
  197. * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
  198. * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
  199. *
  200. * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
  201. * to always have enough balance for new deployments. Consider exposing this function under a payable method.
  202. */
  203. function cloneDeterministicWithImmutableArgs(
  204. address implementation,
  205. bytes memory args,
  206. bytes32 salt,
  207. uint256 value
  208. ) internal returns (address instance) {
  209. bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
  210. return Create2.deploy(value, salt, bytecode);
  211. }
  212. /**
  213. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
  214. */
  215. function predictDeterministicAddressWithImmutableArgs(
  216. address implementation,
  217. bytes memory args,
  218. bytes32 salt,
  219. address deployer
  220. ) internal pure returns (address predicted) {
  221. bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
  222. return Create2.computeAddress(salt, keccak256(bytecode), deployer);
  223. }
  224. /**
  225. * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
  226. */
  227. function predictDeterministicAddressWithImmutableArgs(
  228. address implementation,
  229. bytes memory args,
  230. bytes32 salt
  231. ) internal view returns (address predicted) {
  232. return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
  233. }
  234. /**
  235. * @dev Get the immutable args attached to a clone.
  236. *
  237. * - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
  238. * function will return an empty array.
  239. * - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
  240. * `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
  241. * creation.
  242. * - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
  243. * function should only be used to check addresses that are known to be clones.
  244. */
  245. function fetchCloneArgs(address instance) internal view returns (bytes memory) {
  246. bytes memory result = new bytes(instance.code.length - 45); // revert if length is too short
  247. assembly ("memory-safe") {
  248. extcodecopy(instance, add(result, 32), 45, mload(result))
  249. }
  250. return result;
  251. }
  252. /**
  253. * @dev Helper that prepares the initcode of the proxy with immutable args.
  254. *
  255. * An assembly variant of this function requires copying the `args` array, which can be efficiently done using
  256. * `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
  257. * abi.encodePacked is more expensive but also more portable and easier to review.
  258. *
  259. * NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
  260. * With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
  261. */
  262. function _cloneCodeWithImmutableArgs(
  263. address implementation,
  264. bytes memory args
  265. ) private pure returns (bytes memory) {
  266. if (args.length > 24531) revert CloneArgumentsTooLong();
  267. return
  268. abi.encodePacked(
  269. hex"61",
  270. uint16(args.length + 45),
  271. hex"3d81600a3d39f3363d3d373d3d3d363d73",
  272. implementation,
  273. hex"5af43d82803e903d91602b57fd5bf3",
  274. args
  275. );
  276. }
  277. }