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

Update starknet counter example for Sepolia (devnet and testnet) #403

Merged
merged 4 commits into from
Oct 2, 2024

Conversation

devnet0x
Copy link
Contributor

@devnet0x devnet0x commented Sep 26, 2024

Fix Starknet Counter example for devnet and sepolia networks. Close issue #399

Summary by CodeRabbit

  • New Features

    • Updated configuration for the StarkNet provider to use a local server.
    • Changed the test network identifier to a new value.
  • Bug Fixes

    • Improved UI responsiveness by altering the control flow in the counter update method.
  • Chores

    • Updated dependency sources from Git repositories to local paths for better project management.
    • Adjusted default versioning format in transaction initialization.
    • Modified development environment configurations for local network access.

Copy link

docs-page bot commented Sep 26, 2024

To view this pull requests documentation preview, visit the following URL:

starknetdart.dev/~403

Documentation is deployed and generated using docs.page.

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes in this pull request involve updates to configuration settings and code logic in the StarkNet counter example. Key modifications include changing the StarkNet provider's URI to a local server, updating contract and account addresses, and altering the test network identifier. Additionally, adjustments were made to the method of handling asynchronous calls in the UI, as well as dependency sources in the project configuration.

Changes

File Path Change Summary
examples/starknet_counter/lib/services/counter_service.dart Updated StarkNet provider configuration, contract address, and account details.
examples/starknet_counter/lib/ui/counter.dart Simplified asynchronous handling in _increaseCount, _increaseCountBy, and _decreaseCount methods.
examples/starknet_counter/pubspec_overrides.yaml Changed dependency sources from Git to local paths for starknet and starknet_provider.
packages/starknet/lib/src/static_config.dart Updated testNet variable from SN_GOERLI to SN_SEPOLIA.
packages/starknet_provider/lib/src/model/invoke_transaction.freezed.dart Changed default version parameter from '0x01' to '0x1'.
packages/starknet_provider/lib/src/model/invoke_transaction.dart Changed default version parameter from '0x01' to '0x1'.

Possibly related issues

🐰 In the meadow, changes bloom,
A counter service sheds its gloom.
From Goerli's grasp to Sepolia's light,
With local paths, the code takes flight.
Async no more, the UI flows,
In the world of StarkNet, progress grows! 🌼


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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: 2

🧹 Outside diff range and nitpick comments (6)
examples/starknet_counter/pubspec_overrides.yaml (2)

5-7: Consider documenting setup process for Sepolia testing

Given that this PR aims to update the Starknet counter example for Sepolia (devnet and testnet), the switch to local package references makes sense for development and testing. However, to ensure that this example remains accessible and easy to use for other developers interested in testing on Sepolia, consider the following:

  1. Add documentation in the README or a separate CONTRIBUTING.md file explaining how to set up the project structure for running this example.
  2. Provide instructions on how to switch between using local packages and the published versions of starknet and starknet_provider.
  3. If possible, consider creating a script that can automatically set up the correct project structure or switch between local and remote package sources.

This will help maintain the balance between ease of development and accessibility for other contributors or users of this example.


Line range hint 9-19: Unchanged commented-out sections

The commented-out sections for wallet_kit and secure_store remain unchanged. While they don't affect the current changes, it might be worth considering:

  1. Are these commented-out sections still relevant to the project?
  2. If they are no longer needed, should they be removed to keep the file clean?
  3. If they are needed in the future, should there be a comment explaining when or why they might be uncommented?

This is a minor point and doesn't require immediate action, but it could help maintain cleaner configuration files in the long run.

examples/starknet_counter/lib/ui/counter.dart (1)

Counter-related logic still present in UI file

The verification shows that counter manipulation functions (increaseCounter, increaseCounterBy, decreaseCounter) are still present in examples/starknet_counter/lib/ui/counter.dart. Please ensure all business logic is moved to the CounterModel to maintain separation of concerns.

🔗 Analysis chain

Line range hint 1-105: Consider refactoring for improved state management and error handling

