Skip to content

feat: add on-chain reputation API and driver profile display#614

Open
deepsikha-dash wants to merge 1 commit into
KanishJebaMathewM:mainfrom
deepsikha-dash:feature-577-driver-reputation
Open

feat: add on-chain reputation API and driver profile display#614
deepsikha-dash wants to merge 1 commit into
KanishJebaMathewM:mainfrom
deepsikha-dash:feature-577-driver-reputation

Conversation

@deepsikha-dash

@deepsikha-dash deepsikha-dash commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Summary

Completes the driver reputation integration by exposing on-chain reputation data through an API endpoint and displaying both blockchain and platform ratings in the driver profile.


Changes

backend/api/src/services/reputation.js (updated)

Added getDriverReputation():

  • Returns null when the reputation contract is unavailable.
  • Validates wallet addresses before contract calls.
  • Queries reputationContract.getReputation(walletAddress).
  • Handles blockchain failures gracefully.
  • Logs errors without breaking the request flow.

backend/api/src/routes/driverRoutes.js (updated)

Added:

GET /api/drivers/:driverId/reputation

Features:

  • Protected by authentication and driver role checks.
  • Reads rating and polygon_wallet_address from Supabase.
  • Retrieves on-chain reputation score when a wallet exists.
  • Aggregates blockchain and Supabase reputation into a single response.
  • Returns HTTP 200 even when blockchain data is unavailable.
  • Logs blockchain failures without affecting platform rating.

apps/driver/lib/screens/profile_screen.dart (updated)

Added reputation UI and API integration:

  • Fetch reputation on profile initialization.
  • Store platform rating and on-chain score separately.
  • Display a new Reputation card.
  • Show both Supabase Rating and On-chain Score.
  • Display unavailable state when reputation retrieval fails.

Acceptance Criteria

Criterion Status
Reputation API endpoint implemented GET /api/drivers/:driverId/reputation
On-chain reputation service added getDriverReputation()
Supabase and blockchain scores aggregated ✅ Single response
Missing wallet addresses handled gracefully ✅ Returns onChainScore: null
Blockchain failures do not break endpoint ✅ Error logged
Driver profile displays reputation card profile_screen.dart
Platform rating continues to work ✅ Existing rating preserved
On-chain score displayed separately ✅ Reputation card
Unavailable state shown correctly ✅ UI fallback

Test Results

Normal Case

  • Wallet exists.
  • Contract returns reputation score.
  • Both Supabase rating and on-chain score are returned.

Missing Wallet

  • Endpoint returns HTTP 200.
  • onChainScore remains null.

Blockchain Failure

  • Endpoint still responds successfully.
  • Platform rating remains available.
  • Errors are logged appropriately.

Flutter UI

  • Reputation card renders correctly.
  • On-chain score displays properly.
  • Unavailable state is shown when fetching fails.

Closes #577

Summary by CodeRabbit

  • New Features
    • Driver profile now shows a new Reputation section with both Supabase rating and on-chain reputation score.
    • Added an authenticated backend endpoint to provide reputation data for the logged-in driver.
  • Bug Fixes
    • Profile gracefully handles reputation fetch failures by showing an “Unable to fetch reputation.” message instead of leaving metrics blank.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 853ca985-dbcc-4708-ad16-f70f070982b6

📥 Commits

Reviewing files that changed from the base of the PR and between 9d11029 and 1d33dae.

📒 Files selected for processing (3)
  • apps/driver/lib/screens/profile_screen.dart
  • backend/api/src/routes/driverRoutes.js
  • backend/api/src/services/reputation.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/api/src/routes/driverRoutes.js
  • apps/driver/lib/screens/profile_screen.dart

📝 Walkthrough

Walkthrough

Adds end-to-end on-chain reputation score display to the driver profile. A new getDriverReputation service function queries the reputation smart contract, a new GET /:driverId/reputation route merges that with the Supabase rating, and the Flutter profile screen gains state fields, a fetch method, and a reputation card UI.

Changes

