Skip to content

Conversation

@remicolin
Copy link
Collaborator

@remicolin remicolin commented Jul 17, 2025

Summary by CodeRabbit

  • New Features

    • Added support for fetching and storing OFAC-related data in the protocol store for both passport and ID card sections, enabling dynamic retrieval of sanction lists for identity verification.
    • Introduced a script to update OFAC root hashes in Ethereum-based identity registries.
    • Added a utility to fetch OFAC data trees from remote endpoints based on environment and document type.
  • Bug Fixes

    • Updated logic and comments to generalize document nullification checks, replacing passport-specific checks with document-wide checks.
  • Refactor

    • Centralized OFAC data sourcing to runtime state, removing reliance on static JSON imports.
    • Updated function and variable names for improved clarity and generalization.
  • Chores

    • Removed unused scripts, data files, and documentation related to OFAC data processing.
    • Updated test data import paths to use local fixtures.
    • Adjusted package configuration and deployment scripts for improved maintainability.
    • Updated .gitignore to exclude .yarnrc.yml file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

This update refactors OFAC (Office of Foreign Assets Control) sanction list handling across the stack. It removes static OFAC data and processing scripts from the repository, shifts SMT (Sparse Merkle Tree) data sourcing to runtime store fetches, generalizes nullification checks for multiple document types, and introduces a new script for updating OFAC roots in registry contracts. Test and deployment scripts are updated accordingly.

Changes

File(s) / Path(s) Change Summary
.gitignore Added .yarnrc.yml to ignore list.
app/src/screens/misc/SplashScreen.tsx
app/src/utils/proving/provingMachine.ts
Updated comments and imports to use isDocumentNullified instead of isPassportNullified.
app/src/stores/protocolStore.ts Added runtime fetching and state management for OFAC SMTs for both passport and ID card; extended fetch methods and error handling.
app/src/utils/ofac.ts Added utility to fetch OFAC SMT data remotely for passport and ID card variants with error handling.
app/src/utils/proving/provingInputs.ts Removed static SMT imports and helper; now sources SMTs dynamically from store; error if SMTs missing.
app/src/utils/proving/validateDocument.ts Renamed and generalized nullification check to isDocumentNullified; switched to new API endpoint and attestation logic.
circuits/tests/disclose/vc_and_disclose.test.ts
circuits/tests/disclose/vc_and_disclose_id.test.ts
circuits/tests/ofac/ofac.test.ts
Changed SMT JSON imports from package to local relative paths.
common/ofacdata/ReadMe.md
common/ofacdata/inputs/eth_addresses.json
common/ofacdata/original/dataspec.txt
common/ofacdata/scripts/ofac.ipynb
Removed OFAC data documentation, processing scripts, and static data files.
common/package.json Bumped version to 0.0.6; removed OFAC SMT JSONs from exports.
contracts/ignition/deployments/staging/deployed_addresses.json Renamed "IdentityRegistryIdCard" key to "IdentityRegistry" for ID card registry.
contracts/ignition/modules/scripts/updateRegistryOfacRoot.ts Deleted Ignition deployment module for updating OFAC roots.
contracts/package.json Changed update:ofacroot script to run new TypeScript script directly, defaulting to "alfajores" network.
contracts/scripts/updateRegistryOfacRoot.ts Added a new script to update OFAC roots in passport and ID card registries, with improved logging and error handling.
contracts/test/utils/generateProof.ts Added ID card variant SMTs to test utility return object.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant ProtocolStore
    participant OFAC_API
    participant RegistryContract

    App->>ProtocolStore: fetch_all(environment, ski)
    ProtocolStore->>OFAC_API: fetch_ofac_trees(environment)
    OFAC_API-->>ProtocolStore: Return OFAC SMTs
    ProtocolStore-->>App: Store OFAC SMTs in state
    App->>ProtocolStore: Retrieve OFAC SMTs for proving
    App->>RegistryContract: isDocumentNullified(passportData)
    RegistryContract-->>App: Nullification status
Loading
sequenceDiagram
    participant Script
    participant Blockchain
    participant PassportRegistry
    participant IdCardRegistry

    Script->>Blockchain: Connect via RPC/PrivateKey
    Script->>PassportRegistry: updateOfacRoot(rootType, newRoot)
    PassportRegistry-->>Script: Transaction receipt
    Script->>IdCardRegistry: updateOfacRoot(rootType, newRoot)
    IdCardRegistry-->>Script: Transaction receipt
    Script-->>Script: Log success/failure
Loading

Possibly related PRs

  • App/eu id updates #638: Refactored proving logic and SMT data sourcing for multi-document support, closely related to this PR's runtime SMT handling and nullification checks.
  • update the smart contracts scripts #684: Updated deployed contract address keys and registry update scripts, directly intersecting with this PR's registry script and deployment key changes.

Poem

OFAC roots now fetched on the fly,
Old scripts and static files say goodbye.
Registries updated, contracts anew,
Nullifiers check more than just a few.
SMTs at runtime, tests in the clear—
Sanctions compliance, smarter this year!
🚀✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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

🧹 Nitpick comments (5)
.gitignore (1)

12-12: Consider ignoring Yarn PnP artifacts as well

Good call adding .yarnrc.yml.
If the team ever switches Yarn to Plug-n-Play resolution (quite common with Yarn ≥2), the repo will also generate .pnp.cjs / .pnp.mjs files at the project root. They’re machine-generated and should stay untracked.

Suggested follow-up diff:

 .yarnrc.yml
+.pnp.*
common/src/constants/constants.ts (1)

570-586: Reduce duplication when declaring new OFAC URLs

Six nearly-identical lines hard-code prod/staging variants.
Consider a helper to avoid drift:

-export const OFAC_PASSPORT_NO_NATIONALITY_SMT_URL = `${TREE_URL}/ofac/passport-no-nationality`;
-export const OFAC_PASSPORT_NO_NATIONALITY_SMT_URL_STAGING = `${TREE_URL_STAGING}/ofac/passport-no-nationality`;
+# const builder
+const ofacUrl = (suffix: string, staging = false) =>
+  `${staging ? TREE_URL_STAGING : TREE_URL}/ofac/${suffix}`;
+
+export const OFAC_PASSPORT_NO_NATIONALITY_SMT_URL          = ofacUrl('passport-no-nationality');
+export const OFAC_PASSPORT_NO_NATIONALITY_SMT_URL_STAGING  = ofacUrl('passport-no-nationality', true);

This trims repetition, keeps prod/staging in sync, and eases future additions.

app/src/utils/proving/validateDocument.ts (1)

148-154: Fix formatting issues flagged by linter

The static analysis tool flagged several formatting issues with indentation and spacing that should be addressed for consistency.

-  const response = await fetch(`${baseUrl}/is-nullifier-onchain-with-attestation-id`, {
-    method: 'POST',
-    headers: {
-      'Content-Type': 'application/json',
-    },
-    body: JSON.stringify({ nullifier: nullifierHex , attestation_id: attestationId}),
-  });
+  const response = await fetch(
+    `${baseUrl}/is-nullifier-onchain-with-attestation-id`,
+    {
+      method: 'POST',
+      headers: {
+        'Content-Type': 'application/json',
+      },
+      body: JSON.stringify({ nullifier: nullifierHex, attestation_id: attestationId }),
+    },
+  );
app/src/utils/proving/provingInputs.ts (1)

77-90: Consider performance implications of runtime SMT initialization

Creating and importing SMTs on every function call could be expensive. Consider caching initialized SMTs or moving initialization to a higher level.

// Consider adding memoization or caching at the store level
const getInitializedOfacTrees = useMemo(() => {
  if (!ofac_trees) return null;
  
  const trees = {
    nameAndDob: new SMT(poseidon2, true),
    nameAndYob: new SMT(poseidon2, true),
    passportNoAndNationality: document === 'passport' ? new SMT(poseidon2, true) : null,
  };
  
  trees.nameAndDob.import(ofac_trees.nameAndDob);
  trees.nameAndYob.import(ofac_trees.nameAndYob);
  if (trees.passportNoAndNationality && ofac_trees.passportNoAndNationality) {
    trees.passportNoAndNationality.import(ofac_trees.passportNoAndNationality);
  }
  
  return trees;
}, [ofac_trees, document]);
app/src/stores/protocolStore.ts (1)

229-236: Add timeout and retry logic for network requests

The fetch operations lack timeout protection and retry logic, which could lead to hanging requests in poor network conditions.