While reviewing the entire file, I noticed several areas where the code could be improved for better maintainability, consistency, and error handling:

  1. State Management: The current implementation mixes UI and business logic. Consider using a state management solution like Provider or Riverpod to separate concerns.

  2. Error Handling: There's no visible error handling for the asynchronous operations. Add try-catch blocks to handle potential errors from the counter service.

  3. Consistent State Updates: The _getCounter method is used inconsistently across different methods. Standardize the approach for updating the counter state.

  4. Performance: Multiple state updates could be optimized to reduce unnecessary rebuilds.

Here's a suggested refactoring approach:

  1. Create a CounterModel class to manage the counter state and operations:
class CounterModel extends ChangeNotifier {
  int _counter = 0;
  int get counter => _counter;

  Future<void> incrementCounter() async {
    try {
      await increaseCounter();
      await _updateCounter();
    } catch (e) {
      // Handle error
    }
  }

  Future<void> decrementCounter() async {
    try {
      await decreaseCounter();
      await _updateCounter();
    } catch (e) {
      // Handle error
    }
  }

  Future<void> incrementCounterBy(String amount) async {
    try {
      await increaseCounterBy(amount);
      await _updateCounter();
    } catch (e) {
      // Handle error
    }
  }

  Future<void> _updateCounter() async {
    _counter = await getCurrentCount();
    notifyListeners();
  }
}
  1. Use Provider to make the CounterModel available to the widget tree:
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => CounterModel(),
      child: MyApp(),
    ),
  );
}
  1. Update the CounterPage to use the CounterModel:
