---
name: coinme-vault-android
description: "Add card capture to an Android app with the Coinme Vault SDK: add the repository and dependency, configure the vault, build the fields in Kotlin, XML or Compose, observe form state, and submit the payment method to Coinme with the transient auth token. Use when asked to collect card details, add a payment method or integrate Coinme's vault in an Android or Kotlin app."
metadata:
  surface: "caas"
  package: "CoinmeVault · Kotlin"
  version: "1.0.0"
---

# Coinme Vault SDK on Android

## When to use this skill

The human wants an Android app to collect a customer's card details and add them as a payment method at Coinme without the card data touching the app's code or servers. It is not for the Coinme Widget, which handles payment 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

An Android app with the vault's secure fields in the payment form, validation wired to the submit control, and a submit that sends the payment method to Coinme with a fresh transient auth token in the Authorization header, a Risk SDK session id fetched right before the submit, and the same device fingerprint the Risk SDK gets.

## 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 |
| --- | --- | --- |
| `registry token` | Read-only token for the private registry that serves the Coinme SDKs. The install steps below read it from an environment variable they name; set that variable. | 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. |
| `customerId, paymentProviderId and the Risk SDK webSessionId` | The customer the payment method belongs to, the payment provider, and the Risk SDK session the submit is tied to. | Values from the human's app state at submit time; the Risk SDK must already be integrated to supply the session id, fetched right before the submit. On the web and React Native the Coinme SDKs share the device fingerprint; on iOS and Android the app passes the same value it gives the Risk SDK. |

## 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

Every payment-method submit carries a Transient Auth Token as `Authorization: Bearer <token>`, minted by the human's backend for the customer (the backend step below). The client fetches one when the add-card screen opens, keeps it in memory, and on a `server` error with status 401 or 403 fetches a fresh one and retries once. Never store it on the device or in the browser, and never put the backend's credentials in the client. Never pass the partner access token to the SDK; the `Authorization` header carries only the Transient Auth Token from `POST /services/browserAuth`.

The submit also needs a Risk SDK session id, fetched right before the submit because a session tag lives 30 minutes. Pass `X-Device-Fingerprint` with the same value the Risk SDK gets. If the Risk SDK is not integrated yet, say so and offer the Risk skill first.

## Backend: mint the Transient Auth Token

Before the client can submit a card, the human's backend needs a route that returns `mintTransientAuthToken(customerId)` for the signed-in customer: a Transient Auth Token with the default `payment-methods` scope, bound to the customer the card will belong to. The client calls it when the add-card screen opens.

#### 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.

# Coinme Vault SDK for Android Native

## Introduction

The Coinme Vault SDK is a Kotlin library for Android that wraps the VGS Collect Android SDK, pre-binds Coinme's VGS vault configuration, and exposes a small, secure data-collection API. It lets your application securely collect sensitive card and payment-method data (card number, expiry, CVV, cardholder name, billing address) and submit it directly to Coinme's vault without that data ever entering your application process.

It is the Android counterpart to the `vault-sdk-react-native` SDK, and the public API mirrors the React Native SDK for cross-platform parity.

**Security model:** Secure field values (card number, CVV, …) never leave the VGS field views and never enter your application process. The SDK exposes only validity and non-sensitive metadata (`isValid`, `isEmpty`, `cardBrand`, `last4`, …). Submission goes directly from the VGS views to the vault. **Error messages never contain field values (PII).**

### What Does It Collect?

The SDK collects only the payment data you explicitly bind into its fields, and submits it directly to the Coinme vault. The supported fields are:

- **Card data** — card number, expiry month/year, CVV
- **Cardholder name**
- **Billing address** — address lines, city, ZIP code

Your application never receives the raw field values — it sees only validity state and non-sensitive metadata such as the detected card brand and the last four digits.

## SDK Requirements

| Requirement | Value |
| --- | --- |
| Minimum Android version | Android 7.0 (Nougat) — API Level 24 |
| Compile SDK | 37 |
| JVM target | 17 |
| VGS Collect | 1.11.0 (re-exported as `api`) |

The SDK ships **no Compose dependency** — VGS fields are Android Views, so "Compose support" is just `AndroidView` interop (see Integration path 3 below).

## Installation

**IMPORTANT:** Ask your Coinme integration contact to obtain your Cloudsmith entitlement token. The library publishes to Cloudsmith (`coinme/coinme-sdk-mobile`) as `com.coinme:vault-sdk-android`.