const fetchTree = async (url: string, retries = 3, timeout = 10000) => {
  const fetchWithTimeout = async (fetchUrl: string, options: RequestInit = {}) => {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    try {
      const response = await fetch(fetchUrl, {
        ...options,
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  };

  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetchWithTimeout(url);
      if (!res.ok) {
        throw new Error(`HTTP error fetching ${url}! status: ${res.status}`);
      }
      const responseData = await res.json();
      if (responseData.status !== 'success' || !responseData.data) {
        throw new Error(
          `Failed to fetch tree from ${url}: ${
            responseData.message || 'Invalid response format'
          }`,
        );
      }
      return responseData.data;
    } catch (error) {
      if (i === retries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2494a43 and b7d1c6c.

⛔ Files ignored due to path filters (4)
  • app/ios/Podfile.lock is excluded by !**/*.lock
  • common/ofacdata/original/add.csv is excluded by !**/*.csv
  • common/ofacdata/original/sdn.csv is excluded by !**/*.csv
  • common/ofacdata/scripts/cleaned_sdn.csv is excluded by !**/*.csv
📒 Files selected for processing (20)
  • .gitignore (1 hunks)
  • app/src/screens/misc/SplashScreen.tsx (1 hunks)
  • app/src/stores/protocolStore.ts (9 hunks)
  • app/src/utils/proving/provingInputs.ts (2 hunks)
  • app/src/utils/proving/provingMachine.ts (2 hunks)
  • app/src/utils/proving/validateDocument.ts (2 hunks)
  • circuits/tests/disclose/vc_and_disclose.test.ts (1 hunks)
  • circuits/tests/disclose/vc_and_disclose_id.test.ts (1 hunks)
  • circuits/tests/ofac/ofac.test.ts (1 hunks)
  • common/ofacdata/ReadMe.md (0 hunks)
  • common/ofacdata/inputs/eth_addresses.json (0 hunks)
  • common/ofacdata/original/dataspec.txt (0 hunks)
  • common/ofacdata/scripts/ofac.ipynb (0 hunks)
  • common/package.json (1 hunks)
  • common/src/constants/constants.ts (1 hunks)
  • contracts/ignition/deployments/staging/deployed_addresses.json (1 hunks)
  • contracts/ignition/modules/scripts/updateRegistryOfacRoot.ts (0 hunks)
  • contracts/package.json (1 hunks)
  • contracts/scripts/updateRegistryOfacRoot.ts (1 hunks)
  • contracts/test/utils/generateProof.ts (1 hunks)
💤 Files with no reviewable changes (5)
  • common/ofacdata/inputs/eth_addresses.json
  • contracts/ignition/modules/scripts/updateRegistryOfacRoot.ts
  • common/ofacdata/ReadMe.md
  • common/ofacdata/original/dataspec.txt
  • common/ofacdata/scripts/ofac.ipynb
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{test,spec}.{ts,js,tsx,jsx}

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

app/src/**/*.{ts,tsx,js,jsx}

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧬 Code Graph Analysis (5)
app/src/utils/proving/provingMachine.ts (1)
app/src/utils/proving/validateDocument.ts (1)
  • isDocumentNullified (138-158)
app/src/utils/proving/provingInputs.ts (1)
app/src/stores/protocolStore.ts (1)
  • useProtocolStore (76-457)
app/src/utils/proving/validateDocument.ts (3)
common/index.ts (2)
  • PassportData (36-36)
  • generateNullifier (56-56)
common/src/utils/types.ts (1)
  • PassportData (4-19)
common/src/constants/constants.ts (2)
  • API_URL (11-11)
  • API_URL_STAGING (14-14)
app/src/stores/protocolStore.ts (1)
common/src/constants/constants.ts (2)
  • TREE_URL (12-12)
  • TREE_URL_STAGING (13-13)
contracts/scripts/updateRegistryOfacRoot.ts (2)
common/src/constants/constants.ts (1)
  • RPC_URL (32-32)
contracts/scripts/constants.ts (5)
  • getSavedRepo (35-38)
  • getDeployedAddresses (40-43)
  • log (68-74)
  • getContractAbi (44-47)
  • getContractAddress (49-54)
🪛 GitHub Check: lint
app/src/utils/proving/validateDocument.ts

[warning] 152-152:
Insert ··


[warning] 151-151:
Insert ··


[warning] 150-150:
Insert ··


[warning] 149-149:
Replace ···· with ······


[warning] 148-148:
Replace ``${baseUrl}/is-nullifier-onchain-with-attestation-id, with `⏎····`${baseUrl}/is-nullifier-onchain-with-attestation-id`,⏎···`


[warning] 146-146:
Delete ⏎···

app/src/stores/protocolStore.ts

[failure] 27-27:
'OFAC_NAME_AND_YOB_SMT_URL_STAGING_ID' is defined but never used


[failure] 26-26:
'OFAC_NAME_AND_YOB_SMT_URL_ID' is defined but never used


[failure] 25-25:
'OFAC_NAME_AND_DOB_SMT_URL_STAGING_ID' is defined but never used


[failure] 24-24:
'OFAC_NAME_AND_DOB_SMT_URL_ID' is defined but never used


[failure] 23-23:
'OFAC_NAME_AND_YOB_SMT_URL_STAGING' is defined but never used


[failure] 22-22:
'OFAC_NAME_AND_YOB_SMT_URL' is defined but never used


[failure] 21-21:
'OFAC_NAME_AND_DOB_SMT_URL_STAGING' is defined but never used


[failure] 20-20:
'OFAC_NAME_AND_DOB_SMT_URL' is defined but never used


[failure] 19-19:
'OFAC_PASSPORT_NO_NATIONALITY_SMT_URL_STAGING' is defined but never used


[failure] 18-18:
'OFAC_PASSPORT_NO_NATIONALITY_SMT_URL' is defined but never used


[warning] 41-41:
Replace ·passportNoAndNationality:·any;·nameAndDob:·any;·nameAndYob:·any; with ⏎······passportNoAndNationality:·any;⏎······nameAndDob:·any;⏎······nameAndYob:·any;⏎···


[warning] 61-61:
Replace ·passportNoAndNationality:·any;·nameAndDob:·any;·nameAndYob:·any; with ⏎······passportNoAndNationality:·any;⏎······nameAndDob:·any;⏎······nameAndYob:·any;⏎···

🪛 GitHub Actions: App CI
app/src/stores/protocolStore.ts

[warning] 3-3: ESLint warning: Run autofix to sort these imports! (simple-import-sort/imports)


[error] 18-18: ESLint error: 'OFAC_PASSPORT_NO_NATIONALITY_SMT_URL' is defined but never used (@typescript-eslint/no-unused-vars)

🔇 Additional comments (9)
app/src/screens/misc/SplashScreen.tsx (1)

95-99: Comment wording looks good

Only a comment change; no action required.

circuits/tests/disclose/vc_and_disclose_id.test.ts (1)

14-15: Relative JSON paths LGTM – double-check test runner cwd

Switching to ../consts/ofac/... is fine, just ensure ts-mocha is invoked from circuits/tests (default) so the paths resolve on CI.

contracts/ignition/deployments/staging/deployed_addresses.json (1)

8-8: Two IdentityRegistry keys may be ambiguous

Now we have
DeployRegistryModule#IdentityRegistry (passport)
DeployIdCardRegistryModule#IdentityRegistry (ID card)

If tooling parses on the suffix #IdentityRegistry, the second entry may shadow the first. Verify downstream scripts (e.g. updateRegistryOfacRoot.ts) explicitly look up the full key string.

circuits/tests/disclose/vc_and_disclose.test.ts (1)

9-11: Import path migration looks good and aligns with the broader OFAC data handling refactor.

The change from package-scoped imports to relative local paths is consistent with the migration from static JSON files to dynamic API fetching described in the PR objectives. The modern ES module syntax with { type: 'json' } is correctly used for JSON imports.

contracts/test/utils/generateProof.ts (2)

435-436: ID card SMT imports follow consistent patterns.

The addition of ID card-specific SMTs (nameAndDobSMT_ID.json and nameAndYobSMT_ID.json) extends the existing OFAC data structure to support multiple document types. The naming convention with the _ID suffix clearly distinguishes these from passport variants.


442-443: SMT return object properly extended for ID card support.

The new SMTs are correctly added to the return object, maintaining consistency with the existing structure and enabling ID card document verification alongside passport verification.

app/src/utils/proving/provingMachine.ts (2)

45-45: Function import renamed to support multiple document types.

The change from isPassportNullified to isDocumentNullified aligns with the broader generalization to support multiple document types (passport and ID cards). This is a logical improvement in naming.


693-693: Audit generalized nullifier check in isDocumentNullified

The original isPassportNullified function no longer exists—its behavior has been folded into the new isDocumentNullified. Please manually verify that this generalization preserves all security guarantees:

  • generateNullifier(passportData) still produces the exact same nullifier value for passports.
  • The attestationId mapping (0x...0001 for documentCategory === 'passport', 0x...0002 otherwise) aligns with the on-chain contract’s expected IDs.
  • The HTTP endpoint (/is-nullifier-onchain-with-attestation-id) and JSON payload structure remain unchanged from the previous implementation.
circuits/tests/ofac/ofac.test.ts (1)

7-12: Comprehensive OFAC SMT import path migration maintains test coverage.

The migration from package-scoped imports to relative local paths is consistent with the broader refactor. The imports cover both passport and ID card variants of OFAC SMT data, ensuring comprehensive test coverage for multiple document types. The modern ES module JSON import syntax is correctly applied.

{
"name": "@selfxyz/common",
"version": "0.0.5",
"version": "0.0.6",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Breaking change warrants at least a minor version bump

Removing previously-exported OFAC JSON files is a breaking change for any consumer that still imports them. Jumping from 0.0.50.0.6 (patch) violates semantic-versioning rules; either bump minor or major and call this out in the changelog.

🤖 Prompt for AI Agents
In common/package.json at line 3, the version is currently set to 0.0.6, which
is a patch version. Since removing previously-exported OFAC JSON files is a
breaking change, update the version to at least 0.1.0 (minor) or 1.0.0 (major)
to comply with semantic versioning. Also, update the changelog to clearly
indicate this breaking change.

"update:cscaroot": "npx dotenv-cli -- bash -c 'yarn hardhat ignition deploy ignition/modules/scripts/updateRegistryCscaRoot.ts --network ${NETWORK:-localhost} ${VERIFY:+--verify}'",
"update:hub": "npx dotenv-cli -- bash -c 'NETWORK=${NETWORK:-staging} npx ts-node scripts/setRegistry.ts'",
"update:ofacroot": "npx dotenv-cli -- bash -c 'yarn hardhat ignition deploy ignition/modules/scripts/updateRegistryOfacRoot.ts --network ${NETWORK:-localhost} ${VERIFY:+--verify}'",
"update:ofacroot": "npx dotenv-cli -- bash -c 'NETWORK=${NETWORK:-alfajores} npx tsx scripts/updateRegistryOfacRoot.ts'",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Script migration from Hardhat Ignition to direct execution - verify network configuration.

The change from Hardhat Ignition deployment to direct tsx execution simplifies the OFAC root update process. However, the network default has changed from localhost to alfajores. Please ensure:

  1. The new script scripts/updateRegistryOfacRoot.ts exists and functions correctly
  2. The alfajores network default is intentional for production usage
  3. Proper error handling and authentication are in place for network operations

🏁 Script executed:

#!/bin/bash
# Description: Verify the new OFAC root update script exists and check its implementation

# Check if the new script exists
if [ -f "scripts/updateRegistryOfacRoot.ts" ]; then
  echo "✓ New script exists"
  # Show the script structure
  head -20 scripts/updateRegistryOfacRoot.ts
else
  echo "✗ New script missing"
fi

# Check if the old Ignition script was removed
if [ -f "ignition/modules/scripts/updateRegistryOfacRoot.ts" ]; then
  echo "⚠ Old Ignition script still exists"
else
  echo "✓ Old Ignition script removed"
fi

Length of output: 230


Missing scripts/updateRegistryOfacRoot.ts – npm script will fail

The update:ofacroot entry in contracts/package.json (line 68) now points to scripts/updateRegistryOfacRoot.ts, but that file isn’t in the repo—even the old Ignition version was removed. Please:

  • Add the new scripts/updateRegistryOfacRoot.ts file (or place it under the correct path)
  • OR update the package.json script to reference the actual file location
  • Ensure the TS script includes proper error handling and network/auth validation

Without this, running npm run update:ofacroot will error out.

🤖 Prompt for AI Agents
In contracts/package.json at line 68, the npm script "update:ofacroot"
references a missing file scripts/updateRegistryOfacRoot.ts, causing the script
to fail. To fix this, either add the missing TypeScript file at the specified
path or update the script to point to the correct existing file location.
Additionally, ensure the TypeScript script includes proper error handling and
validates network and authentication parameters to prevent runtime issues.

Comment on lines +141 to +144
const attestationId =
passportData.documentCategory === 'passport'
? '0x0000000000000000000000000000000000000000000000000000000000000001'
: '0x0000000000000000000000000000000000000000000000000000000000000002';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using constants for attestation IDs to improve maintainability

Hard-coded hex values reduce readability and maintainability. Since PASSPORT_ATTESTATION_ID and ID_CARD_ATTESTATION_ID are already imported, use them consistently.

-  const attestationId =
-    passportData.documentCategory === 'passport'
-      ? '0x0000000000000000000000000000000000000000000000000000000000000001'
-      : '0x0000000000000000000000000000000000000000000000000000000000000002';
+  const attestationId =
+    passportData.documentCategory === 'passport'
+      ? PASSPORT_ATTESTATION_ID
+      : ID_CARD_ATTESTATION_ID;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const attestationId =
passportData.documentCategory === 'passport'
? '0x0000000000000000000000000000000000000000000000000000000000000001'
: '0x0000000000000000000000000000000000000000000000000000000000000002';
const attestationId =
passportData.documentCategory === 'passport'
? PASSPORT_ATTESTATION_ID
: ID_CARD_ATTESTATION_ID;
🤖 Prompt for AI Agents
In app/src/utils/proving/validateDocument.ts around lines 141 to 144, replace
the hard-coded hex strings for attestationId with the imported constants
PASSPORT_ATTESTATION_ID and ID_CARD_ATTESTATION_ID. This improves readability
and maintainability by using named constants instead of literal values.

Comment on lines 138 to 158
export async function isDocumentNullified(passportData: PassportData) {
const nullifier = generateNullifier(passportData);
const nullifierHex = `0x${BigInt(nullifier).toString(16)}`;
console.log('checking for nullifier', nullifierHex);
const response = await fetch(`${API_URL}/is-nullifier-onchain/`, {
const attestationId =
passportData.documentCategory === 'passport'
? '0x0000000000000000000000000000000000000000000000000000000000000001'
: '0x0000000000000000000000000000000000000000000000000000000000000002';
console.log('checking for nullifier', nullifierHex, attestationId);
const baseUrl =
passportData.mock === false ? API_URL : API_URL_STAGING;
const response = await fetch(`${baseUrl}/is-nullifier-onchain-with-attestation-id`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ nullifier: nullifierHex }),
body: JSON.stringify({ nullifier: nullifierHex , attestation_id: attestationId}),
});
const data = await response.json();
console.log('isPassportNullified', data);
console.log('isDocumentNullified', data);
return data.data;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add comprehensive error handling for network requests

The function lacks proper error handling for network failures, malformed responses, or API errors. This could lead to unhandled promise rejections.

 export async function isDocumentNullified(passportData: PassportData) {
+  try {
     const nullifier = generateNullifier(passportData);
     const nullifierHex = `0x${BigInt(nullifier).toString(16)}`;
     const attestationId =
       passportData.documentCategory === 'passport'
         ? PASSPORT_ATTESTATION_ID
         : ID_CARD_ATTESTATION_ID;
     console.log('checking for nullifier', nullifierHex, attestationId);
     const baseUrl =
       passportData.mock === false ? API_URL : API_URL_STAGING;
     const response = await fetch(
       `${baseUrl}/is-nullifier-onchain-with-attestation-id`,
       {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json',
         },
         body: JSON.stringify({ nullifier: nullifierHex, attestation_id: attestationId }),
       },
     );
+    
+    if (!response.ok) {
+      throw new Error(`HTTP error! status: ${response.status}`);
+    }
+    
     const data = await response.json();
     console.log('isDocumentNullified', data);
     return data.data;
+  } catch (error) {
+    console.error('Failed to check document nullification:', error);
+    throw error; // Re-throw to let caller handle
+  }
 }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: lint

[warning] 152-152:
Insert ··


[warning] 151-151:
Insert ··


[warning] 150-150:
Insert ··


[warning] 149-149:
Replace ···· with ······


[warning] 148-148:
Replace ``${baseUrl}/is-nullifier-onchain-with-attestation-id, with `⏎····`${baseUrl}/is-nullifier-onchain-with-attestation-id`,⏎···`


[warning] 146-146:
Delete ⏎···

🤖 Prompt for AI Agents
In app/src/utils/proving/validateDocument.ts around lines 138 to 158, the
isDocumentNullified function does not handle errors from the fetch call or JSON
parsing, which can cause unhandled promise rejections. Wrap the fetch and
response processing in a try-catch block to catch network errors and JSON
parsing issues. In the catch block, log the error and return a safe fallback
value or propagate the error appropriately to ensure the function handles
failures gracefully.

Comment on lines 146 to 148
const baseUrl =
passportData.mock === false ? API_URL : API_URL_STAGING;
const response = await fetch(`${baseUrl}/is-nullifier-onchain-with-attestation-id`, {
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Validate URL selection logic for security

The URL selection based on the mock flag could be vulnerable to manipulation if the mock property can be controlled by untrusted input. Consider validating the environment context.


🏁 Script executed:

#!/bin/bash
# Check if mock flag is validated or sanitized elsewhere in the codebase
rg -A 5 -B 5 "mock.*=" --type ts

Length of output: 157081


🏁 Script executed:

#!/bin/bash
set -e
# Locate PassportData type or interface definitions
rg -n "type PassportData" --type ts
rg -n "interface PassportData" --type ts

Length of output: 308


🏁 Script executed:

#!/bin/bash
set -e
# Show the function signature and context where passportData is used
sed -n '1,50p' app/src/utils/proving/validateDocument.ts
echo "..."
sed -n '100,160p' app/src/utils/proving/validateDocument.ts

Length of output: 4091


Ensure baseUrl selection isn’t user-controlled

Relying on passportData.mock—which can trace back to user-supplied or deep-link inputs—to pick between production (API_URL) and staging (API_URL_STAGING) can be manipulated. Instead, derive your environment at build/runtime (e.g. __DEV__, NODE_ENV, or a secure feature flag) and ignore any mock value coming from untrusted sources.

• File: app/src/utils/proving/validateDocument.ts
Lines 145–149

// ❌ Do not trust passportData.mock for URLs
const baseUrl =
  passportData.mock === false ? API_URL : API_URL_STAGING;

Recommendations:

  • Use a compile-time or process-level environment variable to choose the URL:
    const baseUrl = __DEV__ 
      ? API_URL_STAGING 
      : API_URL;
  • If you still need a “mock” mode, guard it behind a secure flag or only allow it in tests/development builds.
  • Strip out or ignore any mock property on passportData when running in production.
🧰 Tools
🪛 GitHub Check: lint

[warning] 148-148:
Replace ``${baseUrl}/is-nullifier-onchain-with-attestation-id, with `⏎····`${baseUrl}/is-nullifier-onchain-with-attestation-id`,⏎···`


[warning] 146-146:
Delete ⏎···

🤖 Prompt for AI Agents
In app/src/utils/proving/validateDocument.ts around lines 146 to 148, the
baseUrl is currently chosen based on passportData.mock, which can be manipulated
by user input. To fix this, replace the baseUrl assignment to use a secure
environment variable or compile-time flag like __DEV__ or NODE_ENV instead of
passportData.mock. For example, set baseUrl to API_URL_STAGING if __DEV__ is
true, otherwise API_URL. Remove any reliance on passportData.mock for URL
selection and ensure mock mode is only enabled via secure flags or in
development/test environments.

Comment on lines +51 to +53
if (!registryAddress || !registryIdCardAddress) {
throw new Error("❌ Registry addresses not found in deployed_addresses.json");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for critical registry addresses

The script should validate that the registry addresses are valid Ethereum addresses before attempting to create contract instances.

   if (!registryAddress || !registryIdCardAddress) {
     throw new Error("❌ Registry addresses not found in deployed_addresses.json");
   }
+  
+  // Validate addresses are valid Ethereum addresses
+  if (!ethers.isAddress(registryAddress) || !ethers.isAddress(registryIdCardAddress)) {
+    throw new Error("❌ Invalid registry addresses found in deployed_addresses.json");
+  }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In contracts/scripts/updateRegistryOfacRoot.ts around lines 51 to 53, the code
checks for the presence of registry addresses but does not validate if they are
valid Ethereum addresses. Add validation logic to verify that both
registryAddress and registryIdCardAddress conform to the Ethereum address format
before proceeding. If either address is invalid, throw an error to prevent
creating contract instances with invalid addresses.

Comment on lines +74 to +80
const tx = await deployedRegistryInstance.updatePassportNoOfacRoot(passportNo_smt_root);
const receipt = await tx.wait();
log.success(`PassportNo OFAC root updated (tx: ${receipt.hash})`);
successfulUpdates++;
} catch (error) {
log.error(`Failed to update PassportNo OFAC root: ${error}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add transaction receipt validation

The script waits for transaction confirmation but doesn't validate the transaction success status, which could lead to false positives.

       try {
         totalUpdates++;
         const tx = await deployedRegistryInstance.updatePassportNoOfacRoot(passportNo_smt_root);
         const receipt = await tx.wait();
+        if (receipt.status !== 1) {
+          throw new Error(`Transaction failed with status: ${receipt.status}`);
+        }
         log.success(`PassportNo OFAC root updated (tx: ${receipt.hash})`);
         successfulUpdates++;
       } catch (error) {
         log.error(`Failed to update PassportNo OFAC root: ${error}`);
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const tx = await deployedRegistryInstance.updatePassportNoOfacRoot(passportNo_smt_root);
const receipt = await tx.wait();
log.success(`PassportNo OFAC root updated (tx: ${receipt.hash})`);
successfulUpdates++;
} catch (error) {
log.error(`Failed to update PassportNo OFAC root: ${error}`);
}
const tx = await deployedRegistryInstance.updatePassportNoOfacRoot(passportNo_smt_root);
const receipt = await tx.wait();
if (receipt.status !== 1) {
throw new Error(`Transaction failed with status: ${receipt.status}`);
}
log.success(`PassportNo OFAC root updated (tx: ${receipt.hash})`);
successfulUpdates++;
} catch (error) {
log.error(`Failed to update PassportNo OFAC root: ${error}`);
}
🤖 Prompt for AI Agents
In contracts/scripts/updateRegistryOfacRoot.ts around lines 74 to 80, the code
waits for the transaction receipt but does not check if the transaction was
successful. To fix this, after awaiting tx.wait(), check the receipt's status
property to confirm the transaction succeeded (status === 1). Only log success
and increment successfulUpdates if the transaction was successful; otherwise,
log an error indicating the transaction failed.

environment: 'prod' | 'stg',
ski: string,
) => Promise<void>;
fetch_all: (environment: 'prod' | 'stg', ski: string) => Promise<void>;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety for OFAC trees structure

The any type reduces type safety. Consider defining a proper interface for the OFAC trees structure.

interface OfacTrees {
  passportNoAndNationality: any; // Consider defining specific tree structure
  nameAndDob: any;
  nameAndYob: any;
}

// Then update the interface
interface ProtocolState {
  passport: {
    // ... other properties
    ofac_trees: OfacTrees | null;
    // ... methods
  };
  id_card: {
    // ... other properties  
    ofac_trees: OfacTrees | null;
    // ... methods
  };
}

Also applies to: 61-61

🧰 Tools
🪛 GitHub Check: lint

[warning] 41-41:
Replace ·passportNoAndNationality:·any;·nameAndDob:·any;·nameAndYob:·any; with ⏎······passportNoAndNationality:·any;⏎······nameAndDob:·any;⏎······nameAndYob:·any;⏎···

🤖 Prompt for AI Agents
In app/src/stores/protocolStore.ts at lines 41 and 61, the ofac_trees property
uses the any type, which reduces type safety. Define a specific interface, e.g.,
OfacTrees, with properly typed properties for passportNoAndNationality,
nameAndDob, and nameAndYob instead of any. Then update the ProtocolState
interface to use this new OfacTrees interface for the ofac_trees properties in
both passport and id_card sections.

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

🧹 Nitpick comments (3)
app/src/utils/ofac.ts (3)

5-5: Consider using a union type with const assertions for better type safety.

While the current type definition works, using const assertions would provide better IntelliSense and prevent typos.

-export type OfacVariant = 'passport' | 'id_card';
+export const OFAC_VARIANTS = ['passport', 'id_card'] as const;
+export type OfacVariant = typeof OFAC_VARIANTS[number];

46-57: Consider adding logging for performance monitoring.

For a mobile app, it's important to monitor network performance, especially when fetching large datasets like OFAC trees.

   // For ID cards, we intentionally skip fetching the (large) passport-number-tree.
   if (variant === 'id_card') {
+    console.log('[OFAC] Fetching ID card variant trees (skipping passport-number tree)');
+    const startTime = Date.now();
     const [nameDobData, nameYobData] = await Promise.all([
       fetchTree(nameDobUrl),
       fetchTree(nameYobUrl),
     ]);
+    console.log(`[OFAC] ID card trees fetched in ${Date.now() - startTime}ms`);

     return {
       passportNoAndNationality: null,
       nameAndDob: nameDobData,
       nameAndYob: nameYobData,
     };
   }

59-71: Add similar logging for passport variant and consider retry logic.

For production mobile apps, network requests should be resilient to temporary failures.

   // Passport variant → fetch all three.
+  console.log('[OFAC] Fetching passport variant trees (all three trees)');
+  const startTime = Date.now();
   const [ppNoNatData, nameDobData, nameYobData] = await Promise.all([
     fetchTree(ppNoNatUrl),
     fetchTree(nameDobUrl),
     fetchTree(nameYobUrl),
   ]);
+  console.log(`[OFAC] Passport trees fetched in ${Date.now() - startTime}ms`);

   return {
     passportNoAndNationality: ppNoNatData,
     nameAndDob: nameDobData,
     nameAndYob: nameYobData,
   };

Additionally, consider implementing exponential backoff retry logic for network resilience:

const fetchTreeWithRetry = async (url: string, maxRetries = 3): Promise<OfacTreeData> => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await fetchTree(url);
    } catch (error) {
      if (attempt === maxRetries) throw error;
      const delay = Math.pow(2, attempt - 1) * 1000; // Exponential backoff
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw new Error('Max retries exceeded');
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83abd64 and 86518b5.

📒 Files selected for processing (2)
  • app/src/stores/protocolStore.ts (9 hunks)
  • app/src/utils/ofac.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/src/stores/protocolStore.ts
🧰 Additional context used
📓 Path-based instructions (1)
app/src/**/*.{ts,tsx,js,jsx}

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧬 Code Graph Analysis (1)
app/src/utils/ofac.ts (1)
common/src/constants/constants.ts (2)
  • TREE_URL (12-12)
  • TREE_URL_STAGING (13-13)
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run_circuit_tests
🔇 Additional comments (3)
app/src/utils/ofac.ts (3)

1-1: SPDX license header is properly included.

Good practice to include the license header at the top of the file for legal compliance.


3-3: Import statement looks correct.

The import from @selfxyz/common aligns with the relevant code snippets showing these constants are defined there.


37-43: ✅ OFAC endpoint URLs validated

All five endpoints (passport-no-nationality, name-dob, name-yob, and their -id variants) returned HTTP 200 with the expected data and status keys. The URL patterns in app/src/utils/ofac.ts match the live API.

No changes needed here.

Comment on lines +7 to +11
export interface OfacTrees {
passportNoAndNationality: any;
nameAndDob: any;
nameAndYob: any;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace any types with proper TypeScript interfaces for better type safety.

Using any defeats the purpose of TypeScript and can lead to runtime errors. The OFAC tree data should have a predictable structure.

+// Define the structure of OFAC tree data
+interface OfacTreeData {
+  // Add specific properties based on the actual tree structure
+  // This should match the response.data structure from the API
+  root?: string;
+  leaves?: any[]; // or more specific array type
+  // Add other expected properties
+}
+
 export interface OfacTrees {
-  passportNoAndNationality: any;
-  nameAndDob: any;
-  nameAndYob: any;
+  passportNoAndNationality: OfacTreeData | null;
+  nameAndDob: OfacTreeData;
+  nameAndYob: OfacTreeData;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface OfacTrees {
passportNoAndNationality: any;
nameAndDob: any;
nameAndYob: any;
}
// Define the structure of OFAC tree data
interface OfacTreeData {
// Add specific properties based on the actual tree structure
// This should match the response.data structure from the API
root?: string;
leaves?: any[]; // or more specific array type
// Add other expected properties
}
export interface OfacTrees {
passportNoAndNationality: OfacTreeData | null;
nameAndDob: OfacTreeData;
nameAndYob: OfacTreeData;
}
🤖 Prompt for AI Agents
In app/src/utils/ofac.ts between lines 7 and 11, the OfacTrees interface uses
'any' types which reduces type safety. Define and replace 'any' with specific
TypeScript interfaces that describe the expected structure of
passportNoAndNationality, nameAndDob, and nameAndYob properties to ensure proper
type checking and prevent runtime errors.

Comment on lines +31 to +44
export const fetchOfacTrees = async (
environment: 'prod' | 'stg',
variant: OfacVariant = 'passport',
): Promise<OfacTrees> => {
const baseUrl = environment === 'prod' ? TREE_URL : TREE_URL_STAGING;

const ppNoNatUrl = `${baseUrl}/ofac/passport-no-nationality`;
const nameDobUrl = `${baseUrl}/ofac/name-dob${
variant === 'id_card' ? '-id' : ''
}`;
const nameYobUrl = `${baseUrl}/ofac/name-yob${
variant === 'id_card' ? '-id' : ''
}`;

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation and improve type safety for environment parameter.

The environment parameter should be validated and typed more strictly to prevent runtime errors.

+const ENVIRONMENTS = ['prod', 'stg'] as const;
+type Environment = typeof ENVIRONMENTS[number];
+
 export const fetchOfacTrees = async (
-  environment: 'prod' | 'stg',
+  environment: Environment,
   variant: OfacVariant = 'passport',
 ): Promise<OfacTrees> => {
+  if (!ENVIRONMENTS.includes(environment)) {
+    throw new Error(`Invalid environment: ${environment}. Must be one of: ${ENVIRONMENTS.join(', ')}`);
+  }
+  
   const baseUrl = environment === 'prod' ? TREE_URL : TREE_URL_STAGING;
🤖 Prompt for AI Agents
In app/src/utils/ofac.ts around lines 31 to 44, the environment parameter is
currently typed as a union of string literals but lacks runtime validation. Add
a validation step at the start of the fetchOfacTrees function to check if the
environment value is either 'prod' or 'stg'. If it is invalid, throw an error or
handle it appropriately. This ensures type safety and prevents runtime errors
from invalid inputs.

Comment on lines +14 to +28
const fetchTree = async (url: string): Promise<any> => {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error fetching ${url}! status: ${res.status}`);
}
const responseData = await res.json();
if (responseData.status !== 'success' || !responseData.data) {
throw new Error(
`Failed to fetch tree from ${url}: ${
responseData.message || 'Invalid response format'
}`,
);
}
return responseData.data;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timeout and improve error handling for network requests.

The fetch request lacks timeout handling which could cause the app to hang on slow networks, especially important for mobile applications.

-const fetchTree = async (url: string): Promise<any> => {
+const fetchTree = async (url: string): Promise<OfacTreeData> => {
-  const res = await fetch(url);
+  const controller = new AbortController();
+  const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
+  
+  try {
+    const res = await fetch(url, {
+      signal: controller.signal,
+      headers: {
+        'Accept': 'application/json',
+        'Content-Type': 'application/json',
+      },
+    });
+    clearTimeout(timeoutId);
+    
     if (!res.ok) {
       throw new Error(`HTTP error fetching ${url}! status: ${res.status}`);
     }
     const responseData = await res.json();
     if (responseData.status !== 'success' || !responseData.data) {
       throw new Error(
         `Failed to fetch tree from ${url}: ${
           responseData.message || 'Invalid response format'
         }`,
       );
     }
     return responseData.data;
+  } catch (error) {
+    clearTimeout(timeoutId);
+    if (error.name === 'AbortError') {
+      throw new Error(`Request timeout fetching ${url}`);
+    }
+    throw error;
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const fetchTree = async (url: string): Promise<any> => {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error fetching ${url}! status: ${res.status}`);
}
const responseData = await res.json();
if (responseData.status !== 'success' || !responseData.data) {
throw new Error(
`Failed to fetch tree from ${url}: ${
responseData.message || 'Invalid response format'
}`,
);
}
return responseData.data;
};
const fetchTree = async (url: string): Promise<OfacTreeData> => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
try {
const res = await fetch(url, {
signal: controller.signal,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
clearTimeout(timeoutId);
if (!res.ok) {
throw new Error(`HTTP error fetching ${url}! status: ${res.status}`);
}
const responseData = await res.json();
if (responseData.status !== 'success' || !responseData.data) {
throw new Error(
`Failed to fetch tree from ${url}: ${
responseData.message || 'Invalid response format'
}`,
);
}
return responseData.data;
} catch (error) {
clearTimeout(timeoutId);
if ((error as any).name === 'AbortError') {
throw new Error(`Request timeout fetching ${url}`);
}
throw error;
}
};
🤖 Prompt for AI Agents
In app/src/utils/ofac.ts between lines 14 and 28, the fetchTree function lacks
timeout handling for the fetch request, which can cause the app to hang on slow
networks. To fix this, implement a timeout mechanism using AbortController to
abort the fetch if it exceeds a specified duration. Additionally, enhance error
handling by catching fetch errors and throwing descriptive error messages that
include timeout or network failure details.

@remicolin remicolin merged commit 874b426 into dev Jul 21, 2025
11 of 13 checks passed
@remicolin remicolin deleted the feat/retrieve-ofac-trees-from-api branch July 21, 2025 09:07
remicolin added a commit that referenced this pull request Aug 20, 2025
* audit fixes (#645)

* merge dev branch into main (#624)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>

* update contracts (#628)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* fix: vc_and_disclose_id test (#640)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* fix: check if a config id exists

* chore: change the function where the config not set verification is happening

* fix: add await

* feat: add getConfigId function in SelfVerificationRoot (#650)

* feat: add getConfigId function in SelfVerificationRoot

* update comment

---------

Co-authored-by: motemotech <[email protected]>

* chore: fix ofac end index in eu id cards

* chore: fix tests

* fix: example contracts and tests

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>

* Update deployment module for Identity Verification Hub V2 with detailed documentation and library linkage for CustomVerifier. Update initialization process to reflect changes in V2 implementation, ensuring proper setup for proxy deployment. (#658)

* publish npm-package (#651)

* App/eu id updates (#638)

* fix build issues

* generate disclosure proof with euids

* generate disclosure proof with euids

* Eu id updates 2 (#648)

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* add version and user defined data

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>

* remove the mock user define data

* get the useridentifier as a hash from the user defined data

* chore: add version and userDefinedData

* feat: use the version in register / dsc proofs as well

* update calculateUserIdentifierHash

* yarn nice

* refactor: consolidate user context data handling and update payload structure

* fix typing issues on sha1

* remove console.log(sha1)

* fix sha1 import

* refactor: streamline userDefinedData handling and adjust payload type for circuit

* refactor: update sha1 usage and enhance logging in calculateUserIdentifierHash

* yarn nice

* yarn lint common

* use ts-ignore for sha1 import

* fix app ci tests

* fix typing issue

* remove unused ts-ignore

* cast uuid before calling generateinputs

* bump qrcode version

* add tsup on the qrcode sdk

* fix: exports on selfxyz/qrcode

* update how we define config.version

* fix yarn imports

* yarn format

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Ayman <[email protected]>

* Hotfix contract compile error (#660)

* Fix previous rebase error

* Refactor deployment module for Identity Verification Hub V2.

* Fix/sdk (#652)

* fix: sdk build configs

* chore: SelfBackendVerifier (WIP)

* feat: add custom verification

* feat: consider destination chain in user defined data

* chore: export attestation id

* chore: export attestation id

* chore: export config storage

* chore: don't throw an error if the proof is not valid

* chore: trim abi and rm typechain types

* refactor

* chore: rm unnecessary exports

* 📝 Add docstrings to `fix/sdk` (#653)

Docstrings generation was requested by @remicolin.

* https://github.com/selfxyz/self/pull/652#issuecomment-2992046545

The following files were modified:

* `sdk/core/src/utils/hash.ts`
* `sdk/core/src/utils/proof.ts`
* `sdk/core/src/utils/utils.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* review fixes

* chore: fix package.json cjs types

* chore: add minor changes to checks

* feat: add InMemoryConfigStore, allIds constant and verificationResult type

* chore: export Verification config

* feat: change the verification config types

* fix: throw issues early if verification config is null

* fix: update yarn.lock file

* chore: lint

* fix: rm ts expect error directive

* fix: contract tests

* use excluded countries instead forbidden countries list

* chore: change types in constnats

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update npm-publish workflow and bump core package version to 1.0.0 (#661)

* update import

* Update get verification config visibility (#664)

* Update deployment module for Identity Verification Hub V2 to correct file paths and module name for deployment commands.

* Add troubleshooting documentation for verification issues in deployHubV2.ts. Include manual verification steps and common failure reasons to assist users during deployment.

* Change visibility of getVerificationConfigV2 function from internal to public in IdentityVerificationHubImplV2 contract to allow external access.

* Apply BUSL v1.1 license headers to app (#665)

* Add BSL license headers to app sources

* prettier

* fix license reference - https://spdx.org/licenses/BUSL-1.1.html

* bump build: android 73 (#659)

* Contracts/deploy staging (#668)

* update scripts

* deploy vc and disclose id

* fix the deployment scripts on staging

* update yarn.lock

* bump ios build and version (#669)

* configure coderabbitai (#670)

* tweak coderabbit

* bump

* more thorough test spec

* Apply BSL to app codebase (#639)

* Clean up root license wording

* Simplify SPDX header

* simplify license and rename BSL to BUSL

* fix merge issues

* fix missing method

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-423 apply xcode build suggestions (#671)

* apply recommended app settings from xcode

* stick to portrait orientation and update target settings

* remove app clip references

* Circuit audit fixes  (#644)

* feat: add range checks before use of LessEqThan and SelectSubArray

* fix: Num2Bits_strict to constrain virtualKey

* bump core version

* bump core version and fix ci

* chore: use npm_auth_token in yarnrc

* chroe: rm yarnrc changes

* chore: update npm publish

* chore: run npm publish manually

* chore: change hub contract address (#675)

* Update npm-publish.yml

* merge dev to main (#657)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

* CAN auth - android (#613)

* add missed files

* add NFCMethodSelectionScreen

* bump android build

---------

Co-authored-by: Justin Hernandez <[email protected]>

* feat: add MRZ correction method to NFCMethodSelectionScreen (#627)

* add npm auth token env (#632)

* bump sdk version (#633)

* publish npm package when merging on dev

* bump common sdk version

* replace yarn publish by npm publish

* update common package version

* Simplify dev mode gesture (#635)

* Simplify developer mode gesture

* Enable dev mode on MockData screen with five taps

* add build smt function to common sdk

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* Bump build: ios 133; android 72 and build fixes (#654)

* update gesture version and bump android build

* bump and fix ios build

* update lock files

* fixes

* fix fotoapparat library source

* Update example contracts to include EUID usage (#656)

* refactor: update HappyBirthday contract to V2 with support for E-Passport and EUID cards, introduce bonus multipliers, and enhance verification logic

* refactor: update Airdrop contract to V2 with support for E-Passport and EU ID Card attestations

* refactor: remove BASIS_POINTS constant from Airdrop contract

* feat: introduce SelfIdentityERC721 contract for issuing NFTs based on verified identity credentials, replacing SelfPassportERC721

* fix: update verification functions in Airdrop, HappyBirthday, and SelfIdentityERC721 contracts to use customVerificationHook

* cherry pick commit from add-test-self-verification...

* block non-dev pr to main branch

* audit fixes (#645)

* merge dev branch into main (#624)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>

* update contracts (#628)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* fix: vc_and_disclose_id test (#640)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* fix: check if a config id exists

* chore: change the function where the config not set verification is happening

* fix: add await

* feat: add getConfigId function in SelfVerificationRoot (#650)

* feat: add getConfigId function in SelfVerificationRoot

* update comment

---------

Co-authored-by: motemotech <[email protected]>

* chore: fix ofac end index in eu id cards

* chore: fix tests

* fix: example contracts and tests

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>

* Update deployment module for Identity Verification Hub V2 with detailed documentation and library linkage for CustomVerifier. Update initialization process to reflect changes in V2 implementation, ensuring proper setup for proxy deployment. (#658)

* publish npm-package (#651)

* App/eu id updates (#638)

* fix build issues

* generate disclosure proof with euids

* generate disclosure proof with euids

* Eu id updates 2 (#648)

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* add version and user defined data

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>

* remove the mock user define data

* get the useridentifier as a hash from the user defined data

* chore: add version and userDefinedData

* feat: use the version in register / dsc proofs as well

* update calculateUserIdentifierHash

* yarn nice

* refactor: consolidate user context data handling and update payload structure

* fix typing issues on sha1

* remove console.log(sha1)

* fix sha1 import

* refactor: streamline userDefinedData handling and adjust payload type for circuit

* refactor: update sha1 usage and enhance logging in calculateUserIdentifierHash

* yarn nice

* yarn lint common

* use ts-ignore for sha1 import

* fix app ci tests

* fix typing issue

* remove unused ts-ignore

* cast uuid before calling generateinputs

* bump qrcode version

* add tsup on the qrcode sdk

* fix: exports on selfxyz/qrcode

* update how we define config.version

* fix yarn imports

* yarn format

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Ayman <[email protected]>

* Hotfix contract compile error (#660)

* Fix previous rebase error

* Refactor deployment module for Identity Verification Hub V2.

* Fix/sdk (#652)

* fix: sdk build configs

* chore: SelfBackendVerifier (WIP)

* feat: add custom verification

* feat: consider destination chain in user defined data

* chore: export attestation id

* chore: export attestation id

* chore: export config storage

* chore: don't throw an error if the proof is not valid

* chore: trim abi and rm typechain types

* refactor

* chore: rm unnecessary exports

* 📝 Add docstrings to `fix/sdk` (#653)

Docstrings generation was requested by @remicolin.

* https://github.com/selfxyz/self/pull/652#issuecomment-2992046545

The following files were modified:

* `sdk/core/src/utils/hash.ts`
* `sdk/core/src/utils/proof.ts`
* `sdk/core/src/utils/utils.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* review fixes

* chore: fix package.json cjs types

* chore: add minor changes to checks

* feat: add InMemoryConfigStore, allIds constant and verificationResult type

* chore: export Verification config

* feat: change the verification config types

* fix: throw issues early if verification config is null

* fix: update yarn.lock file

* chore: lint

* fix: rm ts expect error directive

* fix: contract tests

* use excluded countries instead forbidden countries list

* chore: change types in constnats

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update npm-publish workflow and bump core package version to 1.0.0 (#661)

* update import

* Update get verification config visibility (#664)

* Update deployment module for Identity Verification Hub V2 to correct file paths and module name for deployment commands.

* Add troubleshooting documentation for verification issues in deployHubV2.ts. Include manual verification steps and common failure reasons to assist users during deployment.

* Change visibility of getVerificationConfigV2 function from internal to public in IdentityVerificationHubImplV2 contract to allow external access.

* Apply BUSL v1.1 license headers to app (#665)

* Add BSL license headers to app sources

* prettier

* fix license reference - https://spdx.org/licenses/BUSL-1.1.html

* bump build: android 73 (#659)

* Contracts/deploy staging (#668)

* update scripts

* deploy vc and disclose id

* fix the deployment scripts on staging

* update yarn.lock

* bump ios build and version (#669)

* configure coderabbitai (#670)

* tweak coderabbit

* bump

* more thorough test spec

* Apply BSL to app codebase (#639)

* Clean up root license wording

* Simplify SPDX header

* simplify license and rename BSL to BUSL

* fix merge issues

* fix missing method

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-423 apply xcode build suggestions (#671)

* apply recommended app settings from xcode

* stick to portrait orientation and update target settings

* remove app clip references

* Circuit audit fixes  (#644)

* feat: add range checks before use of LessEqThan and SelectSubArray

* fix: Num2Bits_strict to constrain virtualKey

* bump core version

* bump core version and fix ci

* chore: use npm_auth_token in yarnrc

* chroe: rm yarnrc changes

* chore: update npm publish

* chore: run npm publish manually

* chore: change hub contract address (#675)

* Update npm-publish.yml

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Kevin Lin <[email protected]>
Co-authored-by: kevinsslin <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Eric Nakagawa <[email protected]>

* chore: use proper secret when publishing

* feat: enable publishing if workflow was triggered manually

* Contracts/update verifier (#673)

* update hardhat config

* update vc and disclose verifier

* update vc and disclose verifier script and run it

* update test self verification root

* update verifier

* bump sdk version and use new hub address

* chore: update zk-kit binary merkle root dep (#674)

* Dev (#677)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

* CAN auth - android (#613)

* add missed files

* add NFCMethodSelectionScreen

* bump android build

---------

Co-authored-by: Justin Hernandez <[email protected]>

* feat: add MRZ correction method to NFCMethodSelectionScreen (#627)

* add npm auth token env (#632)

* bump sdk version (#633)

* publish npm package when merging on dev

* bump common sdk version

* replace yarn publish by npm publish

* update common package version

* Simplify dev mode gesture (#635)

* Simplify developer mode gesture

* Enable dev mode on MockData screen with five taps

* add build smt function to common sdk

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* Bump build: ios 133; android 72 and build fixes (#654)

* update gesture version and bump android build

* bump and fix ios build

* update lock files

* fixes

* fix fotoapparat library source

* Update example contracts to include EUID usage (#656)

* refactor: update HappyBirthday contract to V2 with support for E-Passport and EUID cards, introduce bonus multipliers, and enhance verification logic

* refactor: update Airdrop contract to V2 with support for E-Passport and EU ID Card attestations

* refactor: remove BASIS_POINTS constant from Airdrop contract

* feat: introduce SelfIdentityERC721 contract for issuing NFTs based on verified identity credentials, replacing SelfPassportERC721

* fix: update verification functions in Airdrop, HappyBirthday, and SelfIdentityERC721 contracts to use customVerificationHook

* cherry pick commit from add-test-self-verification...

* block non-dev pr to main branch

* audit fixes (#645)

* merge dev branch into main (#624)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>

* update contracts (#628)

* remove sdk/tests (#622)

* remove sdk/tests

* chore: update yarn.lock

---------

Co-authored-by: Ayman <[email protected]>

* fix: add range check on paddedInLength of shaBytesDynamic (#623)

* fix ci (#626)

* implement self uups upgradeable (#592)

* implement self uups upgradeable

* small changes in identityVerificationHubImplV2

* delete aderyn.toml

* chore: add custom verifier

* chnage return output

* feat: use self structs and a Generic output struct

* feat: add userIdentifier, nullifier, forbiddencountries to returned output

* add root view functions from registry

* fix: build and compilation errors

* add userDefined data into selfVerificationRoot

* "resolve conflicts"

* fix compilation problem

* fix how to register verification config

* test: CustomVerifier

* fix verification root and hub integration

* add scope check in hub impl

* replace poseidon hash to ripemd+sha256

* add todo list

* feat: refactor and add test cases for generic formatter

* add performUserIdentifierCheck in basicVerification

* change how to handle additionalData and fix stack too deep

* start adding test codes

* fix dependency problems in monorepo

* fix: forbidden countries (#612)

LGTM!

* able to run test code

* pass happy path

* delete unused codes

* change error code name, add caller address validation and add scripts to run test and build in monorepo

* add all test cases in vcAndDisclose flow

* remove comment out

* chore: use actual user identifier outputs

* success in registration tests

* cover all cases

* pass contractVersion instead of circuitVersion

* fix disclose test

* chore: add natspecs for ImplHubV2, CustomVerifier and GenericFormatter

* change val name and remove unused lines

* add val name change

* remove userIdentifier from return data

* feat: use GenericDiscloseOutput struct in verfication hook  fix test cases for user identifier

* chore: change the function order for Hub Impl V2 (#625)

* fix nat specs

* add nat spec in SelfStructs

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* prettier (#629)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>

* fix: vc_and_disclose_id test (#640)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* fix: check if a config id exists

* chore: change the function where the config not set verification is happening

* fix: add await

* feat: add getConfigId function in SelfVerificationRoot (#650)

* feat: add getConfigId function in SelfVerificationRoot

* update comment

---------

Co-authored-by: motemotech <[email protected]>

* chore: fix ofac end index in eu id cards

* chore: fix tests

* fix: example contracts and tests

---------

Co-authored-by: turnoffthiscomputer <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>

* Update deployment module for Identity Verification Hub V2 with detailed documentation and library linkage for CustomVerifier. Update initialization process to reflect changes in V2 implementation, ensuring proper setup for proxy deployment. (#658)

* publish npm-package (#651)

* App/eu id updates (#638)

* fix build issues

* generate disclosure proof with euids

* generate disclosure proof with euids

* Eu id updates 2 (#648)

* update vc_and_disclose_id test (dev branch) (#641)

* fix: vc_and_disclose_id test

* chore: yarn prettier

* Show modal on NFC scan error (#642)

* Add help button and error modal actions

* fix the screen management

* yarn nice

* Bump build v2.5.4: ios 132; android 71 (#631)

* bump version and build numbers

* remove tamagui/toast

* fix marketing version

* fix: update TD1 and TD3 checks (#643)

* bum yarn.lock

* add version and user defined data

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>

* remove the mock user define data

* get the useridentifier as a hash from the user defined data

* chore: add version and userDefinedData

* feat: use the version in register / dsc proofs as well

* update calculateUserIdentifierHash

* yarn nice

* refactor: consolidate user context data handling and update payload structure

* fix typing issues on sha1

* remove console.log(sha1)

* fix sha1 import

* refactor: streamline userDefinedData handling and adjust payload type for circuit

* refactor: update sha1 usage and enhance logging in calculateUserIdentifierHash

* yarn nice

* yarn lint common

* use ts-ignore for sha1 import

* fix app ci tests

* fix typing issue

* remove unused ts-ignore

* cast uuid before calling generateinputs

* bump qrcode version

* add tsup on the qrcode sdk

* fix: exports on selfxyz/qrcode

* update how we define config.version

* fix yarn imports

* yarn format

---------

Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Ayman <[email protected]>

* Hotfix contract compile error (#660)

* Fix previous rebase error

* Refactor deployment module for Identity Verification Hub V2.

* Fix/sdk (#652)

* fix: sdk build configs

* chore: SelfBackendVerifier (WIP)

* feat: add custom verification

* feat: consider destination chain in user defined data

* chore: export attestation id

* chore: export attestation id

* chore: export config storage

* chore: don't throw an error if the proof is not valid

* chore: trim abi and rm typechain types

* refactor

* chore: rm unnecessary exports

* 📝 Add docstrings to `fix/sdk` (#653)

Docstrings generation was requested by @remicolin.

* https://github.com/selfxyz/self/pull/652#issuecomment-2992046545

The following files were modified:

* `sdk/core/src/utils/hash.ts`
* `sdk/core/src/utils/proof.ts`
* `sdk/core/src/utils/utils.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* review fixes

* chore: fix package.json cjs types

* chore: add minor changes to checks

* feat: add InMemoryConfigStore, allIds constant and verificationResult type

* chore: export Verification config

* feat: change the verification config types

* fix: throw issues early if verification config is null

* fix: update yarn.lock file

* chore: lint

* fix: rm ts expect error directive

* fix: contract tests

* use excluded countries instead forbidden countries list

* chore: change types in constnats

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update npm-publish workflow and bump core package version to 1.0.0 (#661)

* update import

* Update get verification config visibility (#664)

* Update deployment module for Identity Verification Hub V2 to correct file paths and module name for deployment commands.

* Add troubleshooting documentation for verification issues in deployHubV2.ts. Include manual verification steps and common failure reasons to assist users during deployment.

* Change visibility of getVerificationConfigV2 function from internal to public in IdentityVerificationHubImplV2 contract to allow external access.

* Apply BUSL v1.1 license headers to app (#665)

* Add BSL license headers to app sources

* prettier

* fix license reference - https://spdx.org/licenses/BUSL-1.1.html

* bump build: android 73 (#659)

* Contracts/deploy staging (#668)

* update scripts

* deploy vc and disclose id

* fix the deployment scripts on staging

* update yarn.lock

* bump ios build and version (#669)

* configure coderabbitai (#670)

* tweak coderabbit

* bump

* more thorough test spec

* Apply BSL to app codebase (#639)

* Clean up root license wording

* Simplify SPDX header

* simplify license and rename BSL to BUSL

* fix merge issues

* fix missing method

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-423 apply xcode build suggestions (#671)

* apply recommended app settings from xcode

* stick to portrait orientation and update target settings

* remove app clip references

* Circuit audit fixes  (#644)

* feat: add range checks before use of LessEqThan and SelectSubArray

* fix: Num2Bits_strict to constrain virtualKey

* bump core version

* bump core version and fix ci

* chore: use npm_auth_token in yarnrc

* chroe: rm yarnrc changes

* chore: update npm publish

* chore: run npm publish manually

* chore: change hub contract address (#675)

* Update npm-publish.yml

* chore: use proper secret when publishing

* feat: enable publishing if workflow was triggered manually

* Contracts/update verifier (#673)

* update hardhat config

* update vc and disclose verifier

* update vc and disclose verifier script and run it

* update test self verification root

* update verifier

* bump sdk version and use new hub address

* chore: update zk-kit binary merkle root dep (#674)

---------

Co-authored-by: Ayman <[email protected]>
Co-authored-by: Vishalkulkarni45 <[email protected]>
Co-authored-by: nicoshark <[email protected]>
Co-authored-by: Nesopie <[email protected]>
Co-authored-by: Seshanth.S🐺 <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Justin Hernandez <[email protected]>
Co-authored-by: Kevin Lin <[email protected]>
Co-authored-by: kevinsslin <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Eric Nakagawa <[email protected]>

* refactor deployment scripts (#678)

* feat: add register eu id instances (#682)

* feat: add register eu id instances

* feat: add new instances

* chore: update scripts

* chore: fix sig alg

* chore: rm circuits

* update the smart contracts scripts (#684)

* remove the && false

* fix euid (#685)

* keep build and version in sync (#686)

* fix env set to null

* fix: circuit for register ci (#690)

* fix: circuit for register ci

* fix: rm duplicate workflow_dispatch

* feat: add better error handling (#691)

* fix: older than bug (#692)

* bump: sdk/[email protected]

* fix: config not found bug

* decrease parallel circuits to 3

* ci: add prettier check for contract sdk (#602)

* Add Prettier check for code formatting in contracts workflow

* Update contracts workflow: remove unused checkout action and fix build step name

* Run formatter

* Run lint fix

* chore: update build_cpp to 2 concurrent builds

* Contract/fix sdk (#695)

* fix contracts sdk

* fix contracts sdk

* Fix contract example v2 (#694)

* feat: add verification config ID functionality to Airdrop, HappyBirthday, and SelfIdentityERC721 contracts

* Run formatter

* SEL-473: Add lint rule for BUSL headers (#698)

* chore(app): enforce license header via eslint

* update lock and order

* fix formatting

* SEL-444: Fix android cloud backup (#697)

* feat(android): migrate google backup

* update lock and google services config

* add bulk format command

* backup fixes

* working drive settings!!!!!!!!

* remove unneeded intent filter

* add tests

* coderabbit feedback

* coderabbit feedback

* abstract google method

* coderabbit feedback and fix test

* more coderabbit suggestions and tests fixes

* chore: update relayer verifier enum to include the register circuits (#699)

* fix env sample (#700)

* Abstract iOS cloud backup logic (#701)

* feat(ios): abstract cloud backup logic

* prettier and cr feedback

* tested on iOS and android and functionality is the same

* Fix navigation serialization warnings (#702)

* test: cover modal callbacks

* coderabbit feedback

* feat(app): clarify passport linking (#704)

* Show NFC support message (#708)

* SEL-425: Add document management analytics events (#706)

* Add document management analytics

* coderabbit feedback

* SEL-447: Improve proof failure feedback (#707)

* feat: flag stale proofs as failed

* make a constant

* format

* SEL-330: Add backup check after verification (#711)

* route to save phrase if backup disabled

* format

* SEL-483: Implement recovery backup prompts (#710)

* feat: prompt users to back up account

* feat: prompt users to back up account

* format

* Add tests for recovery prompt logic

* more lint updates

* fix imports

* fix unused import

* update cursor suggestions

* implement coderabbit suggestions and fix tests

* SEL-472: Enable production push notifications (#703)

* chore: leave sandbox apns token comment

* tweak entitlement

* coderabbit ai feedback

* firebase tweaks

* Chore: ensure there is an extra empty line after the license declaration (#712)

* ensure there is an extra empty line after the license declaration

* ignore adding header to cjs config files

* add missing license header

* ignore linting metro config

* bump version and add mainnet hub address

* Bugfix: Show recovery prompt only when user has docs (#714)

* feat(app): prompt recovery only when docs exist

* cr feedbacl

* SEL-487: Prompt user to backup recovery phrase before registering (#715)

* feat: prompt backup before registration

* coderabbit feedback

* fix tests

* coderabbitai feedback and fix tests

* Remove StartupFlushPolicy (#717)

* SEL-479: Multi-ID onboarding mvp flow (#688)

* save new launch screen wip

* save wip

* finalize launch look

* replace launch screen

* rename

* update camera onboarding and scan screen

* update tips looks

* update nfc scan issue screens

* update copy

* add launch screen todo

* fix casing

* update launch screen link, copy and add tracking event

* bump project version to match app store

* match app store

* updated supported bio id link

* add dialog message support back in

* cr feedback

* bump version and build

* update images

* tweak animation layout

* loop with setTimeout

* fix onboarding assets (#719)

* feat: add flag to use PACEPolling (#680)

* feat: add flag to use PACEPolling

* fix: santize before storing in store

* bump ios build number and update podfile lock

* prettier

* bump build

* feat: add flag to use PACEPolling

* fix: santize before storing in store

* bump ios build number and update podfile lock

* prettier

* bump build

---------

Co-authored-by: Justin Hernandez <[email protected]>

* fix backup button label (#722)

* update version to 2.6.0 and bump build numbers (#721)

* SEL-179 & SEL-312: Add gitleaks and GitGuardian scanning (#705)

* chore: add secret scanning setup

* fix: correct GitGuardian action path

* cr feedbacak

* test husky commit

* pr feedback

* fix workflows

* tweaks

* fix versions

* upgrade: migrate from husky v8 to v9

- Update husky from ^8.0.0 to ^9.1.7
- Change prepare script from 'husky install' to 'husky'
- Remove v8 hook structure (shebang, husky.sh sourcing)
- Delete .husky/_/ directory as it's not needed in v9
- Maintain gitleaks pre-commit hook functionality

* coderabbitai feedback

* add bulk sort command (#723)

* feat(app): redirect empty docs to launch (#725)

* Apply consistent safe area padding across screens (#726)

* Contracts/update verifiers (#729)

* update the verifiers

* update deployment script

* update deployment script and deploy to prod

* prettier run write

* App/ethcc fixes (#730)

* fix mock data screen

* increase timout between dsc and register proof

* fix the isUserRegisteredWithAlternativeCSCA function

* yarn nice

* allow people to switch to a mock id (#732)

* yarn nice

* chore: update default config id method

* chore: use named exports

* Update README.md

* Temporarily disable recovery redirect and reminder prompts  (#733)

* Revert "SEL-487: Prompt user to backup recovery phrase before registering (#715)"

This reverts commit fe14ac655e11b4b9e0c4023002b84fcc79bedd31.

* revert update

* fix safe area context pkg

* Revert "SEL-487: Prompt user to backup recovery phrase before registering (#715)"

This reverts commit fe14ac655e11b4b9e0c4023002b84fcc79bedd31.

* fix old flow

* more silent tests

* update lock files

* hard code return

* SEL-486: Fix unwrap DO (#718)

* update podfile: unwrapDO

* update lock

* bump version and builds

* bump build; forgot to enable logs

* fix version to not interfere with release

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-494: Update proving machine event tracking (#734)

* Add extensive proof analytics instrumentation

* prettier and sort events by key name

* remove loading screen race condition redirect (#736)

* Chore: new build for v2.6.0 ios 145 android 81 (#737)

* bump version and build

* properly bump app

* bump build

* Improve manual mobile deploy workflow and docs (#728)

* Add basic Fastlane helper tests

* Upgrade fastlane and enhance helper tests (#738)

* simplify mobile deploy pipelines and make them manual. update readme

* update fastlane dev readme

* update tests and add helper script

* cr feedback, update tests, revert circuits package.json sort change

* tweaks

* fix slack

* cr feedback and fixes

* add better cjs eslint support

* save wip. add confirmation check script. update scripts

* remove auto increment feature

* migrate readme items over to DEV due to fastlane auto regen docs flow

* use regular xcode

* fix hermes compiler path

* coderabbit feedback

* reinstall when on local dev

* fix upload

* simplify

* simplify confirmation feedback with tests

* fix mobile deploys

* cr feedback

* test iOS building

* fix trigger logic

* cr feedback

* updates

* fix env var

* fix order

* re-enable upload to testflight for ios

* updated notes

* chore: update readme

* Bugfix: android deeplinks (#742)

* bugfix: deep linking

* add android manifest test

* bump build and version

* format readme

* fix deeplink genmockiddoc

* add the gender to the deeplink optoin

* bump version (#743)

* fix the female bug

* bump build 148 (#744)

* SEL-496: Add Firebase Remote Config and dev feature flag screen (#735)

* feat: add remote config support

* update lock

* tweak config logic. add feature flag viewing screen

* add tests

* allow for local overriding of feature flags

* save local override work

* save wip

* clean up ui

* update screen to handle multi value types

* fix tests

* cr feedback and fix tests

* remote config upates. fix tests, codex feedback

* Improve AGENTS workflow notes (#747)

* clarify workflow instructions

* agents feedback

* Address minor mobile deployment bugs (#745)

* feat: improve deployment tooling

* cr feedback

* for temp testing

* clean build artifacts after deploy

* add deploy source

* uncomment ios commands

* Add tests for minor deployment fixes (#750)

* Add test coverage for deployment scripts and Fastfile

* format

* increase github check to 5 minutes

* Extend platform build file tests (#748)

* Add build file tests

* cr feedback

* Add proving machine tests (#749)

* Add actor mock helper and tests

* format tests

* fix tests

* wip fix tests

* address cr feedback

* Add thorough test cases for mobile app (#752)

* Add actor mock helper and tests

* format tests

* fix tests

* Revert non-app tests

* update tests

* fix tests

* coderabbit feedback

* revert change

* remove spurious tests

* don't use crypto in core sdk

* Start of Web App (#689)

* Add .cursorignore to optimize AI editor performance and security (#758)

Prevents Cursor AI from accessing sensitive files (keys, credentials,
deployment configs) and large generated artifacts that slow down indexing.
Keeps source code accessible while excluding build outputs, node_modules,
and circuit/contract compilation artifacts across the monorepo.

* SEL-504: fix fonts and some styles (#762)

* fix fonts and some styles

* dry config

* fix some warnings

* lets start with coverage for app (#763)

* lets start with coverage for app

* lint

* better setup

* SEL-559: Update td1 regex (#760)

* feat: update td1 regex

* update review comments

* fix: NPE on expirationDate regex

* fix user defined data (#766)

* fix: name formatting for middle name

* bump: sdk/core to 1.0.7-beta.1

* Feat/retrieve OFAC trees from api (#769)

* retrieve the ofac trees from the api

* remove the ofac trees from the common repo

* fix ofac test

* yarn nice

* yarn nice

* yarn nice

* refactor ofac fetching

* Release new build v2.6.2 (#779)

* bump version and build

* ignore podfile

* Remove failing version test (#780)

* remove version check test

* remove test all together

* SEL-269: Update ESLint rules & lock prettier config (#781)

* Update ESLint config and lock prettier config

* Refine ESLint config and fix lint issues

* Apply eslint fixes

* Use socketIo alias (#782)

* move gesture handler

* save wip updates

* fix svg imports

* update tsconfig

* eslint updates

* eslint fixes

* improve ignore folders

* coderabbit feedback

* Fix style prop shorthands (#787)

* Expand view style props

* Expand remaining style props

* update types

* fix pipeline

* fix test env check

* nicer casting

* fix booleans

* update deeplink url handling and make it more robust

* add socket error handler

* Add COSE signature verification tests (#788)

* Update ESLint config and lock prettier config

* Refine ESLint config and fix lint issues

* save wip updates

* eslint updates

* eslint fixes

* Add COSE signature verification tests

* fix tests

* SEL-553: Show NFC Progress (#764)

* feat: add haptics

* fix: BAC FAILED error event

* update lock file

---------

Co-authored-by: Justin Hernandez <[email protected]>

* SEL-566: Navigate Home based on document validity (#768)

* feat: navigate home if atleast one valid document is present

* update comments

* Review: Remove unnecessary continue statement

* feat: add tracking

* SEL-544: Generate Mock DSC on mock-passport flow (#772)

* feat: Generate mock DSC on mock-passport flow

* Remove console log

* yarn format

* revert to mock dsc generation

* SEL-570: Display user ID in prove screen (#790)

* Display user ID on prove screen

* Add user ID formatting util and tests

* Clarify user ID formatting

* fix nice

* add tests and save toggle wip

* update tests based on feedback

* say connected wallet when wallet

* fix: Add localhost validation to prevent invalid endpoint usage in QR Code SDK (#794)

* Feat/mobile deployment automation (#759)

* feat: add version management system with build number tracking

- Add version.json to track iOS/Android build numbers separately
- Create version.cjs script for build number management
- Add Fastlane version_manager.rb helper
- Keep npm version for semver, version.json for build tracking

* feat: integrate version.json with Fastlane deployment process

## What Changed
- Updated iOS and Android Fastlane lanes to use version.json for build number management
- Added automatic build number increment on deployment
- Added deployment timestamp tracking

## How It Works

### iOS Deployment
1. Reads current build number from version.json
2. Increments iOS build number (e.g., 148 → 149)
3. Updates Xcode project with new build number via increment_build_number
4. Proceeds with TestFlight deployment
5. Updates lastDeployed timestamp on successful upload

### Android Deployment
1. Reads current build number from version.json
2. Increments Android build number (e.g., 82 → 83)
3. Updates build.gradle with new version code via increment_version_code
4. Proceeds with Play Store deployment
5. Updates lastDeployed timestamp on successful upload

## Why This Change
- Eliminates manual version/build number entry
- Prevents version conflicts between deployments
- Provides single source of truth for build numbers
- Enables automatic deployments without human intervention
- Tracks deployment history with timestamps

## Dependencies
- Requires version.json file (already created in previous commit)
- Uses existing Fastlane plugins:
  - increment_build_number (iOS - built-in)
  - increment_version_code (Android - from plugin)
- Version numbers still managed by npm version command

* feat: enhance deploy confirmation with version.json info

* fix: use ENV variable directly in increment_build_number to avoid secret masking

* fix: correct xcodeproj path for GitHub Actions workflow

* feat: add test mode to workflow for safe testing

- Skip store uploads when test_mode is true
- Test version bumps and builds without deployment
- Prevent accidental pushes to TestFlight/Play Store

* fix: use gradle_file_path instead of gradle_file for increment_version_code

* fix: use gsub to remove ../ prefix for CI compatibility

* chore: remove accidentally committed files

- Remove .cursor/mcp.json
- Remove .cursorignore
- Remove deployment-automation-summary.md
- Remove deployment-meeting-questions.md
- Remove pipeline.md

* feat: auto-commit version.json after successful deployment

- Commits version.json changes back to repository
- Only runs when test_mode is false
- Uses [skip ci] to prevent infinite loops
- Checks for actual changes before committing

* feat : update package.json in build step using npm version

* feat: add comprehensive caching to mobile deployment workflow

- Add caching for Yarn dependencies, Ruby gems, CocoaPods, Gradle, and Android NDK
- Implement cache versioning strategy for easy cache invalidation
- Fix cache order: caches now restored after checkout but before dependency installation
- Update mobile-setup action to skip installs when dependencies are cached
- Add cache size monitoring to track usage against GitHub's 10GB limit
- Fix Slack notification bug: skip notifications in test_mode
- Add detailed logging for package.json version updates (show from/to versions)

Expected performance improvement: ~50% faster builds (from ~15min to ~7-10min)

* fix: move bundler config after Ruby setup in mobile-setup action

* fix: rename cache env vars to avoid Yarn conflicts

Yarn was interpreting YARN_CACHE_VERSION as its own config setting.
Prefixed all cache version env vars with GH_ to avoid conflicts.

* fix: remove bundler deployment mode to allow Gemfile updates

The deployment mode was causing bundler to fail when Gemfile
changed (nokogiri was removed). CI should be able to update
the lockfile as needed.

* feat: implement strict lock file enforcement (Option 1)

- Re-enable bundler deployment mode for strict Gemfile.lock checking
- Use yarn install --immutable for strict yarn.lock checking
- Add clear error messages when lock files are out of date
- Add pre-checks to verify lock files exist
- This ensures reproducible builds and makes caching maximally effective

When developers change dependencies, they must now:
1. Run yarn install or bundle install locally
2. Commit the updated lock files
3. CI will fail with helpful instructions if they forget

* fix: update Gemfile.lock for CI environment

Remove nokogiri from Gemfile.lock since it's excluded in CI
environments (GITHUB_ACTIONS=true). This allows the strict
lock file checks to pass in CI.

* fix: correct yarn.lock path for monorepo workspace

The project uses Yarn workspaces with yarn.lock at the repository
root, not in the app directory. Updated paths to check for yarn.lock
at workspace root and use it for cache keys.

* fix: handle both boolean and string test_mode parameter

The test_mode parameter was only checking for string 'true' but
could be passed as boolean true from command line. Now handles both
cases to ensure test mode works correctly for iOS and Android.

* fix: address code review feedback for mobile deployment workflow

- Replace jq with Node.js for version extraction (jq not available on macOS runners)
- Fix concurrent commit race condition by creating separate update-version job
- Add platform validation to version_manager.rb and version.cjs scripts
- Use POSIX-compatible single = for shell string comparisons
- Ensure single atomic commit when deploying to both platforms

* fix: formatting and linting issues

- Remove trailing spaces from workflow YAML file
- Fix prettier formatting in JavaScript files
- Add -y flag to yarn version command for non-interactive mode
- Address all lint warnings from CI

---------

Co-authored-by: Jayaditya Gupta <[email protected]>

* fix: increment iOS build number

* fix: bump app version to 2.6.3 for iOS release

* App/deeplink callback (#789)

* add deepllinkCallback support

* bump package version

* yarn nice

* fix background countdown

* cast the URL to prevent malicious code introduction

* fix: use cleanDocumentNumber (#784)

* increment iOS bundle version

* Feat/push to dev main (#767)

* feat: add version management system with build number tracking

- Add version.json to track iOS/Android build numbers separately
- Create version.cjs script for build number management
- Add Fastlane version_manager.rb helper
- Keep npm version for semver, version.json for build tracking

* feat: integrate version.json with Fastlane deployment process

## What Changed
- Updated iOS and Android Fastlane lanes to use version.json for build number management
- Added automatic build number increment on deployment
- Added deployment timestamp tracking

## How It Works

### iOS Deployment
1. Reads current build number from version.json
2. Increments iOS build number (e.g., 148 → 149)
3. Updates Xcode project with new build number via increment_build_number
4. Proceeds with TestFlight deployment
5. Updates lastDeployed timestamp on successful upload

### Android Deployment
1. Reads current build number from version.json
2. Increments Android build number (e.g., 82 → 83)
3. Updates build.gradle with new version code via increment_version_code
4. Proceeds with Play Store deployment
5. Updates lastDeployed timestamp on successful upload

## Why This Change
- Eliminates manual version/build number entry
- Prevents version conflicts between deployments
- Provides single source of truth for build numbers
- Enables automatic deployments without human intervention
- Tracks deployment history with timestamps

## Dependencies
- Requires version.json file (already created in previous commit)
- Uses existing Fastlane plugins:
  - increment_build_number (iOS - built-in)
  - increment_version_code (Android - from plugin)
- Version numbers still managed by npm version command

* feat: enhance deploy confirmation with version.json info

* fix: use ENV variable directly in increment_build_number to avoid secret masking

* fix: correct xcodeproj path for GitHub Actions workflow

* feat: add test mode to workflow for safe testing

- Skip store uploads when test_mode is true
- Test version bumps and builds without deployment
- Prevent accidental pushes to TestFlight/Play Store

* fix: use gradle_file_path instead of gradle_file for increment_version_code

* fix: use gsub to remove ../ prefix for CI compatibility

* chore: remove accidentally committed files

- Remove .cursor/mcp.json
- Remove .cursorignore
- Remove deployment-automation-summary.md
- Remove deployment-meeting-questions.md
- Remove pipeline.md

* feat: auto-commit version.json after successful deployment

- Commits version.json changes back to repository
- Only runs when test_mode is false
- Uses [skip ci] to prevent infinite loops
- Checks for actual changes before committing

* feat : update package.json in build step using npm version

* feat: add comprehensive caching to mobile deployment workflow

- Add caching for Yarn dependencies, Ruby gems, CocoaPods, Gradle, and Android NDK
- Implement cache versioning strategy for easy cache invalidation
- Fix cache order: caches now restored after checkout but before dependency installation
- Update mobile-setup action to skip installs when dependencies are cached
- Add cache size monitoring to track usage against GitHub's 10GB limit
- Fix Slack notification bug: skip notifications in test_mode
- Add detailed logging for package.json version updates (show from/to versions)

Expected performance improvement: ~50% faster builds (from ~15min to ~7-10min)

* fix: move bundler config after Ruby setup in mobile-setup action

* fix: rename cache env vars to avoid Yarn conflicts

Yarn was interpreting YARN_CACHE_VERSION as its own config setting.
Prefixed all cache version env vars with GH_ to avoid conflicts.

* fix: remove bundler deployment mode to allow Gemfile updates

The deployment mode was causing bundler to fail when Gemfile
changed (nokogiri was removed). CI should be able to update
the lockfile as needed.

* feat: implement strict lock file enforcement (Option 1)

- Re-enable bundler deployment mode for strict Gemfile.lock checking
- Use yarn install --immutable for strict yarn.lock checking
- Add clear error messages when lock files are out of date
- Add pre-checks to verify lock files exist
- This ensures reproducible builds and makes caching maximally effective

When developers change dependencies, they must now:
1. Run yarn install or bundle install locally
2. Commit the updated lock files
3. CI will fail with helpful instructions if they forget

* fix: update Gemfile.lock for CI environment

Remove nokogiri from Gemfile.lock since it's excluded in CI
environments (GITHUB_ACTIONS=true). This allows the strict
lock file checks to pass in CI.

* fix: correct yarn.lock path for monorepo workspace

The project uses Yarn workspaces with yarn.lock at the repository
root, not in the app directory. Updated paths to check for yarn.lock
at workspace root and use it for cache keys.

* fix: handle both boolean and string test_mode parameter

The test_mode parameter was only checking for string 'true' but
could be passed as boolean true from command line. Now handles both
cases to ensure test mode works correctly for iOS and Android.

* fix: address code review feedback for mobile deployment workflow

- Replace jq with Node.js for version extraction (jq not available on macOS runners)
- Fix concurrent commit race condition by creating separate update-version job
- Add platform validation to version_manager.rb and version.cjs scripts
- Use POSIX-compatible single = for shell string comparisons
- Ensure single atomic commit when deploying to both platforms

* fix: formatting and linting issues

- Remove trailing spaces from workflow YAML file
- Fix prettier formatting in JavaScript files
- Add -y flag to yarn version command for non-interactive mode
- Address all lint warnings from CI

* feat: implement automated branch-based mobile deployments

- Add mobile-deploy-auto.yml workflow that triggers on PR merges to dev/main
- Update mobile-deploy.yml to support workflow_call for reusability
- Add deployment_track, version_bump, and auto_deploy parameters
- Create new Fastlane lanes (deploy_auto) for iOS and Android
- Implement smart version bumping based on PR labels (major/minor/patch)
- Add graceful error handling for Play Store permission issues
- Enhance Slack notifications with deployment track information

This enables automatic deployments when PRs are merged:
- dev branch → internal testing track
- main branch → production track
- Skip deployment with [skip-deploy] in PR or no-deploy label

* feat: add automated git tagging and release system

- Add automatic git tagging for production deployments (v2.5.5, platform-specific tags)
- Create GitHub releases with changelogs for production deployments
- Add manual release script (yarn release) for version bumping and tagging
- Implement simple changelog generation from git history
- Add comprehensive deployment documentation in .github/MOBILE_DEPLOYMENT.md
- Update app/README.md with deployment commands and workflows

This completes the release automation system requested in the ticket for
manual tagging and versioning with automated changelogs and release notes.

---------

Co-authored-by: Jayaditya Gupta <[email protected]>

* Implement basic code splitting

* cm feedback

* update lock

* yarn nice

* add typing to crypto loader

* fix type. more opportunities

* lint suggestions

* build dependencies before linting

* fix build command

* save updated imports

* update build checks

* fix import

* fix imports and test

* fix install commands

* Update Gemfile.lock to exclude nokogiri in CI environments

- Regenerated Gemfile.lock with GITHUB_ACTIONS=true to match the conditional
  nokogiri exclusion in the Ge…
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