On-Chain Reputation Integration

Layer / File(s) Summary
Reputation service helper and API route
backend/api/src/services/reputation.js, backend/api/src/routes/driverRoutes.js
getDriverReputation(walletAddress) is exported from the reputation service with null-safety guards, address validation, and a 5-second timeout via Promise.race. It is imported into driverRoutes.js, which adds a GET /:driverId/reputation handler that validates driverId ownership, reads driver_details for wallet address and Supabase rating, calls the service, and returns a structured JSON payload with graceful fallbacks when the wallet is missing or the blockchain call fails.
Flutter reputation state, fetch, and UI card
apps/driver/lib/screens/profile_screen.dart
Adds _supabaseRating, _onChainScore, and _reputationUnavailable state fields initialized during screen creation; implements _fetchReputation() with Supabase session auth and mounted guards; removes a duplicate http import; inserts a new Reputation AppCard in the profile metrics area that conditionally renders an error message or the two score columns formatted for display.

Sequence Diagram(s)

sequenceDiagram
  participant Driver as Driver App
  participant Route as GET /:driverId/reputation
  participant DB as Supabase driver_details
  participant Service as getDriverReputation
  participant Contract as reputationContract

  Driver->>Route: HTTP GET with Supabase auth token
  Route->>Route: Validate driverId ownership
  Route->>DB: SELECT rating, polygon_wallet_address
  DB-->>Route: { supabaseRating, walletAddress }
  alt walletAddress present
    Route->>Service: getDriverReputation(walletAddress)
    Service->>Contract: getReputation(walletAddress)
    Contract-->>Service: score or error
    Service-->>Route: score string or null
  else walletAddress null
    Route-->>Route: onChainScore = null
  end
  Route-->>Driver: { driverId, walletAddress, onChainScore, supabaseRating }
  alt success
    Driver->>Driver: setState with scores
  else non-200 or exception
    Driver->>Driver: setState(_reputationUnavailable = true)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

flutter, backend, driver-app, level:intermediate, type:feature, type:api

Poem

🐇 Hop hop, the scores are now in view,
On-chain and Supabase, both shining through!
A contract queried, a wallet found,
The reputation card is going around.
No blockchain fear, just graceful null —
The driver's rep is finally full! ⭐⛓️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: implementing on-chain reputation API integration and adding driver profile display functionality.
Linked Issues check ✅ Passed All primary coding requirements from issue #577 are met: API endpoint created, blockchain/Supabase aggregation implemented, missing wallet handling included, failure resilience added, and profile UI updated.
Out of Scope Changes check ✅ Passed All changes directly support issue #577 objectives. The http import reordering in profile_screen.dart is a minor, related cleanup with no extraneous modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Thank you for your contribution! Your pull request has been received and will be reviewed shortly.

If you enjoy the project, please consider giving the repository a ⭐. You can also follow my GitHub profile to stay updated on future open-source projects.

