---
name: coinme-compliance-react-native
description: "Apply Coinme's regional compliance rules in a React Native or Expo app (iOS and Android) using @coinme-security/compliance-sdk-react-native: install the 1.0.2 beta from the private registry, create the platform with createNativePlatform and a store such as AsyncStorage, mount ComplianceProvider, gate on getRegionStatus (ISO 3166-2 region codes only, unknown fails closed), offer only onboardable states, find missing consents and the disclosures to present, render Coinme's localized copy with ComplianceText, record attestations after onboarding with an attestation store authorized by the backend, and check each transaction with evaluateTransaction. For a React or JavaScript web app use the coinme-compliance-react skill. Use when asked about state or jurisdiction availability, consents, disclosures, attestations or the Coinme Compliance SDK in a React Native app."
metadata:
  surface: "caas"
  package: "@coinme-security/compliance-sdk-react-native"
  version: "1.0.2"
  status: "beta"
  peerDependencies: "react >=18, react-native >=0.79"
---

# Coinme compliance rules in a React Native app with the Compliance SDK

## When to use this skill

The human's own React Native app (a Coinme-as-a-Service integration, Expo or bare, on iOS and Android) needs to follow Coinme's compliance rules in its screens: which states to offer, what a region excludes, which consents and transactional disclosures a customer must accept, and a record of what the customer accepted. For a web app, use the coinme-compliance-react skill instead. It is not for the Coinme Widget, which applies these rules inside its own frame.

## Which integration this is

This skill is for the **Coinme-as-a-Service (CaaS) integration**: the partner keeps its own users and its own screens, and Coinme performs regulated services for them (onboarding and KYC, card vaulting, risk signals, transactions). The users are the partner's customers, not Coinme users. There is no Coinme Widget here, so no `rampId`, `partnerKey`, widget URL or embed allowlist. If the human wants to embed the Coinme Widget instead, this is the wrong skill: read [Two ways to build on Coinme](https://platformdocs.coinme.com/agents/surfaces.md) and pick a Widget skill.

## What you will produce

A React Native app with one platform from createNativePlatform (with a store, so a relaunch starts from the last configuration) and one ComplianceProvider near the root, a state picker built from the onboardable regions, a region gate that treats 'unknown' and 'notOperating' as unavailable, consent and disclosure screens that render Coinme's copy through ComplianceText and record each acceptance as an attestation once the customer has a customerId, and a transaction screen that checks evaluateTransaction before calling the human's backend, which remains the authority.

## Before you start: ask the human for these

The documentation does not contain them and you cannot derive them. Stop and ask, then continue. Never write a real value into a tracked file; keep each where the row says.

| Value | What it is | Where it goes |
| --- | --- | --- |
| `COINME_REGISTRY_TOKEN` | Read-only token for the private npm registry that serves @coinme-security/compliance-sdk-react-native. | An environment variable or a gitignored registry config read at install time; CI reads it from a secret. Never in a committed file. |
| `API client ID and client secret` | The credentials the human's backend exchanges at `POST /services/authorize` for a partner access token, which mints the Transient Auth Token. The client ID is not the partner ID, and not the Risk SDK's `clientId`. | The backend's secret store or environment variables; never in client code or a committed file. |
| `production base URL` | The base URL for `/services/authorize` and `/services/browserAuth` in production; sandbox is `https://caas-staging.coinme.com`. Coinme provides it at onboarding. | Backend configuration, one value per environment. |

## Rules for this skill

- Follow the steps in order and keep the code as written; change only identifiers the human gives you and the places marked as yours.
- Do not invent configuration fields, event names or API methods. What exists is what this skill shows plus what the installed package declares in its type definitions; check those before adding anything.
- Samples show the environment (such as `'sandbox'`, `'test'` or a staging base URL) as a literal so each stays self-contained. In the project, read it from the runtime configuration the human's build uses (for Vite, `VITE_*` variables in a gitignored `.env.local` with a committed `.env.example`), with a value per environment.
- This integration has no `rampId`, `partnerKey`, widget URL or embed allowlist. Do not ask for them or add them; they belong to the Widget skills.
- The Transient Auth Token is minted only in the human's backend, never in the browser or the app: write that backend route as the backend step below shows, reading the API client ID, client secret and base URL from the server's configuration. Never send the partner access token, the client ID or the client secret to the client.
- Never pass the partner access token to the SDK, not in sandbox, not in a prototype and not as a fallback when minting fails; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.
- When a step needs a value you do not have, ask; do not substitute a placeholder that could ship.
- Read the linked pages when a step is unclear; they are the source this skill was generated from.

## Read first

The release on this site is `1.0.2`, a beta: published and installable, but not generally available, so the interface can still change and not all functionality is guaranteed. Tell the human it is in beta: fine for development builds, but they should check with their Coinme integration contact before taking it to production. Install `@coinme-security/compliance-sdk-react-native` as the guide shows and do not pin another version; before using a function from the guide, check that the installed package exports it (its type definitions), and if it does not, tell the human rather than writing a substitute.

The SDK is advisory. Coinme's backend enforces every rule on every onboarding and transaction. Never skip, weaken or replace a backend call because the SDK allowed something, and never present an SDK answer as a guarantee.