class _CounterPageState extends State<CounterPage> {
  TextEditingController amount = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Consumer<CounterModel>(
        builder: (context, counterModel, child) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Counter is: ${counterModel.counter}"),
              // ... other widgets ...
              ElevatedButton(
                onPressed: counterModel.incrementCounter,
                child: const Text('increment'),
              ),
              ElevatedButton(
                onPressed: () => counterModel.incrementCounterBy(amount.text.trim()),
                child: const Text('incrementBy'),
              ),
              ElevatedButton(
                onPressed: counterModel.decrementCounter,
                child: const Text('decrement'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This refactoring separates the business logic from the UI, provides consistent error handling, and optimizes state updates. It also makes the code more testable and maintainable.

To ensure that all counter-related logic is moved to the CounterModel, we can run the following check:

This should return no results if all the logic has been properly moved to the CounterModel.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that counter-related logic is not present in the UI file

# Test: Search for counter manipulation logic in the UI file
rg --type dart 'await (increase|decrease|get)Counter' examples/starknet_counter/lib/ui/counter.dart

Length of output: 208

examples/starknet_counter/lib/services/counter_service.dart (2)

10-10: Contract address update looks good.

The contract address has been updated, which is consistent with deploying a new contract for the Sepolia network or local devnet.

Consider adding a comment to indicate which network (Sepolia testnet, devnet, or local) this contract address corresponds to, for better clarity and maintainability.


Line range hint 1-95: Summary of review findings

  1. The changes appear to shift the example towards a local development setup, which may not fully align with the PR objective of updating for Sepolia (devnet and testnet).
  2. There are security concerns with hardcoded private keys in the source code.
  3. The core functionality of the counter service remains unchanged.

To improve this PR:

  1. Clarify the intention behind using local URIs and how it relates to the Sepolia update.
  2. Address the security issue with exposed private keys.
  3. Consider making the environment (local, devnet, testnet) configurable to support all use cases mentioned in the PR objectives.
  4. Add comments to improve code clarity, especially for network-specific details like contract addresses.

Once these points are addressed, the changes will better align with the PR objectives and improve the overall quality and security of the example.

packages/starknet/lib/src/static_config.dart (1)

Review Network-Specific Configurations

The change to Sepolia for the testNet value is correct. However, multiple references to goerli and testnet remain across the codebase. To ensure consistency and prevent potential issues, please address the following:

  • Configuration Files:

    • packages/starknet_provider/test/utils.dart
    • packages/starknet_provider/lib/src/provider.dart
    • packages/starknet_provider/lib/src/read_provider.dart
  • Wallet Services:

    • packages/wallet_kit/lib/services/wallet_service.dart
  • Builder Examples:

    • packages/starknet_builder/lib/src/examples/erc20_upgradeable.dart
    • packages/starknet_builder/lib/src/examples/transfer_erc20.dart
  • Static Configurations:

    • packages/starknet/lib/src/static_config.dart
  • Utilities and Accounts:

    • packages/starknet/lib/src/util.dart
    • packages/starknet/lib/src/account.dart
  • Example Deployments:

    • packages/starknet/example/examples/deploy_openzeppelin.dart

Ensure that all instances referencing goerli and testnet are updated to reflect the transition to Sepolia. This includes updating URIs, environment variables, and any hardcoded values tied to the previous network configurations.

🔗 Analysis chain

Line range hint 1-91: Review network-specific configurations

While the change to Sepolia for the testNet value is correct, it's important to ensure that all network-specific configurations in this file and throughout the codebase are consistent with this change.

Please review the following areas:

  1. Check if the v010PathfinderGoerliTestnetUri and infuraGoerliTestnetUri constants need to be updated or removed.
  2. Verify if any Sepolia-specific constants need to be added (e.g., infuraSepoliaTestnetUri).
  3. Review any other files that might contain network-specific configurations to ensure they are updated for Sepolia.

You can use the following script to help identify potential areas that might need updating:

Please review the results and make any necessary updates to ensure consistency with the move to Sepolia.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for Goerli-related configurations and URIs

# Test: Search for Goerli-related terms in Dart files. Expect: Results showing potential areas for update.
rg --type-add 'dart:*.dart' --type dart -i 'goerli|testnet'

# Test: Search for URIs in Dart files. Expect: Results showing URIs that might need updating.
rg --type-add 'dart:*.dart' --type dart 'Uri\.parse\(.*\)'

Length of output: 6163

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 59920c6 and 8a777bb.

📒 Files selected for processing (5)
  • examples/starknet_counter/lib/services/counter_service.dart (1 hunks)
  • examples/starknet_counter/lib/ui/counter.dart (1 hunks)
  • examples/starknet_counter/pubspec_overrides.yaml (1 hunks)
  • packages/starknet/lib/src/static_config.dart (1 hunks)
  • packages/starknet_provider/lib/src/model/invoke_transaction.freezed.dart (1 hunks)
🔇 Additional comments (5)
examples/starknet_counter/pubspec_overrides.yaml (1)

5-7: Dependency source updated to local paths

The changes switch the source of starknet and starknet_provider packages from Git repositories to local paths. This modification has several implications:

  1. It simplifies local development by using the packages directly from the project structure.
  2. It allows for easier testing of local changes to these packages.
  3. However, it may complicate the setup process for other developers who clone this repository, as they'll need to ensure the correct directory structure.

To ensure the referenced local packages exist, run the following script:

This script will help verify that the local package directories exist in the expected locations.

✅ Verification successful

Local package dependencies are correctly referenced

Both packages/starknet and packages/starknet_provider directories exist as specified in pubspec_overrides.yaml. This ensures that the dependency overrides are set up correctly, facilitating smooth local development.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of local package directories

echo "Checking for starknet package..."
if [ -d "packages/starknet" ]; then
    echo "starknet package found."
else
    echo "Warning: starknet package directory not found!"
fi

echo "Checking for starknet_provider package..."
if [ -d "packages/starknet_provider" ]; then
    echo "starknet_provider package found."
else
    echo "Warning: starknet_provider package directory not found!"
fi

Length of output: 370

examples/starknet_counter/lib/services/counter_service.dart (2)

8-8: Verify the provider URI change and its alignment with PR objectives.

The provider URI has been changed from a remote endpoint to a local server (http://localhost:3030). While this is useful for local development, it may not align with the PR objective of updating the example for Sepolia (devnet and testnet).

Could you please clarify if this change is intentional and how it supports the goal of updating the example for Sepolia? If this is meant for local testing, consider adding a comment or making the URI configurable to support both local and Sepolia environments.


19-19: Consistent change in signer account URI.

The signer account URI has been updated to 'http://localhost:3030', which is consistent with the earlier change to the provider URI.

As mentioned in the earlier comment about the provider URI, please clarify if this local server setup is intended for development purposes or if it should be configurable to support both local and Sepolia environments.

packages/starknet/lib/src/static_config.dart (1)

5-5: LGTM! Verify other occurrences of 'SN_GOERLI'

The update from 'SN_GOERLI' to 'SN_SEPOLIA' for the testNet value is correct and aligns with the PR objective of updating the Starknet counter example for Sepolia.

To ensure consistency across the codebase, please run the following script to check for any remaining occurrences of 'SN_GOERLI':

If any occurrences are found, please update them accordingly to maintain consistency with this change.

packages/starknet_provider/lib/src/model/invoke_transaction.freezed.dart (1)

622-622: LGTM. Verify source file and potential impacts.

The change from '0x01' to '0x1' for the version parameter's default value is acceptable. Both represent the same value (1 in decimal), with the new version omitting the leading zero.

As this is a generated file, please ensure that:

  1. The corresponding change has been made in the source file that generates this code.
  2. This change doesn't negatively impact any other parts of the codebase that might expect the '0x01' format.

Run the following script to check for any other occurrences of '0x01' that might need updating:

If any results are found, review them to determine if they should also be updated to '0x1' for consistency.

@ptisserand
Copy link
Collaborator

Thanks a lot for your contribution!
Could you please fix the failed signer test: I think it's related to your fix on invoke transaction version.

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: 0

🧹 Outside diff range and nitpick comments (2)
packages/starknet/test/signer_test.dart (1)

Line range hint 1-124: Address test coverage and failing signer test

While the changes update the expected signature values, there are a few points to consider:

  1. The failing signer test mentioned in the PR comments is not directly addressed in these changes. Please investigate and resolve this issue.

  2. Consider adding specific test cases for Sepolia devnet and testnet to ensure the changes are properly covered.

  3. The 'Public key' test group remains unchanged. Verify if any updates are needed here to align with the changes made for Sepolia.

Investigate and fix the failing signer test mentioned in the PR comments. This may be related to the recent changes in the invoke transaction version.

Add test cases specifically for Sepolia devnet and testnet configurations to ensure comprehensive coverage of the changes made in this PR.

melos.yaml (1)

Line range hint 101-104: Consider using variables for expected transaction hashes.

The addition of comments specifying expected transaction hashes is helpful for debugging and verification. However, hardcoding these hashes might lead to outdated information if the contract or invocation parameters change.

Consider using environment variables or a configuration file to store these expected transaction hashes. This would make it easier to update them when necessary and could be used for automated testing. For example:

- # should create tx hash 0x029583643cd8932f1955bf28bfebf4c907b13df1e5c2d202b133cfbf783697a2
+ # should create tx hash $EXPECTED_TX_HASH

Then, you could set the EXPECTED_TX_HASH environment variable or read it from a configuration file before running the script.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3a7e314 and 4ad5d2b.

📒 Files selected for processing (3)
  • examples/starknet_counter/lib/services/counter_service.dart (1 hunks)
  • melos.yaml (1 hunks)
  • packages/starknet/test/signer_test.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/starknet_counter/lib/services/counter_service.dart
🔇 Additional comments (5)
packages/starknet/test/signer_test.dart (2)

50-51: 🛠️ Refactor suggestion

Verify the updated signature value and consider additional testing

The expected signature value for the second element has been updated. This change aligns with the PR objective to update the Starknet counter example for Sepolia (devnet and testnet).

Please run the following verification script:

#!/bin/bash
# Description: Verify the updated signature value in the test case and check for related tests

# Test: Check if the new signature value is used consistently across the codebase
rg --type dart "1904177602932261497361499193520322287574011759183225218778227195148991255212"

# Test: Look for any remaining occurrences of the old signature value (if known)
# Note: Replace OLD_SIGNATURE_VALUE with the actual old value if available
# rg --type dart "OLD_SIGNATURE_VALUE"

# Test: Check for other test cases related to signTransactions
rg --type dart "test\(.*signTransactions.*\)" packages/starknet/test/

Consider adding more test cases for different transaction versions and network configurations to ensure comprehensive coverage of the changes made for Sepolia devnet and testnet.


47-48: Verify the updated signature value

The expected signature value for the first element has been updated. This change is consistent with the PR objective to update the Starknet counter example for Sepolia (devnet and testnet).

To ensure the correctness of this change, please run the following verification script:

✅ Verification successful

Signature value update verified

The updated signature value 107701415394463892922670165541267022802175117514579709928775579816864470554 is present in packages/starknet/test/signer_test.dart.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the updated signature value in the test case

# Test: Check if the new signature value is used consistently across the codebase
rg --type dart "107701415394463892922670165541267022802175117514579709928775579816864470554"

# Test: Look for any remaining occurrences of the old signature value (if known)
# Note: Replace OLD_SIGNATURE_VALUE with the actual old value if available
# rg --type dart "OLD_SIGNATURE_VALUE"

Length of output: 301


Script:

#!/bin/bash
# Description: Extract all signature values from signer_test.dart for verification

# Extract all long numerical strings assumed to be signature values
grep -oE '"[0-9]{60,}"' packages/starknet/test/signer_test.dart | tr -d '"' > extracted_signatures.txt

# Display the extracted signature values
cat extracted_signatures.txt

Length of output: 337

melos.yaml (3)

65-65: Consistent port change in devnet:start:dump script.

The port change from 3030 to 5050 is consistent with the previous change in the devnet:start script.


Line range hint 1-138: Overall assessment of melos.yaml changes.

The changes in this file are consistent with the PR objectives of updating the Starknet counter example for Sepolia (devnet and testnet). The port changes and the addition of transaction hash comments contribute to this goal. However, there are a few points to consider:

  1. Ensure that the port change from 3030 to 5050 is reflected in all relevant documentation and code.
  2. Consider using variables or a configuration file for the expected transaction hashes to improve maintainability.

These changes appear to address the update requirements, but please verify that all tests, especially the signer test mentioned in the PR comments, pass with these modifications.


60-60: Verify the impact of changing the devnet port.

The port for the local devnet has been changed from 3030 to 5050. This change aligns with the PR objectives to update for Sepolia (devnet and testnet).

To ensure this change doesn't break any existing setups or documentation, please run the following script:

Please review the results and update any affected files or documentation accordingly.

✅ Verification successful

Port change from 3030 to 5050 verified as safe.
No hardcoded references to port 3030 were found in configuration files that could be affected by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any hardcoded references to port 3030 in the codebase

# Test: Search for hardcoded references to port 3030
echo "Searching for hardcoded references to port 3030:"
rg --type-not yaml '3030'

# Test: Search for environment variables or configuration settings related to the devnet port
echo "Searching for environment variables or configuration settings related to the devnet port:"
rg --type-not yaml 'DEVNET_PORT|devnet[_\s]port'

Length of output: 1790

@devnet0x
Copy link
Contributor Author

devnet0x commented Sep 30, 2024

Fixed. It was related to a hardcoded signature in the test file (signed with SN_GOERLI instead of SN_SEPOLIA). Algo fixed the melos test devnet port because test was looking for devnet in 5050 and setup was loading devnet in 3030.

image

@ptisserand
Copy link
Collaborator

Thanks for your contribution

@ptisserand ptisserand merged commit 78e9da6 into focustree:main Oct 2, 2024
4 checks passed
PaulRbl pushed a commit that referenced this pull request Oct 3, 2024
* Update starknet counter for Sepolia (devnet and testnet)

* Fixtransaction version string for devnet

* Fix call to async functions

* Change goerli test signature for sepolia signature. And fix devnet port in test (5050 instead of 3030)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants