Skip to content

Setup FairScale Environment and Protected Swap Logic#11

Open
Freedomwithin wants to merge 2 commits into
fairscale-integrationfrom
feature/fairscale-production-bounty-3042713778793509027
Open

Setup FairScale Environment and Protected Swap Logic#11
Freedomwithin wants to merge 2 commits into
fairscale-integrationfrom
feature/fairscale-production-bounty-3042713778793509027

Conversation

@Freedomwithin

@Freedomwithin Freedomwithin commented Feb 14, 2026

Copy link
Copy Markdown
Owner

This PR sets up the environment for the FairScale Production Bounty. It includes:

  1. Vercel Configuration: Added frontend/vercel.json to isolate the production environment.
  2. Documentation: Created docs/FAIRSCALE_API.md with reconstructed API details and integration flow.
  3. Frontend Boilerplate:
    • frontend/src/hooks/useIntegrity.ts: A custom hook to fetch and manage wallet integrity scores from the backend.
    • frontend/src/components/Guard.tsx: A React component that wraps protected actions (like Swaps) and blocks access for wallets with high Gini scores (> 0.5) or Sybil status.

Verified by running vite build successfully.


PR created automatically by Jules for task 3042713778793509027 started by @Freedomwithin

Summary by Sourcery

Introduce FairScale integration scaffolding including wallet integrity checks and protected UI for high-risk wallets.

New Features:

  • Add reconstructed FairScale API documentation and integration logic reference.
  • Add a frontend integrity hook to retrieve wallet risk metrics from the backend for the connected wallet.
  • Add a Guard UI component to gate protected actions based on integrity signals such as Gini score and Sybil status.

Deployment:

  • Add Vercel configuration file for the frontend to support a dedicated production deployment environment.

Documentation:

  • Document the reconstructed FairScale API, integration flow with Gini-based logic, and required environment variables.

- Initialized `frontend/vercel.json` for `trustchain-fairscale-prod`.
- Added `docs/FAIRSCALE_API.md` documenting the reconstructed API.
- Implemented `useIntegrity` hook for fetching wallet scores.
- Created `Guard` component for Protected Swap logic (Gini < 0.5).

Co-authored-by: Freedomwithin <166790647+Freedomwithin@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel

vercel Bot commented Feb 14, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
trust-chain-backend Ready Ready Preview, Comment Feb 14, 2026 8:31am
trust-chain-frontend Ready Ready Preview, Comment Feb 14, 2026 8:31am
trustchain_backend_solana Ready Ready Preview, Comment Feb 14, 2026 8:31am
trustchain-2-frontend Ready Ready Preview, Comment Feb 14, 2026 8:31am

Request Review

@sourcery-ai

sourcery-ai Bot commented Feb 14, 2026

Copy link
Copy Markdown

Reviewer's Guide

Sets up FairScale integration scaffolding by documenting the reconstructed API, adding a frontend integrity hook that queries the backend verification endpoint, and introducing a Guard component that blocks protected UI flows for wallets marked as Sybil or with high Gini scores, plus Vercel config for a separate frontend environment.

Sequence diagram for wallet integrity verification and guarded swap

sequenceDiagram
    actor User
    participant DAppUI
    participant GuardComponent
    participant useIntegrityHook
    participant WalletAdapter
    participant BackendAPI as Backend_API

    User->>DAppUI: Open protected swap screen
    DAppUI->>GuardComponent: Render Guard with children
    GuardComponent->>useIntegrityHook: Call useIntegrity()

    useIntegrityHook->>WalletAdapter: Read publicKey, connected
    alt Wallet connected
        useIntegrityHook->>BackendAPI: POST /api/verify { address }
        BackendAPI-->>useIntegrityHook: giniScore, hhiScore, status
        useIntegrityHook-->>GuardComponent: { giniScore, status, loading=false, error=null }
        GuardComponent->>GuardComponent: Compute isSybil (giniScore > 0.5 or status == SYBIL)
        alt isSybil
            GuardComponent-->>DAppUI: Render fallback or blocked message
            DAppUI-->>User: Show "Protected Swap: Access Denied"
        else not Sybil
            GuardComponent-->>DAppUI: Render protected children
            DAppUI-->>User: Allow swap interaction
        end
    else Wallet not connected
        useIntegrityHook-->>GuardComponent: { giniScore=null, status=null, loading=false }
        GuardComponent-->>DAppUI: Render children (no block)
        DAppUI-->>User: Prompt to connect wallet or proceed
    end
