`
qrDisplay.appendChild(info)
} else {
// Fallback to text display if QR generation fails
qrDisplay.innerHTML =
'
QR Code generation failed
${status.sessionURI}
'
}
} else {
qrDisplay.textContent = 'No session URI available'
}
} else {
statusDisplay.textContent = formatStatus(null)
statusDisplay.className = 'status-box'
qrDisplay.textContent = 'Session URI will appear here when created'
}
}
// Event Handlers
createBtn.addEventListener('click', async () => {
try {
log('Creating new session...')
await IDKitSession.create({
app_id: 'app_ce4cb73cb75fc3b73b71ffb4de178410',
action: 'test-action',
signal: 'test_signal_' + Date.now(),
action_description: 'Test session-based verification',
verification_level: 'orb',
partner: true,
})
log('Session created successfully!')
await updateUI()
} catch (error) {
log(`Error creating session: ${error.message}`)
}
})
pollBtn.addEventListener('click', async () => {
try {
log('Polling for updates...')
const status = await IDKitSession.pollStatus()
log(`Poll result: ${status.state}`)
await updateUI(status)
} catch (error) {
log(`Error polling: ${error.message}`)
}
})
startPollingBtn.addEventListener('click', async () => {
log('Starting automatic polling...')
pollingInterval = setInterval(async () => {
try {
// Check if session is still active before polling
if (!IDKitSession.isActive) {
log('Session no longer active. Stopping auto-polling.')
clearInterval(pollingInterval)
pollingInterval = null
// Don't clear UI - preserve last status
return
}
const status = await IDKitSession.pollStatus()
// Stop polling if verification is complete
if (status.state === 'confirmed' || status.state === 'failed') {
log(`Verification ${status.state.toLowerCase()}. Stopping auto-polling.`) // UI already updated with final status above
clearInterval(pollingInterval)
pollingInterval = null
}
await updateUI(status)
} catch (error) {
log(`Polling error: ${error.message}`)
// Stop polling on error (session might be destroyed or invalid)
log('Stopping auto-polling due to error.')
clearInterval(pollingInterval)
pollingInterval = null
}
}, 1000)
})
stopPollingBtn.addEventListener('click', () => {
log('Stopping automatic polling...')
clearInterval(pollingInterval)
pollingInterval = null
})
destroyBtn.addEventListener('click', async () => {
try {
log('Destroying session...')
await IDKitSession.destroy()
log('Session destroyed.')
await updateUI()
} catch (error) {
log(`Error destroying session: ${error.message}`)
}
})
// Initial UI update
updateUI()
```
--------------------------------
### Run Local Test Project using Yarn
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react/README.md
Starts a local development server for testing the widget. Access the running application at http://localhost:3000. This command should be run from within the '/idkit' folder.
```bash
cd idkit/
yarn dev
```
--------------------------------
### Install IDKit for React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/README.md
Installs the IDKit library specifically for React Native applications. This package includes necessary components and utilities for integrating World ID verification into mobile apps.
```bash
yarn add @worldcoin/idkit-react-native
# or
npm i @worldcoin/idkit-react-native
# or
pnpm install @worldcoin/idkit-react-native
```
--------------------------------
### Install Crypto Polyfills for React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Ensures necessary crypto functionality is available in React Native by installing the 'react-native-quick-crypto' package. This is crucial as React Native lacks native crypto support.
```typescript
// polyfills.ts
import { install } from 'react-native-quick-crypto'
install()
```
```typescript
// Add to your entry file
import { install } from 'react-native-quick-crypto'
install()
```
--------------------------------
### IDKit Session API: Polling and UI Updates (JavaScript)
Source: https://github.com/worldcoin/idkit-js/blob/main/examples/with-html/session-example.html
Handles automatic polling for IDKit session updates and manual UI updates. It uses `setInterval` for polling and `clearInterval` to stop it. The `updateUI` function is responsible for refreshing the user interface based on the session status. No external dependencies are explicitly mentioned beyond the `IDKitSession` object.
```javascript
const startPollingBtn = document.getElementById('start-polling')
const stopPollingBtn = document.getElementById('stop-polling')
const destroyBtn = document.getElementById('destroy')
let pollingInterval = null
function log(message) {
console.log(message)
const logEl = document.getElementById('log')
if (logEl) {
logEl.innerText = message + '\n' + logEl.innerText
}
}
async function updateUI() {
const status = await IDKitSession.getStatus()
const isPolling = pollingInterval !== null
document.getElementById('status').innerText = `Status: ${status}`
document.getElementById('start-polling').disabled = isPolling
document.getElementById('stop-polling').disabled = !isPolling
document.getElementById('destroy').disabled = status === 'none'
}
startPollingBtn.addEventListener('click', async () => {
log('Starting automatic polling...')
pollingInterval = setInterval(async () => {
await updateUI()
// Don't clear UI - preserve last known status
}, 3000)
await updateUI()
})
stopPollingBtn.addEventListener('click', async () => {
if (pollingInterval) {
log('Manually stopping automatic polling...')
clearInterval(pollingInterval)
pollingInterval = null
await updateUI() // Update button states only
}
})
destroyBtn.addEventListener('click', async () => {
if (pollingInterval) {
clearInterval(pollingInterval)
pollingInterval = null
}
IDKitSession.destroy()
log('Session destroyed')
await updateUI()
})
// Initialize UI
updateUI()
log('IDKit Session API example ready!')
```
--------------------------------
### Start World ID Verification in React Native with Session Management
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Initiates World ID verification in a React Native application using the Session class. It creates a session, opens the World App for verification, and polls for the status, handling confirmation or failure. Requires `@worldcoin/idkit-react-native` and `react-native`'s Linking module.
```typescript
import { Session, VerificationState } from '@worldcoin/idkit-react-native'
import { Linking } from 'react-native'
async function startVerification() {
// Create session
const session = await new Session().create(
'app_020c82fbf3c087eb31600929a34990e4',
'login-action',
{
signal: 'user_123',
verification_level: VerificationLevel.Device
}
)
// Open World App with return URL
const returnUrl = 'myapp://verification'
const connectorUrl = new URL(session.sessionURI)
connectorUrl.searchParams.set('return_to', returnUrl)
await Linking.openURL(connectorUrl.toString())
// Poll for verification status
const pollInterval = setInterval(async () => {
const status = await session.status()
if (status.state === VerificationState.Confirmed) {
console.log('Verification proof:', status.result)
clearInterval(pollInterval)
session.destroy()
} else if (status.state === VerificationState.Failed) {
console.error('Failed:', status.errorCode)
clearInterval(pollInterval)
session.destroy()
}
}, 2000)
}
```
--------------------------------
### Initialize and Open IDKit JS SDK
Source: https://github.com/worldcoin/idkit-js/blob/main/examples/with-html/index.html
Initializes the IDKit SDK with essential parameters such as signal, app_id, action, and verification level. It also sets up an event listener to open the IDKit modal when a button is clicked. The `handleVerify` and `onSuccess` callbacks are crucial for processing the verification results.
```javascript
import '@worldcoin/idkit-standalone'
IDKit.init({
signal: 'test_signal',
app_id: 'app_ce4cb73cb75fc3b73b71ffb4de178410',
action: 'test-action',
action_description: 'Test action description',
show_modal: true,
container_id: 'idkit-container',
partner: true,
verification_level: 'orb',
disable_default_modal_behavior: true,
handleVerify: response => {
// verify the IDKIt proof, throw an error to show the error screen
},
onSuccess: response => {
console.log(response)
},
});
document.getElementById('open-idkit').addEventListener('click', async () => {
console.log(IDKit.isInitialized)
await IDKit.open()
});
```
--------------------------------
### Build Production Bundle using Yarn
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react/README.md
Compiles the project into a production-ready bundle. This command should be run from within the '/idkit' folder.
```bash
cd idkit/
yarn build
```
--------------------------------
### IDKit Widget API
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/standalone/README.md
Documentation for the IDKit Widget global object, which provides methods to initialize, open, close, and update the verification modal.
```APIDOC
## IDKit Widget API
### Global Object: `window.IDKit`
Provides methods for interacting with the IDKit verification modal.
### Methods
- **`IDKit.init(config)`**
- **Description**: Initializes the IDKit widget with the provided configuration.
- **Parameters**:
- `config` (object) - Required - Configuration object for the widget.
- **Example**:
```javascript
IDKit.init({
"app_id": "app_12345",
"action_id": "act_12345",
"enable_testing": true
});
```
- **`IDKit.open()`**
- **Description**: Opens the verification modal.
- **Example**:
```javascript
IDKit.open();
```
- **`IDKit.close()`**
- **Description**: Closes the verification modal.
- **Example**:
```javascript
IDKit.close();
```
- **`IDKit.update(config)`**
- **Description**: Updates the widget configuration after initialization.
- **Parameters**:
- `config` (object) - Required - Configuration object to update.
- **Example**:
```javascript
IDKit.update({
"enable_testing": false
});
```
### Properties
- **`IDKit.isInitialized`**
- **Description**: A boolean indicating whether the widget has been initialized.
- **Type**: boolean
- **Example**:
```javascript
if (IDKit.isInitialized) {
console.log('IDKit widget is ready.');
}
```
```
--------------------------------
### Run Tests using Yarn
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react/README.md
Executes the test suite for the IDKit package. This command should be run from within the '/idkit' folder.
```bash
cd idkit/
yarn test
```
--------------------------------
### IDKit React Native - Polyfills
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Instructions on how to set up necessary polyfills for crypto functionality in React Native environments.
```APIDOC
## Polyfills
This package requires some crypto functionality that isn't natively available in React Native. You'll need to set up the necessary polyfills:
```javascript
// polyfills.ts
import { install } from 'react-native-quick-crypto';
install();
```
**Note**: For `expo` projects you need to prebuild your project for crypto to be available.
```
--------------------------------
### Session API
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/standalone/README.md
Documentation for the Session API global object, used for custom verification flows with full UI control.
```APIDOC
## Session API
### Global Object: `window.IDKitSession`
Provides methods for managing custom World ID verification flows.
### Methods
- **`IDKitSession.create(config)`**
- **Description**: Creates a new verification session.
- **Parameters**:
- `config` (object) - Required - Configuration object for the session.
- **Example**:
```javascript
IDKitSession.create({
"app_id": "app_12345",
"action_id": "act_12345"
});
```
- **`IDKitSession.pollStatus()`**
- **Description**: Polls the server for the current status of the verification session.
- **Returns**: A promise that resolves with the current session state.
- **Example**:
```javascript
const status = await IDKitSession.pollStatus();
console.log(status);
```
- **`IDKitSession.getURI()`**
- **Description**: Retrieves the session URI, typically used for QR code generation.
- **Returns**: A promise that resolves with the session URI string.
- **Example**:
```javascript
const qrCodeUri = await IDKitSession.getURI();
console.log(qrCodeUri);
```
- **`IDKitSession.destroy()`**
- **Description**: Destroys the current session and cleans up resources.
- **Example**:
```javascript
IDKitSession.destroy();
```
### Properties
- **`IDKitSession.isActive`**
- **Description**: A boolean indicating whether there is an active verification session.
- **Type**: boolean
- **Example**:
```javascript
if (IDKitSession.isActive) {
console.log('An active session exists.');
}
```
### Session States
- **`awaiting_connection`**: Waiting for the user to scan the QR code.
- **`awaiting_app`**: The user has scanned the QR code and is waiting for verification within the World App.
- **`confirmed`**: Verification has been completed successfully.
- **`failed`**: Verification has failed.
```
--------------------------------
### IDKit React Native - Troubleshooting
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Common troubleshooting steps for issues like Zustand import errors and crypto availability.
```APIDOC
## Troubleshooting
### Zustand Import Error
If you encounter errors related to Zustand's use of `import.meta`, you may need to update your Babel configuration:
Set `unstable_transformImportMeta` to `true`.
### Crypto Not Available
If you see errors about crypto not being available, make sure you've added the necessary polyfills as described in the "Polyfills" section.
```
--------------------------------
### Configure Verification Levels with TypeScript
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Demonstrates how to configure different verification levels (Orb, Device, SecureDocument) using the VerificationLevel enum from '@worldcoin/idkit'. Each level has specific security requirements and use cases.
```typescript
import { VerificationLevel } from '@worldcoin/idkit'
// Orb - highest security, requires biometric verification at Worldcoin Orb
const orbConfig = {
app_id: 'app_...',
action: 'high-value-transaction',
verification_level: VerificationLevel.Orb
}
// Device - standard security, phone-based verification
const deviceConfig = {
app_id: 'app_...',
action: 'user-registration',
verification_level: VerificationLevel.Device
}
// SecureDocument - government ID with liveness check
const docConfig = {
app_id: 'app_...',
action: 'kyc-verification',
verification_level: VerificationLevel.SecureDocument
}
```
--------------------------------
### Standalone World ID Verification with Vanilla JavaScript
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Enables World ID verification in web applications using vanilla JavaScript, without React dependencies. It utilizes the `@worldcoin/idkit-standalone` library, allowing initialization and control of the verification modal directly through HTML buttons and JavaScript functions.
```html
```
--------------------------------
### Verify Cloud Proofs with Worldcoin API
Source: https://context7.com/worldcoin/idkit-js/llms.txt
This backend function validates World ID proofs using the `verifyCloudProof` function from the `@worldcoin/idkit` library. It takes proof details from the request body and returns a success or error response based on the Worldcoin verification API's result.
```typescript
import { verifyCloudProof, ISuccessResult } from '@worldcoin/idkit'
async function handler(req, res) {
const { proof, app_id, action, signal } = req.body
const verificationResponse = await verifyCloudProof(
proof,
app_id,
action,
signal
)
if (verificationResponse.success) {
// Proof is valid - proceed with authentication
return res.status(200).json({ verified: true })
} else {
// Invalid proof
return res.status(400).json({
error: verificationResponse.detail,
code: verificationResponse.code
})
}
}
```
--------------------------------
### Configure Localization for IDKit Widget with TypeScript
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Illustrates how to manage localization for the IDKit widget using functions like 'setLocalizationConfig', 'getSupportedLanguages', and 'getCurrentLanguage' from '@worldcoin/idkit'. It shows setting a custom language, retrieving supported languages, and detecting the current language.
```typescript
import {
setLocalizationConfig,
getSupportedLanguages,
getCurrentLanguage
} from '@worldcoin/idkit'
// Set custom language
setLocalizationConfig({ language: 'es' })
// Get all supported language codes
const languages = getSupportedLanguages()
console.log('Supported:', languages) // ['en', 'es', 'th', ...]
// Detect current language
const current = getCurrentLanguage()
console.log('Current:', current)
// Use in widget (example with React)
//
// {({ open }) => }
//
```
--------------------------------
### Handle World ID Verification Success with TypeScript
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Defines a function 'handleSuccess' to process the 'ISuccessResult' interface returned after a successful World ID verification. It logs proof data, Merkle root, nullifier hash, and verification level, and demonstrates storing the nullifier to prevent reuse.
```typescript
import { ISuccessResult } from '@worldcoin/idkit'
async function handleSuccess(result: ISuccessResult) {
// Zero-knowledge proof data (hex string)
console.log('Proof:', result.proof)
// Merkle tree root used for verification
console.log('Merkle Root:', result.merkle_root)
// Unique nullifier hash prevents double-verification
console.log('Nullifier:', result.nullifier_hash)
// Verification level achieved
console.log('Level:', result.verification_level) // 'orb', 'device', etc.
// Store nullifier to prevent reuse
await database.storeNullifier(result.nullifier_hash, {
proof: result.proof,
timestamp: Date.now()
})
}
```
--------------------------------
### IDKit React Native - Session Management
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
This section details how to create, manage, and interact with verification sessions using the IDKit React Native SDK.
```APIDOC
## Session Class
The main class for interacting with World ID verification.
### Creating a Session
```typescript
// Create a session
const session = await new Session().create(
app_id: string, // Required: Your App ID from Developer Portal
action: string, // Required: Action identifier
options?: {
signal?: string, // Optional: Signal to be included in the proof
bridge_url?: string, // Optional: URL to a custom bridge
verification_level?: string, // Optional: Minimum verification level
action_description?: string, // Optional: Human-readable action description
partner?: boolean // Optional: Whether this is a partner app
}
)
```
### Methods
- `create(app_id, action, options?)`: Creates a new verification session.
- `pollForUpdates()`: Poll for verification status updates.
- `status()`: Poll for updates and return a combined status object (state, result, and error).
- `destroy()`: Clean up the session and its resources.
### Properties
- `sessionURI`: Getter for the URI to connect with World App.
### Types
```typescript
type SessionStatus = {
state: VerificationState // Current verification state
result: ISuccessResult | null // Verification result (if successful)
errorCode: AppErrorCodes | null // Error code (if verification failed)
}
```
### Basic Example
```typescript
import { Session, VerificationLevel, VerificationState } from '@worldcoin/idkit-react-native';
// Create a new verification session
const session = await new Session().create('app_id', 'your-action', {
signal: 'signal', // Optional
bridge_url: undefined, // Optional: URL to a custom bridge
verification_level: VerificationLevel.Orb, // Optional: Minimum verification level
action_description: 'Verify with World ID', // Optional
partner: false, // Optional
});
// Get the connector URI that redirects user to the World App
// Optional: Add a `return_to` query param that deeplinks that redirects back to the app
const returnTo = 'yourapp://callback'; // Replace with your deep link
const connectorUrl = new URL(session.sessionURI);
connectorUrl.searchParams.set('return_to', returnTo);
const connectUrlWithReturnAddress = connectorUrl.toString();
// Poll for updates to check verification status
const checkStatus = async () => {
const status = await session.status();
if (status.state === VerificationState.Confirmed) {
console.log('Verification successful:', status.result);
}
else if (status.state === VerificationState.Failed) {
console.log('Verification failed:', status.errorCode);
}
};
// Clean up when done
const cleanup = () => {
session.destroy();
};
```
```
--------------------------------
### IDKit React Native - Deep Linking
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Guidance on setting up deep linking for mobile verification flows to redirect users back to the application after World ID verification.
```APIDOC
## Deep Linking
For mobile verification, you'll need to set up deep linking so users can return to your app after verification:
```typescript
// In your component
import { createURL } from 'expo-linking'; // For Expo projects
import { Linking } from 'react-native'; // For non-Expo projects
const handleVerify = async (appId: string, action: string) => {
// Create session
const session = await new Session().create(appId, action);
// Set up return URL
const returnTo = createURL(''); // Replace with your deep link path, e.g., 'myapp://verification'
// Add return_to parameter to connector URL
if (session.sessionURI) {
const connectorUrl = new URL(session.sessionURI);
connectorUrl.searchParams.set('return_to', returnTo);
// Open the URL
Linking.openURL(connectorUrl.toString());
}
};
```
```
--------------------------------
### Use IDKit Widget in React
Source: https://github.com/worldcoin/idkit-js/blob/main/README.md
Demonstrates the basic usage of the IDKitWidget in a React application. It requires an actionId, signal, and a handleVerify callback function. The widget renders a button that, when clicked, opens the World ID verification modal.
```jsx
import { IDKitWidget } from "@worldcoin/idkit";
{({ open }) => (
{/* You can render whatever you want here, and call open() to open the widget */}
)}
```
--------------------------------
### Basic Usage of IDKit Session in React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/README.md
Illustrates the fundamental steps for initiating and managing a World ID verification session in React Native. This includes creating a session, obtaining a connector URL for user redirection, checking the verification status, and cleaning up the session.
```typescript
import { Session, VerificationState } from '@worldcoin/idkit-react-native'
// Create a new verification session
const session = await new Session().create('app_id', 'your-action')
// Get the connector URI that redirects user to the World App
// Optional: Add a `return_to` query param that deeplinks back to the app
const connectorUrl = new URL(session.sessionURI)
connectorUrl.searchParams.set('return_to', returnTo)
const connectUrlWithReturnAddress = connectorUrl.toString()
// Poll for updates to check verification status
const checkStatus = async () => {
const status = await session.status()
if (status.state === VerificationState.Confirmed) {
console.log('Verification successful:', status.result)
} else if (status.state === VerificationState.Failed) {
console.log('Verification failed:', status.errorCode)
}
}
// Clean up when done
const cleanup = () => {
session.destroy()
}
```
--------------------------------
### IDKit React Native Session Creation API
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Details the parameters required for creating a new World ID verification session using the IDKit React Native SDK. Includes mandatory `app_id` and `action`, along with optional configuration for `signal`, `bridge_url`, `verification_level`, `action_description`, and `partner`.
```typescript
// Create a session
const session = await new Session().create(
app_id: string, // Required: Your App ID from Developer Portal
action: string, // Required: Action identifier
options?: {
signal?: string, // Optional: Signal to be included in the proof
bridge_url?: string, // Optional: URL to a custom bridge
verification_level?: string, // Optional: Minimum verification level
action_description?: string, // Optional: Human-readable action description
partner?: boolean // Optional: Whether this is a partner app
}
)
```
--------------------------------
### useSession Hook for Verification State Management
Source: https://context7.com/worldcoin/idkit-js/llms.txt
This React hook, `useSession`, from `@worldcoin/idkit` manages the state of a World ID verification session. It handles QR code generation for mobile scanning, polls for session status, and provides results or error codes. It requires `qrcode.react` for displaying the QR code.
```tsx
import { useSession, VerificationState } from '@worldcoin/idkit'
import { QRCodeSVG } from 'qrcode.react'
function VerificationPage() {
const { status, sessionURI, result, errorCode, reset } = useSession({
app_id: 'app_staging_45068dca85829d2fd90e2dd6f0bff997',
action: 'verify-identity',
signal: 'user_session_123',
verification_level: VerificationLevel.Orb
})
if (status === VerificationState.WaitingForConnection) {
return (
Scan QR Code
{sessionURI && }
)
}
if (status === VerificationState.Confirmed) {
return (
Verified Successfully
Nullifier: {result?.nullifier_hash}
Merkle Root: {result?.merkle_root}
)
}
if (status === VerificationState.Failed) {
return (
Verification Failed
Error: {errorCode}
)
}
return
Preparing verification...
}
```
--------------------------------
### IDKitWidget Component for World ID Verification
Source: https://context7.com/worldcoin/idkit-js/llms.txt
This React component renders a modal dialog for World ID verification, managing the UI and state. It requires the `@worldcoin/idkit` library and uses a callback function to handle the verification result by sending the proof to a backend API.
```jsx
import { IDKitWidget, VerificationLevel, ISuccessResult } from '@worldcoin/idkit'
function App() {
const handleVerify = async (proof) => {
const response = await fetch('/api/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
proof,
app_id: 'app_b43756ba8253a1b97e8ce4bc41c261a0',
action: 'login',
signal: 'user_id_123'
})
})
if (!response.ok) {
throw new Error('Verification failed')
}
}
return (
console.log('Verified:', result)}
handleVerify={handleVerify}
onError={(error) => console.error('Error:', error)}
>
{({ open }) => (
)}
)
}
```
--------------------------------
### Hash Data to Field using hashToField for Signals
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Hashes string or bytes data using the keccak256 algorithm, generating a field suitable for signal generation in World ID proofs. This utility is available in `@worldcoin/idkit-core/hashing`. It returns both a raw hash and a digest suitable for verification.
```typescript
import { hashToField } from '@worldcoin/idkit-core/hashing'
// Hash string signal
const userSignal = hashToField('user_email@example.com')
console.log('Hash:', userSignal.hash)
console.log('Digest:', userSignal.digest) // 0x...
// Hash address
const addressSignal = hashToField('0x1234567890123456789012345678901234567890')
console.log('Address hash:', addressSignal.digest)
// Use in verification
const proof = await verify({
app_id: 'app_...',
action: 'action_name',
signal: userSignal.digest
})
```
--------------------------------
### Control IDKit Widget with useIDKit React Hook
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Provides a React hook, `useIDKit`, for managing the IDKitWidget modal programmatically. It allows opening and closing the modal and defining callbacks for verification success and errors without using render props. This hook simplifies modal integration in React applications.
```tsx
import { useIDKit } from '@worldcoin/idkit'
function CustomButton() {
const { open, setOpen } = useIDKit({
handleVerify: async (proof) => {
const res = await fetch('/api/verify', {
method: 'POST',
body: JSON.stringify(proof)
})
if (!res.ok) throw new Error('Verification failed')
},
onSuccess: (result) => {
console.log('Success:', result.nullifier_hash)
}
})
return (
)
}
```
--------------------------------
### Basic World ID Verification Session in React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Demonstrates how to create and manage a basic World ID verification session using the IDKit React Native SDK. It includes session creation, obtaining a connector URI, polling for status updates, and session cleanup. Handles success and failure states.
```typescript
import { Session, VerificationLevel, VerificationState } from '@worldcoin/idkit-react-native'
// Create a new verification session
const session = await new Session().create('app_id', 'your-action', {
signal: 'signal', // Optional
bridge_url: undefined, // Optional: URL to a custom bridge
verification_level: VerificationLevel.Orb, // Optional: Minimum verification level
action_description: 'Verify with World ID', // Optional
partner: false, // Optional
})
// Get the connector URI that redirects user to the World App
// Optional: Add a `return_to` query param that deeplinks that redirects back to the app
const connectorUrl = new URL(session.sessionURI)
connectorUrl.searchParams.set('return_to', returnTo)
const connectUrlWithReturnAddress = connectorUrl.toString()
// Poll for updates to check verification status
const checkStatus = async () => {
const status = await session.status()
if (status.state === VerificationState.Confirmed) {
console.log('Verification successful:', status.result)
} else if (status.state === VerificationState.Failed) {
console.log('Verification failed:', status.errorCode)
}
}
// Clean up when done
const cleanup = () => {
session.destroy()
}
```
--------------------------------
### IDKit Widget with Automatic Language Detection
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react/README.md
Shows the default configuration for the IDKitWidget where language detection is automatic. No specific `language` prop is needed. The widget requires `app_id`, `action`, and an `onSuccess` callback.
```tsx
{({ open }) => }
```
--------------------------------
### Configure Crypto Polyfills for React Native IDKit
Source: https://github.com/worldcoin/idkit-js/blob/main/README.md
Provides the necessary polyfills for crypto functionality required by IDKit in React Native environments. This ensures that cryptographic operations are correctly handled on the mobile platform.
```javascript
// polyfills.ts
import { install } from 'react-native-quick-crypto'
install()
```
--------------------------------
### Configure Deep Linking for World ID Verification in React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Sets up deep linking to enable users to return to the React Native application after completing World ID verification in the World App. This involves using a deep linking library (like expo-linking) to construct the return URL and opening the session URI with this parameter.
```typescript
// In your component
import { createURL } from 'expo-linking' // For Expo projects
import * as Linking from 'expo-linking'; // Import Linking
import { Session } from '@worldcoin/idkit-react-native'; // Import Session
const handleVerify = async () => {
// Create session
const session = await new Session().create(appId, action)
// Set up return URL
const returnTo = createURL('') // Replace with your deep link path
// Add return_to parameter to connector URL
if (session.sessionURI) {
const connectorUrl = new URL(session.sessionURI)
connectorUrl.searchParams.set('return_to', returnTo)
// Open the URL
Linking.openURL(connectorUrl.toString())
}
}
```
--------------------------------
### Encode Values to ABI Format using solidityEncode
Source: https://context7.com/worldcoin/idkit-js/llms.txt
Encodes multiple values into the Application Binary Interface (ABI) format, suitable for use as action or signal parameters in World ID verification. This function is part of the core IDKit library. It takes an array of types and an array of corresponding values as input.
```typescript
import { solidityEncode } from '@worldcoin/idkit'
// Encode user address and timestamp as action
const encodedAction = solidityEncode(
['address', 'uint256'],
['0x1234567890123456789012345678901234567890', 1234567890]
)
// Use in verification
const config = {
app_id: 'app_b43756ba8253a1b97e8ce4bc41c261a0',
action: encodedAction,
signal: 'custom_signal_data'
}
```
--------------------------------
### Manage Multiple Independent Verification Sessions in React Native
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react-native/README.md
Illustrates how to create and manage multiple independent World ID verification sessions within the same React Native application. Each session maintains its own state, allowing for distinct verification flows like login and transactions concurrently.
```typescript
// Create two separate sessions for different actions
const loginSession = await new Session().create('app_your_app_id', 'login')
const transactionSession = await new Session().create('app_your_app_id', 'transaction')
// Each session has its own state and doesn't affect the other
```
--------------------------------
### IDKit Widget with Explicit Spanish Language
Source: https://github.com/worldcoin/idkit-js/blob/main/packages/react/README.md
Demonstrates how to configure the IDKitWidget to explicitly use the Spanish language ('es'). The widget is a React component that requires `app_id`, `action`, and an `onSuccess` callback. The language is set via the `language` prop.
```tsx
{({ open }) => }
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.