---
title: "Compliance SDK for JavaScript & React"
url: "https://platformdocs.coinme.com/#/docs/compliance-sdk-react"
markdown: "https://platformdocs.coinme.com/docs/compliance-sdk-react.md"
summary: "The Coinme Compliance SDK gives your web app the compliance rules Coinme applies in each jurisdiction, so you can apply them in your own interface instead of re-implementing them. Use it from a React app through its provider and hooks, or from any JavaScript app through the framework-agnostic core the React layer is built on. Either way it is the one package, `@coinme-security/compliance-sdk-react`."
surface: "caas"
platform: "web"
package: "@coinme-security/compliance-sdk-react"
version: "1.1.3"
status: "beta"
peerDependencies: {"react":">=18","react-dom":">=18"}
updated: "2026-11-04"
---

# Compliance SDK for JavaScript & React

The Coinme Compliance SDK gives your web app the compliance rules Coinme applies in each jurisdiction, so you can apply them in your own interface instead of re-implementing them. Use it from a React app through its provider and hooks, or from any JavaScript app through the framework-agnostic core the React layer is built on. Either way it is the one package, `@coinme-security/compliance-sdk-react`.

> **Beta.**
>
> Version 1.1.3 is published and installable, but the Compliance SDK 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 UI asks, so a change Coinme makes reaches your screens 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 safely.
- **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 SDK is advisory. It helps your UI 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.

## Two entry points

| Import | Use it for |
| --- | --- |
| `@coinme-security/compliance-sdk-react/core` | Any JavaScript app. No React or browser dependency. |
| `@coinme-security/compliance-sdk-react` | React apps: everything in `/core`, plus a provider, hooks and components. |

`react` and `react-dom` 18 or later are optional peer dependencies. You only need them for the React entry point.

## 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
# or: yarn add @coinme-security/compliance-sdk-react
```

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

## Compatibility

| Requirement | Supported |
| --- | --- |
| React | 18 or later (optional `react` and `react-dom` peers, for the React entry point only) |
| Other JavaScript | Any runtime with `fetch` and timers, through `/core` and a platform object |
| Server-side rendering | Safe: on the server and on the first browser render the hooks return the configuration and copy built into the SDK release, and `<ComplianceHtml>` renders empty until the page hydrates, so markup hydrates cleanly |
| TypeScript | Full typings ship with the package |

If your site sets a Content-Security-Policy, its `connect-src` must allow the Coinme hosts the SDK loads its configuration, copy and attestations from. The SDK carries those hosts per environment; ask your Coinme integration contact for the list to allow.

## 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](#region-codes)). For a US customer whose address gives a two-letter state, pass ``US-${customer.state}``; the examples on this page write `customer.region` for that code.
3. **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](#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 {
  ComplianceProvider,
  useSupportedRegions,
} from '@coinme-security/compliance-sdk-react';

export const App = () => (
  <ComplianceProvider environment="stage">
    <StatePicker />
  </ComplianceProvider>
);

const StatePicker = () => {
  const regions = useSupportedRegions();
  return (
    <select>
      {regions
        .filter((region) => region.onboardable)
        .map((region) => (
          <option key={region.code} value={region.code}>
            {region.name}
          </option>
        ))}
    </select>
  );
};
```

The option 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 copy built into the SDK release.

## The configuration client

The SDK loads Coinme's compliance configuration from Coinme and keeps it fresh for as long as your app runs. You don't supply or edit this configuration: it is Coinme's, and the SDK always uses what Coinme serves. In React, `ComplianceProvider` creates and owns the client for you; this section is for apps that use the core directly, and explains what the hooks return.

### Create a client

Create one client per app and keep it for the app's lifetime.

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

const client = createComplianceClient({
  environment: 'stage', // 'prod' for real customers
  platform: createWebPlatform(),
});
```

`createWebPlatform()` connects the client to the browser: `fetch`, timers, `localStorage` (for the last configuration it loaded) and tab-visible and back-online events. It is safe to call during server-side rendering.

Outside the browser, import from `/core` and pass a platform object with `fetch`, `setTimeout` and `clearTimeout`, plus optional `storage`, `subscribeToResume` and `randomUUID` (used to key attestation requests). See the `CompliancePlatform` type in the package.

### Read the configuration

```typescript
// Always returns a configuration, without waiting.
const { regions, jurisdictions, source, stale } = client.getConfig();

// Or wait (up to 5 seconds by default) for the first fetch from Coinme.
const state = await client.ready();

// Re-render when the configuration changes.
const unsubscribe = client.subscribe((next) => render(next));
```

For the two things most UIs need, use the convenience getters. Like `getConfig()`, they return immediately and are never empty:

```typescript
// Every region Coinme lists, for example for a state picker.
const regions = client.getSupportedRegions();

// The complete configuration: policy version, rules per region and supported regions.
const { policyVersion, regions: rules, supportedRegions } = client.getComplianceConfig();
```

Both return the same object until the configuration's content changes, so you can compare them by reference, for example as a memo dependency. A routine refresh that brings back the same configuration does not replace them.

Each state returned by `getConfig()` has:

| Field | Meaning |
| --- | --- |
| `regions` | One `RegionComplianceConfig` per region with rules. A region without an entry has no rules. |
| `jurisdictions` | Every region Coinme lists: `{ code, shortCode, name, operating, onboardable }`. |
| `source` | `'remote'` (fetched this session), `'cached'` (from an earlier session) or `'snapshot'` (built into the SDK release). |
| `fetchedAt` | When Coinme served this configuration (ISO 8601). |
| `policyVersion` | Identifies the policy this configuration expresses. Record it with anything a customer agrees to. |
| `stale` | `true` until a fetch succeeds this session, and again whenever the latest fetch fails. |
| `lastError` | A `CoinmeComplianceError` describing the latest failed fetch, if any. |

A region is `onboardable` when Coinme operates there and its configuration does not exclude onboarding.

Vocabulary values are available as constants: `ExclusionType` (also exported as `Rail`), `RailType`, `ConsentType`, `TransactionConsentType`, `SpecialRequirement` and `ComplianceReceiptLocationMode`. Coinme can add values before your SDK version knows them; those are passed through unchanged, so compare against the constants rather than assuming the list is complete.

The configuration the SDK returns is frozen and shared by every client and component on the page: modifying it, or a region, rule or list inside it, throws a `TypeError`, so copy a list before changing it (`[...regions].sort(...)`). Lists the helpers compute for you (`getMissingConsents`, `getOnboardableRegions` and the rest) are new arrays you own.

### How it stays fresh

- **Right away**, the client serves the newest configuration it already has: the one saved by an earlier session, or the one built into the SDK release. It never serves an empty configuration.
- **When created** (every page load), it fetches the current configuration from Coinme.
- **While running**, it fetches again every five minutes, when the tab becomes visible or the browser comes back online (if the configuration is five minutes old), and in the background when `getConfig()` reads a configuration that 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).

If Coinme serves a configuration this SDK version cannot read, for example one in a newer format, the client rejects it, keeps the configuration it has and reports the failure in `lastError`. A rejected configuration never replaces a good one.

Call `client.dispose()` to stop refreshing, for example in tests or when unmounting a micro-frontend.

### Building your own UI bindings

The React provider and hooks are built on two `/core` helpers, available from 1.1.0, that you can use to bind the configuration to another UI layer, such as Vue or your own store:

| Helper | What it gives you |
| --- | --- |
| `peekComplianceClient(client)` | `getComplianceConfig()` and `getSupportedRegions()` readers with no side effects. The values keep their identity until the configuration's content changes. |
| `getBundledComplianceConfig()` | The configuration built into this SDK release, for a first render that happens before your client exists. |

The client's own getters start a background refresh when the configuration is five minutes old, so don't call them while rendering. Read through the peek instead, for example in `useSyncExternalStore`'s `getSnapshot`, and use `client.subscribe` to know when to read again.

## React: provider and hooks

`ComplianceProvider` owns the client: it loads the configuration when it mounts, keeps it fresh, and stops when it unmounts.

| Prop | Meaning |
| --- | --- |
| `environment` | `'stage'` or `'prod'` (or `'dev'`). Required. |
| `platform` | Optional; defaults to `createWebPlatform()`. 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](#attestations)). Read once, on mount. |
| `customerId` | Optional; the onboarded customer the attestations belong to. Leave it out until onboarding completes. |

```tsx
import {
  ComplianceProvider,
  getAllowedOperations,
  useComplianceConfig,
  useRegionStatus,
} from '@coinme-security/compliance-sdk-react';

const PolicyNotice = () => {
  const { policyVersion } = useComplianceConfig();
  return <small>Compliance policy {policyVersion}</small>;
};

const BuyButton = ({ region }: { region: string }) => {
  const status = useRegionStatus(region); // region is an ISO code such as 'US-MN'
  const config = useComplianceConfig();
  if (status !== 'onboardable' && status !== 'operating') return null;
  return getAllowedOperations(config, region).includes('buy') ? <button>Buy</button> : null;
};
```

- `useSupportedRegions()` returns the same list as `client.getSupportedRegions()`, and `useComplianceConfig()` the same object as `client.getComplianceConfig()`.
- `useRegionStatus(region)` returns the region's status (see [Regions](#regions)) and re-renders only when that region's status changes.
- Components re-render only when the configuration's content changes, not on every refresh.
- On the server, and on the first render in the browser, the hooks return the configuration built into the SDK, so server-rendered markup hydrates cleanly. They switch to Coinme's current configuration once it loads.
- `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

Coinme describes each region at three levels: **listed** (in the supported regions at all), **operating** (Coinme operates there) and **onboardable** (operating, and new customers can onboard; some operating regions exclude onboarding). These functions answer questions at each level. They work on any supported-regions list, from `client.getSupportedRegions()` or `useSupportedRegions()`.

```typescript
import {
  getOnboardableRegions,
  getRegionRules,
  getRegionStatus,
  lookupRegion,
  RegionStatus,
} from '@coinme-security/compliance-sdk-react';

const regions = client.getSupportedRegions();

getRegionStatus(regions, 'US-NY'); // for example 'operating': no new customers; see getAllowedOperations
getRegionStatus(regions, 'US-ZZ'); // 'unknown': Coinme does not list it
getRegionStatus(regions, 'NY'); // throws CoinmeComplianceError 'invalidRegion': not an ISO code

const options = getOnboardableRegions(regions);
const consents = getRegionRules(client.getComplianceConfig(), 'US-MN')?.consents ?? [];

// Everything about one region, saying why:
const region = lookupRegion(client.getComplianceConfig(), 'US-NY');
// { code: 'US-NY', shortCode: 'NY', name: 'New York', listed: true, operating: true,
//   onboardable: false, rules: { … } }   (rules is null when the region has none)
```

`getRegionStatus` returns one of four values, from most to least available:

| Status | Constant | Meaning |
| --- | --- | --- |
| `'onboardable'` | `RegionStatus.Onboardable` | Coinme operates there and new customers can onboard. |
| `'operating'` | `RegionStatus.Operating` | Coinme operates there, but onboarding is excluded: new customers cannot onboard. |
| `'notOperating'` | `RegionStatus.NotOperating` | Coinme lists the region but does not operate there. |
| `'unknown'` | `RegionStatus.Unknown` | Coinme does not list the region. |

| Function | Answers |
| --- | --- |
| `getRegionStatus(regions, region)` | `'onboardable'`, `'operating'`, `'notOperating'` or `'unknown'` |
| `isRegionOperating(regions, region)` | Does Coinme operate there? |
| `isRegionOnboardable(regions, region)` | Can new customers onboard there? |
| `findRegion(regions, region)` | The region's entry, or `undefined` |
| `getUnsupportedRegions(regions)` | Regions Coinme lists but does not operate in |
| `getNonOnboardableRegions(regions)` | Regions where new customers cannot onboard |
| `getOnboardableRegions(regions)` | Regions where new customers can onboard |
| `getRegionRules(config, region)` | The region's rules (consents, disclosures, exclusions and more), or `undefined` |
| `lookupRegion(config, region)` | `{ code, shortCode, name, listed, operating, onboardable, rules }`, with `rules: null` when the region has none |

Every `region` is an ISO 3166-2 code such as `'US-NY'`, in any letter case. A short code (`'NY'`), a name or anything else that is not an ISO code throws a `CoinmeComplianceError` of kind `invalidRegion`; it is never treated as an unknown region. An ISO code Coinme does not list is unknown, and unknown fails closed: never operating, never onboardable.

