Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using fully qualified names in library Transformations as identifiers #1487

Merged
merged 8 commits into from
Jul 24, 2024

Conversation

kuzdogan
Copy link
Member

@kuzdogan kuzdogan commented Jul 23, 2024

See #1486

Summary by CodeRabbit

  • New Features

    • Introduced new properties for handling link references, enhancing verification capabilities.
    • Added the LinkReferences interface for structured representation of library paths in the codebase.
    • Implemented new libraries for key and claim management, improving decentralized application functionality.
    • Included a comprehensive ABI and metadata for a new smart contract for claims management.
  • Bug Fixes

    • Enhanced error handling for library placeholder mismatches in bytecode verification.
  • Tests

    • Expanded testing suite for contracts compiled with older Solidity versions, enhancing verification robustness.
  • Chores

    • Added a new dependency to improve semantic versioning management within the project.

@kuzdogan kuzdogan requested a review from manuelwedler July 23, 2024 10:23
Copy link
Collaborator

@manuelwedler manuelwedler left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add another test, other than that it looks good

kuzdogan added 2 commits July 24, 2024 10:43
…s value

Prev. we were starting from offset zero and having values like: 0x73abcd... However the bytecode already has 0x73 when comparing for a call protection. So it's actually an offset 1 byte and just 0xabcd
@kuzdogan kuzdogan requested a review from manuelwedler July 24, 2024 09:41
@kuzdogan
Copy link
Member Author

