@openzeppelin/upgrades-core 1.35.1 → 1.36.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 (47) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/cli/cli.test.js +160 -0
  3. package/dist/cli/cli.test.js.map +1 -1
  4. package/dist/cli/validate/build-info-file.d.ts +4 -0
  5. package/dist/cli/validate/build-info-file.d.ts.map +1 -1
  6. package/dist/cli/validate/build-info-file.js +7 -2
  7. package/dist/cli/validate/build-info-file.js.map +1 -1
  8. package/dist/cli/validate/contract-report.d.ts +5 -5
  9. package/dist/cli/validate/contract-report.d.ts.map +1 -1
  10. package/dist/cli/validate/contract-report.js +12 -6
  11. package/dist/cli/validate/contract-report.js.map +1 -1
  12. package/dist/cli/validate/find-contract.d.ts +7 -2
  13. package/dist/cli/validate/find-contract.d.ts.map +1 -1
  14. package/dist/cli/validate/find-contract.js +32 -4
  15. package/dist/cli/validate/find-contract.js.map +1 -1
  16. package/dist/cli/validate/upgradeability-assessment.d.ts +2 -1
  17. package/dist/cli/validate/upgradeability-assessment.d.ts.map +1 -1
  18. package/dist/cli/validate/upgradeability-assessment.js +2 -2
  19. package/dist/cli/validate/upgradeability-assessment.js.map +1 -1
  20. package/dist/cli/validate/validate-upgrade-safety.d.ts +11 -3
  21. package/dist/cli/validate/validate-upgrade-safety.d.ts.map +1 -1
  22. package/dist/cli/validate/validate-upgrade-safety.js +27 -7
  23. package/dist/cli/validate/validate-upgrade-safety.js.map +1 -1
  24. package/dist/cli/validate/validate-upgrade-safety.test.js +1 -1
  25. package/dist/cli/validate/validations.d.ts +1 -0
  26. package/dist/cli/validate/validations.d.ts.map +1 -1
  27. package/dist/cli/validate/validations.js +1 -0
  28. package/dist/cli/validate/validations.js.map +1 -1
  29. package/dist/cli/validate/validations.test.js +8 -4
  30. package/dist/cli/validate/validations.test.js.map +1 -1
  31. package/dist/cli/validate.d.ts +1 -0
  32. package/dist/cli/validate.d.ts.map +1 -1
  33. package/dist/cli/validate.js +6 -3
  34. package/dist/cli/validate.js.map +1 -1
  35. package/package.json +2 -2
  36. package/src/cli/cli.test.ts +274 -0
  37. package/src/cli/cli.test.ts.md +119 -0
  38. package/src/cli/cli.test.ts.snap +0 -0
  39. package/src/cli/validate/build-info-file.ts +15 -4
  40. package/src/cli/validate/contract-report.ts +12 -7
  41. package/src/cli/validate/find-contract.ts +50 -4
  42. package/src/cli/validate/upgradeability-assessment.ts +3 -2
  43. package/src/cli/validate/validate-upgrade-safety.test.ts +1 -1
  44. package/src/cli/validate/validate-upgrade-safety.ts +36 -6
  45. package/src/cli/validate/validations.test.ts +8 -4
  46. package/src/cli/validate/validations.ts +2 -0
  47. package/src/cli/validate.ts +7 -2