Pass every region as an ISO 3166-2 code ('US-NY'; for a US customer's two-letter state, `US-${state}`): a short code, a name or a padded string throws a CoinmeComplianceError of kind invalidRegion, so never pass one and never read that error as an unknown region. Fail closed: treat 'unknown' and 'notOperating' as unavailable; call getRegionStatus before the rule helpers, which exclude nothing for a region without rules; always pass the transaction's channels as `rails` to getDisclosuresToPresent; and treat a missing or failed attestation answer (a `status` other than `'ready'`, `missing` still `undefined`, a thrown `CoinmeComplianceError`) as still owed.

Create the platform once, outside any component, with createNativePlatform({ storage }) and a store the app already uses (AsyncStorage or MMKV); install that store in the app, since the SDK has none of its own. Hermes has no crypto.randomUUID: pass randomUUID (for example from expo-crypto), or the same idempotencyKey to every retry of one attest. Create the attestation store before mounting ComplianceProvider: the provider reads it, and its platform, once.

Attestations start after onboarding: pass customerId to ComplianceProvider only once the Onboarding SDK has returned it (CustomerOnboardingForm's onSuccess). getHeaders, which the human writes, always returns `{ Authorization: 'Bearer <token>' }` with a Transient Auth Token the human's backend minted with the `attestations` scope for that customer (the backend step below), never the partner access token. Attestations are not available in the beta at this time: Coinme does not issue tokens with the attestations scope, so createHttpAttestationStore cannot read or record. Build and test the flow with createInMemoryAttestationStore, and tell the human that recording attestations with Coinme is not available in the beta.

Render Coinme copy only through ComplianceText (or a renderer over parseComplianceHtml), never in a WebView. Do not hard-code Coinme hosts, routes or the copy itself: the SDK carries them.

## Backend: mint the Transient Auth Token

Attestations are not available in the beta at this time: Coinme does not issue tokens with the `attestations` scope, so build this route only if the human asks for it. Before the attestation store can read or record anything, the human's backend needs a route that returns `mintTransientAuthToken(customerId, 'attestations')` for the signed-in, onboarded customer: a Transient Auth Token with the `attestations` scope, bound to that customer. The attestation store's `getHeaders`, which the human writes, calls it before every request and returns `{ Authorization: 'Bearer <token>' }`. Hand the token to the app just in time; never store it there.

#### Get a partner access token

Call this from your backend only. It authenticates with HTTP Basic: your API client ID and client secret, joined by a colon and base64-encoded.

```bash
curl -X POST "https://caas-staging.coinme.com/services/authorize" \
  -H "Authorization: Basic $(printf '%s:%s' "$CLIENT_ID" "$CLIENT_SECRET" | base64)"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "1800"
}
```

The lifetime differs by environment: 30 minutes (`1800`) in sandbox and 60 minutes (`3600`) in production. Read `expires_in` (seconds, sent as a string) rather than hard-coding it, keep the token in your backend and reuse it until shortly before it expires.

> **Never send the partner access token to a browser or an app.**
>
> It authorizes every CaaS endpoint on your behalf. Only the Transient Auth Token from the next step goes to the client.

#### Mint the Transient Auth Token

Also from your backend only, authenticated with the partner access token from step 1.

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

| Parameter | In | Required | Notes |
| --- | --- | --- | --- |
| `Authorization` | header | yes | `Bearer <partner access token>`. |
| `customerId` | query | yes | For card capture, the Coinme customer the card will belong to. For onboarding, your identifier for the customer's sign-up session. For phone verification, the Coinme `customerId` onboarding returned, read from your backend's own record, never from the client. For attestations, the Coinme `customerId` of the onboarded customer. The token is bound to this value. |
| `scope` | query | no | `payment-methods` (the default) for the Vault SDK's payment-method submit, `onboarding` for the Onboarding SDK's onboarding submit and phone verification calls (sandbox only for now: Coinme's production environment does not issue tokens with this scope yet), or `attestations` for the Compliance SDK's attestation store, which is not available in the beta at this time. |

For onboarding, pass `scope=onboarding` and the sign-up session's identifier:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${SIGNUP_SESSION_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For phone verification, pass `scope=onboarding` and the `customerId` onboarding returned. Mint a fresh one for each verification call (sending the code, checking it), since a customer waiting for the text can easily pass the 10 minutes:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=onboarding" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

For the Compliance SDK's attestations, pass `scope=attestations` and the onboarded customer's `customerId`. Attestations are not available in the Compliance SDK beta at this time, and Coinme does not issue tokens with this scope:

```bash
curl -X POST "https://caas-staging.coinme.com/services/browserAuth?customerId=${CUSTOMER_ID}&scope=attestations" \
  -H "Authorization: Bearer ${PARTNER_ACCESS_TOKEN}"
```

```json
{
  "access_token": "eyJ…",
  "token_type": "Bearer",
  "expires_in": "600"
}
```

Mint a fresh token each time the customer reaches the add-card, onboarding or consent screen. Tokens last 10 minutes and are cheap to mint; never cache one or reuse it across sessions or customers.

> **Check the body, not just the status.**
>
> A mint that reaches the service but fails validation returns HTTP `200` with an error envelope in the body (for example `{"status":400}`) and no `access_token`. Treat any response without an `access_token` as a failure.

#### In your backend

The two calls as a Node.js module. The route that hands the token to your page or app calls `mintTransientAuthToken`: for card capture, for a signed-in customer only; for onboarding, for the customer's sign-up session, because the customer is not signed in yet; for phone verification, for the `customerId` your backend saved against that customer's record when onboarding succeeded, read from your own record and never from the request; for attestations, for the signed-in customer only.

```typescript
const BASE_URL = process.env.COINME_BASE_URL!; // https://caas-staging.coinme.com in sandbox

let partnerToken: { value: string; expiresAt: number } | undefined;

const getPartnerAccessToken = async (): Promise<string> => {
  if (partnerToken && partnerToken.expiresAt > Date.now() + 60_000) {
    return partnerToken.value;
  }
  const credentials = Buffer.from(
    `${process.env.COINME_CLIENT_ID}:${process.env.COINME_CLIENT_SECRET}`
  ).toString('base64');
  const response = await fetch(`${BASE_URL}/services/authorize`, {
    method: 'POST',
    headers: { Authorization: `Basic ${credentials}` },
  });
  const body = await response.json();
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme authorize failed (${response.status})`);
  }
  partnerToken = {
    value: body.access_token,
    expiresAt: Date.now() + Number(body.expires_in) * 1000,
  };
  return partnerToken.value;
};