Loading

Class diagram for integrity hook and Guard component

classDiagram
    class IntegrityData {
        number giniScore
        number hhiScore
        string status
        boolean loading
        string error
    }

    class GuardProps {
        ReactNode children
        ReactNode fallback
    }

    class GuardComponent {
        +render(props GuardProps) ReactNode
    }

    class UseIntegrityHook {
        +useIntegrity() IntegrityData
    }

    class WalletAdapterContext {
        PublicKey publicKey
        boolean connected
        +useWallet() WalletAdapterContext
    }

    class BackendAPIClient {
        +verify(address string) IntegrityData
    }

    GuardComponent --> GuardProps : uses
    GuardComponent --> UseIntegrityHook : calls
    UseIntegrityHook --> WalletAdapterContext : reads
    UseIntegrityHook --> BackendAPIClient : calls
    BackendAPIClient --> IntegrityData : returns
Loading

File-Level Changes

Change Details Files
Document reconstructed FairScale reputation API and integration logic with TrustChain’s Gini-based gating.
  • Add high-level description of FairScale reputation tiers and scoring
  • Define hypothetical wallet reputation endpoint and example JSON response
  • Describe combined gatekeeper logic using Gini threshold and minimum FairScale tier, with illustrative JS and Python pseudocode
  • List required environment variables for FairScale integration
docs/FAIRSCALE_API.md
Introduce a frontend integrity hook that queries the backend to retrieve wallet integrity metrics and manages loading/error state.
  • Create useIntegrity hook that reads the connected Solana wallet via @solana/wallet-adapter-react
  • POST to the backend /api/verify endpoint using a configurable API base URL (VITE_API_BASE_URL with a production default)
  • Parse giniScore, hhiScore, and status from the response, normalizing numeric fields and tracking loading/error flags
  • Reset integrity state when the wallet disconnects or changes
frontend/src/hooks/useIntegrity.ts
Add a Guard React component to protect sensitive actions (e.g., swaps) based on integrity scores and Sybil status.
  • Use the useIntegrity hook within Guard to obtain current wallet integrity data
  • Block children rendering when Gini score exceeds 0.5 or status equals SYBIL, optionally rendering a caller-provided fallback
  • Provide a default denial UI with clear messaging and display of current Gini score vs threshold
  • Handle loading and error states with simple inline messaging
frontend/src/components/Guard.tsx
Configure a Vercel deployment file for the frontend to isolate production environment settings.
  • Add placeholder vercel.json in the frontend directory for environment-specific configuration (routes/build settings to be defined)
frontend/vercel.json

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai 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.

Hey - I've found 2 issues, and left some high level feedback:

  • In useIntegrity, the default API_BASE_URL hardcodes a specific backend URL; consider requiring this to be provided via configuration only so different environments (local, staging, prod) don't accidentally point to the same backend.
  • The Guard component bakes in both the PROBATIONARY_THRESHOLD and the status === 'SYBIL' check; exposing these as props or shared constants (e.g., an enum for integrity statuses) would make the access logic easier to reuse and keep consistent across the app.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `useIntegrity`, the default `API_BASE_URL` hardcodes a specific backend URL; consider requiring this to be provided via configuration only so different environments (local, staging, prod) don't accidentally point to the same backend.
- The `Guard` component bakes in both the `PROBATIONARY_THRESHOLD` and the `status === 'SYBIL'` check; exposing these as props or shared constants (e.g., an enum for integrity statuses) would make the access logic easier to reuse and keep consistent across the app.

## Individual Comments

