Clones.test.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const { expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
  2. const { computeCreate2Address } = require('../helpers/create2');
  3. const { expect } = require('chai');
  4. const shouldBehaveLikeClone = require('./Clones.behaviour');
  5. const Clones = artifacts.require('$Clones');
  6. contract('Clones', function (accounts) {
  7. const [ deployer ] = accounts;
  8. describe('clone', function () {
  9. shouldBehaveLikeClone(async (implementation, initData, opts = {}) => {
  10. const factory = await Clones.new();
  11. const receipt = await factory.$clone(implementation);
  12. const address = receipt.logs.find(({ event }) => event === 'return$clone').args.instance;
  13. await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData });
  14. return { address };
  15. });
  16. });
  17. describe('cloneDeterministic', function () {
  18. shouldBehaveLikeClone(async (implementation, initData, opts = {}) => {
  19. const salt = web3.utils.randomHex(32);
  20. const factory = await Clones.new();
  21. const receipt = await factory.$cloneDeterministic(implementation, salt);
  22. const address = receipt.logs.find(({ event }) => event === 'return$cloneDeterministic').args.instance;
  23. await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData });
  24. return { address };
  25. });
  26. it('address already used', async function () {
  27. const implementation = web3.utils.randomHex(20);
  28. const salt = web3.utils.randomHex(32);
  29. const factory = await Clones.new();
  30. // deploy once
  31. expectEvent(
  32. await factory.$cloneDeterministic(implementation, salt),
  33. 'return$cloneDeterministic',
  34. );
  35. // deploy twice
  36. await expectRevert(
  37. factory.$cloneDeterministic(implementation, salt),
  38. 'ERC1167: create2 failed',
  39. );
  40. });
  41. it('address prediction', async function () {
  42. const implementation = web3.utils.randomHex(20);
  43. const salt = web3.utils.randomHex(32);
  44. const factory = await Clones.new();
  45. const predicted = await factory.$predictDeterministicAddress(implementation, salt);
  46. const creationCode = [
  47. '0x3d602d80600a3d3981f3363d3d373d3d3d363d73',
  48. implementation.replace(/0x/, '').toLowerCase(),
  49. '5af43d82803e903d91602b57fd5bf3',
  50. ].join('');
  51. expect(computeCreate2Address(
  52. salt,
  53. creationCode,
  54. factory.address,
  55. )).to.be.equal(predicted);
  56. expectEvent(
  57. await factory.$cloneDeterministic(implementation, salt),
  58. 'return$cloneDeterministic',
  59. { instance: predicted },
  60. );
  61. });
  62. });
  63. });