export const mintTransientAuthToken = async (
  customerId: string, // or, for onboarding, the sign-up session's identifier
  scope: 'payment-methods' | 'onboarding' | 'attestations' = 'payment-methods'
): Promise<{ token: string; expiresIn: number }> => {
  const url = new URL(`${BASE_URL}/services/browserAuth`);
  url.searchParams.set('customerId', customerId);
  url.searchParams.set('scope', scope);
  const response = await fetch(url, {
    method: 'POST',
    headers: { Authorization: `Bearer ${await getPartnerAccessToken()}` },
  });
  const body = await response.json();
  // A failed mint can arrive as HTTP 200 with an error envelope and no token.
  if (!response.ok || !body.access_token) {
    throw new Error(`Coinme browserAuth failed (${body.status ?? response.status})`);
  }
  return { token: body.access_token, expiresIn: Number(body.expires_in) };
};
```

The token lasts 10 minutes. When a submit fails because it expired, fetch a fresh one from the backend and retry once; [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) has the error tables.

## Procedure

Follow the guide below in order. It is the integration guide for this platform as published, so the section names are the guide's own.

# Compliance SDK for React Native

The Coinme Compliance SDK for React Native gives your iOS or Android app built with React Native the compliance rules Coinme applies in each jurisdiction, so you can apply them in your own screens instead of re-implementing them. It is one package, `@coinme-security/compliance-sdk-react-native`, with the same rules, provider and hooks as the [JavaScript & React SDK](https://platformdocs.coinme.com/docs/compliance-sdk-react.md), and a native component for the compliance copy.

> **Beta.**
>
> Version 1.0.2 is published and installable, but the Compliance SDK for React Native is not generally available yet: the interface can still change and not all functionality is guaranteed. You can use it in development builds but check with your Coinme integration contact before taking it to production.

## Why use it

Coinme's rules differ by region: which states it operates in, where new customers can onboard, which payment rails and assets a region excludes, which consents and disclosures a customer must see and which receipt applies. This SDK loads those rules from Coinme, keeps them current while your app runs, and answers the questions your screens ask, so a change Coinme makes reaches your app without a release of yours.

You get:

- **Jurisdictions.** The regions Coinme lists, and whether it operates and onboards in each, so you don't hard-code a state list.
- **Rule helpers.** Whether a payment rail, an operation or an asset is available in a region, which consents a customer still owes, which disclosures to present before a transaction, and which custom receipt applies.
- **Content.** The text of each consent, disclosure and receipt, localized, with an English fallback, and a component that renders it natively, with no WebView.
- **Attestations.** A record of what a customer accepted, with the exact text and policy version they saw, and the hooks that tell you what is still owed.

The rules come from the same compliance core as the JavaScript & React SDK, so your React Native and web apps always reach the same answers. The SDK is advisory. It helps your app match Coinme's rules; Coinme's backend still enforces every one of them, on every onboarding and every transaction. Never treat an answer from the SDK as permission.

## Install

The package is published to Coinme's private npm registry. Configure the `@coinme-security` scope with the registry token Coinme provides, then install.

`.npmrc` (npm / Yarn Classic):

```properties
@coinme-security:registry=https://npm.coinme.com/coinme-security-wrapper/
//npm.coinme.com/coinme-security-wrapper/:_authToken=${COINME_REGISTRY_TOKEN}
//npm.coinme.com/coinme-security-wrapper/:always-auth=true
```

`.yarnrc.yml` (Yarn Berry v2+):

```yaml
nodeLinker: node-modules