### Comment 1
<location> `frontend/src/hooks/useIntegrity.ts:22-31` </location>
<code_context>
+    useEffect(() => {
</code_context>

<issue_to_address>
**issue (bug_risk):** Guard against state updates after unmount / stale responses from in-flight fetches.

If the wallet changes quickly or the component unmounts while a request is in flight, the effect can still resolve and call the state setters with stale data, and may hit React warnings. Consider wiring an `AbortController` into the fetch and/or tracking a `currentRequestId` or `mounted` flag so late responses from prior wallet states are ignored.
</issue_to_address>

### Comment 2
<location> `frontend/src/hooks/useIntegrity.ts:32-37` </location>
<code_context>
+            setLoading(true);
+            setError(null);
+
+            fetch(`${API_BASE_URL}/api/verify`, {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json' },
+                body: JSON.stringify({ address: publicKey.toBase58() })
+            })
+            .then(res => {
</code_context>

<issue_to_address>
**suggestion:** Include more context in error handling, e.g. HTTP status, to aid debugging.

Currently any non-2xx status results in the same `Failed to fetch integrity score` error. Please include the HTTP status (and, where safe, a snippet of the response body) in the error message so client-side and backend issues are easier to diagnose in production.

```suggestion
            .then(async res => {
                if (!res.ok) {
                    const { status, statusText } = res;
                    let bodySnippet = '';

                    try {
                        const text = await res.text();
                        if (text) {
                            bodySnippet = ` - Response: ${text.slice(0, 200)}`;
                        }
                    } catch {
                        // Ignore body parsing errors; we still have status information.
                    }

                    throw new Error(
                        `Failed to fetch integrity score (status ${status} ${statusText || ''})${bodySnippet}`
                    );
                }

                return res.json();
            })
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread frontend/src/hooks/useIntegrity.ts
Comment thread frontend/src/hooks/useIntegrity.ts
@Freedomwithin

Copy link
Copy Markdown
Owner Author

Jules Protocol: Technical Hardening (Sourcery Feedback)

Objective

Apply senior-level refactoring to the useIntegrity hook and Guard component to ensure production stability and environment flexibility.

Execution Steps

  1. useIntegrity.ts Refactor:

    • Implement an AbortController to handle component unmounting and prevent stale state updates during in-flight fetches.
    • Replace the hardcoded API_BASE_URL with a dynamic reference to process.env.VITE_API_BASE_URL.
    • Update the .then(res => ...) block to include the suggested Sourcery logic for detailed error reporting (capturing status and statusText).
  2. Guard.tsx Optimization:

    • Extract the PROBATIONARY_THRESHOLD (0.5) and the SYBIL status check into a separate constants/integrity.ts file.
    • Allow these thresholds to be passed as optional props to the Guard component for better reusability.
  3. Verification:

    • Ensure the Vite build still passes.
    • Push these changes to the existing feature/fairscale-production-bounty branch.

@google-labs-jules

Copy link
Copy Markdown
Contributor

Jules Protocol: Technical Hardening (Sourcery Feedback)

Objective

Apply senior-level refactoring to the useIntegrity hook and Guard component to ensure production stability and environment flexibility.

Execution Steps

  1. useIntegrity.ts Refactor:

    • Implement an AbortController to handle component unmounting and prevent stale state updates during in-flight fetches.
    • Replace the hardcoded API_BASE_URL with a dynamic reference to process.env.VITE_API_BASE_URL.
    • Update the .then(res => ...) block to include the suggested Sourcery logic for detailed error reporting (capturing status and statusText).
  2. Guard.tsx Optimization:

    • Extract the PROBATIONARY_THRESHOLD (0.5) and the SYBIL status check into a separate constants/integrity.ts file.
    • Allow these thresholds to be passed as optional props to the Guard component for better reusability.
  3. Verification:

    • Ensure the Vite build still passes.
    • Push these changes to the existing feature/fairscale-production-bounty branch.

Refactored useIntegrity to use AbortController and import.meta.env (Vite standard). Improved error handling. Extracted constants to frontend/src/constants/integrity.ts and updated Guard to accept optional props. Verified build passes.

- Extract constants to `frontend/src/constants/integrity.ts`
- Implement `AbortController` in `useIntegrity` hook
- Update `Guard` component to accept optional threshold props
- Improve error handling in fetch response
- Ensure `import.meta.env` usage for Vite compatibility

Co-authored-by: Freedomwithin <166790647+Freedomwithin@users.noreply.github.com>
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.

1 participant