### Step 1: Add the Repository

In `settings.gradle.kts`:

`settings.gradle.kts`

```kotlin
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven {
            url = uri("https://maven.cloudsmith.io/coinme/coinme-sdk-mobile/")
            // Cloudsmith entitlement token, supplied by Coinme.
            credentials(HttpHeaderCredentials::class) {
                name = "Authorization"
                value = "Bearer ${providers.gradleProperty("CLOUDSMITH_ENTITLEMENT_TOKEN").get()}"
            }
            authentication { create<HttpHeaderAuthentication>("header") }
        }
    }
}
```

### Step 2: Add the Dependency

In `app/build.gradle.kts`:

`app/build.grqadle.kts`

```kotlin
dependencies {
    implementation("com.coinme:vault-sdk-android:1.0.0")
}
```

Because the SDK declares `api(vgscollect)`, the VGS field-view classes (`VGSCardNumberEditText`, …) are available on your compile classpath without an extra dependency.

## Configuration

The account-scoped **vault ID** is baked into the library as a `BuildConfig` field, read from an **environment variable with a** `local.properties` **fallback**. Copy `local.properties.example` to `local.properties` and fill in the values, or set the env vars in CI:

```
COINME_VAULT_ID_SANDBOX=your_sandbox_vault_id
COINME_VAULT_ID_LIVE=your_live_vault_id
```

The env var names match the React Native SDK's `gen-vault-config`, so one `.env` serves both repos.

**Ingress hostnames and the submit path are not configured here** — they are public, stable values baked into the SDK per environment: sandbox → `secure.payments-stage.coinme.com`, live → `secure.payments.coinme.com`, path → `/caas/v2/paymentmethods`. They can be overridden per-runtime (but never the vault ID) via `RuntimeVaultConfig` — see Runtime configuration overrides below.

## Quick Start

```kotlin
import com.coinme.vaultsdk.CoinmeVault
import com.coinme.vaultsdk.CoinmeVaultEnvironment
import com.coinme.vaultsdk.core.VaultSubmitOptions
import com.coinme.vaultsdk.widget.CoinmeFields

// 1. Create the vault for an environment.
val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX)

// 2. Build pre-named VGS fields and bind them.
val cardNumber = CoinmeFields.cardNumber(context)
val expiry     = CoinmeFields.expiry(context)
val cvc        = CoinmeFields.cvc(context)
val holder     = CoinmeFields.cardHolder(context)
vault.bind(cardNumber, expiry, cvc, holder)   // add the views to your layout too

// 3. Observe form validity (drive your submit button's enabled state).
lifecycleScope.launch {
    vault.formState.collect { state -> submitButton.isEnabled = state.isValid }
}

// 4. Submit. Throws CoinmeVaultException on failure.
lifecycleScope.launch {
    val result = vault.submit(
        VaultSubmitOptions(
            extraData = mapOf("accountId" to "abc", "country" to "US"),
            headers = mapOf("Authorization" to "Bearer $transientAuthToken"),
        )
    )
    println("status=${result.status} body=${result.body}")
}

// 5. Release VGS resources when done (e.g. onDestroy / onDispose).
vault.dispose()
```

## Core Concepts

| Type | Role |
| --- | --- |
| `CoinmeVault` | Entry point. Wraps a `VGSCollect` collector, tracks form validity, performs submits. |
| `CoinmeVaultEnvironment` | `SANDBOX` or `LIVE`. Selects the baked-in vault ID / ingress / path. |
| `CoinmeFields` | Factory that builds VGS field views with the correct Coinme field name pre-set. |
| `VaultFieldNames` | The dot-notation field-name constants VGS deep-merges into nested JSON. |
| `VaultSubmitOptions` | Per-submit `extraData` (non-secure JSON) and `headers`. |
| `VaultSubmitResult` | `status: Int`, `body: String?`, `data: JsonElement?` on success. |
| `CoinmeVaultException` | Sealed error hierarchy thrown by `submit`. |

The collector is exposed as `vault.collector: VGSCollect` — the documented escape hatch for advanced VGS usage not covered by the wrapper. You rarely need it.

### Creating a vault

```kotlin
val vault = CoinmeVault.create(
    context = context,
    environment = CoinmeVaultEnvironment.SANDBOX,
    config = null,   // optional RuntimeVaultConfig; see "Runtime configuration overrides"
)
```