npmScopes:
  coinme-security:
    npmRegistryServer: 'https://npm.coinme.com/coinme-security-wrapper/'
    npmAuthToken: '${COINME_REGISTRY_TOKEN}'
    npmAlwaysAuth: true
```

Then export the token and install:

```bash
export COINME_REGISTRY_TOKEN=<your-token>
npm install @coinme-security/compliance-sdk-react-native
# or: yarn add @coinme-security/compliance-sdk-react-native
# or, in an Expo app: npx expo install @coinme-security/compliance-sdk-react-native
```

`COINME_REGISTRY_TOKEN` is the registry access token, the same one that installs the other Coinme SDKs. Request it from your Coinme integration contact.

`react` and `react-native` are peer dependencies. The SDK has no storage dependency of its own: to keep the last configuration between launches, install the store you choose, such as `@react-native-async-storage/async-storage` or an MMKV instance (see [The platform](https://platformdocs.coinme.com/docs/compliance-sdk-react-native.md#the-platform)).

### Expo and bare React Native

The package is JavaScript, with no native module of its own. There's nothing to link: no config plugin, no prebuild, no `pod install` or Gradle changes, and nothing to configure for either React Native architecture.

- **Expo:** it runs in Expo Go. You need a development build only if your app adds other native modules.
- **Bare React Native:** adding it changes only JavaScript. Restart Metro with a clean cache and reload the app.

After installing, restart Metro with a clean cache (`npx expo start --clear` or `npx react-native start --reset-cache`).

## Compatibility

| Requirement | Supported |
| --- | --- |
| React Native | 0.79 or later (`react-native` peer), tested with 0.86 and 0.87 |
| React | 18 or later, as bundled with your React Native release (`react` peer) |
| Expo | SDK 53 or later (the first SDK on React Native 0.79), including Expo Go; tested with SDK 57 |
| JavaScript engine | Hermes, React Native's default (tested) |
| Platforms | iOS and Android |
| React Native architecture | Old and New Architecture; there's no native code to configure |
| TypeScript | Full typings ship with the package |

The SDK loads its compliance core through `package.json` `exports`, which Metro reads by default from React Native 0.79. On an older Metro, see [Troubleshooting](https://platformdocs.coinme.com/docs/compliance-sdk-react-native.md#troubleshooting).

## Before you start

1. **Pick the environment.** `'stage'` is for testing your integration and `'prod'` for real customers. (`'dev'` is Coinme's own development environment.) Read it from your app's configuration.
2. **Know the customer's region as an ISO 3166-2 code.** Every function, hook and option that takes a region takes an ISO 3166-2 code such as `'US-MN'`, in any letter case. A short code (`'MN'`), a state's name or anything else throws a `CoinmeComplianceError` of kind `invalidRegion` (see [Region codes](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#region-codes)). For a US customer whose address gives a two-letter state, pass ``US-${customer.state}``.
3. **Choose where the configuration is kept between launches.** Pass a store to `createNativePlatform` so the next launch starts from the last configuration Coinme served, even offline.
4. **Plan the backend route for attestations.** Recording what a customer accepted needs a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints for that customer with `scope=attestations` (see [Attestations](https://platformdocs.coinme.com/docs/compliance-sdk-react-native.md#attestations)). Never your partner access token. Attestations are not available in the beta at this time. Reading the rules and the copy needs no credentials.

## Quickstart

Wrap the part of your app that needs compliance data in `ComplianceProvider` once, then read it with the hooks. This picker offers only the states where new customers can onboard:

```tsx
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
  ComplianceProvider,
  createNativePlatform,
  useSupportedRegions,
} from '@coinme-security/compliance-sdk-react-native';
import { Pressable, Text, View } from 'react-native';

const platform = createNativePlatform({ storage: AsyncStorage });

export const App = () => (
  <ComplianceProvider environment="stage" platform={platform}>
    <StatePicker onPick={(region) => console.log(region)} />
  </ComplianceProvider>
);

const StatePicker = ({ onPick }: { onPick: (region: string) => void }) => {
  const regions = useSupportedRegions();
  return (
    <View>
      {regions
        .filter((region) => region.onboardable)
        .map((region) => (
          <Pressable key={region.code} onPress={() => onPick(region.code)}>
            <Text>{region.name}</Text>
          </Pressable>
        ))}
    </View>
  );
};
```

The values are ISO codes (`'US-MN'`), the form every helper takes. The list is never empty: before Coinme's current configuration loads, it comes from the last launch's copy or from the copy built into the SDK release.

## The platform

`createNativePlatform()` connects the SDK to React Native: the app's `fetch` and timers, and a refresh when the app returns to the foreground. Create it once, outside any component, and pass it to `ComplianceProvider` (or to `createComplianceClient` and `createHttpAttestationStore`).

```typescript
import AsyncStorage from '@react-native-async-storage/async-storage';
import { randomUUID } from 'expo-crypto';
import { createNativePlatform } from '@coinme-security/compliance-sdk-react-native';

