@openzeppelin/upgrades-core 1.12.0 → 1.13.0

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 (106) hide show
  1. package/artifacts/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol/ERC1967Proxy.dbg.json +1 -1
  2. package/artifacts/@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol/BeaconProxy.dbg.json +1 -1
  3. package/artifacts/@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol/UpgradeableBeacon.dbg.json +1 -1
  4. package/dist/add-proxy-to-manifest.d.ts +3 -0
  5. package/dist/add-proxy-to-manifest.d.ts.map +1 -0
  6. package/dist/add-proxy-to-manifest.js +15 -0
  7. package/dist/add-proxy-to-manifest.js.map +1 -0
  8. package/dist/deployment.d.ts +21 -1
  9. package/dist/deployment.d.ts.map +1 -1
  10. package/dist/deployment.js +65 -15
  11. package/dist/deployment.js.map +1 -1
  12. package/dist/eip-1967-type.d.ts +1 -0
  13. package/dist/eip-1967-type.d.ts.map +1 -1
  14. package/dist/eip-1967-type.js +6 -1
  15. package/dist/eip-1967-type.js.map +1 -1
  16. package/dist/eip-1967.d.ts +1 -0
  17. package/dist/eip-1967.d.ts.map +1 -1
  18. package/dist/eip-1967.js +3 -2
  19. package/dist/eip-1967.js.map +1 -1
  20. package/dist/impl-address.js +1 -1
  21. package/dist/impl-address.js.map +1 -1
  22. package/dist/impl-store.d.ts +22 -2
  23. package/dist/impl-store.d.ts.map +1 -1
  24. package/dist/impl-store.js +59 -15
  25. package/dist/impl-store.js.map +1 -1
  26. package/dist/impl-store.test.js +24 -0
  27. package/dist/impl-store.test.js.map +1 -1
  28. package/dist/index.d.ts +6 -5
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +20 -4
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest-storage-layout.d.ts.map +1 -1
  33. package/dist/manifest-storage-layout.js +3 -2
  34. package/dist/manifest-storage-layout.js.map +1 -1
  35. package/dist/manifest-storage-layout.test.js.map +1 -1
  36. package/dist/manifest.d.ts +2 -0
  37. package/dist/manifest.d.ts.map +1 -1
  38. package/dist/manifest.js +6 -4
  39. package/dist/manifest.js.map +1 -1
  40. package/dist/manifest.test.js +32 -0
  41. package/dist/manifest.test.js.map +1 -1
  42. package/dist/provider.d.ts +1 -0
  43. package/dist/provider.d.ts.map +1 -1
  44. package/dist/provider.js +6 -2
  45. package/dist/provider.js.map +1 -1
  46. package/dist/proxy-kind.d.ts +9 -0
  47. package/dist/proxy-kind.d.ts.map +1 -1
  48. package/dist/proxy-kind.js +27 -1
  49. package/dist/proxy-kind.js.map +1 -1
  50. package/dist/scripts/migrate-oz-cli-project.test.js +1 -1
  51. package/dist/scripts/migrate-oz-cli-project.test.js.map +1 -1
  52. package/dist/solc-api.d.ts +5 -0
  53. package/dist/solc-api.d.ts.map +1 -1
  54. package/dist/standalone.test.js.map +1 -1
  55. package/dist/storage/extract.d.ts +1 -1
  56. package/dist/storage/extract.d.ts.map +1 -1
  57. package/dist/storage/extract.js +76 -38
  58. package/dist/storage/extract.js.map +1 -1
  59. package/dist/storage/layout.d.ts +4 -0
  60. package/dist/storage/layout.d.ts.map +1 -1
  61. package/dist/storage/layout.js.map +1 -1
  62. package/dist/storage/report.test.js.map +1 -1
  63. package/dist/storage.test.js +1 -1
  64. package/dist/storage.test.js.map +1 -1
  65. package/dist/usage-error.d.ts +3 -0
  66. package/dist/usage-error.d.ts.map +1 -1
  67. package/dist/usage-error.js +7 -1
  68. package/dist/usage-error.js.map +1 -1
  69. package/dist/validate/query.d.ts.map +1 -1
  70. package/dist/validate/query.js +10 -5
  71. package/dist/validate/query.js.map +1 -1
  72. package/dist/validate/run.d.ts.map +1 -1
  73. package/dist/validate/run.js +1 -1
  74. package/dist/validate/run.js.map +1 -1
  75. package/dist/validate.test.js.map +1 -1
  76. package/package.json +4 -4
  77. package/src/add-proxy-to-manifest.ts +12 -0
  78. package/src/deployment.ts +81 -14
  79. package/src/eip-1967-type.ts +7 -0
  80. package/src/eip-1967.ts +4 -3
  81. package/src/impl-address.ts +1 -1
  82. package/src/impl-store.test.ts +33 -1
  83. package/src/impl-store.ts +69 -12
  84. package/src/index.ts +22 -4
  85. package/src/manifest-storage-layout.test.ts +3 -2
  86. package/src/manifest-storage-layout.ts +8 -3
  87. package/src/manifest.test.ts +34 -1
  88. package/src/manifest.ts +9 -4
  89. package/src/provider.ts +5 -1
  90. package/src/proxy-kind.ts +24 -1
  91. package/src/scripts/migrate-oz-cli-project.test.ts +1 -1
  92. package/src/scripts/migrate-oz-cli-project.test.ts.snap +0 -0
  93. package/src/solc-api.ts +5 -0
  94. package/src/standalone.test.ts +2 -2
  95. package/src/storage/extract.ts +98 -52
  96. package/src/storage/layout.ts +4 -0
  97. package/src/storage/report.test.ts +2 -2
  98. package/src/storage/report.test.ts.snap +0 -0
  99. package/src/storage.test.ts +3 -3
  100. package/src/storage.test.ts.snap +0 -0
  101. package/src/usage-error.ts +9 -0
  102. package/src/utils/parse-type-id.test.ts.md +106 -106
  103. package/src/utils/parse-type-id.test.ts.snap +0 -0
  104. package/src/validate/query.ts +9 -5
  105. package/src/validate/run.ts +6 -1
  106. package/src/validate.test.ts +2 -2