`create` resolves the vault configuration, builds the underlying `VGSCollect`, and registers a single form-state listener. Create **one** `CoinmeVault` per form/screen and `dispose()` it when the screen goes away.

### Field names

Android VGS has no `{{ placeholder }}` templating. Field names are **dot-notation keys** that VGS deep-merges with `setCustomData` into nested submit JSON. They are defined in `VaultFieldNames`:

| Constant | Value | Notes |
| --- | --- | --- |
| `CARD_NUMBER` | `card.cardNumber` |  |
| `EXP_MONTH` | `card.month` | child of the expiry serializer |
| `EXP_YEAR` | `card.year` | child of the expiry serializer |
| `CVC` | `card.cvv` |  |
| `CARD_HOLDER` | `cardHolderName` |  |
| `ADDRESS1` | `billingAddress.addressLine1` |  |
| `ADDRESS2` | `billingAddress.addressLine2` |  |
| `CITY` | `billingAddress.city` |  |
| `ZIPCODE` | `billingAddress.zipCode` |  |
| `EXPIRY` | `card` | parent field name for `ExpirationDateEditText` |

Unlike the RN SDK's template allowlist, **Android submits every bound field.** Bind only the fields you intend to send.

The expiry field is the special case: its own field name is `card` and it uses a `VGSExpDateSeparateSerializer("card.month", "card.year")` so a single input writes two JSON keys. `CoinmeFields.expiry()` configures this for you.

## Integration Paths

The same `CoinmeVault` instance supports three ways of constructing fields.

### 1.`CoinmeFields`factory (Kotlin / Java)

**Recommended for native (View-based and Compose) usage.**

VGS field views are `final` and cannot be subclassed, so the SDK does not ship `CoinmeXField` subclasses. Instead, `CoinmeFields` is a factory that builds a stock VGS view with the correct default field name already applied.

```kotlin
import com.coinme.vaultsdk.widget.CoinmeFields

val cardNumber = CoinmeFields.cardNumber(context)   // VGSCardNumberEditText, name "card.cardNumber"
val expiry     = CoinmeFields.expiry(context)       // ExpirationDateEditText, separate-date serializer
val cvc        = CoinmeFields.cvc(context)          // CardVerificationCodeEditText, name "card.cvv"
val holder     = CoinmeFields.cardHolder(context)   // PersonNameEditText, name "cardHolderName"
val custom     = CoinmeFields.text(context, "myField") // VGSEditText, arbitrary field name

container.addView(cardNumber)
container.addView(expiry)
vault.bind(cardNumber, expiry, cvc, holder)
```

`cardNumber`, `cvc`, and `cardHolder` accept an optional `fieldName` override; `expiry` does not (its serializer is fixed); `text` requires the field name.

### 2. XML layouts

Declare the VGS view classes directly in your layout and set `app:fieldName` to the matching `VaultFieldNames` value.

```markup
<com.verygoodsecurity.vgscollect.widget.VGSCardNumberEditText
    android:id="@+id/card_number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:fieldName="card.cardNumber" />

<com.verygoodsecurity.vgscollect.widget.CardVerificationCodeEditText
    android:id="@+id/cvc"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:fieldName="card.cvv" />

<com.verygoodsecurity.vgscollect.widget.PersonNameEditText
    android:id="@+id/card_holder"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:fieldName="cardHolderName" />
```

```markup
val vault = CoinmeVault.create(this, CoinmeVaultEnvironment.SANDBOX)
vault.bind(
	findViewById(R.id.card_number),    
	findViewById(R.id.cvc),   
	findViewById(R.id.card_holder),
)
```

**Expiry in XML:** the separate-date serializer can't be expressed in XML attributes. Either build the expiry field via `CoinmeFields.expiry(context)` in code and add it to your layout, or set the serializer on the `ExpirationDateEditText` after `findViewById`:

```markup
findViewById<ExpirationDateEditText>(R.id.expiry).setSerializer(
    VGSExpDateSeparateSerializer(VaultFieldNames.EXP_MONTH, VaultFieldNames.EXP_YEAR)
)
```

### 3. Jetpack Compose (AndroidView)

The SDK ships **no Compose artifact**. VGS fields are Android Views, so Compose support is just `AndroidView` interop. Copy these two reference helpers into your app (the canonical copy lives in the demo at `app/.../screens/VaultFields.kt`):