`'operating'` only means new customers cannot onboard. It does not mean existing customers can transact: an operating region can also exclude every buy, sell, send, receive and redeem channel. Use `getAllowedOperations` (see [Transaction rules](#transaction-rules)) to see what they can still do.

### Region codes

Every function, hook and option that takes a region takes an ISO 3166-2 subdivision code: the two-letter country, a hyphen, then one to three letters or digits. Letter case does not matter. Nothing else is accepted.

| Input | Result |
| --- | --- |
| `'US-MN'`, `'us-mn'`, `'CA-ON'`, `'AU-NSW'` | Accepted |
| `'MN'` (a short code), `'Minnesota'`, `'US_MN'` | Throws `CoinmeComplianceError` `invalidRegion` |
| `' US-MN'` or `'US-MN '` (surrounding spaces) | Throws `invalidRegion`; inputs are not trimmed |
| `''`, `null`, a number | Throws `invalidRegion` |

- **Why not short codes:** they repeat across countries (`WA` is Washington and Western Australia), so a short code would make the SDK guess.
- **US customers:** CAAS and most address forms give a two-letter state. Pass ``US-${customer.state}``.
- **Where it applies:** every region helper (`findRegion`, `getRegionStatus`, `isRegionOperating`, `isRegionOnboardable`, `getRegionRules`, `lookupRegion`), every rule helper (`evaluateTransaction`, `isRailExcluded`, `getMissingConsents`, `getDisclosuresToPresent`, `getCustomReceipts` and the rest, including `kioskRegion` and `residenceRegion`), the content getters, the attestation helpers (`buildAttestation`, and the `region` filter of `acceptedConsents` and `attestedDisclosures`), the React hooks that take a region and `attest({ region })`.
- **The error is immediate.** Functions throw, and hooks throw while rendering, so an error boundary sees it. The error's `detail` names the field (`region`, `kioskRegion` or `residenceRegion`) and never contains the value you passed.
- **Attestations record the code in upper case** (`'US-MN'`), and the `region` filter compares codes exactly.
- **Copy is keyed by short code.** Coinme's compliance copy is stored under the part after the hyphen (`MN`); the SDK derives that key from the ISO code for you.

### What each region gives you

Every answer says what happened: an answer from Coinme's rules, an explicit "this region has no rules", or a typed `CoinmeComplianceError`. A mistake in your input is never reported as "no rules" or "allowed".

| Region you pass | Region helpers | Rule helpers | `lookupRegion` |
| --- | --- | --- | --- |
| Not an ISO code (`'MN'`) | Throw `invalidRegion` | Throw `invalidRegion` | Throws `invalidRegion` |
| An ISO code Coinme does not list (`'US-ZZ'`) | `'unknown'`; never operating or onboardable | Nothing excluded, nothing required; `evaluateTransaction` returns `allowed: true, hasRules: false` | `listed: false`, `rules: null` |
| A listed region without rules | Its status from the list | Nothing excluded, nothing required; `hasRules: false` | `listed: true`, `rules: null` |
| A listed region with rules | Its status from the list | Answers from its rules; `hasRules: true` | `listed: true`, `rules: { … }` |

"No rules" means Coinme's configuration places no restrictions on that region. It does not mean the region is available: whether Coinme operates there is a separate question for `getRegionStatus`. The boolean helpers (`isRailExcluded` and the rest) answer `false` both when the rules allow something and when there are no rules; use `lookupRegion`, or `hasRules` on `evaluateTransaction`, when you need to know which.

## Transaction rules

A region's rules can exclude payment rails, whole operations and assets. These functions apply them the way Coinme does, so you don't re-implement the details. They take the configuration from `client.getComplianceConfig()` or `useComplianceConfig()`.

```typescript
import { evaluateTransaction, isRailExcluded, Rail } from '@coinme-security/compliance-sdk-react';

const config = client.getComplianceConfig();

const verdict = evaluateTransaction(config, customer.region, {
  operation: 'buy',
  rail: Rail.TransactBuyDebit,
  asset: 'USDC',
});
if (!verdict.allowed) showNotAvailable(verdict.reasons); // for example ['railExcluded']

if (isRailExcluded(config, customer.region, Rail.TransactSellReadycode)) hideCashPickup();
```

| Function | Answers |
| --- | --- |
| `evaluateTransaction(config, region, request)` | `{ allowed, reasons, hasRules }`, with every reason (`railExcluded`, `assetExcluded`) |
| `isRailExcluded(config, region, rail)` | Is this payment rail excluded? |
| `getExcludedRails(config, region)` | Every excluded rail, as a `Set` |
| `isAssetExcluded(config, region, operation, asset)` | Is this asset excluded for this operation? |
| `getExcludedAssets(config, region, operation)` | The excluded assets as Coinme lists them, upper-cased, as a `Set`; to test one asset, use `isAssetExcluded` |
| `getAllowedOperations(config, region)` | The operations (`buy`, `sell`, `send`, `receive`, `swap`, `redeem`) still open: not excluded outright, and not every known channel excluded |

- **Excluding an operation excludes all of its channels.** A region that excludes the bare `transact_buy` excludes `transact_buy_debit`, `transact_buy_ach` and every other buy channel; likewise `transact_sell`, and `transact_redeem` with its Coinstar channel. `isRailExcluded` and `getExcludedRails` apply this expansion for you.
- **A channel newer than your SDK fails closed.** `isRailExcluded` and `evaluateTransaction` also cover a channel Coinme adds after your SDK version (`transact_buy_<channel>`), so a new channel is blocked until you upgrade rather than allowed. `getExcludedRails` lists only the channels your version knows.
- **Without a rail, `evaluateTransaction` checks the operation as a whole.** It is excluded when the bare operation is, or when every channel of it is excluded one by one: the same test `getAllowedOperations` uses, so the two always agree.
- **Rail keys match exactly**, including case. Use the `Rail` constants.
- **Assets match by base symbol.** Pass the key you have, base (`'USDC'`) or chain-qualified (`'USDC_SOL'`), in any case: an asset is excluded when it is listed itself or when its base symbol is, so excluding `USDC` excludes every chain of USDC.
- **Rules apply only to regions that have them.** A region without rules, or one Coinme does not list, excludes nothing; `evaluateTransaction` says so with `hasRules: false`, and `lookupRegion` tells the two apart. Check `getRegionStatus` first to know whether Coinme operates there at all (see [What each region gives you](#what-each-region-gives-you)).

## Consents and transactional disclosures

Some regions require customers to accept session consents (for example `minnesota_consent`), and some require transactional disclosures before particular kinds of transaction. Pass in what the customer has already accepted or attested; the SDK works out what is still owed.

```typescript
import {
  getDisclosuresToPresent,
  getMissingConsents,
  RailType,
} from '@coinme-security/compliance-sdk-react';

const config = client.getComplianceConfig();

const missing = getMissingConsents(config, customer.region, customer.acceptedConsents);

const disclosures = getDisclosuresToPresent(config, customer.region, {
  rails: [RailType.Greendot],
  attested: customer.attestedDisclosures,
});
```

| Function | Answers |
| --- | --- |
| `getRequiredConsents(config, region)` | Which session consents does the region require? |
| `getMissingConsents(config, region, accepted)` | Which of them has the customer not accepted yet? |
| `getDisclosuresToPresent(config, region, { rails, attested })` | Which transactional disclosures to show now |

A disclosure applies when its channels overlap the transaction's `rails`. Whether it is shown then depends on whether the customer has attested to it and whether it is `alwaysRequired`:

| Channels overlap `rails` | Customer has attested | `alwaysRequired` | Shown |
| --- | --- | --- | --- |
| No | Either | Either | No |
| Yes | No | Either | Yes |
| Yes | Yes | No | No |
| Yes | Yes | Yes | Yes, on every transaction |

A region without rules requires nothing. Both sides fail closed: a disclosure Coinme configures without channels applies to every transaction, and an empty `rails` returns every disclosure the region has, so always pass the transaction's channels.

## Custom receipts and special requirements

Some regions require a custom receipt for certain channels. Whether one applies depends on where the kiosk is, where the customer lives and the receipt's `mode`: `kioskLocation` (the kiosk is in the region), `userResidence` (the customer lives there) or `any` (either). A mode your SDK version does not know is treated like `any`, so a receipt Coinme adds is issued rather than skipped.

```typescript
import {
  getCustomReceipts,
  hasRequirement,
  RailType,
  SpecialRequirement,
} from '@coinme-security/compliance-sdk-react';

const config = client.getComplianceConfig();

const receipts = getCustomReceipts(config, {
  rail: RailType.Coinstar,
  kioskRegion: kiosk.region,
  residenceRegion: customer.region,
});
// for example [{ region: 'US-ND', mode: 'kioskLocation', rails: ['coinstar'] }]

if (hasRequirement(config, customer.region, SpecialRequirement.DocumentaryKyc)) {
  requireDocumentUpload();
}
```

| Function | Answers |
| --- | --- |
| `getCustomReceipts(config, { rail, kioskRegion?, residenceRegion? })` | Which custom receipts to issue, each with its region |
| `getRequirements(config, region)` | The region's special requirements |
| `hasRequirement(config, region, requirement)` | Does the region have this requirement? |

Receipts come back in configuration order, each listed once, even when the kiosk and the customer are in the same region. When more than one region requires a receipt, Coinme's own transaction history shows only the first, so `receipts[0]` is the receipt Coinme issues.

## Localized copy

The text of consents, transactional disclosures and custom receipts is Coinme's, maintained by Coinme and published in several languages (English, Spanish, Chinese, Hmong, Somali, Vietnamese and more). Load a language, then ask for the copy of what the rules require.

### Load a language

```tsx
import {
  ComplianceHtml,
  createComplianceContent,
  createWebPlatform,
  getMissingConsents,
} from '@coinme-security/compliance-sdk-react';

const content = createComplianceContent({ platform: createWebPlatform() });
const catalog = await content.load('es');

for (const type of getMissingConsents(config, customer.region, accepted)) {
  const consent = catalog.getConsentContent(customer.region, type);
  // consent.body, consent.intro, consent.labels (one checkbox each), consent.outro,
  // consent.continueLabel, plus consent.language and consent.contentHash
}

const disclosure = catalog.getDisclosureContent('US-CT', 'irreversibility_disclosure', 'card_buy');
const receipt = catalog.getReceiptContent('US-CT', 'coinstar');

<ComplianceHtml html={disclosure.body[0]} />;
```

| Function | Returns |
| --- | --- |
| `catalog.getConsentContent(region, type)` | `{ body, intro, labels, outro, continueLabel }`, or `undefined` |
| `catalog.getDisclosureContent(region, type, variant)` | The same plus `lineItemLabels` and `footnotes`; variants are `cash_buy`, `card_buy`, `card_sell` and `send` |
| `catalog.getReceiptContent(region, rail)` | `{ html }` to append to the receipt, or `undefined` |
| `getBundledComplianceContent()` | A catalog of the English copy built into the SDK release, available synchronously |

Show a consent as its `body`, then `intro`, one checkbox per entry in `labels` (every one must be ticked), then `outro`, and a button labelled `continueLabel`. Show every part: the attestation records a hash of all of it. A disclosure adds line items: show each of `lineItemLabels` beside the value your app supplies for it, by position, with its `footnotes`.

- **Fallback.** Each item comes whole from the requested language, else English, else the English copy built into the SDK release, so one screen never mixes languages. `language` on each item says which one you got. `load()` never rejects.
- **`contentHash`** fingerprints the copy Coinme published for the item (its language and each field, before sanitizing). Record it when they accept (the attestation helpers do), so the agreement can be traced to the text.

### Render it safely

The copy is HTML and arrives unsanitized. Render it with `<ComplianceHtml>`, or pass it through `sanitizeComplianceHtml()` before inserting it yourself. Only text, list, heading, link and image elements survive, with only `data-role`, `href`, `target`, `src` and `alt`: no scripts, event handlers, forms, media, inline styles or `srcset`. Links go only to `coinme.com`, over `https` (a plain `http:` link is upgraded to `https:`), or to `mailto:` a single coinme.com address (without any query). Images load only over `https` from `coinme.com`, or from a root-relative path on your own site (`/logo.png`); a path that only looks relative, such as `/\evil.com/p.gif`, is removed. On the server, `<ComplianceHtml>` renders an empty element and fills in once the page hydrates; `sanitizeComplianceHtml()` returns escaped text, never markup.

`<ComplianceHtml html={…} />` renders a `div` by default; pass `as` for another element, and any other attribute (such as `className`) is passed to it. Style the copy through its `data-role` attributes: `body-title`, `disclosure-title`, `disclosure-text`, `disclosure-text-centered`, `section-title` and `body-list`.

```css
.consent [data-role='section-title'] {
  font-weight: 600;
}
.consent [data-role='body-list'] {
  padding-left: 1.25rem;
}
```

### Content hooks

`ComplianceProvider` also loads the copy, in the language of its `language` prop, and these hooks read it:

| 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)` | The consent's copy, or `undefined` |
| `useDisclosureContent(region, type, variant)` | The disclosure variant's copy, or `undefined` |
| `useReceiptContent(region, rail)` | The receipt addendum, or `undefined` |

```tsx
<ComplianceProvider environment="prod" language={userLanguage}>
  <App />
</ComplianceProvider>;

const MinnesotaConsent = () => {
  const consent = useConsentContent('US-MN', 'minnesota_consent');
  return consent ? <ComplianceHtml html={consent.body.join('')} /> : null;
};
```

On the server and the first browser render the hooks return the English copy built into the SDK, so markup hydrates cleanly, and they switch once the requested language loads. Changing `language` loads the new language. A component re-renders only when its own item changes.

## 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; recording never changes earlier ones or anything else about the customer.

> **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](https://platformdocs.coinme.com/docs/coinme-onboarding-sdk.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`).

In a browser or app, the attestation store refuses a request whose `Authorization` header carries a partner access token and rejects with a `configuration` `CoinmeComplianceError` before anything is sent. If you see it, your backend is returning the partner access token to the browser or app: change that route to mint a Transient Auth Token from `POST /services/browserAuth` with `scope=attestations` and return only its `access_token`. The partner access token is a long-lived credential that must stay on your backend.

### Record and read

```typescript
import {
  acceptedConsents,
  buildAttestation,
  createHttpAttestationStore,
  createWebPlatform,
  getMissingConsents,
} from '@coinme-security/compliance-sdk-react';

const store = createHttpAttestationStore({
  environment: 'prod',
  platform: createWebPlatform(),
  getHeaders: async () => ({ Authorization: `Bearer ${await myBackend.complianceToken()}` }),
});

const config = client.getComplianceConfig();
const latest = await store.list(customerId, { latest: true });
const missing = getMissingConsents(config, 'US-MN', acceptedConsents(latest, { region: 'US-MN' }));

// After the customer accepts the copy you showed them. `consent` is undefined when the copy is
// not published, in which case there is nothing to attest to.
const consent = catalog.getConsentContent('US-MN', 'minnesota_consent');
if (consent !== undefined) {
  await store.record(
    customerId,
    buildAttestation({ config, region: 'US-MN', type: 'minnesota_consent', content: consent })
  );
}
```

| Function | Purpose |
| --- | --- |
| `createHttpAttestationStore({ environment, platform, getHeaders })` | Coinme's attestation store |
| `store.list(customerId, { latest? })` | The customer's attestations, oldest first; `latest` keeps the newest per type and variant |
| `store.record(customerId, attestation, { idempotencyKey? })` | Records one attestation and returns it as stored |
| `buildAttestation({ config, region, type, variant?, content })` | The attestation for the copy shown |
| `acceptedConsents(attestations, { region?, policyVersion? })` | Input for `getMissingConsents` |
| `attestedDisclosures(attestations, { region?, policyVersion? })` | Input for `getDisclosuresToPresent` |
| `latestAttestations(attestations)` | The newest attestation per type and variant |
| `createInMemoryAttestationStore()` | For tests and demos only; nothing is persisted |

- A store call without a `customerId` rejects with a `CoinmeComplianceError` of kind `'missingCustomerId'`. In React, the attestation hooks throw `'missingAttestationStore'` when the provider has no store; before a `customerId` is set, `useAttestations` and `useMissingConsents` report status `'needsCustomer'` (with `missing` still `undefined`) and `attest()` rejects with `'missingCustomerId'`. None of these means "not attested", and never treat a failure as attested.
- Each `record` call is a new attestation. To retry the same one safely, pass the same `idempotencyKey`.
- Filter by `policyVersion` to ask customers to accept again after Coinme's policy changes.

### Attestation hooks

Give the provider the store, and the `customerId` once onboarding completes:

```tsx
<ComplianceProvider environment="prod" attestationStore={store} customerId={customerId}>
  <App />
</ComplianceProvider>;

const { status, missing } = useMissingConsents('US-MN'); // missing is undefined until status is 'ready'
const attest = useAttest();
await attest({ region: 'US-MN', type: 'minnesota_consent', content: consent });
```

| Hook | Returns |
| --- | --- |
| `useAttestations()` | `{ status, attestations, error }`: the customer's latest attestation per type and variant |
| `useMissingConsents(region)` | `{ status, missing, error }`: the consents the customer still owes in the region |
| `useAttest()` | A function that builds and records an attestation from `{ region, type, variant?, content }` |

`status` is `'needsCustomer'` until there is a `customerId`, then `'loading'`, then `'ready'` or `'error'`. `missing` stays `undefined` until `'ready'`: never read an unknown answer as "nothing owed". After `attest`, the hooks update without reloading.

## Putting it together: an end-to-end integration

This walkthrough follows one customer from your app's start to a checked transaction, with the React entry point. `fetchComplianceToken`, `NotAvailable` and the other names that are not imported stand for your own code.

### 1. Mount the provider

Create the attestation store once, outside any component, and mount the provider near the root. Pass `customerId` only once the customer has onboarded.

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

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

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

### 2. Check the region

Before onboarding, offer only onboardable regions (the [Quickstart](#quickstart) picker). For a returning customer, check their region before showing anything transactional:

```tsx
import type { ReactNode } from 'react';
import { RegionStatus, useRegionStatus } from '@coinme-security/compliance-sdk-react';

const RegionGate = ({ region, children }: { region: string; children: ReactNode }) => {
  const status = useRegionStatus(region);
  if (status === RegionStatus.Unknown || status === RegionStatus.NotOperating) {
    return <NotAvailable />;
  }
  return <>{children}</>;
};
```

`'operating'` only closes onboarding; it does not mean the customer can transact. Step 6 checks the transaction against the region's rules before offering it.

### 3. Find the missing consents

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

const ConsentGate = ({ region, children }: { region: string; children: ReactNode }) => {
  const { status, missing } = useMissingConsents(region);
  if (status !== 'ready' || missing === undefined) return <Loading status={status} />;
  if (missing.length > 0) return <ConsentScreen region={region} type={missing[0]} />;
  return <>{children}</>;
};
```

Stay on the loading state for `'loading'`, `'error'` and `'needsCustomer'`: an unknown answer is never "nothing owed".

### 4. Show the content

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

const ConsentScreen = ({ region, type }: { region: string; type: string }) => {
  const consent = useConsentContent(region, type);
  const [ticked, setTicked] = useState<boolean[]>([]);
  if (consent === undefined) return <ContactSupport />;
  const allTicked = consent.labels.every((_, index) => ticked[index]);
  return (
    <form>
      {consent.body.map((html, index) => <ComplianceHtml key={index} html={html} />)}
      {consent.intro.map((html, index) => <ComplianceHtml key={index} html={html} />)}
      {consent.labels.map((html, index) => (
        <label key={index}>
          <input
            type="checkbox"
            checked={ticked[index] ?? false}
            onChange={(event) => setTicked((prev) => Object.assign([...prev], { [index]: event.target.checked }))}
          />
          <ComplianceHtml as="span" html={html} />
        </label>
      ))}
      {consent.outro.map((html, index) => <ComplianceHtml key={index} html={html} />)}
      <AcceptButton region={region} type={type} content={consent} disabled={!allTicked} label={consent.continueLabel} />
    </form>
  );
};
```

### 5. Attest

```tsx
import { useAttest } from '@coinme-security/compliance-sdk-react';
import type { ConsentContent } from '@coinme-security/compliance-sdk-react';

const AcceptButton = ({ region, type, content, disabled, label }: {
  region: string;
  type: string;
  content: ConsentContent;
  disabled: boolean;
  label: string;
}) => {
  const attest = useAttest();
  return (
    <button type="button" disabled={disabled} onClick={() => attest({ region, type, content })}>
      {label}
    </button>
  );
};
```

Once the attestation is recorded, `useMissingConsents` updates on its own and `ConsentGate` moves to the next consent or to its children. If `attest` rejects, show the error and keep the customer on the consent.

### 6. Check the transaction and present its disclosures

```tsx
import {
  attestedDisclosures,
  evaluateTransaction,
  getDisclosuresToPresent,
  Rail,
  RailType,
  useAttestations,
  useComplianceConfig,
} from '@coinme-security/compliance-sdk-react';

const CardBuy = ({ region, asset }: { region: string; asset: string }) => {
  const config = useComplianceConfig();
  const { status, attestations } = useAttestations();

  const verdict = evaluateTransaction(config, region, {
    operation: 'buy',
    rail: Rail.TransactBuyDebit,
    asset,
  });
  if (!verdict.allowed) return <NotAvailable reasons={verdict.reasons} />;
  if (status !== 'ready') return <Loading status={status} />;

  const disclosures = getDisclosuresToPresent(config, region, {
    rails: [RailType.DigitalBuy],
    attested: attestedDisclosures(attestations, { region }),
  });
  if (disclosures.length > 0) {
    return <DisclosureScreen region={region} type={disclosures[0].type} variant="card_buy" />;
  }
  return <ConfirmBuy region={region} asset={asset} />;
};
```

`DisclosureScreen` is `ConsentScreen` with `useDisclosureContent(region, type, variant)`, the line items beside your values, and `variant` passed to `attest`. A disclosure that is `alwaysRequired` comes back on every transaction, so show it each time and attest each time.

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

| Kind | When | How you get it |
| --- | --- | --- |
| `invalidRegion` | A region is not an ISO 3166-2 code. | Thrown immediately; in React, thrown while rendering. |
| `configuration` | A client is created with an unknown `environment` or an incomplete `platform`, a hook is used outside `ComplianceProvider`, or the attestation store's `getHeaders` returns a partner access token instead of a Transient Auth Token. | Thrown. Attestation store: rejects before anything is sent. |
| `missingAttestationStore` | An attestation hook is used, or `attest()` called, without an `attestationStore` on the provider. | Hooks throw while rendering; `attest()` rejects. |
| `missingCustomerId` | An attestation store call, or `attest()`, without a `customerId`. | Rejects. The read hooks report status `'needsCustomer'` instead of failing. |
| `network` | A request did not complete, or timed out. | Configuration: reported on `getConfig().lastError`, never thrown. Attestation store: rejects. |
| `unauthorized` | Coinme rejected the request's credentials (401 or 403), for example a Transient Auth Token from `getHeaders` that expired or was minted for another customer. | As for `network`. |
| `server` | Coinme returned another error status or an error response. | As for `network`. |
| `invalidResponse` | Coinme's response was not what its API returns, or a configuration failed validation. | As for `network`; an invalid configuration never replaces the one in use. |

A failed configuration fetch never throws to your code: the client keeps the configuration it has, marks it `stale` and reports the error in `lastError`. If your `getHeaders` function throws or rejects, that error reaches you unchanged, not wrapped in a `CoinmeComplianceError`. Errors may carry `status` (the HTTP status) and `detail` (which option, field or part of the response was rejected); messages and details never contain customer data or the input that was rejected, so they are safe to log. 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 and that, after the first fetch, `getConfig().source` is `'remote'`.
2. Check that the state picker lists only onboardable regions with ISO codes as values, that an ISO code Coinme does not list, such as `'US-ZZ'`, comes back `'unknown'` and is treated as unavailable, and that a short code such as `'MN'` throws `invalidRegion`.
3. For a region with a session consent, check that the consent screen shows the copy in the provider's `language`, and that every checkbox must be ticked before the button enables.
4. 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.
5. Check a transaction against a rail and an asset the region excludes, and confirm your screen hides or refuses it before it reaches your backend.

## Security

- **Never put partner credentials in the browser.** 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 the sanitizer.** Use `<ComplianceHtml>` or `sanitizeComplianceHtml()`; never insert the raw HTML yourself.
- **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

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

No. It helps your UI 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.

### Why do I check the region's status before the rule helpers?

The rule helpers apply a region's rules, and a region with no rules has nothing to exclude, so they answer "not excluded" for a region Coinme does not operate in at all (`evaluateTransaction` marks that case with `hasRules: false`). `getRegionStatus` (or `useRegionStatus`) is the check that says whether Coinme operates there; do it first.

### Which regions does Coinme operate in?

Ask the SDK rather than keeping a list: `getSupportedRegions()` or `useSupportedRegions()` returns every region Coinme lists with its `operating` and `onboardable` flags, kept current while your app runs.

### Can I pass a state's name or its two-letter code?

No. Every region is an ISO 3166-2 code such as `'US-NY'`, in any letter case. A name, a short code (`'NY'`) or a code with spaces around it throws `invalidRegion`; it is never treated as unknown. For a US customer whose address gives a two-letter state, pass ``US-${customer.state}``.

### What token does the attestation store send?

Whatever your `getHeaders` returns, on every request, and that must always be a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) with the `attestations` scope, never your partner access token. Your backend exchanges its API client ID and client secret for a partner access token (`POST /services/authorize`), then calls `POST /services/browserAuth` with the customer's `customerId` and `scope=attestations`, and hands the token to the page. It lasts 10 minutes and works for the attestation store's calls only, so mint a fresh one inside `getHeaders`.

### 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'`; collect consents that must come before onboarding as your onboarding flow requires, and record them once the `customerId` exists.

### What happens when Coinme changes a policy?

The configuration's `policyVersion` changes. Pass it as the `policyVersion` filter to `acceptedConsents` and `attestedDisclosures` when customers must accept again under the new policy.

## Troubleshooting

**A helper or hook throws `invalidRegion`.** The region is not an ISO 3166-2 code: a short code (`'MN'`), a name, or a value with spaces around it. Pass ``US-${state}`` for a US state.

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

**An attestation store call rejects with `configuration` and nothing is sent.** `getHeaders` returned a partner access token. Mint a Transient Auth Token with `scope=attestations` on your backend and return only its `access_token`; see [Attestations](#attestations).

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

**Reading or recording attestations fails.** Attestations are not available in the beta at this time; see [Attestations](#attestations).

**The configuration stays `stale`.** Fetches to Coinme are failing; check `lastError`, the browser's network panel and your Content-Security-Policy's `connect-src`. The SDK keeps serving the last good configuration meanwhile.

**Copy shows in English after choosing another language.** That item is not published in the requested language yet; `language` on the item says which one was served.