export const platform = createNativePlatform({ storage: AsyncStorage, randomUUID });
```

| Option | What it does |
| --- | --- |
| `storage` | Where the last configuration loaded from Coinme is kept, so the next launch starts from it even without a network. Any store with `getItem` and `setItem` works: AsyncStorage, an MMKV instance, or your own. Store errors are ignored. |
| `randomUUID` | A UUID source used to key attestation requests, for example `randomUUID` from `expo-crypto`. Hermes has no `crypto.randomUUID`; without this option the SDK uses its own timestamp-and-random key. |

Both are optional. Without `storage`, each launch starts from the configuration built into the SDK release until Coinme answers.

## The configuration client

In React Native, `ComplianceProvider` creates and owns the client for you. For code outside React, create one client per app and keep it for the app's lifetime:

```typescript
import { createComplianceClient } from '@coinme-security/compliance-sdk-react-native';

const client = createComplianceClient({ environment: 'stage', platform });

const { regions, jurisdictions, source, stale } = client.getConfig(); // never empty, never waits
const supportedRegions = client.getSupportedRegions();
const config = client.getComplianceConfig();
```

The client, the state it returns and the convenience getters are the same as on the web; see [The configuration client](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#the-configuration-client) for every field. How it stays fresh on React Native:

- **Right away**, the client serves the newest configuration it already has: the one `storage` kept from an earlier launch, or the one built into the SDK release. It never serves an empty configuration.
- **When created** (every app launch), it fetches the current configuration from Coinme.
- **While running**, it fetches again every five minutes, and when the app returns to the foreground if the configuration is five minutes old.
- **If a fetch fails**, it keeps the configuration it has, marks it `stale`, and retries with exponential backoff (about 2 seconds, growing to 5 minutes).

Call `client.dispose()` to stop refreshing and remove its app-state listener, for example in tests.

## Provider and hooks

`ComplianceProvider` owns the client: it loads the configuration when it mounts, keeps it fresh, and stops when it unmounts. Its props, hooks and return values are the same as the JavaScript & React SDK's, so code moves between the two.

| Prop | Meaning |
| --- | --- |
| `environment` | `'stage'` or `'prod'` (or `'dev'`). Required. |
| `platform` | Optional; defaults to `createNativePlatform()`, which keeps nothing between launches. Read once, on mount. |
| `language` | Optional; the language of the compliance copy the content hooks return. Defaults to `'en'`. |
| `attestationStore` | Optional; where attestations are read and recorded (see [Attestations](https://platformdocs.coinme.com/docs/compliance-sdk-react-native.md#attestations)). Read once, on mount. |
| `customerId` | Optional; the onboarded customer the attestations belong to. Leave it out until onboarding completes. |

```tsx
import {
  evaluateTransaction,
  RegionStatus,
  useComplianceConfig,
  useRegionStatus,
} from '@coinme-security/compliance-sdk-react-native';
import { Button } from 'react-native';

const BuyButton = ({ region, onBuy }: { region: string; onBuy: () => void }) => {
  const status = useRegionStatus(region); // region is an ISO code such as 'US-MN'
  const config = useComplianceConfig();
  if (status !== RegionStatus.Onboardable && status !== RegionStatus.Operating) return null;
  const { allowed } = evaluateTransaction(config, region, { operation: 'buy', asset: 'USDC' });
  return allowed ? <Button title="Buy USDC" onPress={onBuy} /> : null;
};
```

| Hook | Returns |
| --- | --- |
| `useComplianceConfig()` | The complete configuration: policy version, rules per region and supported regions |
| `useSupportedRegions()` | Every region Coinme lists, with `operating` and `onboardable` |
| `useRegionStatus(region)` | One region's status: `'onboardable'`, `'operating'`, `'notOperating'` or `'unknown'` |

- Components re-render only when what their hook returns changes, not on every refresh.
- `platform` and `attestationStore` are read once, when the provider mounts: create them first, because passing a different one later has no effect. `environment`, `customerId` and `language` can change at any time, and the hooks follow them.
- Using a hook outside `ComplianceProvider` throws a `CoinmeComplianceError` with `kind: 'configuration'`.

## Regions and rules

The package includes the whole compliance core the JavaScript & React SDK uses, and it behaves exactly the same: import every function from `@coinme-security/compliance-sdk-react-native`. The JavaScript & React guide describes each one:

- [Regions](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#regions): `getRegionStatus`, `getOnboardableRegions`, `lookupRegion` and the rest, and [what each region gives you](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#what-each-region-gives-you).
- [Transaction rules](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#transaction-rules): `evaluateTransaction`, `isRailExcluded`, `isAssetExcluded`, `getAllowedOperations` and the rest.
- [Consents and transactional disclosures](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#consents-and-transactional-disclosures): `getMissingConsents`, `getDisclosuresToPresent` and when a disclosure is shown.
- [Custom receipts and special requirements](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#custom-receipts-and-special-requirements): `getCustomReceipts`, `getRequirements`, `hasRequirement`.

Wherever those examples pass `createWebPlatform()`, pass your `createNativePlatform()` platform instead.

## Localized copy

The text of consents, transactional disclosures and custom receipts is Coinme's, maintained by Coinme and published in several languages with an English fallback. Set the provider's `language` and read the copy with the content hooks:

```tsx
import { ComplianceProvider, useConsentContent } from '@coinme-security/compliance-sdk-react-native';