Thanks for pushing for that @manuelwedler. Added a test, and found two bugs during that:

  1. It wouldn't work as expected if the library FQN was longer
  2. We were saving the callProtection transformation with offset: 0 whereas the first byte 0x73 is not changed. Only the next 20 bytes (contract's own address) is replaced.

Copy link
Collaborator

@manuelwedler manuelwedler left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, I'm glad you found these problems :)

@kuzdogan
Copy link
Member Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jul 24, 2024

Walkthrough

The recent updates across the lib-sourcify package improve the handling of link references and library addresses in smart contract verification. Key enhancements include the introduction of structured types for link references, improved management of contract transformations, and updates to test cases to ensure robust verification processes. These changes streamline functionality and bolster type safety, ultimately enhancing the overall efficiency and reliability of smart contract interactions.

Changes

Files Change Summary
packages/lib-sourcify/src/lib/*.ts Simplified handling of immutableReferences, added creationLinkReferences and runtimeLinkReferences, enhancing type safety and readability.
packages/lib-sourcify/src/lib/verification.ts Enhanced functions for handling link references, improving accuracy in bytecode verification by integrating reference properties into existing functions.
services/server/src/server/services/... Updated library mapping logic to standardize library names based on compiler versions, improving clarity and consistency in output JSON.
services/server/test/helpers/assertions.ts Introduced assertTransformations function to validate transformation data in the database, enhancing the integrity checks within the testing framework.
services/server/test/integration/... Added new test cases to verify contracts using older Solidity versions, focusing on library transformations and function interactions.
services/server/test/testcontracts/... New artifact.json and metadata.json files to define the ABI and metadata for the ClaimHolderLibrary, detailing functions and events for interaction.
services/server/test/verifier-alliance/... Updated library identifiers in JSON configuration for better clarity and traceability, replacing generic placeholders with specific contract references.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant Database

    User->>Server: Request contract verification
    Server->>Database: Query for contract details
    Database-->>Server: Return contract data
    Server->>Server: Process link references and transformations
    Server-->>User: Return verification results
Loading

🐇
In the land of code, where changes sprout,
Libraries linked, without a doubt!
Transformations now take flight,
Enhancing contracts, oh what a sight!
With structured types and tests anew,
Our rabbit hops on, ready to pursue! 🌟


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9ef9d27 and 806221a.

Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (12)
  • packages/lib-sourcify/src/lib/CheckedContract.ts (1 hunks)
  • packages/lib-sourcify/src/lib/types.ts (2 hunks)
  • packages/lib-sourcify/src/lib/verification.ts (11 hunks)
  • packages/lib-sourcify/test/verification.spec.ts (5 hunks)
  • services/server/package.json (1 hunks)
  • services/server/src/server/services/storageServices/SourcifyDatabaseService.ts (3 hunks)
  • services/server/test/helpers/assertions.ts (2 hunks)
  • services/server/test/integration/verification-handlers/verify.stateless.spec.ts (3 hunks)
  • services/server/test/testcontracts/LibrariesPreSolidity050/artifact.json (1 hunks)
  • services/server/test/testcontracts/LibrariesPreSolidity050/metadata.json (1 hunks)
  • services/server/test/testcontracts/LibrariesPreSolidity050/sources/ClaimHolderLibrary.sol (1 hunks)
  • services/server/test/verifier-alliance/libraries_manually_linked.json (1 hunks)
Additional context used
GitHub Check: codecov/patch
services/server/src/server/services/storageServices/SourcifyDatabaseService.ts

[warning] 323-327: services/server/src/server/services/storageServices/SourcifyDatabaseService.ts#L323-L327
Added lines #L323 - L327 were not covered by tests

packages/lib-sourcify/src/lib/verification.ts

[warning] 180-180: packages/lib-sourcify/src/lib/verification.ts#L180
Added line #L180 was not covered by tests


[warning] 202-202: packages/lib-sourcify/src/lib/verification.ts#L202
Added line #L202 was not covered by tests


[warning] 732-732: packages/lib-sourcify/src/lib/verification.ts#L732
Added line #L732 was not covered by tests


[warning] 736-737: packages/lib-sourcify/src/lib/verification.ts#L736-L737
Added lines #L736 - L737 were not covered by tests

Additional comments not posted (50)
services/server/test/testcontracts/LibrariesPreSolidity050/metadata.json (1)

1-1: Metadata structure is correct.

The metadata file adheres to the expected structure for Solidity contracts compiled with version 0.4.26. The ABI and other fields are properly formatted.

services/server/package.json (1)

73-73: New dependency "semver" added correctly.

The "semver" package version "7.6.2" has been correctly added to the dependencies section.

services/server/test/helpers/assertions.ts (3)

115-123: Function assertTransformations correctly implemented.

The function is well-structured and takes appropriate parameters to validate transformation data in the database.


124-139: SQL query and data retrieval in assertTransformations are correct.

The SQL query correctly joins the necessary tables and retrieves the relevant data for validation.


141-160: Data validation in assertTransformations is correct.

The function correctly validates the retrieved data against the expected values using assertions.

services/server/test/verifier-alliance/libraries_manually_linked.json (3)

139-141: LGTM! The library identifier change improves clarity.

The new fully qualified name enhances the specificity and traceability of the library reference.


147-149: LGTM! The transformation ID change improves clarity.

The new fully qualified name enhances the specificity and traceability of the transformation reference.


155-157: LGTM! The runtime library identifier and transformation ID changes improve clarity.

The new fully qualified names enhance the specificity and traceability of the library and transformation references.

Also applies to: 163-165

packages/lib-sourcify/src/lib/types.ts (3)

157-166: LGTM! The LinkReferences interface is well-defined.

The new interface enhances type safety and clarity in managing link references.


173-174: LGTM! The update to RecompilationResult improves functionality.

The new properties enhance the tracking and management of link references during both creation and runtime phases.


193-194: LGTM! The CallProtectionTransformation offset change is well-justified.

The change from 0 to 1 aligns with the PUSH20 opcode, and the comment provides clear justification.

services/server/test/testcontracts/LibrariesPreSolidity050/sources/ClaimHolderLibrary.sol (10)

4-9: LGTM! The events in KeyHolderLibrary are well-defined.

The events cover key management and execution, providing necessary logging for these actions.


11-30: LGTM! The structs in KeyHolderLibrary are well-defined.

The structs provide a clear and organized way to manage keys, key holder data, and executions.


32-41: LGTM! The init function is well-implemented.

The function correctly initializes the key holder data with the sender's key and emits the KeyAdded event.


43-69: LGTM! The key retrieval functions are well-implemented.

The functions provide a clear and efficient way to retrieve keys and key purposes from the key holder data.


71-105: LGTM! The key addition functions are well-implemented.

The functions provide a clear and efficient way to add keys and multiple keys to the key holder data.


107-141: LGTM! The approve function is well-implemented.

The function correctly handles the approval of executions and emits the appropriate events.


143-160: LGTM! The execute function is well-implemented.

The function correctly handles the execution of transactions and emits the appropriate events.


162-201: LGTM! The removeKey function is well-implemented.

The function correctly handles the removal of keys and emits the appropriate events.


203-221: LGTM! The keyHasPurpose function is well-implemented.

The function correctly checks if a key has a specific purpose in the key holder data.


224-374: LGTM! The ClaimHolderLibrary functions and events are well-implemented.

The functions and events provide a clear and efficient way to manage claims and emit the appropriate events.

services/server/test/testcontracts/LibrariesPreSolidity050/artifact.json (2)

2-67: ABI is well-formed.

The ABI definitions for the functions and events appear to be correct and consistent with standard practices.


243-244: Bytecode is well-formed.

The bytecode appears to be correctly formatted and consistent with standard practices.

services/server/src/server/services/storageServices/SourcifyDatabaseService.ts (2)

5-5: New imports are necessary and correct.

The new imports for StringMap, keccak256Str, format, and semver are necessary for the added functionality and are correctly imported.

Also applies to: 26-26, 28-28, 31-31


312-330: Library mapping and transformation logic is well-structured.

The logic correctly handles the transformation of library names based on the Solidity compiler version. Ensure that this logic is covered by tests.

Tools
GitHub Check: codecov/patch

[warning] 323-327: services/server/src/server/services/storageServices/SourcifyDatabaseService.ts#L323-L327
Added lines #L323 - L327 were not covered by tests

services/server/test/integration/verification-handlers/verify.stateless.spec.ts (2)

2-2: New imports are necessary and correct.

The new imports for assertTransformations, CallProtectionTransformation, and LibraryTransformation are necessary for the added test functionality and are correctly imported.

Also applies to: 21-24


770-835: New test case is well-structured.

The test case correctly tests the verification of contracts with Solidity < 0.5.0 and handling non-keccak values for library placeholders.

packages/lib-sourcify/src/lib/verification.ts (16)

426-427: Ensure linkReferences is correctly integrated.

The addition of linkReferences should be verified for correct usage in the function.


459-464: Ensure correct handling of immutableReferences and linkReferences.

Verify that both immutableReferences and linkReferences are correctly handled in the function.

Verification successful

Ensure correct handling of immutableReferences and linkReferences.

The immutableReferences and linkReferences are indeed used and handled in the verification.ts file and other related files. The context provided by the search results shows that these references are being processed appropriately.

  • packages/lib-sourcify/src/lib/verification.ts: Multiple instances where immutableReferences and linkReferences are utilized.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct handling of `immutableReferences` and `linkReferences`.

# Test: Search for the usage of `immutableReferences` and `linkReferences`.
rg --type python -A 5 $'immutableReferences'

Length of output: 74


Script:

#!/bin/bash
# Description: Verify correct handling of `immutableReferences` and `linkReferences`.

# Test: Search for the usage of `immutableReferences` and `linkReferences` in TypeScript files.
rg --type ts -A 5 'immutableReferences'
rg --type ts -A 5 'linkReferences'

Length of output: 20438


530-530: Ensure linkReferences is correctly integrated.

The addition of linkReferences should be verified for correct usage in the function.

Verification successful

linkReferences is correctly integrated and used within the matchWithCreationTx function and other parts of the codebase.

The search results confirm its usage in various contexts, ensuring proper integration.

  • packages/lib-sourcify/src/lib/verification.ts: Multiple instances of linkReferences being used as a parameter and within function logic.
  • Other files also show usage, indicating it is a well-integrated part of the codebase.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences`.
rg --type python -A 5 $'linkReferences'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type typescript -A 5 'linkReferences'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type ts -A 5 'linkReferences'

Length of output: 7488


701-706: Ensure linkReferences is correctly integrated.

The addition of linkReferences should be verified for correct usage in the function.

Verification successful

The linkReferences parameter is correctly integrated.

The parameter linkReferences is used appropriately within the handleLibraries function and related code, ensuring that the necessary transformations are performed.

  • File: packages/lib-sourcify/src/lib/verification.ts
  • Lines: 701-706
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences`.
rg --type python -A 5 $'linkReferences'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type typescript -A 5 'linkReferences'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences`.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type ts -A 5 'linkReferences'

Length of output: 7488


739-755: Ensure correct handling of linkReferences in library address replacements.

Verify that linkReferences is correctly handled when replacing library addresses.


202-202: Ensure recompiled.creationLinkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the recompiled.creationLinkReferences parameter.

Verification successful

recompiled.creationLinkReferences is correctly integrated into the retry logic.

The parameter is consistently passed to the matchWithCreationTx function in both the initial attempt and the retry logic.

  • packages/lib-sourcify/src/lib/verification.ts: Lines where recompiled.creationLinkReferences is used in the retry logic.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in retry logic.

# Test: Search for the usage of `recompiled.creationLinkReferences` in retry logic.
rg --type python -A 5 $'recompiled.creationLinkReferences'

Length of output: 88


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in retry logic.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the TypeScript codebase.
rg --type ts -A 10 'recompiled.creationLinkReferences' packages/lib-sourcify/src/lib/verification.ts

Length of output: 729


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in retry logic.

# Test: Get more context around the retry logic involving `recompiled.creationLinkReferences`.
rg --type ts -A 20 -B 10 'recompiled.creationLinkReferences' packages/lib-sourcify/src/lib/verification.ts

Length of output: 1725

Tools
GitHub Check: codecov/patch

[warning] 202-202: packages/lib-sourcify/src/lib/verification.ts#L202
Added line #L202 was not covered by tests


712-737: Verify the handling of linkReferences in library placeholders.

Ensure that linkReferences is correctly handled when dealing with library placeholders.

Verification successful

Verify the handling of linkReferences in library placeholders.

The handling of linkReferences in the provided code snippet is consistent and correctly implemented. The code ensures that the placeholders are calculated and compared accurately, handling both the current and pre v0.5.0 formats.

  • packages/lib-sourcify/src/lib/verification.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in library placeholders.

# Test: Search for the usage of `linkReferences` in library placeholders.
rg --type python -A 5 $'linkReferences'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in library placeholders.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type typescript -A 5 'linkReferences'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in library placeholders.

# Test: Search for the usage of `linkReferences` in TypeScript files.
rg --type ts -A 5 'linkReferences'

Length of output: 7488

Tools
GitHub Check: codecov/patch

[warning] 732-732: packages/lib-sourcify/src/lib/verification.ts#L732
Added line #L732 was not covered by tests


[warning] 736-737: packages/lib-sourcify/src/lib/verification.ts#L736-L737
Added lines #L736 - L737 were not covered by tests


576-581: Verify the handling of linkReferences in handleLibraries.

Ensure that linkReferences is correctly passed and handled in the handleLibraries function.

Verification successful

linkReferences is correctly passed and handled in handleLibraries.

The linkReferences parameter is iterated over, and its contents are used to generate placeholders and addresses, which are then used to update the template and libraryMap.

  • File: packages/lib-sourcify/src/lib/verification.ts
  • Function: handleLibraries
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Test: Search for the usage of `linkReferences` in `handleLibraries`.
rg --type python -A 5 $'handleLibraries'

Length of output: 70


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Locate the `handleLibraries` function definition in TypeScript files.
ast-grep --lang typescript --pattern 'function handleLibraries($_, $_, $_, $_, $_) { $$$ }'

# Check how `linkReferences` is used within the `handleLibraries` function.
rg 'handleLibraries' -A 10 --type ts

Length of output: 2738


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Extract the full implementation of the `handleLibraries` function from the specified file.
ast-grep --lang typescript --pattern $'function handleLibraries($_, $_, $_, $_, $_) { $$$ }' packages/lib-sourcify/src/lib/verification.ts

Length of output: 139


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Search for the `handleLibraries` function definition and include sufficient context lines to capture the full implementation.
rg 'function handleLibraries' -A 50 packages/lib-sourcify/src/lib/verification.ts

Length of output: 2016


142-142: Ensure recompiled.runtimeLinkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the recompiled.runtimeLinkReferences parameter.

Verification successful

Verified: recompiled.runtimeLinkReferences is correctly integrated into the retry logic.

The parameter is consistently used in both the initial matching attempt and the retry mechanism, ensuring proper handling within the retry logic.

  • packages/lib-sourcify/src/lib/verification.ts:
    • Lines involving recompiled.runtimeLinkReferences and the retry logic are correctly implemented.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.runtimeLinkReferences` in retry logic.

# Test: Search for the usage of `recompiled.runtimeLinkReferences` in retry logic.
rg --type python -A 5 $'recompiled.runtimeLinkReferences'

Length of output: 87


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.runtimeLinkReferences` in retry logic.

# Test: Search for the usage of `recompiled.runtimeLinkReferences` in retry logic.
rg --type typescript -A 5 'recompiled.runtimeLinkReferences'

Length of output: 95


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.runtimeLinkReferences` in retry logic.

# Test: Search for the usage of `recompiled.runtimeLinkReferences` in retry logic.
rg --type ts -A 5 'recompiled.runtimeLinkReferences'

Length of output: 913


Script:

#!/bin/bash
# Description: Extract a larger portion of the verification.ts file around the found instances to understand the retry logic and the integration of recompiled.runtimeLinkReferences.

# Extract 20 lines before and after the first instance of recompiled.runtimeLinkReferences
rg --type ts -A 20 -B 20 'recompiled.runtimeLinkReferences' packages/lib-sourcify/src/lib/verification.ts

Length of output: 1861


123-123: Ensure recompiled.runtimeLinkReferences is correctly integrated.

The addition of recompiled.runtimeLinkReferences should be verified for correct usage in the function.


776-776: Ensure linkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the linkReferences parameter.


180-180: Ensure recompiled.creationLinkReferences is correctly integrated.

The addition of recompiled.creationLinkReferences should be verified for correct usage in the function.

Verification successful

Ensure recompiled.creationLinkReferences is correctly integrated.

The occurrences of recompiled.creationLinkReferences appear to be correctly integrated within the function calls and tests. They are used consistently along with other parameters such as sourcifyChainHardhat, contractAddress, recompiledMetadata, and generateCreationCborAuxdataPositions.

  • Integration points:
    • Multiple instances in function calls and test cases, indicating that recompiled.creationLinkReferences is being utilized as intended.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences`.

# Test: Search for the usage of `recompiled.creationLinkReferences`.
rg --type python -A 5 $'recompiled.creationLinkReferences'

Length of output: 88


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences`.

# Test: Search for the usage of `recompiled.creationLinkReferences` in TypeScript files.
rg --type typescript -A 5 'recompiled.creationLinkReferences'

Length of output: 96


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences`.

# Find all TypeScript files and search for the usage of `recompiled.creationLinkReferences`.
fd --type f --extension ts --exec rg 'recompiled.creationLinkReferences' {}

Length of output: 386


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences`.

# Find all TypeScript files and search for the usage of `recompiled.creationLinkReferences` with additional context.
fd --type f --extension ts --exec rg -C 5 'recompiled.creationLinkReferences' {}

Length of output: 2616

Tools
GitHub Check: codecov/patch

[warning] 180-180: packages/lib-sourcify/src/lib/verification.ts#L180
Added line #L180 was not covered by tests


Line range hint 904-904: Ensure linkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the linkReferences parameter.


Line range hint 822-822: Ensure linkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the linkReferences parameter.


Line range hint 860-860: Ensure linkReferences is correctly integrated in the retry logic.

The retry logic should correctly handle the linkReferences parameter.


450-455: Verify the handling of linkReferences in handleLibraries.

Ensure that linkReferences is correctly passed and handled in the handleLibraries function.

Verification successful

Verified the handling of linkReferences in handleLibraries.

The linkReferences parameter is correctly passed and used within the function to iterate over its properties, perform necessary transformations, and update relevant data structures.

  • linkReferences is used in nested loops to access its properties.
  • Data extracted from linkReferences is used to perform string manipulations and transformations.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Test: Search for the usage of `linkReferences` in `handleLibraries`.
rg --type python -A 5 $'handleLibraries'

Length of output: 70


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Test: Search for the definition of `handleLibraries` function in TypeScript files.
rg --type typescript 'function handleLibraries'

# Test: Search for the usage of `linkReferences` within the `handleLibraries` function.
rg --type typescript 'handleLibraries' -A 10

Length of output: 164


Script:

#!/bin/bash
# Description: Verify correct handling of `linkReferences` in `handleLibraries`.

# Test: Search for the definition of `handleLibraries` function in TypeScript files.
rg --type ts 'function handleLibraries'

# Test: Search for the usage of `linkReferences` within the `handleLibraries` function.
rg --type ts 'handleLibraries' -A 10

Length of output: 2765


Script:

#!/bin/bash
# Description: Extract the full implementation of the `handleLibraries` function to verify the handling of `linkReferences`.

# Test: Extract the full implementation of `handleLibraries` function in TypeScript files.
rg --type ts --context 50 'export function handleLibraries' packages/lib-sourcify/src/lib/verification.ts

Length of output: 4063

packages/lib-sourcify/src/lib/CheckedContract.ts (3)

481-481: Simplified handling of immutableReferences.

The change simplifies the logic by defaulting to an empty object if immutableReferences is not present.


482-482: Introduction of creationLinkReferences.

The change introduces creationLinkReferences to improve the robustness of the code.


483-484: Introduction of runtimeLinkReferences.

The change introduces runtimeLinkReferences to improve the robustness of the code.

packages/lib-sourcify/test/verification.spec.ts (4)

860-860: **


776-776: Ensure recompiled.creationLinkReferences is correctly integrated in the test case.

The test case should correctly handle the recompiled.creationLinkReferences parameter.

Verification successful

Ensure recompiled.creationLinkReferences is correctly integrated in the test case.

The recompiled.creationLinkReferences parameter is correctly integrated and tested in the verification.spec.ts file.

  • Instances of recompiled.creationLinkReferences are found in multiple test cases within packages/lib-sourcify/test/verification.spec.ts.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the test case.
rg --type python -A 5 $'recompiled.creationLinkReferences'

Length of output: 88


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the test case.
rg --type ts -A 5 'recompiled.creationLinkReferences'

Length of output: 3510


714-714: Ensure recompiled.creationLinkReferences is correctly integrated in the test case.

The test case should correctly handle the recompiled.creationLinkReferences parameter.

Verification successful

Ensure recompiled.creationLinkReferences is correctly integrated in the test case.

The parameter recompiled.creationLinkReferences is correctly integrated and referenced in multiple test cases within the verification.spec.ts file, ensuring thorough testing.

  • File: packages/lib-sourcify/test/verification.spec.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the test case.
rg --type python -A 5 $'recompiled.creationLinkReferences'

Length of output: 88


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the test case.
rg --type ts -A 5 'recompiled.creationLinkReferences'

Length of output: 3510


822-822: Ensure recompiled.creationLinkReferences is correctly integrated in the test case.

The test case should correctly handle the recompiled.creationLinkReferences parameter.

Verification successful

The integration of recompiled.creationLinkReferences in the test cases is correct.

The parameter recompiled.creationLinkReferences is appropriately included and tested in the test cases.

  • File: packages/lib-sourcify/test/verification.spec.ts
  • Lines: Multiple instances found
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the test case.
rg --type python -A 5 $'recompiled.creationLinkReferences'

Length of output: 88


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in the TypeScript test file.
rg --type typescript -A 5 'recompiled.creationLinkReferences'

Length of output: 96


Script:

#!/bin/bash
# Description: Verify correct integration of `recompiled.creationLinkReferences` in the test case.

# Test: Search for the usage of `recompiled.creationLinkReferences` in TypeScript test files.
rg 'recompiled.creationLinkReferences' --glob '*.ts' -A 5

Length of output: 3514


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
packages/lib-sourcify/src/lib/verification.ts (1)

714-714: Ensure linkReferences is correctly integrated in error handling.

The current implementation includes some conditional checks for linkReferences, but it lacks comprehensive error handling mechanisms such as try-catch blocks or detailed conditional checks. Consider enhancing the error handling for linkReferences to ensure robustness.

  • Add explicit error handling mechanisms for linkReferences, such as try-catch blocks or detailed conditional checks.
Analysis chain

Ensure linkReferences is correctly integrated in error handling.

The error handling should correctly handle the linkReferences parameter.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences` in error handling.

# Test: Search for the usage of `linkReferences` in error handling.
rg --type python -A 5 $'linkReferences'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences` in error handling.

# Test: Search for the usage of `linkReferences` in error handling.
rg --type ts -A 5 'linkReferences'

Length of output: 7488


Script:

#!/bin/bash
# Description: Verify correct integration of `linkReferences` in error handling.

# Test: Search for error handling constructs involving `linkReferences` in the verification.ts file.
rg --type ts -A 5 'linkReferences' packages/lib-sourcify/src/lib/verification.ts | rg -B 5 -A 5 'try|catch|if|throw|error'

Length of output: 1169

Comment on lines +323 to +327
// Solidity < 0.5.0 is __MyLib__________ (total 40 characters)
const libName = key.split(":")[1];
const trimmedLibName = libName.slice(0, 36); // in case it's longer
formattedKey = "__" + trimmedLibName.padEnd(38, "_");
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add test coverage for library names handling for Solidity < 0.5.0.

The logic for handling library names for Solidity < 0.5.0 is not covered by tests.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 323-327: services/server/src/server/services/storageServices/SourcifyDatabaseService.ts#L323-L327
Added lines #L323 - L327 were not covered by tests

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generate unit testing code

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kuzdogan, here are the unit tests to cover the handling of library names for Solidity < 0.5.0 in the SourcifyDatabaseService class:

import { SourcifyDatabaseService } from '../src/server/services/storageServices/SourcifyDatabaseService';
import { StorageService } from '../src/server/services/StorageService';
import { Pool } from 'pg';
import { Match } from '@ethereum-sourcify/lib-sourcify';
import semver from 'semver';

describe('SourcifyDatabaseService', () => {
  let sourcifyDatabaseService: SourcifyDatabaseService;
  let mockStorageService: jest.Mocked<StorageService>;
  let mockDatabasePool: jest.Mocked<Pool>;

  beforeEach(() => {
    mockStorageService = {} as jest.Mocked<StorageService>;
    mockDatabasePool = {} as jest.Mocked<Pool>;
    sourcifyDatabaseService = new SourcifyDatabaseService(mockStorageService, { pool: mockDatabasePool });
  });

  describe('getFiles', () => {
    it('should format library names correctly for Solidity < 0.5.0', async () => {
      const chainId = '1';
      const address = '0x1234567890abcdef1234567890abcdef12345678';
      const sourcifyMatch: Match = {
        address,
        chainId,
        runtimeMatch: 'partial',
        creationMatch: 'partial',
        storageTimestamp: new Date(),
        runtime_values: {
          libraries: {
            'contracts/MyLib.sol:MyLib': '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef'
          }
        },
        metadata: {
          compiler: {
            version: '0.4.26'
          }
        }
      };

      jest.spyOn(Database, 'getSourcifyMatchByChainAddress').mockResolvedValueOnce({
        rowCount: 1,
        rows: [sourcifyMatch]
      });

      const result = await sourcifyDatabaseService.getFiles(chainId, address);

      expect(result.files['library-map.json']).toBeDefined();
      const formattedLibraries = JSON.parse(result.files['library-map.json']);
      expect(formattedLibraries['__MyLib___________________________']).toBe('0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef');
    });

    it('should format library names correctly for Solidity >= 0.5.0', async () => {
      const chainId = '1';
      const address = '0x1234567890abcdef1234567890abcdef12345678';
      const sourcifyMatch: Match = {
        address,
        chainId,
        runtimeMatch: 'partial',
        creationMatch: 'partial',
        storageTimestamp: new Date(),
        runtime_values: {
          libraries: {
            'contracts/MyLib.sol:MyLib': '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef'
          }
        },
        metadata: {
          compiler: {
            version: '0.5.0'
          }
        }
      };

      jest.spyOn(Database, 'getSourcifyMatchByChainAddress').mockResolvedValueOnce({
        rowCount: 1,
        rows: [sourcifyMatch]
      });

      const result = await sourcifyDatabaseService.getFiles(chainId, address);

      expect(result.files['library-map.json']).toBeDefined();
      const formattedLibraries = JSON.parse(result.files['library-map.json']);
      expect(formattedLibraries['__$' + keccak256Str('contracts/MyLib.sol:MyLib').slice(2).slice(0, 34) + '$__']).toBe('0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef');
    });
  });
});

These tests cover the logic for handling library names for both Solidity < 0.5.0 and Solidity >= 0.5.0. The tests ensure that the library names are correctly formatted to their respective placeholder formats.


Learnings added
Learnt from: kuzdogan
PR: ethereum/sourcify#1487
File: services/server/src/server/services/storageServices/SourcifyDatabaseService.ts:323-327
Timestamp: 2024-07-24T13:35:59.966Z
Learning: Generate unit tests for handling library names in Solidity < 0.5.0 by creating scenarios where the library names are processed and ensuring that the output matches the expected placeholder format.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do it in nock, chai and mocha

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kuzdogan, here are the unit tests rewritten to use nock, chai, and mocha:

import { expect } from 'chai';
import nock from 'nock';
import { SourcifyDatabaseService } from '../src/server/services/storageServices/SourcifyDatabaseService';
import { StorageService } from '../src/server/services/StorageService';
import { Pool } from 'pg';
import { Match } from '@ethereum-sourcify/lib-sourcify';
import semver from 'semver';
import * as Database from '../src/server/services/utils/database-util';

describe('SourcifyDatabaseService', () => {
  let sourcifyDatabaseService: SourcifyDatabaseService;
  let mockStorageService: StorageService;
  let mockDatabasePool: Pool;

  beforeEach(() => {
    mockStorageService = {} as StorageService;
    mockDatabasePool = {} as Pool;
    sourcifyDatabaseService = new SourcifyDatabaseService(mockStorageService, { pool: mockDatabasePool });
  });

  describe('getFiles', () => {
    it('should format library names correctly for Solidity < 0.5.0', async () => {
      const chainId = '1';
      const address = '0x1234567890abcdef1234567890abcdef12345678';
      const sourcifyMatch: Match = {
        address,
        chainId,
        runtimeMatch: 'partial',
        creationMatch: 'partial',
        storageTimestamp: new Date(),
        runtime_values: {
          libraries: {
            'contracts/MyLib.sol:MyLib': '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef'
          }
        },
        metadata: {
          compiler: {
            version: '0.4.26'
          }
        }
      };

      nock('http://localhost')
        .get(`/sourcifyMatch/${chainId}/${address}`)
        .reply(200, {
          rowCount: 1,
          rows: [sourcifyMatch]
        });

      const result = await sourcifyDatabaseService.getFiles(chainId, address);

      expect(result.files['library-map.json']).to.exist;
      const formattedLibraries = JSON.parse(result.files['library-map.json']);
      expect(formattedLibraries['__MyLib___________________________']).to.equal('0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef');
    });

    it('should format library names correctly for Solidity >= 0.5.0', async () => {
      const chainId = '1';
      const address = '0x1234567890abcdef1234567890abcdef12345678';
      const sourcifyMatch: Match = {
        address,
        chainId,
        runtimeMatch: 'partial',
        creationMatch: 'partial',
        storageTimestamp: new Date(),
        runtime_values: {
          libraries: {
            'contracts/MyLib.sol:MyLib': '0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef'
          }
        },
        metadata: {
          compiler: {
            version: '0.5.0'
          }
        }
      };

      nock('http://localhost')
        .get(`/sourcifyMatch/${chainId}/${address}`)
        .reply(200, {
          rowCount: 1,
          rows: [sourcifyMatch]
        });

      const result = await sourcifyDatabaseService.getFiles(chainId, address);

      expect(result.files['library-map.json']).to.exist;
      const formattedLibraries = JSON.parse(result.files['library-map.json']);
      expect(formattedLibraries['__$' + keccak256Str('contracts/MyLib.sol:MyLib').slice(2).slice(0, 34) + '$__']).to.equal('0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef');
    });
  });
});

These tests now use nock to mock HTTP requests, chai for assertions, and mocha as the test runner. This should align with your preferred testing stack.


Learnings used
Learnt from: kuzdogan
PR: ethereum/sourcify#1487
File: services/server/src/server/services/storageServices/SourcifyDatabaseService.ts:323-327
Timestamp: 2024-07-24T13:36:00.611Z
Learning: Generate unit tests for handling library names in Solidity < 0.5.0 by creating scenarios where the library names are processed and ensuring that the output matches the expected placeholder format.

@ethereum ethereum deleted a comment Jul 24, 2024
@kuzdogan kuzdogan merged commit 9f005c8 into staging Jul 24, 2024
6 checks passed
@kuzdogan kuzdogan deleted the fqn-in-library-map branch July 29, 2024 11:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: COMPLETED
Development

Successfully merging this pull request may close these issues.

2 participants