```kotlin
@Composable
fun rememberCoinmeVault(
    environment: CoinmeVaultEnvironment,
    config: RuntimeVaultConfig? = null,
): CoinmeVault {
    val context = LocalContext.current
    val vault = remember(environment, config) {
        CoinmeVault.create(context, environment, config)
    }
    DisposableEffect(vault) { onDispose { vault.dispose() } }
    return vault
}

/** Builds a Coinme widget, binds it to [vault], and renders it via AndroidView. */
@Composable
fun <T : InputFieldView> VaultField(
    vault: CoinmeVault,
    modifier: Modifier = Modifier,
    factory: (Context) -> T,
    configure: (T.() -> Unit)? = null,
) {
    AndroidView(
        modifier = modifier,
        factory = { context ->
            factory(context).apply {
                configure?.invoke(this)
                vault.bind(this)
            }
        },
    )
}
```

## Observing Form State

```kotlin
val formState: StateFlow<VaultFormState>                    // whole-form snapshot
fun fieldState(fieldName: String): Flow<VaultFieldState?>   // one field

data class VaultFormState(
    val fields: Map<String, VaultFieldState> = emptyMap(),
    val isValid: Boolean = false,   // true only when every bound field is valid
)

data class VaultFieldState(
    val fieldName: String,
    val isValid: Boolean,
    val isEmpty: Boolean,
    val isFocused: Boolean,
    val contentLength: Int,
    val cardBrand: String? = null,  // card-number field only
    val last4: String? = null,      // card-number field only
)
```

Binding seeds each field as invalid (RN parity) — a freshly bound form reports `isValid == false` until VGS emits its first state change.

**No secure values are ever present in these flows** — only validity and the non-sensitive metadata shown above.

## Submitting