export const SpanishApp = () => (
  <ComplianceProvider environment="prod" platform={platform} language="es">
    <ConsentScreen region="US-MN" type="minnesota_consent" />
  </ComplianceProvider>
);
```

| Hook | Returns |
| --- | --- |
| `useComplianceContent()` | `{ status, language, catalog }`: `status` is `'loading'` until the requested language has loaded, then `'ready'`; until then `catalog` serves the built-in English copy, so it is never empty |
| `useConsentContent(region, type)` | A session consent's `body`, `intro`, `labels`, `outro` and `continueLabel`, or `undefined` |
| `useDisclosureContent(region, type, variant)` | A transactional disclosure variant (`cash_buy`, `card_buy`, `card_sell`, `send`), or `undefined` |
| `useReceiptContent(region, rail)` | A custom receipt addendum (`html`), or `undefined` |

- **Never empty while loading:** until the language loads, the hooks serve the English copy built into the SDK. Copy that isn't published in a language falls back to English, and `language` on each item says which one you got.
- **Fetched only when used:** the provider fetches copy only once a content hook is mounted, and again only when `language` changes.
- **HTML strings:** the copy fields are unsanitized HTML. Render them with `ComplianceText`, never yourself.

Show a consent as its `body`, then `intro`, one required switch or checkbox per entry in `labels`, then `outro`, and a button labelled `continueLabel`. Show every part: the attestation records a hash of all of it.

### Render it natively

`ComplianceText` renders one piece of compliance copy with native components (no WebView): text, bold, italic, underline, lists and links. The HTML is parsed, never evaluated.

```tsx
import { ComplianceText, useConsentContent } from '@coinme-security/compliance-sdk-react-native';

const ConsentBody = () => {
  const consent = useConsentContent('US-MN', 'minnesota_consent');
  return consent?.body.map((html, index) => (
    <ComplianceText
      key={index}
      html={html}
      styles={{
        text: { fontSize: 15, lineHeight: 21, color: '#0f172a' },
        'body-title': { fontWeight: '700' },
        'disclosure-text-centered': { textAlign: 'center', fontWeight: '600' },
        link: { color: '#2563eb' },
      }}
    />
  ));
};
```

- **Styling is yours.** `styles` styles the copy by its `data-role` slots (`body-title`, `body-list`, `section-title`, `disclosure-title`, `disclosure-text`, `disclosure-text-centered`) or by part (`text`, `block`, `p`, `strong`, `em`, `u`, `link`, `list`, `listItem`, `bullet`); `imageStyle` styles images. As in CSS, text properties on a block (font, colour, alignment) apply to the text inside it. Every other prop goes to the container `View`. The SDK adds only bold, italic, underline, bullets and numbering.
- **Links are safe.** A link is pressable only when it points to `coinme.com` over `https` (a plain `http:` link is upgraded to `https:`) or to a coinme.com email address; anything else shows as plain text. Links open with `Linking.openURL`, or pass `onLinkPress` to open them your way, for example in an in-app browser.
- **Nothing active survives.** Scripts, styles and embedded content are dropped; images load only over `https` from `coinme.com`.
- **Your own rendering.** `renderNode` replaces how any node is drawn, and `parseComplianceHtml(html)` gives you the parsed tree to render entirely yourself.

## Attestations

When a customer accepts a consent or a disclosure, record it as an attestation. An attestation records what was required (type, variant, region, `policyVersion`) and exactly what the customer saw (`locale`, `contentHash`). Coinme stamps the time and keeps every attestation.

> **Attestations are not available in the beta at this time.**
>
> Coinme does not issue Transient Auth Tokens with `scope=attestations`, so `createHttpAttestationStore` cannot read or record attestations. To build and test the flow, use `createInMemoryAttestationStore`, which keeps nothing.

Attestations belong to an onboarded customer, so they start **after onboarding**, once you have the `customerId` (from the [Onboarding SDK for React Native](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md)). The store is authorized by `getHeaders`, a function you write: it returns `{ Authorization: 'Bearer <token>' }` with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints for that `customerId` with `scope=attestations`. The SDK calls `getHeaders` before every request and never stores or logs what it returns. Each token lasts 10 minutes, so fetch a fresh one inside `getHeaders`.

> **Never give the Compliance SDK your partner access token.**
>
> `getHeaders` must always return a Transient Auth Token your backend mints from `POST /services/browserAuth` with `scope=attestations`, never your partner access token (from `POST /services/authorize`).

```tsx
import {
  ComplianceProvider,
  createHttpAttestationStore,
} from '@coinme-security/compliance-sdk-react-native';

const attestationStore = createHttpAttestationStore({
  environment: 'prod',
  platform,
  getHeaders: async () => ({ Authorization: `Bearer ${await fetchComplianceToken()}` }),
});