@@ -19,6 +19,7 @@ Generated by [AVA](https://avajs.dev).
19
19
  --contract <CONTRACT> The name or fully qualified name of the contract to validate. If not specified, all upgradeable contracts in the build info directory will be validated.␊
20
20
  --reference <REFERENCE_CONTRACT> Can only be used when the --contract option is also provided. The name or fully qualified name of the reference contract to use for storage layout comparisons. If not specified, uses the @custom:oz-upgrades-from annotation if it is defined in the contract that is being validated.␊
21
21
  --requireReference Can only be used when the --contract option is also provided. Not compatible with --unsafeSkipStorageCheck. If specified, requires either the --reference option to be provided or the contract to have a @custom:oz-upgrades-from annotation.␊
22
+ --referenceBuildInfoDirs Optional paths of additional build info directories from previous versions of the project to use for storage layout comparisons. When using this option, refer to one of these directories using prefix '<dirName>:' before the contract name or fully qualified name in the --reference option or @custom:oz-upgrades-from annotation, where <dirName> is the directory short name. Each directory short name must be unique, including compared to the main build info directory.␊
22
23
  --unsafeAllow "<VALIDATION_ERRORS>" Selectively disable one or more validation errors. Comma-separated list with one or more of the following: state-variable-assignment, state-variable-immutable, external-library-linking, struct-definition, enum-definition, constructor, delegatecall, selfdestruct, missing-public-upgradeto, internal-function-storage␊
23
24
  --unsafeAllowRenames Configure storage layout check to allow variable renaming.␊
24
25
  --unsafeSkipStorageCheck Skips checking for storage layout compatibility errors. This is a dangerous option meant to be used as a last resort.␊
@@ -39,6 +40,7 @@ Generated by [AVA](https://avajs.dev).
39
40
  --contract <CONTRACT> The name or fully qualified name of the contract to validate. If not specified, all upgradeable contracts in the build info directory will be validated.␊
40
41
  --reference <REFERENCE_CONTRACT> Can only be used when the --contract option is also provided. The name or fully qualified name of the reference contract to use for storage layout comparisons. If not specified, uses the @custom:oz-upgrades-from annotation if it is defined in the contract that is being validated.␊
41
42
  --requireReference Can only be used when the --contract option is also provided. Not compatible with --unsafeSkipStorageCheck. If specified, requires either the --reference option to be provided or the contract to have a @custom:oz-upgrades-from annotation.␊
43
+ --referenceBuildInfoDirs Optional paths of additional build info directories from previous versions of the project to use for storage layout comparisons. When using this option, refer to one of these directories using prefix '<dirName>:' before the contract name or fully qualified name in the --reference option or @custom:oz-upgrades-from annotation, where <dirName> is the directory short name. Each directory short name must be unique, including compared to the main build info directory.␊
42
44
  --unsafeAllow "<VALIDATION_ERRORS>" Selectively disable one or more validation errors. Comma-separated list with one or more of the following: state-variable-assignment, state-variable-immutable, external-library-linking, struct-definition, enum-definition, constructor, delegatecall, selfdestruct, missing-public-upgradeto, internal-function-storage␊
43
45
  --unsafeAllowRenames Configure storage layout check to allow variable renaming.␊
44
46
  --unsafeSkipStorageCheck Skips checking for storage layout compatibility errors. This is a dangerous option meant to be used as a last resort.␊
@@ -187,6 +189,22 @@ Generated by [AVA](https://avajs.dev).
187
189
 
188
190
  ## validate - single contract, reference
189
191
 
192
+ > Snapshot 1
193
+
194
+ `Stdout: ✘ contracts/test/cli/Validate.sol:BecomesBadLayout (upgrades from contracts/test/cli/Validate.sol:StorageV1)␊
195
+ ␊
196
+ StorageV1: Deleted \`x\`␊
197
+ > Keep the variable even if unused␊
198
+ ␊
199
+ StorageV1: Deleted \`__gap\`␊
200
+ > Keep the variable even if unused␊
201
+ ␊
202
+ FAILED␊
203
+ ␊
204
+ Stderr: `
205
+
206
+ ## validate - single contract, reference with same build info dir
207
+
190
208
  > Snapshot 1
191
209
 
192
210
  `Stdout: ✘ contracts/test/cli/Validate.sol:BecomesBadLayout (upgrades from contracts/test/cli/Validate.sol:StorageV1)␊
@@ -304,3 +322,104 @@ Generated by [AVA](https://avajs.dev).
304
322
  ␊
305
323
  SUCCESS␊
306
324
  `
325
+
326
+ ## validate - references other build info dir by command - ok
327
+
328
+ > Snapshot 1
329
+
330
+ {
331
+ stderr: '',
332
+ stdout: ` ✔ contracts/test/cli/ValidateBuildInfoV2_Ok.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
333
+ ␊
334
+ SUCCESS␊
335
+ `,
336
+ }
337
+
338
+ ## validate - references other build info dir by command with fully qualified names - ok
339
+
340
+ > Snapshot 1
341
+
342
+ {
343
+ stderr: '',
344
+ stdout: ` ✔ contracts/test/cli/ValidateBuildInfoV2_Ok.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
345
+ ␊
346
+ SUCCESS␊
347
+ `,
348
+ }
349
+
350
+ ## validate - references other build info dir by command - bad
351
+
352
+ > Snapshot 1
353
+
354
+ `Stdout: ✘ contracts/test/cli/ValidateBuildInfoV2_Bad.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
355
+ ␊
356
+ MyContract: Deleted \`y\`␊
357
+ > Keep the variable even if unused␊
358
+ ␊
359
+ contracts/test/cli/ValidateBuildInfoV2_Bad.sol:6: Upgraded \`__gap\` to an incompatible type␊
360
+ - Bad storage gap resize from 48 to 49␊
361
+ Size cannot increase␊
362
+ ␊
363
+ FAILED␊
364
+ ␊
365
+ Stderr: `
366
+
367
+ ## validate - references other build info dir by command with fully qualified names - bad
368
+
369
+ > Snapshot 1
370
+
371
+ `Stdout: ✘ contracts/test/cli/ValidateBuildInfoV2_Bad.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
372
+ ␊
373
+ MyContract: Deleted \`y\`␊
374
+ > Keep the variable even if unused␊
375
+ ␊
376
+ contracts/test/cli/ValidateBuildInfoV2_Bad.sol:6: Upgraded \`__gap\` to an incompatible type␊
377
+ - Bad storage gap resize from 48 to 49␊
378
+ Size cannot increase␊
379
+ ␊
380
+ FAILED␊
381
+ ␊
382
+ Stderr: `
383
+
384
+ ## validate - references multiple build info dirs by annotation
385
+
386
+ > Snapshot 1
387
+
388
+ `Stdout: ✘ contracts/test/cli/ValidateBuildInfoV2_Branch_Bad.sol:MyContract (upgrades from build-info-v2:contracts/test/cli/ValidateBuildInfoV2_Ok.sol:MyContract)␊
389
+ ␊
390
+ contracts/test/cli/ValidateBuildInfoV2_Branch_Bad.sol:8: Renamed \`z\` to \`zBranch\`␊
391
+ ␊
392
+ ✔ contracts/test/cli/ValidateBuildInfoV2_Branch_Ok.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
393
+ ␊
394
+ FAILED (2 upgradeable contracts detected, 1 passed, 1 failed)␊
395
+ ␊
396
+ Stderr: `
397
+
398
+ ## validate - references other build info dir by annotation - ok
399
+
400
+ > Snapshot 1
401
+
402
+ {
403
+ stderr: '',
404
+ stdout: ` ✔ contracts/test/cli/ValidateBuildInfoV2_Annotation_Ok.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
405
+ ␊
406
+ SUCCESS␊
407
+ `,
408
+ }
409
+
410
+ ## validate - references other build info dir by annotation - bad
411
+
412
+ > Snapshot 1
413
+
414
+ `Stdout: ✘ contracts/test/cli/ValidateBuildInfoV2_Annotation_Bad.sol:MyContract (upgrades from build-info-v1:contracts/test/cli/ValidateBuildInfoV1.sol:MyContract)␊
415
+ ␊
416
+ MyContract: Deleted \`y\`␊
417
+ > Keep the variable even if unused␊
418
+ ␊
419
+ contracts/test/cli/ValidateBuildInfoV2_Annotation_Bad.sol:7: Upgraded \`__gap\` to an incompatible type␊
420
+ - Bad storage gap resize from 48 to 49␊
421
+ Size cannot increase␊
422
+ ␊
423
+ FAILED␊
424
+ ␊
425
+ Stderr: `
Binary file
@@ -49,6 +49,11 @@ export interface BuildInfoFile {
49
49
  * The Solidity compiler output JSON object.
50
50
  */
51
51
  output: SolcOutput;
52
+
53
+ /**
54
+ * Short name of the build info dir containing this file.
55
+ */
56
+ dirShortName: string;
52
57
  }
53
58
 
54
59
  /**
@@ -57,13 +62,18 @@ export interface BuildInfoFile {
57
62
  * @param buildInfoDir Build info directory, or undefined to use the default Hardhat or Foundry build-info dir.
58
63
  * @returns The build info files with Solidity compiler input and output.
59
64
  */
60
- export async function getBuildInfoFiles(buildInfoDir?: string) {
65
+ export async function getBuildInfoFiles(buildInfoDir?: string): Promise<BuildInfoFile[]> {
61
66
  const dir = await findDir(buildInfoDir);
67
+ const shortName = path.basename(dir);
62
68
  const jsonFiles = await getJsonFiles(dir);
63
- return await readBuildInfo(jsonFiles);
69
+
70
+ return await readBuildInfo(jsonFiles, shortName);
64
71
  }
65
72
 
66
- async function findDir(buildInfoDir: string | undefined) {
73
+ /**
74
+ * Finds the build info dir if provided, otherwise finds the default Hardhat or Foundry build info dir. Throws an error if no build info files were found in the expected dir.
75
+ */
76
+ async function findDir(buildInfoDir?: string): Promise<string> {
67
77
  if (buildInfoDir !== undefined && !(await hasJsonFiles(buildInfoDir))) {
68
78
  throw new ValidateCommandError(
69
79
  `The directory '${buildInfoDir}' does not exist or does not contain any build info files.`,
@@ -123,7 +133,7 @@ async function getJsonFiles(dir: string): Promise<string[]> {
123
133
  return jsonFiles.map(file => path.join(dir, file));
124
134
  }
125
135
 
126
- async function readBuildInfo(buildInfoFilePaths: string[]) {
136
+ async function readBuildInfo(buildInfoFilePaths: string[], dirShortName: string) {
127
137
  const buildInfoFiles: BuildInfoFile[] = [];
128
138
 
129
139
  for (const buildInfoFilePath of buildInfoFilePaths) {
@@ -143,6 +153,7 @@ async function readBuildInfo(buildInfoFilePaths: string[]) {
143
153
  input: buildInfoJson.input,
144
154
  output: buildInfoJson.output,
145
155
  solcVersion: buildInfoJson.solcVersion,
156
+ dirShortName: dirShortName,
146
157
  });
147
158
  }
148
159
  }
@@ -17,7 +17,7 @@ import { getUpgradeabilityAssessment } from './upgradeability-assessment';
17
17
  import { SourceContract } from './validations';
18
18
  import { LayoutCompatibilityReport } from '../../storage/report';
19
19
  import { indent } from '../../utils/indent';
20
- import { SpecifiedContracts } from './validate-upgrade-safety';
20
+ import { BuildInfoDictionary, SpecifiedContracts } from './validate-upgrade-safety';
21
21
 
22
22
  /**
23
23
  * Report for an upgradeable contract.
@@ -58,29 +58,30 @@ export class UpgradeableContractReport implements Report {
58
58
  }
59
59
 
60
60
  /**
61
- * Gets upgradeble contract reports for the upgradeable contracts in the given set of source contracts.
61
+ * Gets upgradeble contract reports for the upgradeable contracts in the set of source contracts at dictionary key ''.
62
+ * Reference contracts can come from source contracts at the corresponding dictionary key.
62
63
  * Only contracts that are detected as upgradeable will be included in the reports.
63
64
  * Reports include upgradeable contracts regardless of whether they pass or fail upgrade safety checks.
64
65
  *
65
- * @param sourceContracts The source contracts to check, which must include all contracts that are referenced by the given contracts. Can also include non-upgradeable contracts, which will be ignored.
66
+ * @param buildInfoDictionary Dictionary of build info directories and the source contracts they contain.
66
67
  * @param opts The validation options.
67
68
  * @param specifiedContracts If provided, only the specified contract (upgrading from its reference contract) will be reported.
68
69
  * @returns The upgradeable contract reports.
69
70
  */
70
71
  export function getContractReports(
71
- sourceContracts: SourceContract[],
72
+ buildInfoDictionary: BuildInfoDictionary,
72
73
  opts: Required<ValidateUpgradeSafetyOptions>,
73
74
  specifiedContracts?: SpecifiedContracts,
74
75
  ) {
75
76
  const upgradeableContractReports: UpgradeableContractReport[] = [];
76
77
 
77
78
  const contractsToReport: SourceContract[] =
78
- specifiedContracts !== undefined ? [specifiedContracts.contract] : sourceContracts;
79
+ specifiedContracts !== undefined ? [specifiedContracts.contract] : buildInfoDictionary[''];
79
80
 
80
81
  for (const sourceContract of contractsToReport) {
81
82
  const upgradeabilityAssessment = getUpgradeabilityAssessment(
82
83
  sourceContract,
83
- sourceContracts,
84
+ buildInfoDictionary,
84
85
  specifiedContracts?.reference,
85
86
  );
86
87
  if (opts.requireReference && upgradeabilityAssessment.referenceContract === undefined) {
@@ -129,7 +130,11 @@ function getUpgradeableContractReport(
129
130
  const referenceVersion = getContractVersion(referenceContract.validationData, referenceContract.fullyQualifiedName);
130
131
  const referenceLayout = getStorageLayout(referenceContract.validationData, referenceVersion);
131
132
 
132
- reference = referenceContract.fullyQualifiedName;
133
+ if (referenceContract.buildInfoDirShortName !== contract.buildInfoDirShortName) {
134
+ reference = `${referenceContract.buildInfoDirShortName}:${referenceContract.fullyQualifiedName}`;
135
+ } else {
136
+ reference = referenceContract.fullyQualifiedName;
137
+ }
133
138
  storageLayoutReport = getStorageUpgradeReport(referenceLayout, layout, withValidationDefaults(opts));
134
139
  }
135
140
 
@@ -1,4 +1,6 @@
1
+ import { assert } from '../../utils/assert';
1
2
  import { ValidateCommandError } from './error';
3
+ import { BuildInfoDictionary } from './validate-upgrade-safety';
2
4
  import { SourceContract } from './validations';
3
5
 
4
6
  export class ReferenceContractNotFound extends Error {
@@ -12,7 +14,12 @@ export class ReferenceContractNotFound extends Error {
12
14
  */
13
15
  readonly origin?: string;
14
16
 
15
- constructor(reference: string, origin?: string) {
17
+ /**
18
+ * Build info directories that were also searched.
19
+ */
20
+ readonly buildInfoDirs?: string[];
21
+
22
+ constructor(reference: string, origin?: string, buildInfoDirs?: string[]) {
16
23
  const msg =
17
24
  origin !== undefined
18
25
  ? `Could not find contract ${reference} referenced in ${origin}.`
@@ -20,11 +27,30 @@ export class ReferenceContractNotFound extends Error {
20
27
  super(msg);
21
28
  this.reference = reference;
22
29
  this.origin = origin;
30
+ this.buildInfoDirs = buildInfoDirs;
23
31
  }
24
32
  }
25
33
 
26
- export function findContract(contractName: string, origin: SourceContract | undefined, allContracts: SourceContract[]) {
27
- const foundContracts = allContracts.filter(c => c.fullyQualifiedName === contractName || c.name === contractName);
34
+ export function findContract(
35
+ contractName: string,
36
+ origin: SourceContract | undefined,
37
+ buildInfoDictionary: BuildInfoDictionary,
38
+ onlyMainBuildInfoDir = false,
39
+ ) {
40
+ const foundContracts: SourceContract[] = [];
41
+ if (onlyMainBuildInfoDir) {
42
+ if (hasBuildInfoDirWithContractName(contractName) || hasBuildInfoDirWithFullyQualifiedName(contractName)) {
43
+ throw new ValidateCommandError(
44
+ `Contract ${contractName} must be specified without a build info directory name`,
45
+ () => `Build info directory names can only be specified for reference contracts.`,
46
+ );
47
+ }
48
+ foundContracts.push(...buildInfoDictionary[''].filter(c => isMatchFound(contractName, c, '')));
49
+ } else {
50
+ for (const [dir, contracts] of Object.entries(buildInfoDictionary)) {
51
+ foundContracts.push(...contracts.filter(c => isMatchFound(contractName, c, dir)));
52
+ }
53
+ }
28
54
 
29
55
  if (foundContracts.length > 1) {
30
56
  const msg =
@@ -39,6 +65,26 @@ export function findContract(contractName: string, origin: SourceContract | unde
39
65
  } else if (foundContracts.length === 1) {
40
66
  return foundContracts[0];
41
67
  } else {
42
- throw new ReferenceContractNotFound(contractName, origin?.fullyQualifiedName);
68
+ throw new ReferenceContractNotFound(contractName, origin?.fullyQualifiedName, Object.keys(buildInfoDictionary));
69
+ }
70
+ }
71
+
72
+ function isMatchFound(contractName: string, foundContract: SourceContract, buildInfoDirShortName: string): boolean {
73
+ let prefix = '';
74
+ if (buildInfoDirShortName.length > 0) {
75
+ assert(foundContract.buildInfoDirShortName === buildInfoDirShortName);
76
+ prefix = `${buildInfoDirShortName}:`;
43
77
  }
78
+ return (
79
+ `${prefix}${foundContract.fullyQualifiedName}` === contractName || `${prefix}${foundContract.name}` === contractName
80
+ );
81
+ }
82
+
83
+ function hasBuildInfoDirWithContractName(contractName: string): boolean {
84
+ return contractName.split(':').length === 2 && !contractName.includes('.sol:');
85
+ }
86
+
87
+ function hasBuildInfoDirWithFullyQualifiedName(contractName: string): boolean {
88
+ const tokens = contractName.split(':');
89
+ return tokens.length === 3 && tokens[1].endsWith('.sol');
44
90
  }
@@ -2,6 +2,7 @@ import { getAnnotationArgs, getDocumentation, hasAnnotationTag } from '../../uti
2
2
  import { inferInitializable, inferUUPS } from '../../validate/query';
3
3
  import { ValidateCommandError } from './error';
4
4
  import { findContract } from './find-contract';
5
+ import { BuildInfoDictionary } from './validate-upgrade-safety';
5
6
  import { SourceContract } from './validations';
6
7
 
7
8
  interface AnnotationAssessment {
@@ -17,7 +18,7 @@ export interface UpgradeabilityAssessment {
17
18
 
18
19
  export function getUpgradeabilityAssessment(
19
20
  contract: SourceContract,
20
- allContracts: SourceContract[],
21
+ buildInfoDictionary: BuildInfoDictionary,
21
22
  overrideReferenceContract?: SourceContract,
22
23
  ): UpgradeabilityAssessment {
23
24
  const fullContractName = contract.fullyQualifiedName;
@@ -29,7 +30,7 @@ export function getUpgradeabilityAssessment(
29
30
 
30
31
  let referenceContract = overrideReferenceContract;
31
32
  if (referenceContract === undefined && annotationAssessment.referenceName !== undefined) {
32
- referenceContract = findContract(annotationAssessment.referenceName, contract, allContracts);
33
+ referenceContract = findContract(annotationAssessment.referenceName, contract, buildInfoDictionary);
33
34
  }
34
35
 
35
36
  let isReferenceUUPS = false;
@@ -100,7 +100,7 @@ test('invalid annotation args - upgrades', async t => {
100
100
 
101
101
  test('findSpecifiedContracts - requireReference option without contract', async t => {
102
102
  try {
103
- findSpecifiedContracts([], withCliDefaults({ requireReference: true }));
103
+ findSpecifiedContracts({}, withCliDefaults({ requireReference: true }));
104
104
  } catch (e: any) {
105
105
  t.true(
106
106
  e.message.includes(
@@ -1,3 +1,4 @@
1
+ import path from 'path';
1
2
  import { ValidationOptions, withValidationDefaults } from '../..';
2
3
 
3
4
  import { getBuildInfoFiles } from './build-info-file';
@@ -22,10 +23,11 @@ export type SpecifiedContracts = {
22
23
  * Validates the upgrade safety of all contracts in the build info dir's build info files.
23
24
  * Only contracts that are detected as upgradeable will be validated.
24
25
  *
25
- * @param buildInfoDir Absolute path of build info directory, or undefined to use the default Hardhat or Foundry build-info dir.
26
+ * @param buildInfoDir Path of build info directory, or undefined to use the default Hardhat or Foundry build-info dir.
26
27
  * @param contract The name or fully qualified name of the contract to validate. If not specified, all upgradeable contracts in the build info directory will be validated.
27
28
  * @param reference The name or fully qualified name of the reference contract to use for storage layout comparisons. Can only be used along with `contract`. If not specified, uses the `@custom:oz-upgrades-from` annotation in the contract that is being validated.
28
29
  * @param opts Validation options, or undefined to use the default validation options.
30
+ * @param referenceBuildInfoDirs Optional paths of additional build info directories from previous versions of the project to use for storage layout comparisons. When using this option, refer to one of these directories using prefix `<dirName>:` before the contract name or fully qualified name in the `reference` param or `@custom:oz-upgrades-from` annotation, where `<dirName>` is the directory short name. Each directory short name must be unique, including compared to the main build info directory.
29
31
  * @returns The project report.
30
32
  */
31
33
  export async function validateUpgradeSafety(
@@ -33,28 +35,56 @@ export async function validateUpgradeSafety(
33
35
  contract?: string,
34
36
  reference?: string,
35
37
  opts: ValidateUpgradeSafetyOptions = {},
38
+ referenceBuildInfoDirs?: string[],
36
39
  ): Promise<ProjectReport> {
37
40
  const allOpts = withCliDefaults(opts);
38
41
 
39
42
  const buildInfoFiles = await getBuildInfoFiles(buildInfoDir);
40
43
  const sourceContracts = validateBuildInfoContracts(buildInfoFiles);
41
44
 
42
- const specifiedContracts = findSpecifiedContracts(sourceContracts, allOpts, contract, reference);
45
+ const buildInfoDictionary: BuildInfoDictionary = {};
46
+ buildInfoDictionary[''] = sourceContracts;
47
+ if (buildInfoFiles.length > 0) {
48
+ buildInfoDictionary[buildInfoFiles[0].dirShortName] = sourceContracts;
49
+ }
50
+
51
+ if (referenceBuildInfoDirs !== undefined) {
52
+ for (const referenceBuildInfoDir of referenceBuildInfoDirs) {
53
+ const key = path.basename(referenceBuildInfoDir);
54
+
55
+ if (buildInfoDictionary[key] !== undefined) {
56
+ throw new Error(`Reference build info directory short name '${key}' is not unique.`);
57
+ }
58
+
59
+ const referenceBuildInfoFiles = await getBuildInfoFiles(referenceBuildInfoDir);
60
+ buildInfoDictionary[key] = validateBuildInfoContracts(referenceBuildInfoFiles);
61
+ }
62
+ }
43
63
 
44
- const contractReports = getContractReports(sourceContracts, allOpts, specifiedContracts);
64
+ const specifiedContracts = findSpecifiedContracts(buildInfoDictionary, allOpts, contract, reference);
65
+
66
+ const contractReports = getContractReports(buildInfoDictionary, allOpts, specifiedContracts);
45
67
  return getProjectReport(contractReports, specifiedContracts !== undefined);
46
68
  }
47
69
 
70
+ /**
71
+ * Dictionary of build info directories and the contracts they contain.
72
+ * Main build info directory can be found with the key '' and also with its short name.
73
+ */
74
+ export interface BuildInfoDictionary {
75
+ [buildInfoDirName: string]: SourceContract[];
76
+ }
77
+
48
78
  export function findSpecifiedContracts(
49
- sourceContracts: SourceContract[],
79
+ buildInfoDictionary: BuildInfoDictionary,
50
80
  opts: Required<ValidateUpgradeSafetyOptions>,
51
81
  contractName?: string,
52
82
  referenceName?: string,
53
83
  ): SpecifiedContracts | undefined {
54
84
  if (contractName !== undefined) {
55
85
  return {
56
- contract: findContract(contractName, undefined, sourceContracts),
57
- reference: referenceName !== undefined ? findContract(referenceName, undefined, sourceContracts) : undefined,
86
+ contract: findContract(contractName, undefined, buildInfoDictionary, true), // only search main build info dir for the specified contract
87
+ reference: referenceName !== undefined ? findContract(referenceName, undefined, buildInfoDictionary) : undefined,
58
88
  };
59
89
  } else if (referenceName !== undefined) {
60
90
  throw new Error(`The reference option can only be specified when the contract option is also specified.`);
@@ -14,13 +14,17 @@ const test = _test as TestFn<Context>;
14
14
  const SOURCE_FILE = 'contracts/test/cli/Validate.sol';
15
15
 
16
16
  test.before(async t => {
17
- const buildInfo = await artifacts.getBuildInfo(`${SOURCE_FILE}:Safe`);
17
+ const hardhatBuildInfo = await artifacts.getBuildInfo(`${SOURCE_FILE}:Safe`);
18
18
 
19
- if (buildInfo === undefined) {
19
+ if (hardhatBuildInfo === undefined) {
20
20
  t.fail();
21
21
  } else {
22
- const sourceContracts = validateBuildInfoContracts([buildInfo]);
23
- t.context.reports = getContractReports(sourceContracts, withCliDefaults({}));
22
+ const buildInfoFile = {
23
+ ...hardhatBuildInfo,
24
+ dirShortName: 'build-info',
25
+ };
26
+ const sourceContracts = validateBuildInfoContracts([buildInfoFile]);
27
+ t.context.reports = getContractReports({ '': sourceContracts }, withCliDefaults({}));
24
28
  }
25
29
  });
26
30
 
@@ -13,6 +13,7 @@ export interface SourceContract {
13
13
  name: string;
14
14
  fullyQualifiedName: string;
15
15
  validationData: ValidationRunData;
16
+ buildInfoDirShortName: string;
16
17
  }
17
18
 
18
19
  export function validateBuildInfoContracts(buildInfoFiles: BuildInfoFile[]): SourceContract[] {
@@ -48,6 +49,7 @@ function addContractsFromBuildInfo(
48
49
  name: contractDef.name,
49
50
  fullyQualifiedName,
50
51
  validationData: validationData,
52
+ buildInfoDirShortName: buildInfoFile.dirShortName,
51
53
  });
52
54
  }
53
55
  }
@@ -16,6 +16,7 @@ Options:
16
16
  --contract <CONTRACT> The name or fully qualified name of the contract to validate. If not specified, all upgradeable contracts in the build info directory will be validated.
17
17
  --reference <REFERENCE_CONTRACT> Can only be used when the --contract option is also provided. The name or fully qualified name of the reference contract to use for storage layout comparisons. If not specified, uses the @custom:oz-upgrades-from annotation if it is defined in the contract that is being validated.
18
18
  --requireReference Can only be used when the --contract option is also provided. Not compatible with --unsafeSkipStorageCheck. If specified, requires either the --reference option to be provided or the contract to have a @custom:oz-upgrades-from annotation.
19
+ --referenceBuildInfoDirs Optional paths of additional build info directories from previous versions of the project to use for storage layout comparisons. When using this option, refer to one of these directories using prefix '<dirName>:' before the contract name or fully qualified name in the --reference option or @custom:oz-upgrades-from annotation, where <dirName> is the directory short name. Each directory short name must be unique, including compared to the main build info directory.
19
20
  --unsafeAllow "<VALIDATION_ERRORS>" Selectively disable one or more validation errors. Comma-separated list with one or more of the following: ${errorKinds.join(
20
21
  ', ',
21
22
  )}
@@ -32,6 +33,7 @@ export async function main(args: string[]): Promise<void> {
32
33
  functionArgs.contract,
33
34
  functionArgs.reference,
34
35
  functionArgs.opts,
36
+ functionArgs.referenceBuildInfoDirs,
35
37
  );
36
38
  console.log(result.explain());
37
39
  process.exitCode = result.ok ? 0 : 1;
@@ -48,7 +50,7 @@ function parseArgs(args: string[]) {
48
50
  'unsafeAllowLinkedLibraries',
49
51
  'requireReference',
50
52
  ],
51
- string: ['unsafeAllow', 'contract', 'reference'],
53
+ string: ['unsafeAllow', 'contract', 'reference', 'referenceBuildInfoDirs'],
52
54
  alias: { h: 'help' },
53
55
  });
54
56
  const extraArgs = parsedArgs._;
@@ -71,6 +73,7 @@ interface FunctionArgs {
71
73
  contract?: string;
72
74
  reference?: string;
73
75
  opts: Required<ValidateUpgradeSafetyOptions>;
76
+ referenceBuildInfoDirs?: string[];
74
77
  }
75
78
 
76
79
  /**
@@ -90,6 +93,7 @@ export function getFunctionArgs(parsedArgs: minimist.ParsedArgs, extraArgs: stri
90
93
  const contract = getAndValidateString(parsedArgs, 'contract');
91
94
  const reference = getAndValidateString(parsedArgs, 'reference');
92
95
  const opts = withDefaults(parsedArgs);
96
+ const referenceBuildInfoDirs = getAndValidateString(parsedArgs, 'referenceBuildInfoDirs')?.split(/,+/);
93
97
 
94
98
  if (contract === undefined) {
95
99
  if (reference !== undefined) {
@@ -98,7 +102,7 @@ export function getFunctionArgs(parsedArgs: minimist.ParsedArgs, extraArgs: stri
98
102
  throw new Error('The --requireReference option can only be used along with the --contract option.');
99
103
  }
100
104
  }
101
- return { buildInfoDir, contract, reference, opts };
105
+ return { buildInfoDir, contract, reference, opts, referenceBuildInfoDirs };
102
106
  }
103
107
  }
104
108
 
@@ -125,6 +129,7 @@ function validateOptions(parsedArgs: minimist.ParsedArgs) {
125
129
  'contract',
126
130
  'reference',
127
131
  'requireReference',
132
+ 'referenceBuildInfoDirs',
128
133
  ].includes(key),
129
134
  );
130
135
  if (invalidArgs.length > 0) {