> **Never use your partner access token with the Vault SDK.**
>
> The `Authorization` header must be `Bearer <transient-auth-token>` with a [Transient Auth Token](https://platformdocs.coinme.com/docs/transient-auth-token.md) your backend mints from `POST /services/browserAuth`. Never pass your partner access token (from `POST /services/authorize`) to the SDK.

```kotlin
suspend fun submit(options: VaultSubmitOptions = VaultSubmitOptions()): VaultSubmitResult

data class VaultSubmitOptions(
    val extraData: Map<String, Any> = emptyMap(),  // deep-merged into the submit JSON alongside fields
    val headers: Map<String, String> = emptyMap(), // merged with trace headers; caller wins on conflict
)
```

What `submit()` does, in order:

1. **Pre-validates** from the tracker; if the form is invalid it throws `CoinmeVaultException.Validation`**before any network call**.
2. Generates per-request `X-B3-TraceId` / `X-B3-SpanId` and merges your `headers` on top (your headers win on conflict).
3. Builds a `POST` to the configured submit path with `extraData` as custom data, then calls VGS **synchronously** on `Dispatchers.IO`.
4. Maps the response — including the **CAAS envelope** case where VGS returns HTTP 200 with an `errorResponse` payload (thrown as `CoinmeVaultException.Caas`, not returned as success).

**Only one submit may be in flight at a time** — a concurrent call throws `CoinmeVaultException.SubmitInProgress`.

### Callback variant (Java / non-coroutine)

```kotlin
vault.submit(VaultSubmitOptions()) { result: Result<VaultSubmitResult> ->
    result.onSuccess { /* ... */ }.onFailure { /* ... */ }
}
```

### Payment-method convenience

```kotlin
import com.coinme.vaultsdk.models.PaymentMethodInput
import com.coinme.vaultsdk.models.PaymentProcessAssociation
import com.coinme.vaultsdk.core.submitPaymentMethod

val result = vault.submitPaymentMethod(
    PaymentMethodInput(
        accountId = "abc",
        providerId = "prov-1",
        webSessionId = "sess-1",
        paymentProcessAssociation = PaymentProcessAssociation.BUY,
        // optional billingAddress* fields default to ""/omitted; country defaults to "US"
    ),
    headers = mapOf("Authorization" to "Bearer $transientAuthToken"),
)
```

It builds the CAAS `extraData` shape (`accountId`, `stagingProviderId`, `webSessionId`, `paymentProcessAssociation`, `billingAddress`) and delegates to `submit`.

## Error Handling

`submit` throws `CoinmeVaultException`, a sealed hierarchy:

```kotlin
try {
    vault.submit(options)
} catch (e: CoinmeVaultException.Validation) {
    e.fields.forEach { (name, reasons) -> showFieldError(name, reasons) }
} catch (e: CoinmeVaultException.Caas) {
    when (e.submitCardError) {
        SubmitCardError.CARD_IN_USE_BY_ANOTHER_USER -> showCardInUse()
        SubmitCardError.MAX_NUMBER_OF_CARDS_REACHED -> showTooManyCards()
        else -> showGenericError()
    }
} catch (e: CoinmeVaultException.Server) {
    showServerError(e.status)
} catch (e: CoinmeVaultException) {
    showGenericError()
}
```

| Subclass | Meaning | Key fields |
| --- | --- | --- |
| `Validation` | Form invalid; thrown before any network call. | `fields: Map<String, List<String>>` (`"required"` / `"invalid"` per field) |
| `Network` | Connectivity / timeout. | `cause` |
| `Server` | HTTP 4xx/5xx from the vault. | `status: Int`, `body: String?` |
| `Caas` | HTTP 200 with a CAAS error envelope. | `status: Int`, `errorResponse: CaasErrorResponse`, `submitCardError: SubmitCardError?` |
| `Unknown` | Anything else. | `cause` |
| `SubmitInProgress` | A submit is already in flight. | — |

`SubmitCardError` (in `com.coinme.vaultsdk.enums`) maps known CAAS error codes to enum constants and is ported from the Coinme app to ease migration. `e.submitCardError` resolves the first known error code to a `SubmitCardError` (or `null` if the code is unrecognized); the raw code remains available via `e.errorResponse.firstKnownError()` (a `CaasErrorData` with `errorCode`, `message`).

**Exception messages never contain field values (PII).** Log them freely.

## Runtime Configuration Overrides

The vault ID is **always** baked in at build time and cannot be overridden. The ingress host and submit path **can** be overridden at runtime by passing a `RuntimeVaultConfig` to `create`:

```kotlin
val runtime = RuntimeVaultConfig(
    sandbox = EnvironmentOverride(ingress = "tnt-xyz.sandbox.verygoodproxy.com", path = "/caas/v2/paymentmethods"),
    live    = EnvironmentOverride(ingress = "tnt-xyz.live.verygoodproxy.com",    path = "/caas/v2/paymentmethods"),
)
val vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX, runtime)
```

When a `RuntimeVaultConfig` is supplied, both environments' `ingress` and `path` must be non-blank (an `IllegalArgumentException` is thrown otherwise). When it is `null`, the baked-in `BuildConfig` values are used.

## Lifecycle

Call `vault.dispose()` when the form is gone (Activity/Fragment `onDestroy`, or Compose `onDispose` via `rememberCoinmeVault`). It cancels the internal coroutine scope and calls `collector.onDestroy()` to release VGS resources. After disposal the instance must not be reused — create a new one.

## Java Interop

`CoinmeVault.create`, `CoinmeFields.*`, and the callback-based `submit` are annotated `@JvmStatic` / `@JvmOverloads`, so they read naturally from Java:

```kotlin
CoinmeVault vault = CoinmeVault.create(context, CoinmeVaultEnvironment.SANDBOX);
VGSCardNumberEditText cardNumber = CoinmeFields.cardNumber(context);
vault.bind(cardNumber);

vault.submit(new VaultSubmitOptions(), result -> {
    if (result.isSuccess()) { /* result.getOrNull() */ }
    return Unit.INSTANCE;
});
```

For Flow-based state observation from Java, collect via the standard `kotlinx-coroutines` Java interop or expose a wrapper on the Kotlin side.

## Verify

Build and run the app. Confirm the secure fields render and validate, that the submit control stays disabled until the form is valid, that the client gets a Transient Auth Token from the human's backend route and sends it as `Authorization: Bearer <token>` together with a Risk SDK session id fetched right before the submit and the device fingerprint the Risk SDK uses, that the `Authorization` header never carries the partner access token, and that no token or backend credential is in the client or a committed file.

### Reading the result

**Done when:** Invalid input keeps the form invalid, the submit succeeds, and listing the customer's payment methods from your backend shows the card `CREATED`.

**Stop and ask the human when** the card is refused as in use and you cannot find the earlier test that holds it, or the session tag keeps failing to match after you minted it on the same device.

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 Vault SDK](https://platformdocs.coinme.com/docs/coinme-vault-sdk.md)
- [Coinme Vault SDK for Android Native](https://platformdocs.coinme.com/docs/coinme-vault-sdk-for-android-native.md)
- [Build: the Library of SDKs and documents](https://platformdocs.coinme.com/pages/build/library.md)