export const Root = ({ customerId }: { customerId?: string }) => (
  <ComplianceProvider
    environment="prod"
    platform={platform}
    attestationStore={attestationStore}
    customerId={customerId}
  >
    <App />
  </ComplianceProvider>
);
```

| Hook | Returns |
| --- | --- |
| `useAttestations()` | `{ status, attestations, error }`: the customer's latest attestation per consent and disclosure |
| `useMissingConsents(region)` | `{ status, missing, error }`: the session consents still owed; `missing` is `undefined` until `'ready'` |
| `useAttest()` | `attest(request, options?)`: records an attestation and updates the other two hooks without reloading |

- **Status:** `'needsCustomer'` until the provider has a `customerId`, then `'loading'`, then `'ready'` or `'error'`. Only `'ready'` answers what is owed: never read an unknown answer as "nothing owed".
- **Errors:** without an `attestationStore` the hooks throw (and `attest` rejects with) `missingAttestationStore`; `attest` before a `customerId` rejects with `missingCustomerId`. A rejected `attest` was not recorded; when retrying, pass the same `options.idempotencyKey`.
- **Stores:** `createHttpAttestationStore` records with Coinme. `createInMemoryAttestationStore` forgets everything on restart: use it in tests and demos only.

### After onboarding with the Onboarding SDK

With the [Onboarding SDK for React Native](https://platformdocs.coinme.com/docs/onboarding-sdk-react-native.md), pass the `customerId` from `CustomerOnboardingForm`'s `onSuccess` to the provider:

```tsx
import { ComplianceProvider } from '@coinme-security/compliance-sdk-react-native';
import { CustomerOnboardingForm } from '@coinme-security/onboarding-sdk-react-native';
import { useState } from 'react';

export const OnboardThenConsent = () => {
  const [customerId, setCustomerId] = useState<string>();

  return (
    <ComplianceProvider
      environment="prod"
      platform={platform}
      attestationStore={attestationStore}
      customerId={customerId}
    >
      {customerId ? (
        <ConsentGate region="US-MN" />
      ) : (
        <CustomerOnboardingForm
          environment="live"
          getHeaders={getOnboardingHeaders}
          onSuccess={(result) => setCustomerId(result.customerId)}
        />
      )}
    </ComplianceProvider>
  );
};
```

## Putting it together: consents and disclosures

This walkthrough gates a screen on the customer's consents, then presents a cash buy's disclosures. `ConsentScreen`, `BuyForm`, `FinishOnboarding`, `TryAgain` and `showRetry` stand for your own code.

### 1. Gate on the missing consents

```tsx
import { useMissingConsents } from '@coinme-security/compliance-sdk-react-native';
import { ActivityIndicator } from 'react-native';

const ConsentGate = ({ region }: { region: string }) => {
  const consents = useMissingConsents(region);
  if (consents.status === 'needsCustomer') return <FinishOnboarding />;
  if (consents.status === 'error') return <TryAgain error={consents.error} />;
  if (consents.status === 'loading' || consents.missing === undefined) return <ActivityIndicator />;
  if (consents.missing.length > 0) return <ConsentScreen region={region} type={consents.missing[0]} />;
  return <CashBuyDisclosures region={region} />;
};
```

`ConsentScreen` shows the consent's copy with `ComplianceText`, one switch per entry in `labels`, and a button that calls `attest({ region, type, content: consent })`. Once the attestation is recorded, `useMissingConsents` updates on its own and the gate moves on.

### 2. Present the transaction's disclosures

```tsx
import {
  attestedDisclosures,
  getDisclosuresToPresent,
  RailType,
  useAttest,
  useAttestations,
  useComplianceConfig,
  useDisclosureContent,
} from '@coinme-security/compliance-sdk-react-native';
import { ActivityIndicator, Button } from 'react-native';

const CashBuyDisclosures = ({ region }: { region: string }) => {
  const config = useComplianceConfig();
  const { status, attestations } = useAttestations();
  if (status !== 'ready') return <ActivityIndicator />;

  const toPresent = getDisclosuresToPresent(config, region, {
    rails: [RailType.Greendot],
    attested: attestedDisclosures(attestations, { region }),
  });
  if (toPresent.length === 0) return <BuyForm />;
  return <Disclosure region={region} type={toPresent[0].type} />;
};