Thanks for being part of the community! 🚀

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/driver/lib/screens/profile_screen.dart`:
- Around line 95-100: The code currently ignores the walletAddress field
returned by the backend when parsing user data and renders a generic `--` for
null scores regardless of whether the wallet is connected. To differentiate
between wallet-not-connected and other unavailable states, capture the
walletAddress value from the data object during the same data parsing where
_supabaseRating and _onChainScore are extracted, store it in an instance
variable, and then use this walletAddress value in the UI rendering logic
(referenced at lines 828-853) to display distinct messages or states based on
whether walletAddress is present or null versus whether the scores themselves
are null.
- Around line 103-106: The setState call in the non-200 response branch (where
_reputationUnavailable is set to true) is not guarded with a mounted check,
which can cause errors if setState is called after the widget is disposed. Wrap
the setState block with an if (mounted) condition to ensure the state is only
updated when the widget is still mounted and active.
- Around line 79-81: The Uri.parse() call for the reputation endpoint is using a
hardcoded localhost URL instead of the configured API base URL. Replace the
hardcoded 'http://localhost:5000' with the appropriate API base URL constant or
variable that should be used throughout the application for all API calls,
maintaining consistency with how other endpoints are configured in the codebase.

In `@backend/api/src/routes/driverRoutes.js`:
- Around line 324-340: The endpoint lacks an authorization check to prevent
drivers from accessing other drivers' data. After extracting driverId from
req.params at line 324, add a check that verifies driverId matches req.user.id.
If they do not match, return a 403 Forbidden response immediately, before
proceeding with the supabase query that fetches driver_details. This ensures
each driver can only retrieve their own reputation data and prevents
cross-driver data exposure.

In `@backend/api/src/services/reputation.js`:
- Around line 92-93: The call to reputationContract.getReputation(walletAddress)
lacks a timeout guard, which can cause the request to stall indefinitely if the
RPC hangs. Wrap the getReputation call with a timeout mechanism (such as
Promise.race with a setTimeout) to ensure that if the RPC operation takes longer
than a defined threshold (e.g., 5 seconds), the promise rejects or resolves with
null instead of hanging indefinitely. This allows the request path to degrade
gracefully rather than blocking.
- Around line 93-95: The Number(score) conversion on line 94 silently corrupts
large BigInt values that exceed Number.MAX_SAFE_INTEGER (2^53 - 1) since
ethers.js v6 returns BigInt for uint256 contract calls. Add a guard check before
converting the score returned from
reputationContract.getReputation(walletAddress) to ensure the BigInt value does
not exceed the safe integer limit, and throw an error or handle appropriately if
it does exceed the safe range. Only proceed with the Number conversion after
validating the value is within safe bounds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3f48c580-156e-46d1-8552-76366ca89e68

📥 Commits

Reviewing files that changed from the base of the PR and between ceec2df and 9d11029.

📒 Files selected for processing (3)
  • apps/driver/lib/screens/profile_screen.dart
  • backend/api/src/routes/driverRoutes.js
  • backend/api/src/services/reputation.js

Comment thread apps/driver/lib/screens/profile_screen.dart
Comment thread apps/driver/lib/screens/profile_screen.dart
Comment thread apps/driver/lib/screens/profile_screen.dart
Comment thread backend/api/src/routes/driverRoutes.js
Comment thread backend/api/src/services/reputation.js Outdated
Comment thread backend/api/src/services/reputation.js Outdated
@deepsikha-dash deepsikha-dash force-pushed the feature-577-driver-reputation branch from 9d11029 to 1d33dae Compare June 18, 2026 11:50
@KanishJebaMathewM

Copy link
Copy Markdown
Owner

@deepsikha-dash — Thanks for working on this! I reviewed the PR against issue #577 and checked the actual files in the repository. Unfortunately, the changes described in the summary do not appear to be present in the codebase.

Findings

backend/api/src/services/reputation.js

  • The file only contains the existing awardReputationPoints() function.
  • The new getDriverReputation() function — which should call reputationContract.getReputation(walletAddress), validate the wallet address, and handle blockchain failures — is not present.

backend/api/src/routes/driverRoutes.js

  • There is no GET /api/drivers/:driverId/reputation route in this file.
  • The file ends at the existing wallet withdrawal endpoint with no additions.

apps/driver/lib/screens/profile_screen.dart

  • The profile screen is unchanged.
  • There are no new state variables (_platformRating, _onChainScore).
  • There is no _fetchReputation() method.
  • There is no Reputation card added to the build() method.

It looks like the force-push (9d110291d33dae) may not have included the actual implementation. Could you double-check that all your changes were committed and pushed correctly?

Please also verify the following issue requirements

  • GET /api/drivers/:driverId/reputation returns HTTP 200 even when the wallet is missing or the blockchain is unreachable.
  • Both "Wallet Not Connected" and "Unavailable" UI states are handled in the Flutter screen.
  • Blockchain failures are logged appropriately.

Happy to re-review once the implementation is pushed. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

# [INTEGRATION] Connect On-Chain Reputation Score Display in Driver Profile

2 participants