package/src/deployment.ts CHANGED
@@ -4,13 +4,16 @@ import debug from './utils/debug';
4
4
  import { makeNonEnumerable } from './utils/make-non-enumerable';
5
5
  import {
6
6
  EthereumProvider,
7
+ getCode,
7
8
  getTransactionByHash,
8
9
  getTransactionReceipt,
9
10
  hasCode,
10
11
  isDevelopmentNetwork,
12
+ isEmpty,
11
13
  isReceiptSuccessful,
12
14
  } from './provider';
13
15
  import { UpgradesError } from './error';
16
+ import { deleteDeployment, ManifestField } from './impl-store';
14
17
 
15
18
  const sleep = promisify(setTimeout);
16
19
 
@@ -31,37 +34,101 @@ export interface DeployOpts {
31
34
  pollingInterval?: number;
32
35
  }
33
36
 
37
+ /**
38
+ * Resumes a deployment or deploys a new one, based on whether the cached deployment should continue to be used and is valid
39
+ * (has a valid txHash for the current network or has runtime bytecode).
40
+ * If a cached deployment is not valid, deletes it if using a development network, otherwise throws an InvalidDeployment error.
41
+ *
42
+ * @param provider the Ethereum provider
43
+ * @param cached the cached deployment
44
+ * @param deploy the function to deploy a new deployment if needed
45
+ * @param type the manifest lens type. If merge is true, used for the timeout message if a previous deployment is not
46
+ * confirmed within the timeout period. Otherwise not used.
47
+ * @param opts polling timeout and interval options. If merge is true, used to check a previous deployment for confirmation.
48
+ * Otherwise not used.
49
+ * @param deployment the manifest field for this deployment. Optional for backward compatibility.
50
+ * If not provided, invalid deployments will not be deleted in a dev network (which is not a problem if merge is false,
51
+ * since it will be overwritten with the new deployment).
52
+ * @param merge whether the cached deployment is intended to be merged with the new deployment. Defaults to false.
53
+ * @returns the cached deployment if it should be used, otherwise the new deployment from the deploy function
54
+ * @throws {InvalidDeployment} if the cached deployment is invalid and we are not on a dev network
55
+ */
34
56
  export async function resumeOrDeploy<T extends Deployment>(
35
57
  provider: EthereumProvider,
36
58
  cached: T | undefined,
37
59
  deploy: () => Promise<T>,
60
+ type?: string,
61
+ opts?: DeployOpts,
62
+ deployment?: ManifestField<T>,
63
+ merge?: boolean,
38
64
  ): Promise<T> {
65
+ const validated = await validateCached(cached, provider, type, opts, deployment, merge);
66
+ if (validated === undefined || merge) {
67
+ const deployment = await deploy();
68
+ debug('initiated deployment', 'transaction hash:', deployment.txHash, 'merge:', merge);
69
+ return deployment;
70
+ } else {
71
+ return validated;
72
+ }
73
+ }
74
+
75
+ async function validateCached<T extends Deployment>(
76
+ cached: T | undefined,
77
+ provider: EthereumProvider,
78
+ type?: string,
79
+ opts?: DeployOpts,
80
+ deployment?: ManifestField<T>,
81
+ merge?: boolean,
82
+ ): Promise<T | undefined> {
39
83
  if (cached !== undefined) {
40
- const { txHash } = cached;
41
- if (txHash === undefined) {
42
- // Nothing to do here without a txHash.
43
- // This is the case for deployments migrated from OpenZeppelin CLI.
44
- return cached;
84
+ try {
85
+ await validateStoredDeployment(cached, provider, type, opts, merge);
86
+ } catch (e) {
87
+ if (e instanceof InvalidDeployment && (await isDevelopmentNetwork(provider))) {
88
+ debug('ignoring invalid deployment in development network', e.deployment.address);
89
+ if (deployment !== undefined) {
90
+ deleteDeployment(deployment);
91
+ }
92
+ return undefined;
93
+ } else {
94
+ throw e;
95
+ }
45
96
  }
97
+ }
98
+ return cached;
99
+ }
100
+
101
+ async function validateStoredDeployment<T extends Deployment>(
102
+ stored: T,
103
+ provider: EthereumProvider,
104
+ type?: string,
105
+ opts?: DeployOpts,
106
+ merge?: boolean,
107
+ ) {
108
+ const { txHash } = stored;
109
+ if (txHash !== undefined) {
46
110
  // If there is a deployment with txHash stored, we look its transaction up. If the
47
111
  // transaction is found, the deployment is reused.
48
112
  debug('found previous deployment', txHash);
49
113
  const tx = await getTransactionByHash(provider, txHash);
50
114
  if (tx !== null) {
51
115
  debug('resuming previous deployment', txHash);
52
- return cached;
53
- } else if (!(await isDevelopmentNetwork(provider))) {
116
+ if (merge) {
117
+ // If merging, wait for the existing deployment to be mined
118
+ waitAndValidateDeployment(provider, stored, type, opts);
119
+ }
120
+ } else {
54
121
  // If the transaction is not found we throw an error, except if we're in
55
122
  // a development network then we simply silently redeploy.
56
- throw new InvalidDeployment(cached);
57
- } else {
58
- debug('ignoring invalid deployment in development network', txHash);
123
+ // This error should be caught by the caller to determine if we're in a dev network.
124
+ throw new InvalidDeployment(stored);
125
+ }
126
+ } else {
127
+ const existingBytecode = await getCode(provider, stored.address);
128
+ if (isEmpty(existingBytecode)) {
129
+ throw new InvalidDeployment(stored);
59
130
  }
60
131
  }
61
-
62
- const deployment = await deploy();
63
- debug('initiated deployment', deployment.txHash);
64
- return deployment;
65
132
  }
66
133
 
67
134
  export async function waitAndValidateDeployment(
@@ -1,8 +1,10 @@
1
1
  import {
2
2
  EIP1967BeaconNotFound,
3
3
  EIP1967ImplementationNotFound,
4
+ getAdminAddress,
4
5
  getBeaconAddress,
5
6
  getImplementationAddress,
7
+ isEmptySlot,
6
8
  } from './eip-1967';
7
9
  import { EthereumProvider } from './provider';
8
10
 
@@ -20,6 +22,11 @@ export async function isTransparentOrUUPSProxy(provider: EthereumProvider, addre
20
22
  }
21
23
  }
22
24
 
25
+ export async function isTransparentProxy(provider: EthereumProvider, address: string): Promise<boolean> {
26
+ const adminAddress = await getAdminAddress(provider, address);
27
+ return !isEmptySlot(adminAddress);
28
+ }
29
+
23
30
  export async function isBeaconProxy(provider: EthereumProvider, address: string): Promise<boolean> {
24
31
  try {
25
32
  await getBeaconAddress(provider, address);
package/src/eip-1967.ts CHANGED
@@ -5,7 +5,6 @@ import { EthereumProvider, getStorageAt } from './provider';
5
5
  import { parseAddress } from './utils/address';
6
6
 
7
7
  export class EIP1967ImplementationNotFound extends UpgradesError {}
8
-
9
8
  export class EIP1967BeaconNotFound extends UpgradesError {}
10
9
 
11
10
  export async function getAdminAddress(provider: EthereumProvider, address: string): Promise<string> {
@@ -28,7 +27,9 @@ export async function getImplementationAddress(provider: EthereumProvider, addre
28
27
  );
29
28
 
30
29
  if (isEmptySlot(storage)) {
31
- throw new EIP1967ImplementationNotFound(`Contract at ${address} doesn't look like an administered ERC 1967 proxy`);
30
+ throw new EIP1967ImplementationNotFound(
31
+ `Contract at ${address} doesn't look like an ERC 1967 proxy with a logic contract address`,
32
+ );
32
33
  }
33
34
 
34
35
  return parseAddressFromStorage(storage);
@@ -67,7 +68,7 @@ export function toEip1967Hash(label: string): string {
67
68
  return '0x' + bigNumber.toString(16);
68
69
  }
69
70
 
70
- function isEmptySlot(storage: string): boolean {
71
+ export function isEmptySlot(storage: string): boolean {
71
72
  storage = storage.replace(/^0x/, '');
72
73
  return new BN(storage, 'hex').isZero();
73
74
  }
@@ -34,7 +34,7 @@ export async function getImplementationAddressFromBeacon(
34
34
  !(
35
35
  e.message.includes('function selector was not recognized') ||
36
36
  e.message.includes('invalid opcode') ||
37
- e.message.includes('reverted')
37
+ e.message.includes('revert')
38
38
  )
39
39
  ) {
40
40
  throw e;
@@ -6,9 +6,10 @@ import util from 'util';
6
6
  import path from 'path';
7
7
  import os from 'os';
8
8
 
9
- import { fetchOrDeploy } from './impl-store';
9
+ import { fetchOrDeploy, mergeAddresses } from './impl-store';
10
10
  import { getVersion } from './version';
11
11
  import { stubProvider } from './stub-provider';
12
+ import { ImplDeployment } from './manifest';
12
13
 
13
14
  const rimraf = util.promisify(rimrafAsync);
14
15
 
@@ -57,3 +58,34 @@ test('cleans up invalid deployment', async t => {
57
58
  // the failed deployment has been cleaned up
58
59
  await fetchOrDeploy(version1, provider2, provider2.deploy);
59
60
  });
61
+
62
+ test('merge addresses', async t => {
63
+ const depl1 = { address: '0x1' } as ImplDeployment;
64
+ const depl2 = { address: '0x2' } as ImplDeployment;
65
+
66
+ const { address, allAddresses } = await mergeAddresses(depl1, depl2);
67
+ t.is(address, '0x1');
68
+ t.true(unorderedEqual(allAddresses, ['0x1', '0x2']), allAddresses.toString());
69
+ });
70
+
71
+ test('merge multiple existing addresses', async t => {
72
+ const depl1 = { address: '0x1', allAddresses: ['0x1a', '0x1b'] } as ImplDeployment;
73
+ const depl2 = { address: '0x2' } as ImplDeployment;
74
+
75
+ const { address, allAddresses } = await mergeAddresses(depl1, depl2);
76
+ t.is(address, '0x1');
77
+ t.true(unorderedEqual(allAddresses, ['0x1', '0x1a', '0x1b', '0x2']), allAddresses.toString());
78
+ });
79
+
80
+ test('merge all addresses', async t => {
81
+ const depl1 = { address: '0x1', allAddresses: ['0x1a', '0x1b'] } as ImplDeployment;
82
+ const depl2 = { address: '0x2', allAddresses: ['0x2a', '0x2b'] } as ImplDeployment;
83
+
84
+ const { address, allAddresses } = await mergeAddresses(depl1, depl2);
85
+ t.is(address, '0x1');
86
+ t.true(unorderedEqual(allAddresses, ['0x1', '0x1a', '0x1b', '0x2', '0x2a', '0x2b']), allAddresses.toString());
87
+ });
88
+
89
+ function unorderedEqual(arr1: string[], arr2: string[]) {
90
+ return arr1.every(i => arr2.includes(i)) && arr2.every(i => arr1.includes(i));
91
+ }
package/src/impl-store.ts CHANGED
@@ -2,7 +2,7 @@ import debug from './utils/debug';
2
2
  import { Manifest, ManifestData, ImplDeployment } from './manifest';
3
3
  import { EthereumProvider, isDevelopmentNetwork } from './provider';
4
4
  import { Deployment, InvalidDeployment, resumeOrDeploy, waitAndValidateDeployment } from './deployment';
5
- import type { Version } from './version';
5
+ import { Version } from './version';
6
6
  import assert from 'assert';
7
7
  import { DeployOpts } from '.';
8
8
 
@@ -12,9 +12,10 @@ interface ManifestLens<T> {
12
12
  (data: ManifestData): ManifestField<T>;
13
13
  }
14
14
 
15
- interface ManifestField<T> {
15
+ export interface ManifestField<T> {
16
16
  get(): T | undefined;
17
17
  set(value: T | undefined): void;
18
+ merge?(value: T | undefined): void;
18
19
  }
19
20
 
20
21
  /**
@@ -24,6 +25,7 @@ interface ManifestField<T> {
24
25
  * @param provider the Ethereum provider
25
26
  * @param deploy the deploy function
26
27
  * @param opts options containing the timeout and pollingInterval parameters. If undefined, assumes the timeout is not configurable and will not mention those parameters in the error message for TransactionMinedTimeout.
28
+ * @param merge if true, adds a deployment to existing deployment by merging their addresses. Defaults to false.
27
29
  * @returns the deployment address
28
30
  * @throws {InvalidDeployment} if the deployment is invalid
29
31
  * @throws {TransactionMinedTimeout} if the transaction was not confirmed within the timeout period
@@ -33,6 +35,7 @@ async function fetchOrDeployGeneric<T extends Deployment>(
33
35
  provider: EthereumProvider,
34
36
  deploy: () => Promise<T>,
35
37
  opts?: DeployOpts,
38
+ merge?: boolean,
36
39
  ): Promise<string> {
37
40
  const manifest = await Manifest.forNetwork(provider);
38
41
 
@@ -41,14 +44,24 @@ async function fetchOrDeployGeneric<T extends Deployment>(
41
44
  debug('fetching deployment of', lens.description);
42
45
  const data = await manifest.read();
43
46
  const deployment = lens(data);
44
- const stored = deployment.get();
45
- if (stored === undefined) {
46
- debug('deployment of', lens.description, 'not found');
47
+ if (merge && !deployment.merge) {
48
+ throw new Error(
49
+ 'fetchOrDeployGeneric was called with merge set to true but the deployment lens does not have a merge function',
50
+ );
47
51
  }
48
- const updated = await resumeOrDeploy(provider, stored, deploy);
52
+
53
+ const stored = deployment.get();
54
+ const updated = await resumeOrDeploy(provider, stored, deploy, lens.type, opts, deployment, merge);
49
55
  if (updated !== stored) {
50
- await checkForAddressClash(provider, data, updated);
51
- deployment.set(updated);
56
+ if (merge && deployment.merge) {
57
+ // only check primary addresses for clashes, since the address could already exist in an allAddresses field
58
+ // but the above updated and stored objects are different instances representing the same entry
59
+ await checkForAddressClash(provider, data, updated, false);
60
+ deployment.merge(updated);
61
+ } else {
62
+ await checkForAddressClash(provider, data, updated, true);
63
+ deployment.set(updated);
64
+ }
52
65
  await manifest.write(data);
53
66
  }
54
67
  return updated;
@@ -77,21 +90,57 @@ async function fetchOrDeployGeneric<T extends Deployment>(
77
90
  }
78
91
  }
79
92
 
93
+ /**
94
+ * Deletes the deployment by setting it to undefined.
95
+ * Should only be used during a manifest run.
96
+ */
97
+ export function deleteDeployment(deployment: ManifestField<Deployment>) {
98
+ deployment.set(undefined);
99
+ }
100
+
80
101
  export async function fetchOrDeploy(
81
102
  version: Version,
82
103
  provider: EthereumProvider,
83
104
  deploy: () => Promise<ImplDeployment>,
84
105
  opts?: DeployOpts,
106
+ merge?: boolean,
85
107
  ): Promise<string> {
86
- return fetchOrDeployGeneric(implLens(version.linkedWithoutMetadata), provider, deploy, opts);
108
+ return fetchOrDeployGeneric(implLens(version.linkedWithoutMetadata), provider, deploy, opts, merge);
87
109
  }
88
110
 
89
111
  const implLens = (versionWithoutMetadata: string) =>
90
112
  lens(`implementation ${versionWithoutMetadata}`, 'implementation', data => ({
91
113
  get: () => data.impls[versionWithoutMetadata],
92
114
  set: (value?: ImplDeployment) => (data.impls[versionWithoutMetadata] = value),
115
+ merge: (value?: ImplDeployment) => {
116
+ const existing = data.impls[versionWithoutMetadata];
117
+ if (existing !== undefined && value !== undefined) {
118
+ const { address, allAddresses } = mergeAddresses(existing, value);
119
+ data.impls[versionWithoutMetadata] = { ...existing, address, allAddresses };
120
+ } else {
121
+ data.impls[versionWithoutMetadata] = value;
122
+ }
123
+ },
93
124
  }));
94
125
 
126
+ /**
127
+ * Merge the addresses in the deployments and returns them.
128
+ *
129
+ * @param existing existing deployment
130
+ * @param value deployment to add
131
+ */
132
+ export function mergeAddresses(existing: ImplDeployment, value: ImplDeployment) {
133
+ const merged = new Set<string>();
134
+
135
+ merged.add(existing.address);
136
+ merged.add(value.address);
137
+
138
+ existing.allAddresses?.forEach(item => merged.add(item));
139
+ value.allAddresses?.forEach(item => merged.add(item));
140
+
141
+ return { address: existing.address, allAddresses: Array.from(merged) };
142
+ }
143
+
95
144
  export async function fetchOrDeployAdmin(
96
145
  provider: EthereumProvider,
97
146
  deploy: () => Promise<Deployment>,
@@ -113,8 +162,9 @@ async function checkForAddressClash(
113
162
  provider: EthereumProvider,
114
163
  data: ManifestData,
115
164
  updated: Deployment,
165
+ checkAllAddresses: boolean,
116
166
  ): Promise<void> {
117
- const clash = lookupDeployment(data, updated.address);
167
+ const clash = lookupDeployment(data, updated.address, checkAllAddresses);
118
168
  if (clash !== undefined) {
119
169
  if (await isDevelopmentNetwork(provider)) {
120
170
  debug('deleting a previous deployment at address', updated.address);
@@ -129,13 +179,20 @@ async function checkForAddressClash(
129
179
  }
130
180
  }
131
181
 
132
- function lookupDeployment(data: ManifestData, address: string): ManifestField<Deployment> | undefined {
182
+ function lookupDeployment(
183
+ data: ManifestData,
184
+ address: string,
185
+ checkAllAddresses: boolean,
186
+ ): ManifestField<Deployment> | undefined {
133
187
  if (data.admin?.address === address) {
134
188
  return adminLens(data);
135
189
  }
136
190
 
137
191
  for (const versionWithoutMetadata in data.impls) {
138
- if (data.impls[versionWithoutMetadata]?.address === address) {
192
+ if (
193
+ data.impls[versionWithoutMetadata]?.address === address ||
194
+ (checkAllAddresses && data.impls[versionWithoutMetadata]?.allAddresses?.includes(address))
195
+ ) {
139
196
  return implLens(versionWithoutMetadata)(data);
140
197
  }
141
198
  }
package/src/index.ts CHANGED
@@ -1,9 +1,16 @@
1
1
  export * from './validate';
2
- export * from './impl-store';
2
+ export { fetchOrDeploy, fetchOrDeployAdmin } from './impl-store';
3
3
  export * from './version';
4
- export * from './manifest';
5
4
  export * from './storage';
6
- export * from './eip-1967';
5
+ export {
6
+ EIP1967BeaconNotFound,
7
+ EIP1967ImplementationNotFound,
8
+ getAdminAddress,
9
+ getBeaconAddress,
10
+ getImplementationAddress,
11
+ toEip1967Hash,
12
+ toFallbackEip1967Hash,
13
+ } from './eip-1967';
7
14
  export * from './provider';
8
15
  export * from './src-decoder';
9
16
  export * from './solc-api';
@@ -11,18 +18,28 @@ export * from './deployment';
11
18
  export * from './link-refs';
12
19
  export * from './error';
13
20
 
21
+ export {
22
+ ManifestData,
23
+ ImplDeployment,
24
+ ProxyDeployment,
25
+ Manifest,
26
+ migrateManifest,
27
+ DeploymentNotFound,
28
+ } from './manifest';
29
+
14
30
  export { getStorageLayoutForAddress } from './manifest-storage-layout';
15
31
 
16
32
  export * from './scripts/migrate-oz-cli-project';
17
33
 
18
34
  export { logWarning } from './utils/log';
19
- export { setProxyKind, processProxyKind } from './proxy-kind';
35
+ export { setProxyKind, processProxyKind, detectProxyKind } from './proxy-kind';
20
36
 
21
37
  export { UpgradeableContract } from './standalone';
22
38
 
23
39
  export { isTransparentOrUUPSProxy, isBeaconProxy } from './eip-1967-type';
24
40
  export { getImplementationAddressFromBeacon, getImplementationAddressFromProxy } from './impl-address';
25
41
  export { isBeacon } from './beacon';
42
+ export { addProxyToManifest } from './add-proxy-to-manifest';
26
43
 
27
44
  export {
28
45
  BeaconProxyUnsupportedError,
@@ -31,5 +48,6 @@ export {
31
48
  DeployBeaconProxyUnsupportedError,
32
49
  DeployBeaconProxyImplUnknownError,
33
50
  DeployBeaconProxyKindError,
51
+ ForceImportUnsupportedError,
34
52
  assertNotProxy,
35
53
  } from './usage-error';
@@ -1,4 +1,4 @@
1
- import _test, { TestInterface } from 'ava';
1
+ import _test, { TestFn } from 'ava';
2
2
  import assert from 'assert';
3
3
 
4
4
  import { artifacts } from 'hardhat';
@@ -17,7 +17,7 @@ interface Context {
17
17
  validationData: ValidationData;
18
18
  }
19
19
 
20
- const test = _test as TestInterface<Context>;
20
+ const test = _test as TestFn<Context>;
21
21
 
22
22
  test.before(async t => {
23
23
  const buildInfo = await artifacts.getBuildInfo('contracts/test/ManifestMigrate.sol:ManifestMigrateUnique');
@@ -44,6 +44,7 @@ test('getStorageLayoutForAddress - update layout', async t => {
44
44
  },
45
45
  proxies: [],
46
46
  });
47
+
47
48
  const layout = await getStorageLayoutForAddress(manifest, t.context.validationData, address);
48
49
  t.deepEqual(layout, updatedLayout);
49
50
  t.like(manifest.data, {
@@ -5,6 +5,7 @@ import { ValidationData } from './validate/data';
5
5
  import { findVersionWithoutMetadataMatches, unfoldStorageLayout } from './validate/query';
6
6
  import { stabilizeTypeIdentifier } from './utils/type-id';
7
7
  import { DeepArray, deepEqual } from './utils/deep-array';
8
+ import { UpgradesError } from './error';
8
9
 
9
10
  export async function getStorageLayoutForAddress(
10
11
  manifest: Manifest,
@@ -12,13 +13,17 @@ export async function getStorageLayoutForAddress(
12
13
  implAddress: string,
13
14
  ): Promise<StorageLayout> {
14
15
  const data = await manifest.read();
15
- const versionWithoutMetadata = Object.keys(data.impls).find(v => data.impls[v]?.address === implAddress);
16
+ const versionWithoutMetadata = Object.keys(data.impls).find(
17
+ v => data.impls[v]?.address === implAddress || data.impls[v]?.allAddresses?.includes(implAddress),
18
+ );
16
19
  if (versionWithoutMetadata === undefined) {
17
- throw new Error(`Deployment at address ${implAddress} is not registered`);
20
+ throw new UpgradesError(
21
+ `Deployment at address ${implAddress} is not registered`,
22
+ () => 'To register a previously deployed proxy for upgrading, use the forceImport function.',
23
+ );
18
24
  }
19
25
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20
26
  const { layout } = data.impls[versionWithoutMetadata]!;
21
-
22
27
  if (isCurrentLayoutVersion(layout)) {
23
28
  return layout;
24
29
  } else {
@@ -1,5 +1,5 @@
1
1
  import test from 'ava';
2
- import { Manifest } from './manifest';
2
+ import { Manifest, ManifestData, normalizeManifestData } from './manifest';
3
3
 
4
4
  test('manifest name for a known network', t => {
5
5
  const manifest = new Manifest(1);
@@ -11,3 +11,36 @@ test('manifest name for an unknown network', t => {
11
11
  const manifest = new Manifest(id);
12
12
  t.is(manifest.file, `.openzeppelin/unknown-${id}.json`);
13
13
  });
14
+
15
+ test('normalize manifest', t => {
16
+ const deployment = {
17
+ address: '0x1234',
18
+ txHash: '0x1234',
19
+ kind: 'uups' as const,
20
+ layout: { types: {}, storage: [] },
21
+ deployTransaction: {},
22
+ };
23
+ const input: ManifestData = {
24
+ manifestVersion: '3.0',
25
+ admin: deployment,
26
+ impls: { a: deployment },
27
+ proxies: [deployment],
28
+ };
29
+ const norm = normalizeManifestData(input);
30
+ t.like(norm.admin, {
31
+ ...deployment,
32
+ kind: undefined,
33
+ layout: undefined,
34
+ deployTransaction: undefined,
35
+ });
36
+ t.like(norm.impls.a, {
37
+ ...deployment,
38
+ kind: undefined,
39
+ deployTransaction: undefined,
40
+ });
41
+ t.like(norm.proxies[0], {
42
+ ...deployment,
43
+ layout: undefined,
44
+ deployTransaction: undefined,
45
+ });
46
+ });
package/src/manifest.ts CHANGED
@@ -22,6 +22,7 @@ export interface ManifestData {
22
22
 
23
23
  export interface ImplDeployment extends Deployment {
24
24
  layout: StorageLayout;
25
+ allAddresses?: string[];
25
26
  }
26
27
 
27
28
  export interface ProxyDeployment extends Deployment {
@@ -57,7 +58,10 @@ export class Manifest {
57
58
 
58
59
  async getDeploymentFromAddress(address: string): Promise<ImplDeployment> {
59
60
  const data = await this.read();
60
- const deployment = Object.values(data.impls).find(d => d?.address === address);
61
+ const deployment = Object.values(data.impls).find(
62
+ d => d?.address === address || d?.allAddresses?.includes(address),
63
+ );
64
+
61
65
  if (deployment === undefined) {
62
66
  throw new DeploymentNotFound(`Deployment at address ${address} is not registered`);
63
67
  }
@@ -160,11 +164,12 @@ export function migrateManifest(data: ManifestData): ManifestData {
160
164
 
161
165
  export class DeploymentNotFound extends Error {}
162
166
 
163
- function normalizeManifestData(input: ManifestData): ManifestData {
167
+ export function normalizeManifestData(input: ManifestData): ManifestData {
164
168
  return {
165
- ...pick(input, ['manifestVersion', 'admin']),
169
+ manifestVersion: input.manifestVersion,
170
+ admin: input.admin && normalizeDeployment(input.admin),
166
171
  proxies: input.proxies.map(p => normalizeDeployment(p, ['kind'])),
167
- impls: mapValues(input.impls, i => i && normalizeDeployment(i, ['layout'])),
172
+ impls: mapValues(input.impls, i => i && normalizeDeployment(i, ['layout', 'allAddresses'])),
168
173
  };
169
174
  }
170
175
 
package/src/provider.ts CHANGED
@@ -71,7 +71,11 @@ export async function call(
71
71
 
72
72
  export async function hasCode(provider: EthereumProvider, address: string, block?: string): Promise<boolean> {
73
73
  const code = await getCode(provider, address, block);
74
- return code !== '0x';
74
+ return !isEmpty(code);
75
+ }
76
+
77
+ export function isEmpty(code: string) {
78
+ return code.replace(/^0x/, '') === '';
75
79
  }
76
80
 
77
81
  export async function getTransactionByHash(
package/src/proxy-kind.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { EthereumProvider } from './provider';
2
2
  import { inferProxyKind, ValidationData, ValidationOptions } from './validate';
3
3
  import { Manifest, DeploymentNotFound, ProxyDeployment } from './manifest';
4
- import { isBeaconProxy } from './eip-1967-type';
4
+ import { isBeaconProxy, isTransparentOrUUPSProxy, isTransparentProxy } from './eip-1967-type';
5
5
  import { Version } from './version';
6
6
  import { BeaconProxyUnsupportedError } from './usage-error';
7
+ import { UpgradesError } from '.';
7
8
 
8
9
  export async function setProxyKind(
9
10
  provider: EthereumProvider,
@@ -57,3 +58,25 @@ export async function processProxyKind(
57
58
  throw new BeaconProxyUnsupportedError();
58
59
  }
59
60
  }
61
+
62
+ /**
63
+ * Detects the kind of proxy at an address by reading its ERC 1967 storage slots.
64
+ *
65
+ * @param provider the Ethereum provider
66
+ * @param proxyAddress the proxy address
67
+ * @returns the proxy kind
68
+ * @throws {UpgradesError} if the contract at address does not look like an ERC 1967 proxy
69
+ */
70
+ export async function detectProxyKind(provider: EthereumProvider, proxyAddress: string) {
71
+ let importKind: ProxyDeployment['kind'];
72
+ if (await isTransparentProxy(provider, proxyAddress)) {
73
+ importKind = 'transparent';
74
+ } else if (await isTransparentOrUUPSProxy(provider, proxyAddress)) {
75
+ importKind = 'uups';
76
+ } else if (await isBeaconProxy(provider, proxyAddress)) {
77
+ importKind = 'beacon';
78
+ } else {
79
+ throw new UpgradesError(`Contract at ${proxyAddress} doesn't look like an ERC 1967 proxy`);
80
+ }
81
+ return importKind;
82
+ }
@@ -50,7 +50,7 @@ test('produces network export data', async t => {
50
50
 
51
51
  test('deletes project file', async t => {
52
52
  const error = await t.throwsAsync(() => fs.access(PROJECT_FILE));
53
- t.is(error.message, `ENOENT: no such file or directory, access '${PROJECT_FILE}'`);
53
+ t.is(error?.message, `ENOENT: no such file or directory, access '${PROJECT_FILE}'`);
54
54
  });
55
55
 
56
56
  test('export file contains networks and compiler data', async t => {
package/src/solc-api.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SourceUnit } from 'solidity-ast';
2
+ import { StorageItem, TypeItem } from './storage';
2
3
 
3
4
  export interface SolcOutput {
4
5
  contracts: {
@@ -8,6 +9,10 @@ export interface SolcOutput {
8
9
  bytecode: SolcBytecode;
9
10
  methodIdentifiers?: Record<string, string>;
10
11
  };
12
+ storageLayout?: {
13
+ storage: StorageItem[];
14
+ types: Record<string, TypeItem>;
15
+ };
11
16
  };
12
17
  };
13
18
  };