const Disclosure = ({ region, type }: { region: string; type: string }) => {
  const content = useDisclosureContent(region, type, 'cash_buy');
  const attest = useAttest();
  if (!content) return null;
  return (
    <Button
      title={content.continueLabel}
      onPress={() => attest({ region, type, variant: 'cash_buy', content }).catch(showRetry)}
    />
  );
};
```

- **Pass the transaction's rails.** An empty `rails` returns every disclosure the region has.
- **`alwaysRequired` disclosures** come back on every transaction, even after the customer has attested them, so show them each time and attest each time.
- **You pick the copy variant** (`cash_buy`, `card_buy`, `card_sell`, `send`) that describes the transaction: the rule says which disclosure, the variant which wording.

Then submit the transaction through your backend as usual. Coinme's backend checks the same rules again and is the authority: if it refuses, show its answer, not the SDK's.

## Error handling

Every failure is a `CoinmeComplianceError` with a `kind`, exactly as in the [JavaScript & React SDK](https://platformdocs.coinme.com/docs/compliance-sdk-react.md#error-handling): `invalidRegion` and `configuration` are thrown (by hooks, while rendering); `missingAttestationStore` is thrown by the attestation hooks and rejected by `attest()`; `missingCustomerId` is rejected by store calls and `attest()`; `network`, `unauthorized`, `server` and `invalidResponse` are reported on `getConfig().lastError` for the configuration and rejected by the attestation store. A failed configuration fetch never throws to your code, and messages and details never contain customer data. None of these errors means "not attested" or "allowed": treat a failure as unknown, never as a yes.

## Verify your integration (stage)

1. Mount `ComplianceProvider` with `environment="stage"` and check that `useComplianceConfig().policyVersion` is set.
2. Turn on airplane mode and relaunch the app: with `storage` set, it starts from the configuration it kept, not the one built into the SDK.
3. Check that the state picker lists only onboardable regions with ISO codes as values, that `'US-ZZ'` comes back `'unknown'` and that a short code such as `'MN'` throws `invalidRegion`.
4. For a region with a session consent, check that the consent screen shows the copy in the provider's `language` with `ComplianceText`, and that every switch must be on before the button enables.
5. Attestations are not available in the beta at this time, so check the attestation flow with `createInMemoryAttestationStore`: onboard a test customer, accept the consent, and check that `useMissingConsents` moves to an empty list without a reload.

## Security

- **Never put partner credentials in the app.** Reading the rules and the copy needs no credentials. The attestation store's `getHeaders` returns a Transient Auth Token your backend minted with `scope=attestations`; your API client credentials and your partner access token stay on your server.
- **Render copy only through `ComplianceText`** (or your own renderer over `parseComplianceHtml`); never put the raw HTML in a WebView.
- **Fail closed.** An unknown region is unavailable, a region that is not an ISO code throws rather than being guessed at, an unknown attestation state is "still owed", and a failed attestation call is not an attestation.
- **The SDK is advisory.** Coinme's backend enforces every rule; never skip a backend check because the SDK allowed something.

## Commonly asked questions

### Is it the same SDK as the JavaScript & React one?

The rules are: the package includes the same compliance core, so both reach the same answers, and the provider and hooks have the same names, props and return values. What differs is the platform (`createNativePlatform` instead of `createWebPlatform`) and the copy renderer (`ComplianceText` instead of `<ComplianceHtml>`).

### Does it need a native module or a development build?

No. It is JavaScript only and runs in Expo Go. Storage is whatever store you pass to `createNativePlatform`.

### Does the SDK enforce Coinme's rules?

No. It helps your app match them, so customers are not offered what Coinme's backend will refuse and are shown what they must see. Coinme's backend checks every onboarding and transaction against the same rules and is the authority.

### Can I record an attestation before the customer is onboarded?

No. Attestations belong to an onboarded customer and need its `customerId`. Before onboarding, the attestation hooks report `'needsCustomer'`.

## Troubleshooting

**`Unable to resolve "@coinme-security/compliance-sdk-react/core"`.** Your Metro doesn't read `package.json` `exports`. Upgrade to React Native 0.79 or later, or set `resolver.unstable_enablePackageExports = true` in `metro.config.js`.

**The configuration is always `'snapshot'` after a relaunch.** Pass `storage` to `createNativePlatform`.

**A retried attestation is recorded twice.** Hermes has no `crypto.randomUUID`. Pass `randomUUID` to `createNativePlatform` (for example from `expo-crypto`), or the same `options.idempotencyKey` to every retry of one `attest`.

**A hook throws `invalidRegion`.** The region is not an ISO 3166-2 code. Pass ``US-${state}`` for a US state.

**A hook throws a `configuration` error.** It is rendered outside `ComplianceProvider`; move the provider above it.

**The attestation hooks stay on `'needsCustomer'`.** The provider has no `customerId`. Pass it once onboarding returns it.

## Verify

Run the app on an iOS simulator and an Android emulator against `environment: 'stage'`. Confirm the provider loads a configuration with a policyVersion, a relaunch in airplane mode starts from the stored configuration, the picker lists only onboardable regions with ISO codes as values, an ISO code Coinme does not list is treated as unavailable, a short code such as 'MN' throws invalidRegion, consent copy renders through ComplianceText in the chosen language with every switch required, the attestation hooks report 'needsCustomer' before onboarding and record and read attestations after it (or fail with a typed error, which must leave the consent owed), a transaction against an excluded rail or asset is refused before the backend call, and no token or partner credential is in the app bundle or a committed file.

### Reading the result

**Done when:** The SDK returns a result for the test customer, with no error in the response body.

**Stop and ask the human when** the result asks for a decision about the customer, or the call is refused with a code that is not about the request.

Judge every Coinme call by its body, not its HTTP status: a refused request usually comes back as HTTP 200 with the error in the body. [Reading results](https://platformdocs.coinme.com/agents/results.md) has the rule, what each common error code asks you to do, and what to send your Coinme integration contact when something fails.

## Reference
- [Coinme Compliance SDK](https://platformdocs.coinme.com/docs/coinme-compliance-sdk.md)
- [Compliance SDK for React Native](https://platformdocs.coinme.com/docs/compliance-sdk-react-native.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
